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

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

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