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

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

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