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

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

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