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

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

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