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

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

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