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

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

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