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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.165   ! raeburn     4: # $Id: loncommon.pm,v 1.164 2003/12/26 21:17:37 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.165   ! raeburn  1013:     my $radioval = "'nochange'";
        !          1014:     my $argfield = 'null';
        !          1015:     if ( grep/^mode$/,(keys %in) ) {
        !          1016:         if ($in{'mode'} eq 'modifycourse')  {
        !          1017:             if ( grep/^curr_authtype$/,(keys %in) ) {
        !          1018:                 $radioval = "'$in{'curr_authtype'}'";
        !          1019:             }
        !          1020:             if ( grep/^curr_autharg$/,(keys %in) ) {
        !          1021:                 unless ($in{'curr_autharg'} eq '') {
        !          1022:                     $argfield = "'$in{'curr_autharg'}'";
        !          1023:                 }
        !          1024:             }
        !          1025:         }
        !          1026:     }
        !          1027: 
1.32      matthew  1028:     $result.=<<"END";
                   1029: var current = new Object();
1.165   ! raeburn  1030: current.radiovalue = $radioval;
        !          1031: current.argfield = $argfield;
1.32      matthew  1032: 
                   1033: function changed_radio(choice,currentform) {
                   1034:     var choicearg = choice + 'arg';
                   1035:     // If a radio button in changed, we need to change the argfield
                   1036:     if (current.radiovalue != choice) {
                   1037:         current.radiovalue = choice;
                   1038:         if (current.argfield != null) {
                   1039:             currentform.elements[current.argfield].value = '';
                   1040:         }
                   1041:         if (choice == 'nochange') {
                   1042:             current.argfield = null;
                   1043:         } else {
                   1044:             current.argfield = choicearg;
                   1045:             switch(choice) {
                   1046:                 case 'krb': 
                   1047:                     currentform.elements[current.argfield].value = 
                   1048:                         "$in{'kerb_def_dom'}";
                   1049:                 break;
                   1050:               default:
                   1051:                 break;
                   1052:             }
                   1053:         }
                   1054:     }
                   1055:     return;
                   1056: }
1.22      www      1057: 
1.32      matthew  1058: function changed_text(choice,currentform) {
                   1059:     var choicearg = choice + 'arg';
                   1060:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 1061:         $Javascript_toUpperCase
1.32      matthew  1062:         // clear old field
                   1063:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   1064:             currentform.elements[current.argfield].value = '';
                   1065:         }
                   1066:         current.argfield = choicearg;
                   1067:     }
                   1068:     set_auth_radio_buttons(choice,currentform);
                   1069:     return;
1.20      www      1070: }
1.32      matthew  1071: 
                   1072: function set_auth_radio_buttons(newvalue,currentform) {
                   1073:     var i=0;
                   1074:     while (i < currentform.login.length) {
                   1075:         if (currentform.login[i].value == newvalue) { break; }
                   1076:         i++;
                   1077:     }
                   1078:     if (i == currentform.login.length) {
                   1079:         return;
                   1080:     }
                   1081:     current.radiovalue = newvalue;
                   1082:     currentform.login[i].checked = true;
                   1083:     return;
                   1084: }
                   1085: END
                   1086:     return $result;
                   1087: }
                   1088: 
                   1089: sub authform_authorwarning{
                   1090:     my $result='';
1.144     matthew  1091:     $result='<i>'.
                   1092:         &mt('As a general rule, only authors or co-authors should be '.
                   1093:             'filesystem authenticated '.
                   1094:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  1095:     return $result;
                   1096: }
                   1097: 
                   1098: sub authform_nochange{  
                   1099:     my %in = (
                   1100:               formname => 'document.cu',
                   1101:               kerb_def_dom => 'MSU.EDU',
                   1102:               @_,
                   1103:           );
1.144     matthew  1104:     my $result = &mt('[_1] Do not change login data',
                   1105:                      '<input type="radio" name="login" value="nochange" '.
                   1106:                      'checked="checked" onclick="'.
                   1107:             "javascript:changed_radio('nochange',$in{'formname'});".'" />');
1.32      matthew  1108:     return $result;
                   1109: }
                   1110: 
                   1111: sub authform_kerberos{  
                   1112:     my %in = (
                   1113:               formname => 'document.cu',
                   1114:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 1115:               kerb_def_auth => 'krb4',
1.32      matthew  1116:               @_,
                   1117:               );
1.165   ! raeburn  1118:     my ($check4,$check5,$krbarg);
1.80      albertel 1119:     if ($in{'kerb_def_auth'} eq 'krb5') {
                   1120:        $check5 = " checked=\"on\"";
                   1121:     } else {
                   1122:        $check4 = " checked=\"on\"";
                   1123:     }
1.165   ! raeburn  1124:     $krbarg = $in{'kerb_def_dom'};
        !          1125: 
        !          1126:     my $krbcheck = "";
        !          1127:     if ( grep/^curr_authtype$/,(keys %in) ) {
        !          1128:         if ($in{'curr_authtype'} =~ m/^krb/) {
        !          1129:             $krbcheck = " checked=\"on\"";
        !          1130:             if ( grep/^curr_autharg$/,(keys %in) ) {
        !          1131:                 $krbarg = $in{'curr_autharg'};
        !          1132:             }
        !          1133:         }
        !          1134:     }
        !          1135: 
1.144     matthew  1136:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   1137:     my $result .= &mt
                   1138:         ('[_1] Kerberos authenticated with domain [_2] '.
                   1139:          '[_3] Version 4 [_4] Version 5',
                   1140:          '<input type="radio" name="login" value="krb" '.
1.165   ! raeburn  1141:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1.144     matthew  1142:          '<input type="text" size="10" name="krbarg" '.
1.165   ! raeburn  1143:              'value="'.$krbarg.'" '.
1.144     matthew  1144:              'onchange="'.$jscall.'" />',
                   1145:          '<input type="radio" name="krbver" value="4" '.$check4.' />',
                   1146:          '<input type="radio" name="krbver" value="5" '.$check5.' />');
1.32      matthew  1147:     return $result;
                   1148: }
                   1149: 
                   1150: sub authform_internal{  
                   1151:     my %args = (
                   1152:                 formname => 'document.cu',
                   1153:                 kerb_def_dom => 'MSU.EDU',
                   1154:                 @_,
                   1155:                 );
1.165   ! raeburn  1156: 
        !          1157:     my $intcheck = "";
        !          1158:     my $intarg = 'value=""';
        !          1159:     if ( grep/^curr_authtype$/,(keys %args) ) {
        !          1160:         if ($args{'curr_authtype'} eq 'int') {
        !          1161:             $intcheck = " checked=\"on\"";
        !          1162:             if ( grep/^curr_autharg$/,(keys %args) ) {
        !          1163:                 $intarg = "value=\"$args{'curr_autharg'}\"";
        !          1164:             }
        !          1165:         }
        !          1166:     }
        !          1167: 
1.144     matthew  1168:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
                   1169:     my $result.=&mt
                   1170:         ('[_1] Internally authenticated (with initial password [_2])',
1.165   ! raeburn  1171:          '<input type="radio" name="login" value="int" '.$intcheck.
        !          1172:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
        !          1173:          '<input type="text" size="10" name="intarg" '.$intarg.
        !          1174:              ' onchange="'.$jscall.'" />');
1.32      matthew  1175:     return $result;
                   1176: }
                   1177: 
                   1178: sub authform_local{  
                   1179:     my %in = (
                   1180:               formname => 'document.cu',
                   1181:               kerb_def_dom => 'MSU.EDU',
                   1182:               @_,
                   1183:               );
1.165   ! raeburn  1184: 
        !          1185:     my $loccheck = "";
        !          1186:     my $locarg = 'value=""';
        !          1187:     if ( grep/^curr_authtype$/,(keys %in) ) {
        !          1188:         if ($in{'curr_authtype'} eq 'loc') {
        !          1189:             $loccheck = " checked=\"on\"";
        !          1190:             if ( grep/^curr_autharg$/,(keys %in) ) {
        !          1191:                 $locarg = "value=\"$in{'curr_autharg'}\"";
        !          1192:             }
        !          1193:         }
        !          1194:     }
        !          1195: 
1.144     matthew  1196:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1.160     matthew  1197:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
1.165   ! raeburn  1198:                     '<input type="radio" name="login" value="loc" '.$loccheck.
        !          1199:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
        !          1200:                     '<input type="text" size="10" name="locarg" '.$locarg.
        !          1201:                         ' onchange="'.$jscall.'" />');
1.32      matthew  1202:     return $result;
                   1203: }
                   1204: 
                   1205: sub authform_filesystem{  
                   1206:     my %in = (
                   1207:               formname => 'document.cu',
                   1208:               kerb_def_dom => 'MSU.EDU',
                   1209:               @_,
                   1210:               );
1.144     matthew  1211:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   1212:     my $result.= &mt
                   1213:         ('[_1] Filesystem Authenticated (with initial password [_2])',
                   1214:          '<input type="radio" name="login" value="fsys" '.
                   1215:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
                   1216:          '<input type="text" size="10" name="fsysarg" value="" '.
                   1217:                   'onchange="'.$jscall.'" />');
1.32      matthew  1218:     return $result;
                   1219: }
                   1220: 
1.80      albertel 1221: ###############################################################
                   1222: ##    Get Authentication Defaults for Domain                 ##
                   1223: ###############################################################
                   1224: 
                   1225: =pod
                   1226: 
1.112     bowersj2 1227: =head1 Domains and Authentication
                   1228: 
                   1229: Returns default authentication type and an associated argument as
                   1230: listed in file 'domain.tab'.
                   1231: 
                   1232: =over 4
                   1233: 
                   1234: =item * get_auth_defaults
1.80      albertel 1235: 
                   1236: get_auth_defaults($target_domain) returns the default authentication
                   1237: type and an associated argument (initial password or a kerberos domain).
                   1238: These values are stored in lonTabs/domain.tab
                   1239: 
                   1240: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
                   1241: 
                   1242: If target_domain is not found in domain.tab, returns nothing ('').
                   1243: 
                   1244: =cut
                   1245: 
                   1246: #-------------------------------------------
                   1247: sub get_auth_defaults {
                   1248:     my $domain=shift;
                   1249:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
                   1250: }
                   1251: ###############################################################
                   1252: ##   End Get Authentication Defaults for Domain              ##
                   1253: ###############################################################
                   1254: 
                   1255: ###############################################################
                   1256: ##    Get Kerberos Defaults for Domain                 ##
                   1257: ###############################################################
                   1258: ##
                   1259: ## Returns default kerberos version and an associated argument
                   1260: ## as listed in file domain.tab. If not listed, provides
                   1261: ## appropriate default domain and kerberos version.
                   1262: ##
                   1263: #-------------------------------------------
                   1264: 
                   1265: =pod
                   1266: 
1.112     bowersj2 1267: =item * get_kerberos_defaults
1.80      albertel 1268: 
                   1269: get_kerberos_defaults($target_domain) returns the default kerberos
                   1270: version and domain. If not found in domain.tabs, it defaults to
                   1271: version 4 and the domain of the server.
                   1272: 
                   1273: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   1274: 
                   1275: =cut
                   1276: 
                   1277: #-------------------------------------------
                   1278: sub get_kerberos_defaults {
                   1279:     my $domain=shift;
                   1280:     my ($krbdef,$krbdefdom) =
                   1281:         &Apache::loncommon::get_auth_defaults($domain);
                   1282:     unless ($krbdef =~/^krb/ && $krbdefdom) {
                   1283:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   1284:         my $krbdefdom=$1;
                   1285:         $krbdefdom=~tr/a-z/A-Z/;
                   1286:         $krbdef = "krb4";
                   1287:     }
                   1288:     return ($krbdef,$krbdefdom);
                   1289: }
1.112     bowersj2 1290: 
                   1291: =pod
                   1292: 
                   1293: =back
                   1294: 
                   1295: =cut
1.32      matthew  1296: 
1.46      matthew  1297: ###############################################################
                   1298: ##                Thesaurus Functions                        ##
                   1299: ###############################################################
1.20      www      1300: 
1.46      matthew  1301: =pod
1.20      www      1302: 
1.112     bowersj2 1303: =head1 Thesaurus Functions
                   1304: 
                   1305: =over 4
                   1306: 
                   1307: =item * initialize_keywords
1.46      matthew  1308: 
                   1309: Initializes the package variable %Keywords if it is empty.  Uses the
                   1310: package variable $thesaurus_db_file.
                   1311: 
                   1312: =cut
                   1313: 
                   1314: ###################################################
                   1315: 
                   1316: sub initialize_keywords {
                   1317:     return 1 if (scalar keys(%Keywords));
                   1318:     # If we are here, %Keywords is empty, so fill it up
                   1319:     #   Make sure the file we need exists...
                   1320:     if (! -e $thesaurus_db_file) {
                   1321:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   1322:                                  " failed because it does not exist");
                   1323:         return 0;
                   1324:     }
                   1325:     #   Set up the hash as a database
                   1326:     my %thesaurus_db;
                   1327:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1328:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1329:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   1330:                                  $thesaurus_db_file);
                   1331:         return 0;
                   1332:     } 
                   1333:     #  Get the average number of appearances of a word.
                   1334:     my $avecount = $thesaurus_db{'average.count'};
                   1335:     #  Put keywords (those that appear > average) into %Keywords
                   1336:     while (my ($word,$data)=each (%thesaurus_db)) {
                   1337:         my ($count,undef) = split /:/,$data;
                   1338:         $Keywords{$word}++ if ($count > $avecount);
                   1339:     }
                   1340:     untie %thesaurus_db;
                   1341:     # Remove special values from %Keywords.
                   1342:     foreach ('total.count','average.count') {
                   1343:         delete($Keywords{$_}) if (exists($Keywords{$_}));
                   1344:     }
                   1345:     return 1;
                   1346: }
                   1347: 
                   1348: ###################################################
                   1349: 
                   1350: =pod
                   1351: 
1.112     bowersj2 1352: =item * keyword($word)
1.46      matthew  1353: 
                   1354: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   1355: than the average number of times in the thesaurus database.  Calls 
                   1356: &initialize_keywords
                   1357: 
                   1358: =cut
                   1359: 
                   1360: ###################################################
1.20      www      1361: 
                   1362: sub keyword {
1.46      matthew  1363:     return if (!&initialize_keywords());
                   1364:     my $word=lc(shift());
                   1365:     $word=~s/\W//g;
                   1366:     return exists($Keywords{$word});
1.20      www      1367: }
1.46      matthew  1368: 
                   1369: ###############################################################
                   1370: 
                   1371: =pod 
1.20      www      1372: 
1.112     bowersj2 1373: =item * get_related_words
1.46      matthew  1374: 
1.160     matthew  1375: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  1376: an array of words.  If the keyword is not in the thesaurus, an empty array
                   1377: will be returned.  The order of the words returned is determined by the
                   1378: database which holds them.
                   1379: 
                   1380: Uses global $thesaurus_db_file.
                   1381: 
                   1382: =cut
                   1383: 
                   1384: ###############################################################
                   1385: sub get_related_words {
                   1386:     my $keyword = shift;
                   1387:     my %thesaurus_db;
                   1388:     if (! -e $thesaurus_db_file) {
                   1389:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   1390:                                  "failed because the file does not exist");
                   1391:         return ();
                   1392:     }
                   1393:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1394:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1395:         return ();
                   1396:     } 
                   1397:     my @Words=();
                   1398:     if (exists($thesaurus_db{$keyword})) {
                   1399:         $_ = $thesaurus_db{$keyword};
                   1400:         (undef,@Words) = split/:/;  # The first element is the number of times
                   1401:                                     # the word appears.  We do not need it now.
                   1402:         for (my $i=0;$i<=$#Words;$i++) {
                   1403:             ($Words[$i],undef)= split/\,/,$Words[$i];
1.20      www      1404:         }
                   1405:     }
1.46      matthew  1406:     untie %thesaurus_db;
                   1407:     return @Words;
1.14      harris41 1408: }
1.46      matthew  1409: 
1.112     bowersj2 1410: =pod
                   1411: 
                   1412: =back
                   1413: 
                   1414: =cut
1.61      www      1415: 
                   1416: # -------------------------------------------------------------- Plaintext name
1.81      albertel 1417: =pod
                   1418: 
1.112     bowersj2 1419: =head1 User Name Functions
                   1420: 
                   1421: =over 4
                   1422: 
                   1423: =item * plainname($uname,$udom)
1.81      albertel 1424: 
1.112     bowersj2 1425: Takes a users logon name and returns it as a string in
                   1426: "first middle last generation" form
1.81      albertel 1427: 
                   1428: =cut
1.61      www      1429: 
1.81      albertel 1430: ###############################################################
1.61      www      1431: sub plainname {
                   1432:     my ($uname,$udom)=@_;
                   1433:     my %names=&Apache::lonnet::get('environment',
                   1434:                     ['firstname','middlename','lastname','generation'],
                   1435: 					 $udom,$uname);
1.62      www      1436:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1.61      www      1437: 	$names{'lastname'}.' '.$names{'generation'};
1.62      www      1438:     $name=~s/\s+$//;
                   1439:     $name=~s/\s+/ /g;
                   1440:     return $name;
1.61      www      1441: }
1.66      www      1442: 
                   1443: # -------------------------------------------------------------------- Nickname
1.81      albertel 1444: =pod
                   1445: 
1.112     bowersj2 1446: =item * nickname($uname,$udom)
1.81      albertel 1447: 
                   1448: Gets a users name and returns it as a string as
                   1449: 
                   1450: "&quot;nickname&quot;"
1.66      www      1451: 
1.81      albertel 1452: if the user has a nickname or
                   1453: 
                   1454: "first middle last generation"
                   1455: 
                   1456: if the user does not
                   1457: 
                   1458: =cut
1.66      www      1459: 
                   1460: sub nickname {
                   1461:     my ($uname,$udom)=@_;
                   1462:     my %names=&Apache::lonnet::get('environment',
                   1463:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1.68      albertel 1464:     my $name=$names{'nickname'};
1.66      www      1465:     if ($name) {
                   1466:        $name='&quot;'.$name.'&quot;'; 
                   1467:     } else {
                   1468:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   1469: 	     $names{'lastname'}.' '.$names{'generation'};
                   1470:        $name=~s/\s+$//;
                   1471:        $name=~s/\s+/ /g;
                   1472:     }
                   1473:     return $name;
                   1474: }
                   1475: 
1.61      www      1476: 
                   1477: # ------------------------------------------------------------------ Screenname
1.81      albertel 1478: 
                   1479: =pod
                   1480: 
1.112     bowersj2 1481: =item * screenname($uname,$udom)
1.81      albertel 1482: 
                   1483: Gets a users screenname and returns it as a string
                   1484: 
                   1485: =cut
1.61      www      1486: 
                   1487: sub screenname {
                   1488:     my ($uname,$udom)=@_;
                   1489:     my %names=
                   1490:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 1491:     return $names{'screenname'};
1.62      www      1492: }
                   1493: 
                   1494: # ------------------------------------------------------------- Message Wrapper
                   1495: 
                   1496: sub messagewrapper {
                   1497:     my ($link,$un,$do)=@_;
                   1498:     return 
                   1499: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1.74      www      1500: }
                   1501: # --------------------------------------------------------------- Notes Wrapper
                   1502: 
                   1503: sub noteswrapper {
                   1504:     my ($link,$un,$do)=@_;
                   1505:     return 
                   1506: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      1507: }
                   1508: # ------------------------------------------------------------- Aboutme Wrapper
                   1509: 
                   1510: sub aboutmewrapper {
1.69      matthew  1511:     my ($link,$username,$domain)=@_;
                   1512:     return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1.62      www      1513: }
                   1514: 
                   1515: # ------------------------------------------------------------ Syllabus Wrapper
                   1516: 
                   1517: 
                   1518: sub syllabuswrapper {
1.109     matthew  1519:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   1520:     if ($fontcolor) { 
                   1521:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   1522:     }
                   1523:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1.61      www      1524: }
1.14      harris41 1525: 
1.112     bowersj2 1526: =pod
                   1527: 
                   1528: =back
                   1529: 
                   1530: =head1 Access .tab File Data
                   1531: 
                   1532: =over 4
                   1533: 
                   1534: =item * languageids() 
                   1535: 
                   1536: returns list of all language ids
                   1537: 
                   1538: =cut
                   1539: 
1.14      harris41 1540: sub languageids {
1.16      harris41 1541:     return sort(keys(%language));
1.14      harris41 1542: }
                   1543: 
1.112     bowersj2 1544: =pod
                   1545: 
                   1546: =item * languagedescription() 
                   1547: 
                   1548: returns description of a specified language id
                   1549: 
                   1550: =cut
                   1551: 
1.14      harris41 1552: sub languagedescription {
1.125     www      1553:     my $code=shift;
                   1554:     return  ($supported_language{$code}?'* ':'').
                   1555:             $language{$code}.
1.126     www      1556: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      1557: }
                   1558: 
                   1559: sub plainlanguagedescription {
                   1560:     my $code=shift;
                   1561:     return $language{$code};
                   1562: }
                   1563: 
                   1564: sub supportedlanguagecode {
                   1565:     my $code=shift;
                   1566:     return $supported_language{$code};
1.97      www      1567: }
                   1568: 
1.112     bowersj2 1569: =pod
                   1570: 
                   1571: =item * copyrightids() 
                   1572: 
                   1573: returns list of all copyrights
                   1574: 
                   1575: =cut
                   1576: 
                   1577: sub copyrightids {
                   1578:     return sort(keys(%cprtag));
                   1579: }
                   1580: 
                   1581: =pod
                   1582: 
                   1583: =item * copyrightdescription() 
                   1584: 
                   1585: returns description of a specified copyright id
                   1586: 
                   1587: =cut
                   1588: 
                   1589: sub copyrightdescription {
                   1590:     return $cprtag{shift(@_)};
                   1591: }
                   1592: 
                   1593: =pod
                   1594: 
                   1595: =item * filecategories() 
                   1596: 
                   1597: returns list of all file categories
                   1598: 
                   1599: =cut
                   1600: 
                   1601: sub filecategories {
                   1602:     return sort(keys(%category_extensions));
                   1603: }
                   1604: 
                   1605: =pod
                   1606: 
                   1607: =item * filecategorytypes() 
                   1608: 
                   1609: returns list of file types belonging to a given file
                   1610: category
                   1611: 
                   1612: =cut
                   1613: 
                   1614: sub filecategorytypes {
                   1615:     return @{$category_extensions{lc($_[0])}};
                   1616: }
                   1617: 
                   1618: =pod
                   1619: 
                   1620: =item * fileembstyle() 
                   1621: 
                   1622: returns embedding style for a specified file type
                   1623: 
                   1624: =cut
                   1625: 
                   1626: sub fileembstyle {
                   1627:     return $fe{lc(shift(@_))};
                   1628: }
                   1629: 
                   1630: =pod
                   1631: 
                   1632: =item * filedescription() 
                   1633: 
                   1634: returns description for a specified file type
                   1635: 
                   1636: =cut
                   1637: 
                   1638: sub filedescription {
                   1639:     return $fd{lc(shift(@_))};
                   1640: }
                   1641: 
                   1642: =pod
                   1643: 
                   1644: =item * filedescriptionex() 
                   1645: 
                   1646: returns description for a specified file type with
                   1647: extra formatting
                   1648: 
                   1649: =cut
                   1650: 
                   1651: sub filedescriptionex {
                   1652:     my $ex=shift;
                   1653:     return '.'.$ex.' '.$fd{lc($ex)};
                   1654: }
                   1655: 
                   1656: # End of .tab access
                   1657: =pod
                   1658: 
                   1659: =back
                   1660: 
                   1661: =cut
                   1662: 
                   1663: # ------------------------------------------------------------------ File Types
                   1664: sub fileextensions {
                   1665:     return sort(keys(%fe));
                   1666: }
                   1667: 
1.97      www      1668: # ----------------------------------------------------------- Display Languages
                   1669: # returns a hash with all desired display languages
                   1670: #
                   1671: 
                   1672: sub display_languages {
                   1673:     my %languages=();
1.118     www      1674:     foreach (&preferred_languages()) {
                   1675: 	$languages{$_}=1;
1.97      www      1676:     }
                   1677:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
                   1678:     if ($ENV{'form.displaylanguage'}) {
                   1679: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
                   1680: 	    $languages{$_}=1;
                   1681:         }
                   1682:     }
                   1683:     return %languages;
1.14      harris41 1684: }
                   1685: 
1.117     www      1686: sub preferred_languages {
                   1687:     my @languages=();
                   1688:     if ($ENV{'environment.languages'}) {
                   1689: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
                   1690:     }
                   1691:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
                   1692: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
                   1693: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1.118     www      1694:     }
1.162     www      1695:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
                   1696:     if ($browser) {
                   1697: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
                   1698:     }
1.118     www      1699:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
                   1700: 	@languages=(@languages,
                   1701: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
                   1702:     }
                   1703:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
                   1704: 	@languages=(@languages,
                   1705: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
                   1706:     }
                   1707:     if ($Apache::lonnet::domain_lang_def{
                   1708: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
                   1709: 	@languages=(@languages,
                   1710: 		$Apache::lonnet::domain_lang_def{
                   1711:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
                   1712:     }
                   1713: # turn "en-ca" into "en-ca,en"
                   1714:     my @genlanguages;
                   1715:     foreach (@languages) {
                   1716: 	unless ($_=~/\w/) { next; }
                   1717: 	push (@genlanguages,$_);
                   1718: 	if ($_=~/(\-|\_)/) {
                   1719: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
                   1720: 	}
                   1721:     }
                   1722:     return @genlanguages;
1.117     www      1723: }
                   1724: 
1.112     bowersj2 1725: ###############################################################
                   1726: ##               Student Answer Attempts                     ##
                   1727: ###############################################################
                   1728: 
                   1729: =pod
                   1730: 
                   1731: =head1 Alternate Problem Views
                   1732: 
                   1733: =over 4
                   1734: 
                   1735: =item * get_previous_attempt($symb, $username, $domain, $course,
                   1736:     $getattempt, $regexp, $gradesub)
                   1737: 
                   1738: Return string with previous attempt on problem. Arguments:
                   1739: 
                   1740: =over 4
                   1741: 
                   1742: =item * $symb: Problem, including path
                   1743: 
                   1744: =item * $username: username of the desired student
                   1745: 
                   1746: =item * $domain: domain of the desired student
1.14      harris41 1747: 
1.112     bowersj2 1748: =item * $course: Course ID
1.14      harris41 1749: 
1.112     bowersj2 1750: =item * $getattempt: Leave blank for all attempts, otherwise put
                   1751:     something
1.14      harris41 1752: 
1.112     bowersj2 1753: =item * $regexp: if string matches this regexp, the string will be
                   1754:     sent to $gradesub
1.14      harris41 1755: 
1.112     bowersj2 1756: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 1757: 
1.112     bowersj2 1758: =back
1.14      harris41 1759: 
1.112     bowersj2 1760: The output string is a table containing all desired attempts, if any.
1.16      harris41 1761: 
1.112     bowersj2 1762: =cut
1.1       albertel 1763: 
                   1764: sub get_previous_attempt {
1.43      ng       1765:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 1766:   my $prevattempts='';
1.43      ng       1767:   no strict 'refs';
1.1       albertel 1768:   if ($symb) {
1.3       albertel 1769:     my (%returnhash)=
                   1770:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 1771:     if ($returnhash{'version'}) {
                   1772:       my %lasthash=();
                   1773:       my $version;
                   1774:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19      harris41 1775:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1       albertel 1776: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
1.19      harris41 1777:         }
1.1       albertel 1778:       }
1.43      ng       1779:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       1780:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16      harris41 1781:       foreach (sort(keys %lasthash)) {
1.31      albertel 1782: 	my ($ign,@parts) = split(/\./,$_);
1.41      ng       1783: 	if ($#parts > 0) {
1.31      albertel 1784: 	  my $data=$parts[-1];
                   1785: 	  pop(@parts);
1.40      ng       1786: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 1787: 	} else {
1.41      ng       1788: 	  if ($#parts == 0) {
                   1789: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   1790: 	  } else {
                   1791: 	    $prevattempts.='<th>'.$ign.'</th>';
                   1792: 	  }
1.31      albertel 1793: 	}
1.16      harris41 1794:       }
1.40      ng       1795:       if ($getattempt eq '') {
                   1796: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   1797: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
                   1798: 	    foreach (sort(keys %lasthash)) {
                   1799: 	       my $value;
                   1800: 	       if ($_ =~ /timestamp/) {
                   1801: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
                   1802: 	       } else {
                   1803: 		  $value=$returnhash{$version.':'.$_};
                   1804: 	       }
1.142     albertel 1805: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
1.40      ng       1806: 	    }
                   1807: 	 }
1.1       albertel 1808:       }
1.40      ng       1809:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16      harris41 1810:       foreach (sort(keys %lasthash)) {
1.5       albertel 1811: 	my $value;
                   1812: 	if ($_ =~ /timestamp/) {
                   1813: 	  $value=scalar(localtime($lasthash{$_}));
                   1814: 	} else {
                   1815: 	  $value=$lasthash{$_};
                   1816: 	}
1.142     albertel 1817: 	$value=&Apache::lonnet::unescape($value);
1.49      ng       1818: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       1819: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 1820:       }
1.40      ng       1821:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 1822:     } else {
                   1823:       $prevattempts='Nothing submitted - no attempts.';
                   1824:     }
                   1825:   } else {
                   1826:     $prevattempts='No data.';
                   1827:   }
1.10      albertel 1828: }
                   1829: 
1.107     albertel 1830: sub relative_to_absolute {
                   1831:     my ($url,$output)=@_;
                   1832:     my $parser=HTML::TokeParser->new(\$output);
                   1833:     my $token;
                   1834:     my $thisdir=$url;
                   1835:     my @rlinks=();
                   1836:     while ($token=$parser->get_token) {
                   1837: 	if ($token->[0] eq 'S') {
                   1838: 	    if ($token->[1] eq 'a') {
                   1839: 		if ($token->[2]->{'href'}) {
                   1840: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   1841: 		}
                   1842: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   1843: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   1844: 	    } elsif ($token->[1] eq 'base') {
                   1845: 		$thisdir=$token->[2]->{'href'};
                   1846: 	    }
                   1847: 	}
                   1848:     }
                   1849:     $thisdir=~s-/[^/]*$--;
                   1850:     foreach (@rlinks) {
                   1851: 	unless (($_=~/^http:\/\//i) ||
                   1852: 		($_=~/^\//) ||
                   1853: 		($_=~/^javascript:/i) ||
                   1854: 		($_=~/^mailto:/i) ||
                   1855: 		($_=~/^\#/)) {
                   1856: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
                   1857: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
                   1858: 	}
                   1859:     }
                   1860: # -------------------------------------------------- Deal with Applet codebases
                   1861:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   1862:     return $output;
                   1863: }
                   1864: 
1.112     bowersj2 1865: =pod
                   1866: 
                   1867: =item * get_student_view
                   1868: 
                   1869: show a snapshot of what student was looking at
                   1870: 
                   1871: =cut
                   1872: 
1.10      albertel 1873: sub get_student_view {
1.64      sakharuk 1874:   my ($symb,$username,$domain,$courseid,$target) = @_;
1.114     www      1875:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.10      albertel 1876:   my (%old,%moreenv);
                   1877:   my @elements=('symb','courseid','domain','username');
                   1878:   foreach my $element (@elements) {
                   1879:     $old{$element}=$ENV{'form.grade_'.$element};
                   1880:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1881:   }
1.64      sakharuk 1882:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1.11      albertel 1883:   &Apache::lonnet::appenv(%moreenv);
1.107     albertel 1884:   $feedurl=&Apache::lonnet::clutter($feedurl);
                   1885:   my $userview=&Apache::lonnet::ssi_body($feedurl);
1.11      albertel 1886:   &Apache::lonnet::delenv('form.grade_');
                   1887:   foreach my $element (@elements) {
                   1888:     $ENV{'form.grade_'.$element}=$old{$element};
                   1889:   }
                   1890:   $userview=~s/\<body[^\>]*\>//gi;
                   1891:   $userview=~s/\<\/body\>//gi;
                   1892:   $userview=~s/\<html\>//gi;
                   1893:   $userview=~s/\<\/html\>//gi;
                   1894:   $userview=~s/\<head\>//gi;
                   1895:   $userview=~s/\<\/head\>//gi;
                   1896:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 1897:   $userview=&relative_to_absolute($feedurl,$userview);
1.11      albertel 1898:   return $userview;
                   1899: }
                   1900: 
1.112     bowersj2 1901: =pod
                   1902: 
                   1903: =item * get_student_answers() 
                   1904: 
                   1905: show a snapshot of how student was answering problem
                   1906: 
                   1907: =cut
                   1908: 
1.11      albertel 1909: sub get_student_answers {
1.100     sakharuk 1910:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      1911:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.11      albertel 1912:   my (%old,%moreenv);
                   1913:   my @elements=('symb','courseid','domain','username');
                   1914:   foreach my $element (@elements) {
                   1915:     $old{$element}=$ENV{'form.grade_'.$element};
                   1916:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1917:   }
                   1918:   $moreenv{'form.grade_target'}='answer';
1.10      albertel 1919:   &Apache::lonnet::appenv(%moreenv);
1.100     sakharuk 1920:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
1.10      albertel 1921:   &Apache::lonnet::delenv('form.grade_');
                   1922:   foreach my $element (@elements) {
                   1923:     $ENV{'form.grade_'.$element}=$old{$element};
                   1924:   }
                   1925:   return $userview;
1.1       albertel 1926: }
1.116     albertel 1927: 
                   1928: =pod
                   1929: 
                   1930: =item * &submlink()
                   1931: 
                   1932: Inputs: $text $uname $udom $symb
                   1933: 
                   1934: Returns: A link to grades.pm such as to see the SUBM view of a student
                   1935: 
                   1936: =cut
                   1937: 
                   1938: ###############################################
                   1939: sub submlink {
                   1940:     my ($text,$uname,$udom,$symb)=@_;
                   1941:     if (!($uname && $udom)) {
                   1942: 	(my $cursymb, my $courseid,$udom,$uname)=
                   1943: 	    &Apache::lonxml::whichuser($symb);
                   1944: 	if (!$symb) { $symb=$cursymb; }
                   1945:     }
                   1946:     if (!$symb) { $symb=&symbread(); }
                   1947:     return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
                   1948: 	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
                   1949: }
                   1950: ##############################################
1.37      matthew  1951: 
1.112     bowersj2 1952: =pod
                   1953: 
                   1954: =back
                   1955: 
                   1956: =cut
                   1957: 
1.37      matthew  1958: ###############################################
1.51      www      1959: 
                   1960: 
                   1961: sub timehash {
                   1962:     my @ltime=localtime(shift);
                   1963:     return ( 'seconds' => $ltime[0],
                   1964:              'minutes' => $ltime[1],
                   1965:              'hours'   => $ltime[2],
                   1966:              'day'     => $ltime[3],
                   1967:              'month'   => $ltime[4]+1,
                   1968:              'year'    => $ltime[5]+1900,
                   1969:              'weekday' => $ltime[6],
                   1970:              'dayyear' => $ltime[7]+1,
                   1971:              'dlsav'   => $ltime[8] );
                   1972: }
                   1973: 
                   1974: sub maketime {
                   1975:     my %th=@_;
                   1976:     return POSIX::mktime(
                   1977:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
                   1978:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1.70      www      1979: }
                   1980: 
                   1981: #########################################
1.51      www      1982: 
                   1983: sub findallcourses {
                   1984:     my %courses=();
                   1985:     my $now=time;
                   1986:     foreach (keys %ENV) {
                   1987: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
                   1988: 	    my ($starttime,$endtime)=$ENV{$_};
                   1989:             my $active=1;
                   1990:             if ($starttime) {
                   1991: 		if ($now<$starttime) { $active=0; }
                   1992:             }
                   1993:             if ($endtime) {
                   1994:                 if ($now>$endtime) { $active=0; }
                   1995:             }
                   1996:             if ($active) { $courses{$1.'_'.$2}=1; }
                   1997:         }
                   1998:     }
                   1999:     return keys %courses;
                   2000: }
1.37      matthew  2001: 
1.54      www      2002: ###############################################
1.60      matthew  2003: ###############################################
                   2004: 
                   2005: =pod
                   2006: 
1.112     bowersj2 2007: =head1 Domain Template Functions
                   2008: 
                   2009: =over 4
                   2010: 
                   2011: =item * &determinedomain()
1.60      matthew  2012: 
                   2013: Inputs: $domain (usually will be undef)
                   2014: 
1.63      www      2015: Returns: Determines which domain should be used for designs
1.60      matthew  2016: 
                   2017: =cut
1.54      www      2018: 
1.60      matthew  2019: ###############################################
1.63      www      2020: sub determinedomain {
                   2021:     my $domain=shift;
                   2022:    if (! $domain) {
1.60      matthew  2023:         # Determine domain if we have not been given one
                   2024:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   2025:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
                   2026:         if ($ENV{'request.role.domain'}) { 
                   2027:             $domain=$ENV{'request.role.domain'}; 
                   2028:         }
                   2029:     }
1.63      www      2030:     return $domain;
                   2031: }
                   2032: ###############################################
                   2033: =pod
                   2034: 
1.112     bowersj2 2035: =item * &domainlogo()
1.63      www      2036: 
                   2037: Inputs: $domain (usually will be undef)
                   2038: 
                   2039: Returns: A link to a domain logo, if the domain logo exists.
                   2040: If the domain logo does not exist, a description of the domain.
                   2041: 
                   2042: =cut
1.112     bowersj2 2043: 
1.63      www      2044: ###############################################
                   2045: sub domainlogo {
                   2046:     my $domain = &determinedomain(shift);    
                   2047:      # See if there is a logo
1.59      www      2048:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.83      albertel 2049: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2050: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
                   2051:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
1.150     matthew  2052: 	    '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
1.60      matthew  2053:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   2054:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      2055:     } else {
1.60      matthew  2056:         return '';
1.59      www      2057:     }
                   2058: }
1.63      www      2059: ##############################################
                   2060: 
                   2061: =pod
                   2062: 
1.112     bowersj2 2063: =item * &designparm()
1.63      www      2064: 
                   2065: Inputs: $which parameter; $domain (usually will be undef)
                   2066: 
                   2067: Returns: value of designparamter $which
                   2068: 
                   2069: =cut
1.112     bowersj2 2070: 
1.63      www      2071: ##############################################
                   2072: sub designparm {
                   2073:     my ($which,$domain)=@_;
1.110     www      2074:     if ($ENV{'browser.blackwhite'} eq 'on') {
                   2075: 	if ($which=~/\.(font|alink|vlink|link)$/) {
                   2076: 	    return '#000000';
                   2077: 	}
                   2078: 	if ($which=~/\.(pgbg|sidebg)$/) {
                   2079: 	    return '#FFFFFF';
                   2080: 	}
                   2081: 	if ($which=~/\.tabbg$/) {
                   2082: 	    return '#CCCCCC';
                   2083: 	}
                   2084:     }
1.96      www      2085:     if ($ENV{'environment.color.'.$which}) {
                   2086: 	return $ENV{'environment.color.'.$which};
                   2087:     }
1.63      www      2088:     $domain=&determinedomain($domain);
                   2089:     if ($designhash{$domain.'.'.$which}) {
                   2090: 	return $designhash{$domain.'.'.$which};
                   2091:     } else {
                   2092:         return $designhash{'default.'.$which};
                   2093:     }
                   2094: }
1.59      www      2095: 
1.60      matthew  2096: ###############################################
                   2097: ###############################################
                   2098: 
                   2099: =pod
                   2100: 
1.112     bowersj2 2101: =back
                   2102: 
                   2103: =head1 HTTP Helpers
                   2104: 
                   2105: =over 4
                   2106: 
                   2107: =item * &bodytag()
1.60      matthew  2108: 
                   2109: Returns a uniform header for LON-CAPA web pages.
                   2110: 
                   2111: Inputs: 
                   2112: 
1.112     bowersj2 2113: =over 4
                   2114: 
                   2115: =item * $title, A title to be displayed on the page.
                   2116: 
                   2117: =item * $function, the current role (can be undef).
                   2118: 
                   2119: =item * $addentries, extra parameters for the <body> tag.
                   2120: 
                   2121: =item * $bodyonly, if defined, only return the <body> tag.
                   2122: 
                   2123: =item * $domain, if defined, force a given domain.
                   2124: 
                   2125: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      2126:             text interface only)
1.60      matthew  2127: 
1.112     bowersj2 2128: =back
                   2129: 
1.60      matthew  2130: Returns: A uniform header for LON-CAPA web pages.  
                   2131: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   2132: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   2133: other decorations will be returned.
                   2134: 
                   2135: =cut
                   2136: 
1.54      www      2137: sub bodytag {
1.86      www      2138:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
1.117     www      2139:     $title=&mt($title);
1.55      www      2140:     unless ($function) {
                   2141: 	$function='student';
                   2142:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   2143: 	    $function='coordinator';
                   2144:         }
                   2145: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   2146:             $function='admin';
                   2147:         }
                   2148:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   2149:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   2150:             $function='author';
                   2151:         }
                   2152:     }
1.63      www      2153:     my $img=&designparm($function.'.img',$domain);
                   2154:     my $pgbg=&designparm($function.'.pgbg',$domain);
                   2155:     my $tabbg=&designparm($function.'.tabbg',$domain);
                   2156:     my $font=&designparm($function.'.font',$domain);
                   2157:     my $link=&designparm($function.'.link',$domain);
                   2158:     my $alink=&designparm($function.'.alink',$domain);
                   2159:     my $vlink=&designparm($function.'.vlink',$domain);
                   2160:     my $sidebg=&designparm($function.'.sidebg',$domain);
1.110     www      2161: # Accessibility font enhance
                   2162:     unless ($addentries) { $addentries=''; }
1.146     www      2163:     my $addstyle='';
1.110     www      2164:     if ($ENV{'browser.fontenhance'} eq 'on') {
1.146     www      2165: 	$addstyle=' font-size: x-large;';
1.110     www      2166:     }
1.63      www      2167:  # role and realm
1.55      www      2168:     my ($role,$realm)
                   2169:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
                   2170: # realm
1.54      www      2171:     if ($ENV{'request.course.id'}) {
1.55      www      2172: 	$realm=
                   2173:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54      www      2174:     }
1.55      www      2175:     unless ($realm) { $realm='&nbsp;'; }
                   2176: # Set messages
1.60      matthew  2177:     my $messages=&domainlogo($domain);
1.101     www      2178: # Port for miniserver
1.83      albertel 2179:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2180:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.101     www      2181: # construct main body tag
1.60      matthew  2182:     my $bodytag = <<END;
1.146     www      2183: <style>
1.147     www      2184: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
1.146     www      2185: a:focus { color: red; background: yellow } 
                   2186: </style>
1.54      www      2187: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
1.151     www      2188: style="margin-top: 0px;$addstyle" $addentries>
1.60      matthew  2189: END
1.94      www      2190:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
1.150     matthew  2191:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
1.60      matthew  2192:     if ($bodyonly) {
                   2193:         return $bodytag;
1.79      www      2194:     } elsif ($ENV{'browser.interface'} eq 'textual') {
1.95      www      2195: # Accessibility
1.93      www      2196:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2197:                                                       $forcereg).
                   2198:                '<h1>LON-CAPA: '.$title.'</h1>';
                   2199:     } elsif ($ENV{'environment.remote'} eq 'off') {
1.95      www      2200: # No Remote
                   2201:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2202:                                                       $forcereg).
1.151     www      2203:       '<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      2204: '</b></font></td></tr></table>';
1.94      www      2205:     }
1.95      www      2206: 
1.93      www      2207: #
1.95      www      2208: # Top frame rendering, Remote is up
1.93      www      2209: #
1.94      www      2210:     return(<<ENDBODY);
1.60      matthew  2211: $bodytag
1.55      www      2212: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95      www      2213: <tr><td bgcolor="$sidebg">
1.94      www      2214: $upperleft</td>
1.95      www      2215: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
1.55      www      2216: </tr>
1.54      www      2217: <tr>
1.55      www      2218: <td rowspan="3" bgcolor="$tabbg">
1.146     www      2219: &nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
                   2220: <td bgcolor="$tabbg" align="right">
                   2221: <font size="2" face="Arial, Helvetica, sans-serif">
1.54      www      2222:     $ENV{'environment.firstname'}
                   2223:     $ENV{'environment.middlename'}
                   2224:     $ENV{'environment.lastname'}
                   2225:     $ENV{'environment.generation'}
1.55      www      2226:     </font>&nbsp;
1.54      www      2227: </td>
                   2228: </tr>
                   2229: <tr><td bgcolor="$tabbg" align="right">
1.146     www      2230: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
1.54      www      2231: </td></tr>
1.55      www      2232: <tr>
1.148     www      2233: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
1.54      www      2234: </table><br>
                   2235: ENDBODY
                   2236: }
1.99      www      2237: 
                   2238: ###############################################
                   2239: 
                   2240: sub get_posted_cgi {
                   2241:     my $r=shift;
                   2242: 
                   2243:     my $buffer;
                   2244:     
                   2245:     $r->read($buffer,$r->header_in('Content-length'),0);
                   2246:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
                   2247: 	my @pairs=split(/&/,$buffer);
                   2248: 	my $pair;
                   2249: 	foreach $pair (@pairs) {
                   2250: 	    my ($name,$value) = split(/=/,$pair);
                   2251: 	    $value =~ tr/+/ /;
                   2252: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2253: 	    $name  =~ tr/+/ /;
                   2254: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2255: 	    &add_to_env("form.$name",$value);
                   2256: 	}
                   2257:     } else {
                   2258: 	my $contentsep=$1;
                   2259: 	my @lines = split (/\n/,$buffer);
                   2260: 	my $name='';
                   2261: 	my $value='';
                   2262: 	my $fname='';
                   2263: 	my $fmime='';
                   2264: 	my $i;
                   2265: 	for ($i=0;$i<=$#lines;$i++) {
                   2266: 	    if ($lines[$i]=~/^$contentsep/) {
                   2267: 		if ($name) {
                   2268: 		    chomp($value);
                   2269: 		    if ($fname) {
                   2270: 			$ENV{"form.$name.filename"}=$fname;
                   2271: 			$ENV{"form.$name.mimetype"}=$fmime;
                   2272: 		    } else {
                   2273: 			$value=~s/\s+$//s;
                   2274: 		    }
                   2275: 		    &add_to_env("form.$name",$value);
                   2276: 		}
                   2277: 		if ($i<$#lines) {
                   2278: 		    $i++;
                   2279: 		    $lines[$i]=~
                   2280: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
                   2281: 		    $name=$1;
                   2282: 		    $value='';
                   2283: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
                   2284: 			$fname=$1;
                   2285: 			if 
                   2286:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
                   2287: 				$fmime=$1;
                   2288: 				$i++;
                   2289: 			    } else {
                   2290: 				$fmime='';
                   2291: 			    }
                   2292: 		    } else {
                   2293: 			$fname='';
                   2294: 			$fmime='';
                   2295: 		    }
                   2296: 		    $i++;
                   2297: 		}
                   2298: 	    } else {
                   2299: 		$value.=$lines[$i]."\n";
                   2300: 	    }
                   2301: 	}
                   2302:     }
                   2303:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
                   2304:     $r->method_number(M_GET);
                   2305:     $r->method('GET');
                   2306:     $r->headers_in->unset('Content-length');
                   2307: }
                   2308: 
1.112     bowersj2 2309: =pod
                   2310: 
                   2311: =item * get_unprocessed_cgi($query,$possible_names)
                   2312: 
                   2313: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   2314: $query.  The parameters listed in $possible_names (an array reference),
                   2315: will be set in $ENV{'form.name'} if they do not already exist.
                   2316: 
                   2317: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   2318: $possible_names is an ref to an array of form element names.  As an example:
                   2319: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2320: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
                   2321: 
                   2322: =cut
1.1       albertel 2323: 
1.6       albertel 2324: sub get_unprocessed_cgi {
1.25      albertel 2325:   my ($query,$possible_names)= @_;
1.26      matthew  2326:   # $Apache::lonxml::debug=1;
1.16      harris41 2327:   foreach (split(/&/,$query)) {
1.6       albertel 2328:     my ($name, $value) = split(/=/,$_);
1.25      albertel 2329:     $name = &Apache::lonnet::unescape($name);
                   2330:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   2331:       $value =~ tr/+/ /;
                   2332:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2333:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 2334:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 2335:     }
1.16      harris41 2336:   }
1.6       albertel 2337: }
                   2338: 
1.112     bowersj2 2339: =pod
                   2340: 
                   2341: =item * cacheheader() 
                   2342: 
                   2343: returns cache-controlling header code
                   2344: 
                   2345: =cut
                   2346: 
1.7       albertel 2347: sub cacheheader {
1.23      www      2348:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.8       albertel 2349:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.7       albertel 2350:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
                   2351:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   2352:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
                   2353:   return $output;
                   2354: }
                   2355: 
1.112     bowersj2 2356: =pod
                   2357: 
                   2358: =item * no_cache($r) 
                   2359: 
                   2360: specifies header code to not have cache
                   2361: 
                   2362: =cut
                   2363: 
1.9       albertel 2364: sub no_cache {
                   2365:   my ($r) = @_;
1.23      www      2366:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.24      albertel 2367:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.9       albertel 2368:   $r->no_cache(1);
                   2369:   $r->header_out("Pragma" => "no-cache");
1.24      albertel 2370:   #$r->header_out("Expires" => $date);
1.123     www      2371: }
                   2372: 
                   2373: sub content_type {
                   2374:   my ($r,$type,$charset) = @_;
                   2375:   unless ($charset) {
                   2376:       $charset=&Apache::lonlocal::current_encoding;
                   2377:   }
                   2378:   $r->content_type($type.($charset?'; charset='.$charset:''));
1.9       albertel 2379: }
1.25      albertel 2380: 
1.112     bowersj2 2381: =pod
                   2382: 
                   2383: =item * add_to_env($name,$value) 
                   2384: 
                   2385: adds $name to the %ENV hash with value
                   2386: $value, if $name already exists, the entry is converted to an array
                   2387: reference and $value is added to the array.
                   2388: 
                   2389: =cut
                   2390: 
1.25      albertel 2391: sub add_to_env {
                   2392:   my ($name,$value)=@_;
1.28      albertel 2393:   if (defined($ENV{$name})) {
1.27      albertel 2394:     if (ref($ENV{$name})) {
1.25      albertel 2395:       #already have multiple values
                   2396:       push(@{ $ENV{$name} },$value);
                   2397:     } else {
                   2398:       #first time seeing multiple values, convert hash entry to an arrayref
                   2399:       my $first=$ENV{$name};
                   2400:       undef($ENV{$name});
                   2401:       push(@{ $ENV{$name} },$first,$value);
                   2402:     }
                   2403:   } else {
                   2404:     $ENV{$name}=$value;
                   2405:   }
1.31      albertel 2406: }
1.149     albertel 2407: 
                   2408: =pod
                   2409: 
                   2410: =item * get_env_multiple($name) 
                   2411: 
                   2412: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
                   2413: values may be defined and end up as an array ref.
                   2414: 
                   2415: returns an array of values
                   2416: 
                   2417: =cut
                   2418: 
                   2419: sub get_env_multiple {
                   2420:     my ($name) = @_;
                   2421:     my @values;
                   2422:     if (defined($ENV{$name})) {
                   2423:         # exists is it an array
                   2424:         if (ref($ENV{$name})) {
                   2425:             @values=@{ $ENV{$name} };
                   2426:         } else {
                   2427:             $values[0]=$ENV{$name};
                   2428:         }
                   2429:     }
                   2430:     return(@values);
                   2431: }
                   2432: 
1.31      albertel 2433: 
1.41      ng       2434: =pod
1.45      matthew  2435: 
                   2436: =back 
1.41      ng       2437: 
1.112     bowersj2 2438: =head1 CSV Upload/Handling functions
1.38      albertel 2439: 
1.41      ng       2440: =over 4
                   2441: 
1.112     bowersj2 2442: =item * upfile_store($r)
1.41      ng       2443: 
                   2444: Store uploaded file, $r should be the HTTP Request object,
                   2445: needs $ENV{'form.upfile'}
                   2446: returns $datatoken to be put into hidden field
                   2447: 
                   2448: =cut
1.31      albertel 2449: 
                   2450: sub upfile_store {
                   2451:     my $r=shift;
                   2452:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   2453:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   2454:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   2455:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   2456: 
                   2457:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   2458: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   2459:     {
1.158     raeburn  2460:         my $datafile = $r->dir_config('lonDaemons').
                   2461:                            '/tmp/'.$datatoken.'.tmp';
                   2462:         if ( open(my $fh,">$datafile") ) {
                   2463:             print $fh $ENV{'form.upfile'};
                   2464:             close($fh);
                   2465:         }
1.31      albertel 2466:     }
                   2467:     return $datatoken;
                   2468: }
                   2469: 
1.56      matthew  2470: =pod
                   2471: 
1.112     bowersj2 2472: =item * load_tmp_file($r)
1.41      ng       2473: 
                   2474: Load uploaded file from tmp, $r should be the HTTP Request object,
                   2475: needs $ENV{'form.datatoken'},
                   2476: sets $ENV{'form.upfile'} to the contents of the file
                   2477: 
                   2478: =cut
1.31      albertel 2479: 
                   2480: sub load_tmp_file {
                   2481:     my $r=shift;
                   2482:     my @studentdata=();
                   2483:     {
1.158     raeburn  2484:         my $studentfile = $r->dir_config('lonDaemons').
                   2485:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
                   2486:         if ( open(my $fh,"<$studentfile") ) {
                   2487:             @studentdata=<$fh>;
                   2488:             close($fh);
                   2489:         }
1.31      albertel 2490:     }
                   2491:     $ENV{'form.upfile'}=join('',@studentdata);
                   2492: }
                   2493: 
1.56      matthew  2494: =pod
                   2495: 
1.112     bowersj2 2496: =item * upfile_record_sep()
1.41      ng       2497: 
                   2498: Separate uploaded file into records
                   2499: returns array of records,
                   2500: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   2501: 
                   2502: =cut
1.31      albertel 2503: 
                   2504: sub upfile_record_sep {
                   2505:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2506:     } else {
                   2507: 	return split(/\n/,$ENV{'form.upfile'});
                   2508:     }
                   2509: }
                   2510: 
1.56      matthew  2511: =pod
                   2512: 
1.112     bowersj2 2513: =item * record_sep($record)
1.41      ng       2514: 
                   2515: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   2516: 
                   2517: =cut
                   2518: 
1.31      albertel 2519: sub record_sep {
                   2520:     my $record=shift;
                   2521:     my %components=();
                   2522:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2523:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   2524:         my $i=0;
                   2525:         foreach (split(/\s+/,$record)) {
                   2526:             my $field=$_;
                   2527:             $field=~s/^(\"|\')//;
                   2528:             $field=~s/(\"|\')$//;
                   2529:             $components{$i}=$field;
                   2530:             $i++;
                   2531:         }
                   2532:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   2533:         my $i=0;
                   2534:         foreach (split(/\t+/,$record)) {
                   2535:             my $field=$_;
                   2536:             $field=~s/^(\"|\')//;
                   2537:             $field=~s/(\"|\')$//;
                   2538:             $components{$i}=$field;
                   2539:             $i++;
                   2540:         }
                   2541:     } else {
                   2542:         my @allfields=split(/\,/,$record);
                   2543:         my $i=0;
                   2544:         my $j;
                   2545:         for ($j=0;$j<=$#allfields;$j++) {
                   2546:             my $field=$allfields[$j];
                   2547:             if ($field=~/^\s*(\"|\')/) {
                   2548: 		my $delimiter=$1;
                   2549:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   2550: 		    $j++;
                   2551: 		    $field.=','.$allfields[$j];
                   2552: 		}
                   2553:                 $field=~s/^\s*$delimiter//;
                   2554:                 $field=~s/$delimiter\s*$//;
                   2555:             }
                   2556:             $components{$i}=$field;
                   2557: 	    $i++;
                   2558:         }
                   2559:     }
                   2560:     return %components;
                   2561: }
                   2562: 
1.144     matthew  2563: ######################################################
                   2564: ######################################################
                   2565: 
1.56      matthew  2566: =pod
                   2567: 
1.112     bowersj2 2568: =item * upfile_select_html()
1.41      ng       2569: 
1.144     matthew  2570: Return HTML code to select a file from the users machine and specify 
                   2571: the file type.
1.41      ng       2572: 
                   2573: =cut
                   2574: 
1.144     matthew  2575: ######################################################
                   2576: ######################################################
1.31      albertel 2577: sub upfile_select_html {
1.144     matthew  2578:     my %Types = (
                   2579:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
                   2580:                  space => &mt('Space separated'),
                   2581:                  tab   => &mt('Tabulator separated'),
                   2582: #                 xml   => &mt('HTML/XML'),
                   2583:                  );
                   2584:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   2585:         '<br />Type: <select name="upfiletype">';
                   2586:     foreach my $type (sort(keys(%Types))) {
                   2587:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   2588:     }
                   2589:     $Str .= "</select>\n";
                   2590:     return $Str;
1.31      albertel 2591: }
                   2592: 
1.144     matthew  2593: ######################################################
                   2594: ######################################################
                   2595: 
1.56      matthew  2596: =pod
                   2597: 
1.112     bowersj2 2598: =item * csv_print_samples($r,$records)
1.41      ng       2599: 
                   2600: Prints a table of sample values from each column uploaded $r is an
                   2601: Apache Request ref, $records is an arrayref from
                   2602: &Apache::loncommon::upfile_record_sep
                   2603: 
                   2604: =cut
                   2605: 
1.144     matthew  2606: ######################################################
                   2607: ######################################################
1.31      albertel 2608: sub csv_print_samples {
                   2609:     my ($r,$records) = @_;
                   2610:     my (%sone,%stwo,%sthree);
                   2611:     %sone=&record_sep($$records[0]);
                   2612:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   2613:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  2614:     #
                   2615:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
                   2616:     foreach (sort({$a <=> $b} keys(%sone))) { 
                   2617:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
1.31      albertel 2618:     $r->print('</tr>');
                   2619:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   2620: 	$r->print('<tr>');
                   2621: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   2622: 	    $r->print('<td>');
                   2623: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   2624: 	    $r->print('</td>');
                   2625: 	}
                   2626: 	$r->print('</tr>');
                   2627:     }
                   2628:     $r->print('</tr></table><br />'."\n");
                   2629: }
                   2630: 
1.144     matthew  2631: ######################################################
                   2632: ######################################################
                   2633: 
1.56      matthew  2634: =pod
                   2635: 
1.112     bowersj2 2636: =item * csv_print_select_table($r,$records,$d)
1.41      ng       2637: 
                   2638: Prints a table to create associations between values and table columns.
1.144     matthew  2639: 
1.41      ng       2640: $r is an Apache Request ref,
                   2641: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   2642: $d is an array of 2 element arrays (internal name, displayed name)
                   2643: 
                   2644: =cut
                   2645: 
1.144     matthew  2646: ######################################################
                   2647: ######################################################
1.31      albertel 2648: sub csv_print_select_table {
                   2649:     my ($r,$records,$d) = @_;
                   2650:     my $i=0;my %sone;
                   2651:     %sone=&record_sep($$records[0]);
1.144     matthew  2652:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   2653: 	     '<table border="2"><tr>'.
                   2654:               '<th>'.&mt('Attribute').'</th>'.
                   2655:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.31      albertel 2656:     foreach (@$d) {
                   2657: 	my ($value,$display)=@{ $_ };
                   2658: 	$r->print('<tr><td>'.$display.'</td>');
                   2659: 
                   2660: 	$r->print('<td><select name=f'.$i.
1.32      matthew  2661: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 2662: 	$r->print('<option value="none"></option>');
                   2663: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   2664: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
                   2665: 	}
                   2666: 	$r->print('</select></td></tr>'."\n");
                   2667: 	$i++;
                   2668:     }
                   2669:     $i--;
                   2670:     return $i;
                   2671: }
1.56      matthew  2672: 
1.144     matthew  2673: ######################################################
                   2674: ######################################################
                   2675: 
1.56      matthew  2676: =pod
1.31      albertel 2677: 
1.112     bowersj2 2678: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       2679: 
                   2680: Prints a table of sample values from the upload and can make associate samples to internal names.
                   2681: 
                   2682: $r is an Apache Request ref,
                   2683: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   2684: $d is an array of 2 element arrays (internal name, displayed name)
                   2685: 
                   2686: =cut
                   2687: 
1.144     matthew  2688: ######################################################
                   2689: ######################################################
1.31      albertel 2690: sub csv_samples_select_table {
                   2691:     my ($r,$records,$d) = @_;
                   2692:     my %sone; my %stwo; my %sthree;
                   2693:     my $i=0;
1.144     matthew  2694:     #
                   2695:     $r->print('<table border=2><tr><th>'.
                   2696:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.31      albertel 2697:     %sone=&record_sep($$records[0]);
                   2698:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   2699:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  2700:     #
1.31      albertel 2701:     foreach (sort keys %sone) {
1.144     matthew  2702: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  2703: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 2704: 	foreach (@$d) {
                   2705: 	    my ($value,$display)=@{ $_ };
1.144     matthew  2706: 	    $r->print('<option value="'.$value.'">'.$display.'</option>');
1.31      albertel 2707: 	}
                   2708: 	$r->print('</select></td><td>');
                   2709: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   2710: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   2711: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   2712: 	$r->print('</td></tr>');
                   2713: 	$i++;
                   2714:     }
                   2715:     $i--;
                   2716:     return($i);
1.115     matthew  2717: }
                   2718: 
1.144     matthew  2719: ######################################################
                   2720: ######################################################
                   2721: 
1.115     matthew  2722: =pod
                   2723: 
                   2724: =item clean_excel_name($name)
                   2725: 
                   2726: Returns a replacement for $name which does not contain any illegal characters.
                   2727: 
                   2728: =cut
                   2729: 
1.144     matthew  2730: ######################################################
                   2731: ######################################################
1.115     matthew  2732: sub clean_excel_name {
                   2733:     my ($name) = @_;
                   2734:     $name =~ s/[:\*\?\/\\]//g;
                   2735:     if (length($name) > 31) {
                   2736:         $name = substr($name,0,31);
                   2737:     }
                   2738:     return $name;
1.25      albertel 2739: }
1.84      albertel 2740: 
1.85      albertel 2741: =pod
                   2742: 
1.112     bowersj2 2743: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 2744: 
                   2745: Returns either 1 or undef
                   2746: 
                   2747: 1 if the part is to be hidden, undef if it is to be shown
                   2748: 
                   2749: Arguments are:
                   2750: 
                   2751: $id the id of the part to be checked
                   2752: $symb, optional the symb of the resource to check
                   2753: $udom, optional the domain of the user to check for
                   2754: $uname, optional the username of the user to check for
                   2755: 
                   2756: =cut
1.84      albertel 2757: 
                   2758: sub check_if_partid_hidden {
                   2759:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 2760:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 2761: 					 $symb,$udom,$uname);
1.141     albertel 2762:     my $truth=1;
                   2763:     #if the string starts with !, then the list is the list to show not hide
                   2764:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 2765:     my @hiddenlist=split(/,/,$hiddenparts);
                   2766:     foreach my $checkid (@hiddenlist) {
1.141     albertel 2767: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 2768:     }
1.141     albertel 2769:     return !$truth;
1.84      albertel 2770: }
1.127     matthew  2771: 
1.138     matthew  2772: 
                   2773: ############################################################
                   2774: ############################################################
                   2775: 
                   2776: =pod
                   2777: 
1.157     matthew  2778: =back 
                   2779: 
1.138     matthew  2780: =head1 cgi-bin script and graphing routines
                   2781: 
1.157     matthew  2782: =over 4
                   2783: 
1.138     matthew  2784: =item get_cgi_id
                   2785: 
                   2786: Inputs: none
                   2787: 
                   2788: Returns an id which can be used to pass environment variables
                   2789: to various cgi-bin scripts.  These environment variables will
                   2790: be removed from the users environment after a given time by
                   2791: the routine &Apache::lonnet::transfer_profile_to_env.
                   2792: 
                   2793: =cut
                   2794: 
                   2795: ############################################################
                   2796: ############################################################
1.152     albertel 2797: my $uniq=0;
1.136     matthew  2798: sub get_cgi_id {
1.154     albertel 2799:     $uniq=($uniq+1)%100000;
1.152     albertel 2800:     return (time.'_'.$uniq);
1.136     matthew  2801: }
                   2802: 
1.127     matthew  2803: ############################################################
                   2804: ############################################################
                   2805: 
                   2806: =pod
                   2807: 
1.134     matthew  2808: =item DrawBarGraph
1.127     matthew  2809: 
1.138     matthew  2810: Facilitates the plotting of data in a (stacked) bar graph.
                   2811: Puts plot definition data into the users environment in order for 
                   2812: graph.png to plot it.  Returns an <img> tag for the plot.
                   2813: The bars on the plot are labeled '1','2',...,'n'.
                   2814: 
                   2815: Inputs:
                   2816: 
                   2817: =over 4
                   2818: 
                   2819: =item $Title: string, the title of the plot
                   2820: 
                   2821: =item $xlabel: string, text describing the X-axis of the plot
                   2822: 
                   2823: =item $ylabel: string, text describing the Y-axis of the plot
                   2824: 
                   2825: =item $Max: scalar, the maximum Y value to use in the plot
                   2826: If $Max is < any data point, the graph will not be rendered.
                   2827: 
1.140     matthew  2828: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  2829: they are plotted.  If undefined, default values will be used.
                   2830: 
                   2831: =item @Values: An array of array references.  Each array reference holds data
                   2832: to be plotted in a stacked bar chart.
                   2833: 
                   2834: =back
                   2835: 
                   2836: Returns:
                   2837: 
                   2838: An <img> tag which references graph.png and the appropriate identifying
                   2839: information for the plot.
                   2840: 
1.127     matthew  2841: =cut
                   2842: 
                   2843: ############################################################
                   2844: ############################################################
1.134     matthew  2845: sub DrawBarGraph {
1.129     matthew  2846:     my ($Title,$xlabel,$ylabel,$Max,$colors,@Values)=@_;
1.134     matthew  2847:     #
                   2848:     if (! defined($colors)) {
                   2849:         $colors = ['#33ff00', 
                   2850:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   2851:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   2852:                   ]; 
                   2853:     }
1.127     matthew  2854:     #
1.136     matthew  2855:     my $identifier = &get_cgi_id();
                   2856:     my $id = 'cgi.'.$identifier;        
1.129     matthew  2857:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  2858:         return '';
                   2859:     }
1.129     matthew  2860:     my $NumBars = scalar(@{$Values[0]});
                   2861:     my %ValuesHash;
                   2862:     my $NumSets=1;
                   2863:     foreach my $array (@Values) {
                   2864:         next if (! ref($array));
1.136     matthew  2865:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  2866:             join(',',@$array);
1.129     matthew  2867:     }
1.127     matthew  2868:     #
1.136     matthew  2869:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
                   2870:     if ($NumBars < 10) {
                   2871:         $width = 120+$NumBars*15;
                   2872:         $xskip = 1;
                   2873:         $bar_width = 15;
                   2874:     } elsif ($NumBars <= 25) {
                   2875:         $width = 120+$NumBars*11;
                   2876:         $xskip = 5;
                   2877:         $bar_width = 8;
                   2878:     } elsif ($NumBars <= 50) {
                   2879:         $width = 120+$NumBars*8;
                   2880:         $xskip = 5;
                   2881:         $bar_width = 4;
                   2882:     } else {
                   2883:         $width = 120+$NumBars*8;
                   2884:         $xskip = 5;
                   2885:         $bar_width = 4;
                   2886:     }
                   2887:     #
                   2888:     my @Labels;
                   2889:     for (my $i=0;$i<@{$Values[0]};$i++) {
                   2890:         push (@Labels,$i+1);
                   2891:     }
                   2892:     #
1.137     matthew  2893:     $Max = 1 if ($Max < 1);
                   2894:     if ( int($Max) < $Max ) {
                   2895:         $Max++;
                   2896:         $Max = int($Max);
                   2897:     }
1.127     matthew  2898:     $Title  = '' if (! defined($Title));
                   2899:     $xlabel = '' if (! defined($xlabel));
                   2900:     $ylabel = '' if (! defined($ylabel));
1.136     matthew  2901:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
                   2902:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
                   2903:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
1.137     matthew  2904:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  2905:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   2906:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   2907:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   2908:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   2909:     $ValuesHash{$id.'.height'}   = $height;
                   2910:     $ValuesHash{$id.'.width'}    = $width;
                   2911:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   2912:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   2913:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  2914:     #
1.137     matthew  2915:     &Apache::lonnet::appenv(%ValuesHash);
                   2916:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   2917: }
                   2918: 
                   2919: ############################################################
                   2920: ############################################################
                   2921: 
                   2922: =pod
                   2923: 
                   2924: =item DrawXYGraph
                   2925: 
1.138     matthew  2926: Facilitates the plotting of data in an XY graph.
                   2927: Puts plot definition data into the users environment in order for 
                   2928: graph.png to plot it.  Returns an <img> tag for the plot.
                   2929: 
                   2930: Inputs:
                   2931: 
                   2932: =over 4
                   2933: 
                   2934: =item $Title: string, the title of the plot
                   2935: 
                   2936: =item $xlabel: string, text describing the X-axis of the plot
                   2937: 
                   2938: =item $ylabel: string, text describing the Y-axis of the plot
                   2939: 
                   2940: =item $Max: scalar, the maximum Y value to use in the plot
                   2941: If $Max is < any data point, the graph will not be rendered.
                   2942: 
                   2943: =item $colors: Array ref containing the hex color codes for the data to be 
                   2944: plotted in.  If undefined, default values will be used.
                   2945: 
                   2946: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   2947: 
                   2948: =item $Ydata: Array ref containing Array refs.  
                   2949: Each of the contained arrays will be plotted as a seperate curve.
                   2950: 
                   2951: =item %Values: hash indicating or overriding any default values which are 
                   2952: passed to graph.png.  
                   2953: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   2954: 
                   2955: =back
                   2956: 
                   2957: Returns:
                   2958: 
                   2959: An <img> tag which references graph.png and the appropriate identifying
                   2960: information for the plot.
                   2961: 
1.137     matthew  2962: =cut
                   2963: 
                   2964: ############################################################
                   2965: ############################################################
                   2966: sub DrawXYGraph {
                   2967:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   2968:     #
                   2969:     # Create the identifier for the graph
                   2970:     my $identifier = &get_cgi_id();
                   2971:     my $id = 'cgi.'.$identifier;
                   2972:     #
                   2973:     $Title  = '' if (! defined($Title));
                   2974:     $xlabel = '' if (! defined($xlabel));
                   2975:     $ylabel = '' if (! defined($ylabel));
                   2976:     my %ValuesHash = 
                   2977:         (
                   2978:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   2979:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   2980:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   2981:          $id.'.y_max_value'=> $Max,
                   2982:          $id.'.labels'     => join(',',@$Xlabels),
                   2983:          $id.'.PlotType'   => 'XY',
                   2984:          );
                   2985:     #
                   2986:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   2987:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   2988:     }
                   2989:     #
                   2990:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   2991:         return '';
                   2992:     }
                   2993:     my $NumSets=1;
1.138     matthew  2994:     foreach my $array (@{$Ydata}){
1.137     matthew  2995:         next if (! ref($array));
                   2996:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   2997:     }
1.138     matthew  2998:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  2999:     #
                   3000:     # Deal with other parameters
                   3001:     while (my ($key,$value) = each(%Values)) {
                   3002:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  3003:     }
                   3004:     #
1.136     matthew  3005:     &Apache::lonnet::appenv(%ValuesHash);
                   3006:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3007: }
                   3008: 
                   3009: ############################################################
                   3010: ############################################################
                   3011: 
                   3012: =pod
                   3013: 
1.138     matthew  3014: =item DrawXYYGraph
                   3015: 
                   3016: Facilitates the plotting of data in an XY graph with two Y axes.
                   3017: Puts plot definition data into the users environment in order for 
                   3018: graph.png to plot it.  Returns an <img> tag for the plot.
                   3019: 
                   3020: Inputs:
                   3021: 
                   3022: =over 4
                   3023: 
                   3024: =item $Title: string, the title of the plot
                   3025: 
                   3026: =item $xlabel: string, text describing the X-axis of the plot
                   3027: 
                   3028: =item $ylabel: string, text describing the Y-axis of the plot
                   3029: 
                   3030: =item $colors: Array ref containing the hex color codes for the data to be 
                   3031: plotted in.  If undefined, default values will be used.
                   3032: 
                   3033: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3034: 
                   3035: =item $Ydata1: The first data set
                   3036: 
                   3037: =item $Min1: The minimum value of the left Y-axis
                   3038: 
                   3039: =item $Max1: The maximum value of the left Y-axis
                   3040: 
                   3041: =item $Ydata2: The second data set
                   3042: 
                   3043: =item $Min2: The minimum value of the right Y-axis
                   3044: 
                   3045: =item $Max2: The maximum value of the left Y-axis
                   3046: 
                   3047: =item %Values: hash indicating or overriding any default values which are 
                   3048: passed to graph.png.  
                   3049: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3050: 
                   3051: =back
                   3052: 
                   3053: Returns:
                   3054: 
                   3055: An <img> tag which references graph.png and the appropriate identifying
                   3056: information for the plot.
1.136     matthew  3057: 
                   3058: =cut
                   3059: 
                   3060: ############################################################
                   3061: ############################################################
1.137     matthew  3062: sub DrawXYYGraph {
                   3063:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   3064:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  3065:     #
                   3066:     # Create the identifier for the graph
                   3067:     my $identifier = &get_cgi_id();
                   3068:     my $id = 'cgi.'.$identifier;
                   3069:     #
                   3070:     $Title  = '' if (! defined($Title));
                   3071:     $xlabel = '' if (! defined($xlabel));
                   3072:     $ylabel = '' if (! defined($ylabel));
                   3073:     my %ValuesHash = 
                   3074:         (
                   3075:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3076:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3077:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3078:          $id.'.labels' => join(',',@$Xlabels),
                   3079:          $id.'.PlotType' => 'XY',
                   3080:          $id.'.NumSets' => 2,
1.137     matthew  3081:          $id.'.two_axes' => 1,
                   3082:          $id.'.y1_max_value' => $Max1,
                   3083:          $id.'.y1_min_value' => $Min1,
                   3084:          $id.'.y2_max_value' => $Max2,
                   3085:          $id.'.y2_min_value' => $Min2,
1.136     matthew  3086:          );
                   3087:     #
1.137     matthew  3088:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3089:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3090:     }
                   3091:     #
                   3092:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   3093:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  3094:         return '';
                   3095:     }
                   3096:     my $NumSets=1;
1.137     matthew  3097:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  3098:         next if (! ref($array));
                   3099:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  3100:     }
                   3101:     #
                   3102:     # Deal with other parameters
                   3103:     while (my ($key,$value) = each(%Values)) {
                   3104:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  3105:     }
                   3106:     #
                   3107:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 3108:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  3109: }
                   3110: 
                   3111: ############################################################
                   3112: ############################################################
                   3113: 
                   3114: =pod
                   3115: 
1.157     matthew  3116: =back 
                   3117: 
1.139     matthew  3118: =head1 Statistics helper routines?  
                   3119: 
                   3120: Bad place for them but what the hell.
                   3121: 
1.157     matthew  3122: =over 4
                   3123: 
1.139     matthew  3124: =item &chartlink
                   3125: 
                   3126: Returns a link to the chart for a specific student.  
                   3127: 
                   3128: Inputs:
                   3129: 
                   3130: =over 4
                   3131: 
                   3132: =item $linktext: The text of the link
                   3133: 
                   3134: =item $sname: The students username
                   3135: 
                   3136: =item $sdomain: The students domain
                   3137: 
                   3138: =back
                   3139: 
1.157     matthew  3140: =back
                   3141: 
1.139     matthew  3142: =cut
                   3143: 
                   3144: ############################################################
                   3145: ############################################################
                   3146: sub chartlink {
                   3147:     my ($linktext, $sname, $sdomain) = @_;
                   3148:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
                   3149:         '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
                   3150:         '&chartoutputmode='.HTML::Entities::encode('html, with all links').
                   3151:        '">'.$linktext.'</a>';
1.153     matthew  3152: }
                   3153: 
                   3154: #######################################################
                   3155: #######################################################
                   3156: 
                   3157: =pod
                   3158: 
                   3159: =head1 Course Environment Routines
1.157     matthew  3160: 
                   3161: =over 4
1.153     matthew  3162: 
                   3163: =item &restore_course_settings 
                   3164: 
                   3165: =item &store_course_settings
                   3166: 
                   3167: Restores/Store indicated form parameters from the course environment.
                   3168: Will not overwrite existing values of the form parameters.
                   3169: 
                   3170: Inputs: 
                   3171: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   3172: 
                   3173: a hash ref describing the data to be stored.  For example:
                   3174:    
                   3175: %Save_Parameters = ('Status' => 'scalar',
                   3176:     'chartoutputmode' => 'scalar',
                   3177:     'chartoutputdata' => 'scalar',
                   3178:     'Section' => 'array',
                   3179:     'StudentData' => 'array',
                   3180:     'Maps' => 'array');
                   3181: 
                   3182: Returns: both routines return nothing
                   3183: 
                   3184: =cut
                   3185: 
                   3186: #######################################################
                   3187: #######################################################
                   3188: sub store_course_settings {
                   3189:     # save to the environment
                   3190:     # appenv the same items, just to be safe
                   3191:     my $courseid = $ENV{'request.course.id'};
                   3192:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
                   3193:     my ($prefix,$Settings) = @_;
                   3194:     my %SaveHash;
                   3195:     my %AppHash;
                   3196:     while (my ($setting,$type) = each(%$Settings)) {
                   3197:         my $basename = 'env.internal.'.$prefix.'.'.$setting;
                   3198:         my $envname = 'course.'.$courseid.'.'.$basename;
                   3199:         if (exists($ENV{'form.'.$setting})) {
                   3200:             # Save this value away
                   3201:             if ($type eq 'scalar' &&
                   3202:                 (! exists($ENV{$envname}) || 
                   3203:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
                   3204:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
                   3205:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
                   3206:             } elsif ($type eq 'array') {
                   3207:                 my $stored_form;
                   3208:                 if (ref($ENV{'form.'.$setting})) {
                   3209:                     $stored_form = join(',',
                   3210:                                         map {
                   3211:                                             &Apache::lonnet::escape($_);
                   3212:                                         } sort(@{$ENV{'form.'.$setting}}));
                   3213:                 } else {
                   3214:                     $stored_form = 
                   3215:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
                   3216:                 }
                   3217:                 # Determine if the array contents are the same.
                   3218:                 if ($stored_form ne $ENV{$envname}) {
                   3219:                     $SaveHash{$basename} = $stored_form;
                   3220:                     $AppHash{$envname}   = $stored_form;
                   3221:                 }
                   3222:             }
                   3223:         }
                   3224:     }
                   3225:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
                   3226:                                           $coursedom,
                   3227:                                           $ENV{'course.'.$courseid.'.num'});
                   3228:     if ($put_result !~ /^(ok|delayed)/) {
                   3229:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   3230:                                  'got error:'.$put_result);
                   3231:     }
                   3232:     # Make sure these settings stick around in this session, too
                   3233:     &Apache::lonnet::appenv(%AppHash);
                   3234:     return;
                   3235: }
                   3236: 
                   3237: sub restore_course_settings {
                   3238:     my $courseid = $ENV{'request.course.id'};
                   3239:     my ($prefix,$Settings) = @_;
                   3240:     while (my ($setting,$type) = each(%$Settings)) {
                   3241:         next if (exists($ENV{'form.'.$setting}));
                   3242:         my $envname = 'course.'.$courseid.'.env.internal.'.$prefix.
                   3243:             '.'.$setting;
                   3244:         if (exists($ENV{$envname})) {
                   3245:             if ($type eq 'scalar') {
                   3246:                 $ENV{'form.'.$setting} = $ENV{$envname};
                   3247:             } elsif ($type eq 'array') {
                   3248:                 $ENV{'form.'.$setting} = [ 
                   3249:                                            map { 
                   3250:                                                &Apache::lonnet::unescape($_); 
                   3251:                                            } split(',',$ENV{$envname})
                   3252:                                            ];
                   3253:             }
                   3254:         }
                   3255:     }
1.127     matthew  3256: }
                   3257: 
                   3258: ############################################################
                   3259: ############################################################
1.154     albertel 3260: 
                   3261: sub propath {
                   3262:     my ($udom,$uname)=@_;
                   3263:     $udom=~s/\W//g;
                   3264:     $uname=~s/\W//g;
                   3265:     my $subdir=$uname.'__';
                   3266:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3267:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3268:     return $proname;
1.156     albertel 3269: } 
                   3270: 
                   3271: sub icon {
                   3272:     my ($file)=@_;
                   3273:     my @file_ext = split(/\./,$file);
                   3274:     my $curfext = $file_ext[-1];
                   3275:     my $iconname="unknown.gif";
                   3276:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
                   3277:     # The unless conditional that follows is a bit of overkill
                   3278:     $iconname = $curfext.".gif" unless
                   3279: 	(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn');
                   3280:     return $Apache::lonnet::perlvar{'lonIconsURL'}."/$iconname";
1.154     albertel 3281: } 
1.84      albertel 3282: 
1.41      ng       3283: =pod
                   3284: 
                   3285: =back
                   3286: 
1.112     bowersj2 3287: =cut
1.41      ng       3288: 
1.112     bowersj2 3289: 1;
                   3290: __END__;
1.41      ng       3291: 

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