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

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

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