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

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

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