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

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

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