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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.200   ! matthew     4: # $Id: loncommon.pm,v 1.199 2004/07/15 18:50:37 albertel Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.22      www        58: use Apache::lonnet();
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.99      www        61: use Apache::Constants qw(:common :http :methods);
1.1       albertel   62: use Apache::lonmsg();
1.82      www        63: use Apache::lonmenu();
1.117     www        64: use Apache::lonlocal;
1.139     matthew    65: use HTML::Entities;
1.117     www        66: 
1.22      www        67: my $readit;
                     68: 
1.157     matthew    69: ##
                     70: ## Global Variables
                     71: ##
1.46      matthew    72: 
1.20      www        73: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41   74: my %language;
1.124     www        75: my %supported_language;
1.12      harris41   76: my %cprtag;
1.192     taceyjo1   77: my %scprtag;
1.12      harris41   78: my %fe; my %fd;
1.41      ng         79: my %category_extensions;
1.12      harris41   80: 
1.63      www        81: # ---------------------------------------------- Designs
                     82: 
                     83: my %designhash;
                     84: 
1.46      matthew    85: # ---------------------------------------------- Thesaurus variables
1.144     matthew    86: #
                     87: # %Keywords:
                     88: #      A hash used by &keyword to determine if a word is considered a keyword.
                     89: # $thesaurus_db_file 
                     90: #      Scalar containing the full path to the thesaurus database.
1.46      matthew    91: 
                     92: my %Keywords;
                     93: my $thesaurus_db_file;
                     94: 
1.144     matthew    95: #
                     96: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                     97: # thesaurus.tab, and filecategories.tab.
                     98: #
1.18      www        99: BEGIN {
1.46      matthew   100:     # Variable initialization
                    101:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    102:     #
1.22      www       103:     unless ($readit) {
1.12      harris41  104: # ------------------------------------------------------------------- languages
                    105:     {
1.158     raeburn   106:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    107:                                    '/language.tab';
                    108:         if ( open(my $fh,"<$langtabfile") ) {
                    109:             while (<$fh>) {
                    110:                 next if /^\#/;
                    111:                 chomp;
                    112:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
                    113:                 $language{$key}=$val.' - '.$enc;
                    114:                 if ($sup) {
                    115:                     $supported_language{$key}=$sup;
                    116:                 }
                    117:             }
                    118:             close($fh);
                    119:         }
1.12      harris41  120:     }
                    121: # ------------------------------------------------------------------ copyrights
                    122:     {
1.158     raeburn   123:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    124:                                   '/copyright.tab';
                    125:         if ( open (my $fh,"<$copyrightfile") ) {
                    126:             while (<$fh>) {
                    127:                 next if /^\#/;
                    128:                 chomp;
                    129:                 my ($key,$val)=(split(/\s+/,$_,2));
                    130:                 $cprtag{$key}=$val;
                    131:             }
                    132:             close($fh);
                    133:         }
1.12      harris41  134:     }
1.192     taceyjo1  135: # ------------------------------------------------------------------ source copyrights
                    136:     {
                    137:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    138:                                   '/source_copyright.tab';
                    139:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
                    140:             while (<$fh>) {
                    141:                 next if /^\#/;
                    142:                 chomp;
                    143:                 my ($key,$val)=(split(/\s+/,$_,2));
                    144:                 $scprtag{$key}=$val;
                    145:             }
                    146:             close($fh);
                    147:         }
                    148:     }
1.63      www       149: 
                    150: # -------------------------------------------------------------- domain designs
                    151: 
                    152:     my $filename;
                    153:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                    154:     opendir(DIR,$designdir);
                    155:     while ($filename=readdir(DIR)) {
                    156: 	my ($domain)=($filename=~/^(\w+)\./);
                    157:     {
1.158     raeburn   158:         my $designfile = $designdir.'/'.$filename;
                    159:         if ( open (my $fh,"<$designfile") ) {
                    160:             while (<$fh>) {
                    161:                 next if /^\#/;
                    162:                 chomp;
                    163:                 my ($key,$val)=(split(/\=/,$_));
                    164:                 if ($val) { $designhash{$domain.'.'.$key}=$val; }
                    165:             }
                    166:             close($fh);
                    167:         }
1.63      www       168:     }
                    169: 
                    170:     }
                    171:     closedir(DIR);
                    172: 
                    173: 
1.15      harris41  174: # ------------------------------------------------------------- file categories
                    175:     {
1.158     raeburn   176:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    177:                                   '/filecategories.tab';
                    178:         if ( open (my $fh,"<$categoryfile") ) {
                    179:             while (<$fh>) {
                    180:                 next if /^\#/;
                    181:                 chomp;
                    182:                 my ($extension,$category)=(split(/\s+/,$_,2));
                    183:                 push @{$category_extensions{lc($category)}},$extension;
                    184:             }
                    185:             close($fh);
                    186:         }
                    187: 
1.15      harris41  188:     }
1.12      harris41  189: # ------------------------------------------------------------------ file types
                    190:     {
1.158     raeburn   191:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    192:                '/filetypes.tab';
                    193:         if ( open (my $fh,"<$typesfile") ) {
1.16      harris41  194:             while (<$fh>) {
1.158     raeburn   195:                 next if (/^\#/);
                    196:                 chomp;
                    197:                 my ($ending,$emb,$descr)=split(/\s+/,$_,3);
                    198:                 if ($descr ne '') {
                    199:                     $fe{$ending}=lc($emb);
                    200:                     $fd{$ending}=$descr;
                    201:                 }
                    202:             }
                    203:             close($fh);
                    204:         }
1.12      harris41  205:     }
1.22      www       206:     &Apache::lonnet::logthis(
1.46      matthew   207:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       208:     $readit=1;
1.46      matthew   209:     }  # end of unless($readit) 
1.32      matthew   210:     
                    211: }
1.112     bowersj2  212: 
1.42      matthew   213: ###############################################################
                    214: ##           HTML and Javascript Helper Functions            ##
                    215: ###############################################################
                    216: 
                    217: =pod 
                    218: 
1.112     bowersj2  219: =head1 HTML and Javascript Functions
1.42      matthew   220: 
1.112     bowersj2  221: =over 4
                    222: 
                    223: =item * browser_and_searcher_javascript ()
                    224: 
                    225: X<browsing, javascript>X<searching, javascript>Returns a string
                    226: containing javascript with two functions, C<openbrowser> and
                    227: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    228: tags.
1.42      matthew   229: 
1.112     bowersj2  230: =item * openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   231: 
                    232: inputs: formname, elementname, only, omit
                    233: 
                    234: formname and elementname indicate the name of the html form and name of
                    235: the element that the results of the browsing selection are to be placed in. 
                    236: 
                    237: Specifying 'only' will restrict the browser to displaying only files
1.185     www       238: with the given extension.  Can be a comma separated list.
1.42      matthew   239: 
                    240: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       241: with the given extension.  Can be a comma separated list.
1.42      matthew   242: 
1.112     bowersj2  243: =item * opensearcher(formname, elementname) [javascript]
1.42      matthew   244: 
                    245: Inputs: formname, elementname
                    246: 
                    247: formname and elementname specify the name of the html form and the name
                    248: of the element the selection from the search results will be placed in.
                    249: 
                    250: =cut
                    251: 
                    252: sub browser_and_searcher_javascript {
1.199     albertel  253:     my ($mode)=@_;
                    254:     if (!defined($mode)) { $mode='edit'; }
1.170     www       255:     my $resurl=&lastresurl();
1.42      matthew   256:     return <<END;
1.50      matthew   257:     var editbrowser = null;
1.135     albertel  258:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       259:         var url = '$resurl/?';
1.42      matthew   260:         if (editbrowser == null) {
                    261:             url += 'launch=1&';
                    262:         }
                    263:         url += 'catalogmode=interactive&';
1.199     albertel  264:         url += 'mode=$mode&';
1.42      matthew   265:         url += 'form=' + formname + '&';
                    266:         if (only != null) {
                    267:             url += 'only=' + only + '&';
                    268:         } 
                    269:         if (omit != null) {
                    270:             url += 'omit=' + omit + '&';
                    271:         }
1.135     albertel  272:         if (titleelement != null) {
                    273:             url += 'titleelement=' + titleelement + '&';
                    274:         }
1.42      matthew   275:         url += 'element=' + elementname + '';
                    276:         var title = 'Browser';
                    277:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    278:         options += ',width=700,height=600';
                    279:         editbrowser = open(url,title,options,'1');
                    280:         editbrowser.focus();
                    281:     }
                    282:     var editsearcher;
1.135     albertel  283:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   284:         var url = '/adm/searchcat?';
                    285:         if (editsearcher == null) {
                    286:             url += 'launch=1&';
                    287:         }
                    288:         url += 'catalogmode=interactive&';
1.199     albertel  289:         url += 'mode=$mode&';
1.42      matthew   290:         url += 'form=' + formname + '&';
1.135     albertel  291:         if (titleelement != null) {
                    292:             url += 'titleelement=' + titleelement + '&';
                    293:         }
1.42      matthew   294:         url += 'element=' + elementname + '';
                    295:         var title = 'Search';
                    296:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    297:         options += ',width=700,height=600';
                    298:         editsearcher = open(url,title,options,'1');
                    299:         editsearcher.focus();
                    300:     }
                    301: END
1.170     www       302: }
                    303: 
                    304: sub lastresurl {
                    305:     if ($ENV{'environment.lastresurl'}) {
                    306: 	return $ENV{'environment.lastresurl'}
                    307:     } else {
                    308: 	return '/res';
                    309:     }
                    310: }
                    311: 
                    312: sub storeresurl {
                    313:     my $resurl=&Apache::lonnet::clutter(shift);
                    314:     unless ($resurl=~/^\/res/) { return 0; }
                    315:     $resurl=~s/\/$//;
                    316:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
                    317:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
                    318:     return 1;
1.42      matthew   319: }
                    320: 
1.74      www       321: sub studentbrowser_javascript {
1.111     www       322:    unless (
                    323:             (($ENV{'request.course.id'}) && 
                    324:              (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})))
                    325:          || ($ENV{'request.role'}=~/^(au|dc|su)/)
                    326:           ) { return ''; }  
1.74      www       327:    return (<<'ENDSTDBRW');
                    328: <script type="text/javascript" language="Javascript" >
                    329:     var stdeditbrowser;
1.111     www       330:     function openstdbrowser(formname,uname,udom,roleflag) {
1.74      www       331:         var url = '/adm/pickstudent?';
                    332:         var filter;
                    333:         eval('filter=document.'+formname+'.'+uname+'.value;');
                    334:         if (filter != null) {
                    335:            if (filter != '') {
                    336:                url += 'filter='+filter+'&';
                    337: 	   }
                    338:         }
                    339:         url += 'form=' + formname + '&unameelement='+uname+
                    340:                                     '&udomelement='+udom;
1.111     www       341: 	if (roleflag) { url+="&roles=1"; }
1.102     www       342:         var title = 'Student_Browser';
1.74      www       343:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    344:         options += ',width=700,height=600';
                    345:         stdeditbrowser = open(url,title,options,'1');
                    346:         stdeditbrowser.focus();
                    347:     }
                    348: </script>
                    349: ENDSTDBRW
                    350: }
1.42      matthew   351: 
1.74      www       352: sub selectstudent_link {
1.111     www       353:    my ($form,$unameele,$udomele)=@_;
                    354:    if ($ENV{'request.course.id'}) {  
                    355:        unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
                    356: 	   return '';
                    357:        }
                    358:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       359:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
1.74      www       360:    }
1.111     www       361:    if ($ENV{'request.role'}=~/^(au|dc|su)/) {
                    362:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
1.119     www       363:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
1.111     www       364:    }
                    365:    return '';
1.91      www       366: }
                    367: 
                    368: sub coursebrowser_javascript {
1.128     albertel  369:     my ($domainfilter)=@_;
                    370:    return (<<ENDSTDBRW);
1.91      www       371: <script type="text/javascript" language="Javascript" >
                    372:     var stdeditbrowser;
1.187     albertel  373:     function opencrsbrowser(formname,uname,udom,desc) {
1.91      www       374:         var url = '/adm/pickcourse?';
                    375:         var filter;
                    376:         if (filter != null) {
                    377:            if (filter != '') {
                    378:                url += 'filter='+filter+'&';
                    379: 	   }
                    380:         }
1.128     albertel  381:         var domainfilter='$domainfilter';
                    382:         if (domainfilter != null) {
                    383:            if (domainfilter != '') {
                    384:                url += 'domainfilter='+domainfilter+'&';
                    385: 	   }
                    386:         }
1.91      www       387:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  388: 	                            '&cdomelement='+udom+
                    389:                                     '&cnameelement='+desc;
1.102     www       390:         var title = 'Course_Browser';
1.91      www       391:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    392:         options += ',width=700,height=600';
                    393:         stdeditbrowser = open(url,title,options,'1');
                    394:         stdeditbrowser.focus();
                    395:     }
                    396: </script>
                    397: ENDSTDBRW
                    398: }
                    399: 
                    400: sub selectcourse_link {
1.187     albertel  401:    my ($form,$unameele,$udomele,$desc)=@_;
1.91      www       402:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
1.187     albertel  403:         '","'.$udomele.'","'.$desc.'");'."'>".&mt('Select Course')."</a>";
1.74      www       404: }
1.42      matthew   405: 
                    406: =pod
1.36      matthew   407: 
1.112     bowersj2  408: =item * linked_select_forms(...)
1.36      matthew   409: 
                    410: linked_select_forms returns a string containing a <script></script> block
                    411: and html for two <select> menus.  The select menus will be linked in that
                    412: changing the value of the first menu will result in new values being placed
                    413: in the second menu.  The values in the select menu will appear in alphabetical
                    414: order.
                    415: 
                    416: linked_select_forms takes the following ordered inputs:
                    417: 
                    418: =over 4
                    419: 
1.112     bowersj2  420: =item * $formname, the name of the <form> tag
1.36      matthew   421: 
1.112     bowersj2  422: =item * $middletext, the text which appears between the <select> tags
1.36      matthew   423: 
1.112     bowersj2  424: =item * $firstdefault, the default value for the first menu
1.36      matthew   425: 
1.112     bowersj2  426: =item * $firstselectname, the name of the first <select> tag
1.36      matthew   427: 
1.112     bowersj2  428: =item * $secondselectname, the name of the second <select> tag
1.36      matthew   429: 
1.112     bowersj2  430: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew   431: 
1.41      ng        432: =back 
                    433: 
1.36      matthew   434: Below is an example of such a hash.  Only the 'text', 'default', and 
                    435: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                    436: values for the first select menu.  The text that coincides with the 
1.41      ng        437: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   438: and text for the second menu are given in the hash pointed to by 
                    439: $menu{$choice1}->{'select2'}.  
                    440: 
1.112     bowersj2  441:  my %menu = ( A1 => { text =>"Choice A1" ,
                    442:                        default => "B3",
                    443:                        select2 => { 
                    444:                            B1 => "Choice B1",
                    445:                            B2 => "Choice B2",
                    446:                            B3 => "Choice B3",
                    447:                            B4 => "Choice B4"
                    448:                            }
                    449:                    },
                    450:                A2 => { text =>"Choice A2" ,
                    451:                        default => "C2",
                    452:                        select2 => { 
                    453:                            C1 => "Choice C1",
                    454:                            C2 => "Choice C2",
                    455:                            C3 => "Choice C3"
                    456:                            }
                    457:                    },
                    458:                A3 => { text =>"Choice A3" ,
                    459:                        default => "D6",
                    460:                        select2 => { 
                    461:                            D1 => "Choice D1",
                    462:                            D2 => "Choice D2",
                    463:                            D3 => "Choice D3",
                    464:                            D4 => "Choice D4",
                    465:                            D5 => "Choice D5",
                    466:                            D6 => "Choice D6",
                    467:                            D7 => "Choice D7"
                    468:                            }
                    469:                    }
                    470:                );
1.36      matthew   471: 
                    472: =cut
                    473: 
                    474: sub linked_select_forms {
                    475:     my ($formname,
                    476:         $middletext,
                    477:         $firstdefault,
                    478:         $firstselectname,
                    479:         $secondselectname, 
                    480:         $hashref
                    481:         ) = @_;
                    482:     my $second = "document.$formname.$secondselectname";
                    483:     my $first = "document.$formname.$firstselectname";
                    484:     # output the javascript to do the changing
                    485:     my $result = '';
                    486:     $result.="<script>\n";
                    487:     $result.="var select2data = new Object();\n";
                    488:     $" = '","';
                    489:     my $debug = '';
                    490:     foreach my $s1 (sort(keys(%$hashref))) {
                    491:         $result.="select2data.d_$s1 = new Object();\n";        
                    492:         $result.="select2data.d_$s1.def = new String('".
                    493:             $hashref->{$s1}->{'default'}."');\n";
                    494:         $result.="select2data.d_$s1.values = new Array(";        
                    495:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
                    496:         $result.="\"@s2values\");\n";
                    497:         $result.="select2data.d_$s1.texts = new Array(";        
                    498:         my @s2texts;
                    499:         foreach my $value (@s2values) {
                    500:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                    501:         }
                    502:         $result.="\"@s2texts\");\n";
                    503:     }
                    504:     $"=' ';
                    505:     $result.= <<"END";
                    506: 
                    507: function select1_changed() {
                    508:     // Determine new choice
                    509:     var newvalue = "d_" + $first.value;
                    510:     // update select2
                    511:     var values     = select2data[newvalue].values;
                    512:     var texts      = select2data[newvalue].texts;
                    513:     var select2def = select2data[newvalue].def;
                    514:     var i;
                    515:     // out with the old
                    516:     for (i = 0; i < $second.options.length; i++) {
                    517:         $second.options[i] = null;
                    518:     }
                    519:     // in with the nuclear
                    520:     for (i=0;i<values.length; i++) {
                    521:         $second.options[i] = new Option(values[i]);
1.143     matthew   522:         $second.options[i].value = values[i];
1.36      matthew   523:         $second.options[i].text = texts[i];
                    524:         if (values[i] == select2def) {
                    525:             $second.options[i].selected = true;
                    526:         }
                    527:     }
                    528: }
                    529: </script>
                    530: END
                    531:     # output the initial values for the selection lists
                    532:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
                    533:     foreach my $value (sort(keys(%$hashref))) {
                    534:         $result.="    <option value=\"$value\" ";
                    535:         $result.=" selected=\"true\" " if ($value eq $firstdefault);
1.119     www       536:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew   537:     }
                    538:     $result .= "</select>\n";
                    539:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                    540:     $result .= $middletext;
                    541:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                    542:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
                    543:     foreach my $value (sort(keys(%select2))) {
                    544:         $result.="    <option value=\"$value\" ";        
                    545:         $result.=" selected=\"true\" " if ($value eq $seconddefault);
1.119     www       546:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew   547:     }
                    548:     $result .= "</select>\n";
                    549:     #    return $debug;
                    550:     return $result;
                    551: }   #  end of sub linked_select_forms {
                    552: 
1.45      matthew   553: =pod
1.44      bowersj2  554: 
1.112     bowersj2  555: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
1.44      bowersj2  556: 
1.112     bowersj2  557: Returns a string corresponding to an HTML link to the given help
                    558: $topic, where $topic corresponds to the name of a .tex file in
                    559: /home/httpd/html/adm/help/tex, with underscores replaced by
                    560: spaces. 
                    561: 
                    562: $text will optionally be linked to the same topic, allowing you to
                    563: link text in addition to the graphic. If you do not want to link
                    564: text, but wish to specify one of the later parameters, pass an
                    565: empty string. 
                    566: 
                    567: $stayOnPage is a value that will be interpreted as a boolean. If true,
                    568: the link will not open a new window. If false, the link will open
                    569: a new window using Javascript. (Default is false.) 
                    570: 
                    571: $width and $height are optional numerical parameters that will
                    572: override the width and height of the popped up window, which may
                    573: be useful for certain help topics with big pictures included. 
1.44      bowersj2  574: 
                    575: =cut
                    576: 
                    577: sub help_open_topic {
1.48      bowersj2  578:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                    579:     $text = "" if (not defined $text);
1.44      bowersj2  580:     $stayOnPage = 0 if (not defined $stayOnPage);
1.108     bowersj2  581:     if ($ENV{'browser.interface'} eq 'textual' ||
                    582: 	$ENV{'environment.remote'} eq 'off' ) {
1.79      www       583: 	$stayOnPage=1;
                    584:     }
1.44      bowersj2  585:     $width = 350 if (not defined $width);
                    586:     $height = 400 if (not defined $height);
                    587:     my $filename = $topic;
                    588:     $filename =~ s/ /_/g;
                    589: 
1.48      bowersj2  590:     my $template = "";
                    591:     my $link;
1.159     www       592: 
                    593:     $topic=~s/\W/\_/g;
1.44      bowersj2  594: 
                    595:     if (!$stayOnPage)
                    596:     {
1.72      bowersj2  597: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.44      bowersj2  598:     }
                    599:     else
                    600:     {
1.48      bowersj2  601: 	$link = "/adm/help/${filename}.hlp";
                    602:     }
                    603: 
                    604:     # Add the text
                    605:     if ($text ne "")
                    606:     {
1.77      www       607: 	$template .= 
                    608:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.78      www       609:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2  610:     }
                    611: 
                    612:     # Add the graphic
1.179     matthew   613:     my $title = &mt('Online Help');
1.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 {
1.200   ! matthew  1790:     my ($link,$username,$domain)=@_;
1.62      www      1791:     return 
1.200   ! matthew  1792:         '<a href="/adm/email?compose=individual&'.
        !          1793:         'recname='.$username.'&recdom='.$domain.'" '.
        !          1794:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      1795: }
                   1796: # --------------------------------------------------------------- Notes Wrapper
                   1797: 
                   1798: sub noteswrapper {
                   1799:     my ($link,$un,$do)=@_;
                   1800:     return 
                   1801: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      1802: }
                   1803: # ------------------------------------------------------------- Aboutme Wrapper
                   1804: 
                   1805: sub aboutmewrapper {
1.166     www      1806:     my ($link,$username,$domain,$target)=@_;
1.200   ! matthew  1807:     return '<a href="/adm/$domain/$username/aboutme"'.
        !          1808: 	($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
1.62      www      1809: }
                   1810: 
                   1811: # ------------------------------------------------------------ Syllabus Wrapper
                   1812: 
                   1813: 
                   1814: sub syllabuswrapper {
1.109     matthew  1815:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
                   1816:     if ($fontcolor) { 
                   1817:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
                   1818:     }
                   1819:     return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1.61      www      1820: }
1.14      harris41 1821: 
1.112     bowersj2 1822: =pod
                   1823: 
                   1824: =back
                   1825: 
                   1826: =head1 Access .tab File Data
                   1827: 
                   1828: =over 4
                   1829: 
                   1830: =item * languageids() 
                   1831: 
                   1832: returns list of all language ids
                   1833: 
                   1834: =cut
                   1835: 
1.14      harris41 1836: sub languageids {
1.16      harris41 1837:     return sort(keys(%language));
1.14      harris41 1838: }
                   1839: 
1.112     bowersj2 1840: =pod
                   1841: 
                   1842: =item * languagedescription() 
                   1843: 
                   1844: returns description of a specified language id
                   1845: 
                   1846: =cut
                   1847: 
1.14      harris41 1848: sub languagedescription {
1.125     www      1849:     my $code=shift;
                   1850:     return  ($supported_language{$code}?'* ':'').
                   1851:             $language{$code}.
1.126     www      1852: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      1853: }
                   1854: 
                   1855: sub plainlanguagedescription {
                   1856:     my $code=shift;
                   1857:     return $language{$code};
                   1858: }
                   1859: 
                   1860: sub supportedlanguagecode {
                   1861:     my $code=shift;
                   1862:     return $supported_language{$code};
1.97      www      1863: }
                   1864: 
1.112     bowersj2 1865: =pod
                   1866: 
                   1867: =item * copyrightids() 
                   1868: 
                   1869: returns list of all copyrights
                   1870: 
                   1871: =cut
                   1872: 
                   1873: sub copyrightids {
                   1874:     return sort(keys(%cprtag));
                   1875: }
                   1876: 
                   1877: =pod
                   1878: 
                   1879: =item * copyrightdescription() 
                   1880: 
                   1881: returns description of a specified copyright id
                   1882: 
                   1883: =cut
                   1884: 
                   1885: sub copyrightdescription {
1.166     www      1886:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 1887: }
1.197     matthew  1888: 
                   1889: =pod
                   1890: 
1.192     taceyjo1 1891: =item * source_copyrightids() 
                   1892: 
                   1893: returns list of all source copyrights
                   1894: 
                   1895: =cut
                   1896: 
                   1897: sub source_copyrightids {
                   1898:     return sort(keys(%scprtag));
                   1899: }
                   1900: 
                   1901: =pod
                   1902: 
                   1903: =item * source_copyrightdescription() 
                   1904: 
                   1905: returns description of a specified source copyright id
                   1906: 
                   1907: =cut
                   1908: 
                   1909: sub source_copyrightdescription {
                   1910:     return &mt($scprtag{shift(@_)});
                   1911: }
1.112     bowersj2 1912: 
                   1913: =pod
                   1914: 
                   1915: =item * filecategories() 
                   1916: 
                   1917: returns list of all file categories
                   1918: 
                   1919: =cut
                   1920: 
                   1921: sub filecategories {
                   1922:     return sort(keys(%category_extensions));
                   1923: }
                   1924: 
                   1925: =pod
                   1926: 
                   1927: =item * filecategorytypes() 
                   1928: 
                   1929: returns list of file types belonging to a given file
                   1930: category
                   1931: 
                   1932: =cut
                   1933: 
                   1934: sub filecategorytypes {
                   1935:     return @{$category_extensions{lc($_[0])}};
                   1936: }
                   1937: 
                   1938: =pod
                   1939: 
                   1940: =item * fileembstyle() 
                   1941: 
                   1942: returns embedding style for a specified file type
                   1943: 
                   1944: =cut
                   1945: 
                   1946: sub fileembstyle {
                   1947:     return $fe{lc(shift(@_))};
1.169     www      1948: }
                   1949: 
                   1950: 
                   1951: sub filecategoryselect {
                   1952:     my ($name,$value)=@_;
1.189     matthew  1953:     return &select_form($value,$name,
1.169     www      1954: 			'' => &mt('Any category'),
                   1955: 			map { $_,$_ } sort(keys(%category_extensions)));
1.112     bowersj2 1956: }
                   1957: 
                   1958: =pod
                   1959: 
                   1960: =item * filedescription() 
                   1961: 
                   1962: returns description for a specified file type
                   1963: 
                   1964: =cut
                   1965: 
                   1966: sub filedescription {
1.188     matthew  1967:     my $file_description = $fd{lc(shift())};
                   1968:     $file_description =~ s:([\[\]]):~$1:g;
                   1969:     return &mt($file_description);
1.112     bowersj2 1970: }
                   1971: 
                   1972: =pod
                   1973: 
                   1974: =item * filedescriptionex() 
                   1975: 
                   1976: returns description for a specified file type with
                   1977: extra formatting
                   1978: 
                   1979: =cut
                   1980: 
                   1981: sub filedescriptionex {
                   1982:     my $ex=shift;
1.188     matthew  1983:     my $file_description = $fd{lc($ex)};
                   1984:     $file_description =~ s:([\[\]]):~$1:g;
                   1985:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 1986: }
                   1987: 
                   1988: # End of .tab access
                   1989: =pod
                   1990: 
                   1991: =back
                   1992: 
                   1993: =cut
                   1994: 
                   1995: # ------------------------------------------------------------------ File Types
                   1996: sub fileextensions {
                   1997:     return sort(keys(%fe));
                   1998: }
                   1999: 
1.97      www      2000: # ----------------------------------------------------------- Display Languages
                   2001: # returns a hash with all desired display languages
                   2002: #
                   2003: 
                   2004: sub display_languages {
                   2005:     my %languages=();
1.118     www      2006:     foreach (&preferred_languages()) {
                   2007: 	$languages{$_}=1;
1.97      www      2008:     }
                   2009:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
                   2010:     if ($ENV{'form.displaylanguage'}) {
                   2011: 	foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
                   2012: 	    $languages{$_}=1;
                   2013:         }
                   2014:     }
                   2015:     return %languages;
1.14      harris41 2016: }
                   2017: 
1.117     www      2018: sub preferred_languages {
                   2019:     my @languages=();
                   2020:     if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
                   2021: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
                   2022: 	         $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1.177     www      2023:     }
                   2024:     if ($ENV{'environment.languages'}) {
                   2025: 	@languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
1.118     www      2026:     }
1.162     www      2027:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
                   2028:     if ($browser) {
                   2029: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
                   2030:     }
1.118     www      2031:     if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
                   2032: 	@languages=(@languages,
                   2033: 		$Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
                   2034:     }
                   2035:     if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
                   2036: 	@languages=(@languages,
                   2037: 		$Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
                   2038:     }
                   2039:     if ($Apache::lonnet::domain_lang_def{
                   2040: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
                   2041: 	@languages=(@languages,
                   2042: 		$Apache::lonnet::domain_lang_def{
                   2043:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
                   2044:     }
                   2045: # turn "en-ca" into "en-ca,en"
                   2046:     my @genlanguages;
                   2047:     foreach (@languages) {
                   2048: 	unless ($_=~/\w/) { next; }
                   2049: 	push (@genlanguages,$_);
                   2050: 	if ($_=~/(\-|\_)/) {
                   2051: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
                   2052: 	}
                   2053:     }
                   2054:     return @genlanguages;
1.117     www      2055: }
                   2056: 
1.112     bowersj2 2057: ###############################################################
                   2058: ##               Student Answer Attempts                     ##
                   2059: ###############################################################
                   2060: 
                   2061: =pod
                   2062: 
                   2063: =head1 Alternate Problem Views
                   2064: 
                   2065: =over 4
                   2066: 
                   2067: =item * get_previous_attempt($symb, $username, $domain, $course,
                   2068:     $getattempt, $regexp, $gradesub)
                   2069: 
                   2070: Return string with previous attempt on problem. Arguments:
                   2071: 
                   2072: =over 4
                   2073: 
                   2074: =item * $symb: Problem, including path
                   2075: 
                   2076: =item * $username: username of the desired student
                   2077: 
                   2078: =item * $domain: domain of the desired student
1.14      harris41 2079: 
1.112     bowersj2 2080: =item * $course: Course ID
1.14      harris41 2081: 
1.112     bowersj2 2082: =item * $getattempt: Leave blank for all attempts, otherwise put
                   2083:     something
1.14      harris41 2084: 
1.112     bowersj2 2085: =item * $regexp: if string matches this regexp, the string will be
                   2086:     sent to $gradesub
1.14      harris41 2087: 
1.112     bowersj2 2088: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 2089: 
1.112     bowersj2 2090: =back
1.14      harris41 2091: 
1.112     bowersj2 2092: The output string is a table containing all desired attempts, if any.
1.16      harris41 2093: 
1.112     bowersj2 2094: =cut
1.1       albertel 2095: 
                   2096: sub get_previous_attempt {
1.43      ng       2097:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 2098:   my $prevattempts='';
1.43      ng       2099:   no strict 'refs';
1.1       albertel 2100:   if ($symb) {
1.3       albertel 2101:     my (%returnhash)=
                   2102:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 2103:     if ($returnhash{'version'}) {
                   2104:       my %lasthash=();
                   2105:       my $version;
                   2106:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19      harris41 2107:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1       albertel 2108: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
1.19      harris41 2109:         }
1.1       albertel 2110:       }
1.43      ng       2111:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       2112:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16      harris41 2113:       foreach (sort(keys %lasthash)) {
1.31      albertel 2114: 	my ($ign,@parts) = split(/\./,$_);
1.41      ng       2115: 	if ($#parts > 0) {
1.31      albertel 2116: 	  my $data=$parts[-1];
                   2117: 	  pop(@parts);
1.40      ng       2118: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 2119: 	} else {
1.41      ng       2120: 	  if ($#parts == 0) {
                   2121: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   2122: 	  } else {
                   2123: 	    $prevattempts.='<th>'.$ign.'</th>';
                   2124: 	  }
1.31      albertel 2125: 	}
1.16      harris41 2126:       }
1.40      ng       2127:       if ($getattempt eq '') {
                   2128: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2129: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
                   2130: 	    foreach (sort(keys %lasthash)) {
                   2131: 	       my $value;
                   2132: 	       if ($_ =~ /timestamp/) {
                   2133: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
                   2134: 	       } else {
                   2135: 		  $value=$returnhash{$version.':'.$_};
                   2136: 	       }
1.142     albertel 2137: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
1.40      ng       2138: 	    }
                   2139: 	 }
1.1       albertel 2140:       }
1.40      ng       2141:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16      harris41 2142:       foreach (sort(keys %lasthash)) {
1.5       albertel 2143: 	my $value;
                   2144: 	if ($_ =~ /timestamp/) {
                   2145: 	  $value=scalar(localtime($lasthash{$_}));
                   2146: 	} else {
                   2147: 	  $value=$lasthash{$_};
                   2148: 	}
1.142     albertel 2149: 	$value=&Apache::lonnet::unescape($value);
1.49      ng       2150: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       2151: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 2152:       }
1.40      ng       2153:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 2154:     } else {
                   2155:       $prevattempts='Nothing submitted - no attempts.';
                   2156:     }
                   2157:   } else {
                   2158:     $prevattempts='No data.';
                   2159:   }
1.10      albertel 2160: }
                   2161: 
1.107     albertel 2162: sub relative_to_absolute {
                   2163:     my ($url,$output)=@_;
                   2164:     my $parser=HTML::TokeParser->new(\$output);
                   2165:     my $token;
                   2166:     my $thisdir=$url;
                   2167:     my @rlinks=();
                   2168:     while ($token=$parser->get_token) {
                   2169: 	if ($token->[0] eq 'S') {
                   2170: 	    if ($token->[1] eq 'a') {
                   2171: 		if ($token->[2]->{'href'}) {
                   2172: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   2173: 		}
                   2174: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   2175: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   2176: 	    } elsif ($token->[1] eq 'base') {
                   2177: 		$thisdir=$token->[2]->{'href'};
                   2178: 	    }
                   2179: 	}
                   2180:     }
                   2181:     $thisdir=~s-/[^/]*$--;
                   2182:     foreach (@rlinks) {
                   2183: 	unless (($_=~/^http:\/\//i) ||
                   2184: 		($_=~/^\//) ||
                   2185: 		($_=~/^javascript:/i) ||
                   2186: 		($_=~/^mailto:/i) ||
                   2187: 		($_=~/^\#/)) {
                   2188: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
                   2189: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
                   2190: 	}
                   2191:     }
                   2192: # -------------------------------------------------- Deal with Applet codebases
                   2193:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   2194:     return $output;
                   2195: }
                   2196: 
1.112     bowersj2 2197: =pod
                   2198: 
                   2199: =item * get_student_view
                   2200: 
                   2201: show a snapshot of what student was looking at
                   2202: 
                   2203: =cut
                   2204: 
1.10      albertel 2205: sub get_student_view {
1.186     albertel 2206:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      2207:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2208:   my (%form);
1.10      albertel 2209:   my @elements=('symb','courseid','domain','username');
                   2210:   foreach my $element (@elements) {
1.186     albertel 2211:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2212:   }
1.186     albertel 2213:   if (defined($moreenv)) {
                   2214:       %form=(%form,%{$moreenv});
                   2215:   }
                   2216:   if ($target eq 'tex') {$form{'grade_target'} = 'tex';}
1.107     albertel 2217:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.186     albertel 2218:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 2219:   $userview=~s/\<body[^\>]*\>//gi;
                   2220:   $userview=~s/\<\/body\>//gi;
                   2221:   $userview=~s/\<html\>//gi;
                   2222:   $userview=~s/\<\/html\>//gi;
                   2223:   $userview=~s/\<head\>//gi;
                   2224:   $userview=~s/\<\/head\>//gi;
                   2225:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 2226:   $userview=&relative_to_absolute($feedurl,$userview);
1.11      albertel 2227:   return $userview;
                   2228: }
                   2229: 
1.112     bowersj2 2230: =pod
                   2231: 
                   2232: =item * get_student_answers() 
                   2233: 
                   2234: show a snapshot of how student was answering problem
                   2235: 
                   2236: =cut
                   2237: 
1.11      albertel 2238: sub get_student_answers {
1.100     sakharuk 2239:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      2240:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 2241:   my (%moreenv);
1.11      albertel 2242:   my @elements=('symb','courseid','domain','username');
                   2243:   foreach my $element (@elements) {
1.186     albertel 2244:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 2245:   }
1.186     albertel 2246:   $moreenv{'grade_target'}='answer';
                   2247:   %moreenv=(%form,%moreenv);
                   2248:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
1.10      albertel 2249:   return $userview;
1.1       albertel 2250: }
1.116     albertel 2251: 
                   2252: =pod
                   2253: 
                   2254: =item * &submlink()
                   2255: 
                   2256: Inputs: $text $uname $udom $symb
                   2257: 
                   2258: Returns: A link to grades.pm such as to see the SUBM view of a student
                   2259: 
                   2260: =cut
                   2261: 
                   2262: ###############################################
                   2263: sub submlink {
                   2264:     my ($text,$uname,$udom,$symb)=@_;
                   2265:     if (!($uname && $udom)) {
                   2266: 	(my $cursymb, my $courseid,$udom,$uname)=
                   2267: 	    &Apache::lonxml::whichuser($symb);
                   2268: 	if (!$symb) { $symb=$cursymb; }
                   2269:     }
                   2270:     if (!$symb) { $symb=&symbread(); }
                   2271:     return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
                   2272: 	'&userdom='.$udom.'&command=submission">'.$text.'</a>';
                   2273: }
                   2274: ##############################################
1.37      matthew  2275: 
1.112     bowersj2 2276: =pod
                   2277: 
                   2278: =back
                   2279: 
                   2280: =cut
                   2281: 
1.37      matthew  2282: ###############################################
1.51      www      2283: 
                   2284: 
                   2285: sub timehash {
                   2286:     my @ltime=localtime(shift);
                   2287:     return ( 'seconds' => $ltime[0],
                   2288:              'minutes' => $ltime[1],
                   2289:              'hours'   => $ltime[2],
                   2290:              'day'     => $ltime[3],
                   2291:              'month'   => $ltime[4]+1,
                   2292:              'year'    => $ltime[5]+1900,
                   2293:              'weekday' => $ltime[6],
                   2294:              'dayyear' => $ltime[7]+1,
                   2295:              'dlsav'   => $ltime[8] );
                   2296: }
                   2297: 
                   2298: sub maketime {
                   2299:     my %th=@_;
                   2300:     return POSIX::mktime(
                   2301:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
                   2302:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1.70      www      2303: }
                   2304: 
                   2305: #########################################
1.51      www      2306: 
                   2307: sub findallcourses {
                   2308:     my %courses=();
                   2309:     my $now=time;
                   2310:     foreach (keys %ENV) {
                   2311: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
                   2312: 	    my ($starttime,$endtime)=$ENV{$_};
                   2313:             my $active=1;
                   2314:             if ($starttime) {
                   2315: 		if ($now<$starttime) { $active=0; }
                   2316:             }
                   2317:             if ($endtime) {
                   2318:                 if ($now>$endtime) { $active=0; }
                   2319:             }
                   2320:             if ($active) { $courses{$1.'_'.$2}=1; }
                   2321:         }
                   2322:     }
                   2323:     return keys %courses;
                   2324: }
1.37      matthew  2325: 
1.54      www      2326: ###############################################
1.60      matthew  2327: ###############################################
                   2328: 
                   2329: =pod
                   2330: 
1.112     bowersj2 2331: =head1 Domain Template Functions
                   2332: 
                   2333: =over 4
                   2334: 
                   2335: =item * &determinedomain()
1.60      matthew  2336: 
                   2337: Inputs: $domain (usually will be undef)
                   2338: 
1.63      www      2339: Returns: Determines which domain should be used for designs
1.60      matthew  2340: 
                   2341: =cut
1.54      www      2342: 
1.60      matthew  2343: ###############################################
1.63      www      2344: sub determinedomain {
                   2345:     my $domain=shift;
                   2346:    if (! $domain) {
1.60      matthew  2347:         # Determine domain if we have not been given one
                   2348:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   2349:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
                   2350:         if ($ENV{'request.role.domain'}) { 
                   2351:             $domain=$ENV{'request.role.domain'}; 
                   2352:         }
                   2353:     }
1.63      www      2354:     return $domain;
                   2355: }
                   2356: ###############################################
                   2357: =pod
                   2358: 
1.112     bowersj2 2359: =item * &domainlogo()
1.63      www      2360: 
                   2361: Inputs: $domain (usually will be undef)
                   2362: 
                   2363: Returns: A link to a domain logo, if the domain logo exists.
                   2364: If the domain logo does not exist, a description of the domain.
                   2365: 
                   2366: =cut
1.112     bowersj2 2367: 
1.63      www      2368: ###############################################
                   2369: sub domainlogo {
                   2370:     my $domain = &determinedomain(shift);    
                   2371:      # See if there is a logo
1.59      www      2372:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.83      albertel 2373: 	my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2374: 	if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
                   2375:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
1.150     matthew  2376: 	    '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
1.60      matthew  2377:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   2378:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      2379:     } else {
1.60      matthew  2380:         return '';
1.59      www      2381:     }
                   2382: }
1.63      www      2383: ##############################################
                   2384: 
                   2385: =pod
                   2386: 
1.112     bowersj2 2387: =item * &designparm()
1.63      www      2388: 
                   2389: Inputs: $which parameter; $domain (usually will be undef)
                   2390: 
                   2391: Returns: value of designparamter $which
                   2392: 
                   2393: =cut
1.112     bowersj2 2394: 
1.63      www      2395: ##############################################
                   2396: sub designparm {
                   2397:     my ($which,$domain)=@_;
1.110     www      2398:     if ($ENV{'browser.blackwhite'} eq 'on') {
                   2399: 	if ($which=~/\.(font|alink|vlink|link)$/) {
                   2400: 	    return '#000000';
                   2401: 	}
                   2402: 	if ($which=~/\.(pgbg|sidebg)$/) {
                   2403: 	    return '#FFFFFF';
                   2404: 	}
                   2405: 	if ($which=~/\.tabbg$/) {
                   2406: 	    return '#CCCCCC';
                   2407: 	}
                   2408:     }
1.96      www      2409:     if ($ENV{'environment.color.'.$which}) {
                   2410: 	return $ENV{'environment.color.'.$which};
                   2411:     }
1.63      www      2412:     $domain=&determinedomain($domain);
                   2413:     if ($designhash{$domain.'.'.$which}) {
                   2414: 	return $designhash{$domain.'.'.$which};
                   2415:     } else {
                   2416:         return $designhash{'default.'.$which};
                   2417:     }
                   2418: }
1.59      www      2419: 
1.60      matthew  2420: ###############################################
                   2421: ###############################################
                   2422: 
                   2423: =pod
                   2424: 
1.112     bowersj2 2425: =back
                   2426: 
                   2427: =head1 HTTP Helpers
                   2428: 
                   2429: =over 4
                   2430: 
                   2431: =item * &bodytag()
1.60      matthew  2432: 
                   2433: Returns a uniform header for LON-CAPA web pages.
                   2434: 
                   2435: Inputs: 
                   2436: 
1.112     bowersj2 2437: =over 4
                   2438: 
                   2439: =item * $title, A title to be displayed on the page.
                   2440: 
                   2441: =item * $function, the current role (can be undef).
                   2442: 
                   2443: =item * $addentries, extra parameters for the <body> tag.
                   2444: 
                   2445: =item * $bodyonly, if defined, only return the <body> tag.
                   2446: 
                   2447: =item * $domain, if defined, force a given domain.
                   2448: 
                   2449: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      2450:             text interface only)
1.60      matthew  2451: 
1.112     bowersj2 2452: =back
                   2453: 
1.60      matthew  2454: Returns: A uniform header for LON-CAPA web pages.  
                   2455: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   2456: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   2457: other decorations will be returned.
                   2458: 
                   2459: =cut
                   2460: 
1.54      www      2461: sub bodytag {
1.86      www      2462:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
1.117     www      2463:     $title=&mt($title);
1.183     matthew  2464:     $function = &get_users_function() if (!$function);
1.63      www      2465:     my $img=&designparm($function.'.img',$domain);
                   2466:     my $pgbg=&designparm($function.'.pgbg',$domain);
                   2467:     my $tabbg=&designparm($function.'.tabbg',$domain);
                   2468:     my $font=&designparm($function.'.font',$domain);
                   2469:     my $link=&designparm($function.'.link',$domain);
                   2470:     my $alink=&designparm($function.'.alink',$domain);
                   2471:     my $vlink=&designparm($function.'.vlink',$domain);
                   2472:     my $sidebg=&designparm($function.'.sidebg',$domain);
1.110     www      2473: # Accessibility font enhance
                   2474:     unless ($addentries) { $addentries=''; }
1.146     www      2475:     my $addstyle='';
1.110     www      2476:     if ($ENV{'browser.fontenhance'} eq 'on') {
1.146     www      2477: 	$addstyle=' font-size: x-large;';
1.110     www      2478:     }
1.63      www      2479:  # role and realm
1.55      www      2480:     my ($role,$realm)
                   2481:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
                   2482: # realm
1.54      www      2483:     if ($ENV{'request.course.id'}) {
1.55      www      2484: 	$realm=
                   2485:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54      www      2486:     }
1.55      www      2487:     unless ($realm) { $realm='&nbsp;'; }
                   2488: # Set messages
1.60      matthew  2489:     my $messages=&domainlogo($domain);
1.101     www      2490: # Port for miniserver
1.83      albertel 2491:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   2492:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1.101     www      2493: # construct main body tag
1.60      matthew  2494:     my $bodytag = <<END;
1.146     www      2495: <style>
1.147     www      2496: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
1.146     www      2497: a:focus { color: red; background: yellow } 
                   2498: </style>
1.54      www      2499: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
1.151     www      2500: style="margin-top: 0px;$addstyle" $addentries>
1.60      matthew  2501: END
1.94      www      2502:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
1.150     matthew  2503:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
1.60      matthew  2504:     if ($bodyonly) {
                   2505:         return $bodytag;
1.79      www      2506:     } elsif ($ENV{'browser.interface'} eq 'textual') {
1.95      www      2507: # Accessibility
1.93      www      2508:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2509:                                                       $forcereg).
                   2510:                '<h1>LON-CAPA: '.$title.'</h1>';
                   2511:     } elsif ($ENV{'environment.remote'} eq 'off') {
1.95      www      2512: # No Remote
                   2513:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
                   2514:                                                       $forcereg).
1.151     www      2515:       '<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      2516: '</b></font></td></tr></table>';
1.94      www      2517:     }
1.95      www      2518: 
1.93      www      2519: #
1.95      www      2520: # Top frame rendering, Remote is up
1.93      www      2521: #
1.94      www      2522:     return(<<ENDBODY);
1.60      matthew  2523: $bodytag
1.55      www      2524: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1.95      www      2525: <tr><td bgcolor="$sidebg">
1.94      www      2526: $upperleft</td>
1.95      www      2527: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
1.55      www      2528: </tr>
1.54      www      2529: <tr>
1.55      www      2530: <td rowspan="3" bgcolor="$tabbg">
1.146     www      2531: &nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
                   2532: <td bgcolor="$tabbg" align="right">
                   2533: <font size="2" face="Arial, Helvetica, sans-serif">
1.54      www      2534:     $ENV{'environment.firstname'}
                   2535:     $ENV{'environment.middlename'}
                   2536:     $ENV{'environment.lastname'}
                   2537:     $ENV{'environment.generation'}
1.55      www      2538:     </font>&nbsp;
1.54      www      2539: </td>
                   2540: </tr>
                   2541: <tr><td bgcolor="$tabbg" align="right">
1.146     www      2542: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
1.54      www      2543: </td></tr>
1.55      www      2544: <tr>
1.148     www      2545: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
1.54      www      2546: </table><br>
                   2547: ENDBODY
1.182     matthew  2548: }
                   2549: 
                   2550: ###############################################
                   2551: 
                   2552: =pod
                   2553: 
                   2554: =item get_users_function
                   2555: 
                   2556: Used by &bodytag to determine the current users primary role.
                   2557: Returns either 'student','coordinator','admin', or 'author'.
                   2558: 
                   2559: =cut
                   2560: 
                   2561: ###############################################
                   2562: sub get_users_function {
                   2563:     my $function = 'student';
                   2564:     if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   2565:         $function='coordinator';
                   2566:     }
                   2567:     if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   2568:         $function='admin';
                   2569:     }
                   2570:     if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   2571:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   2572:         $function='author';
                   2573:     }
                   2574:     return $function;
1.54      www      2575: }
1.99      www      2576: 
                   2577: ###############################################
                   2578: 
                   2579: sub get_posted_cgi {
                   2580:     my $r=shift;
                   2581: 
                   2582:     my $buffer;
                   2583:     
                   2584:     $r->read($buffer,$r->header_in('Content-length'),0);
                   2585:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
                   2586: 	my @pairs=split(/&/,$buffer);
                   2587: 	my $pair;
                   2588: 	foreach $pair (@pairs) {
                   2589: 	    my ($name,$value) = split(/=/,$pair);
                   2590: 	    $value =~ tr/+/ /;
                   2591: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2592: 	    $name  =~ tr/+/ /;
                   2593: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2594: 	    &add_to_env("form.$name",$value);
                   2595: 	}
                   2596:     } else {
                   2597: 	my $contentsep=$1;
                   2598: 	my @lines = split (/\n/,$buffer);
                   2599: 	my $name='';
                   2600: 	my $value='';
                   2601: 	my $fname='';
                   2602: 	my $fmime='';
                   2603: 	my $i;
                   2604: 	for ($i=0;$i<=$#lines;$i++) {
                   2605: 	    if ($lines[$i]=~/^$contentsep/) {
                   2606: 		if ($name) {
                   2607: 		    chomp($value);
                   2608: 		    if ($fname) {
                   2609: 			$ENV{"form.$name.filename"}=$fname;
                   2610: 			$ENV{"form.$name.mimetype"}=$fmime;
                   2611: 		    } else {
                   2612: 			$value=~s/\s+$//s;
                   2613: 		    }
                   2614: 		    &add_to_env("form.$name",$value);
                   2615: 		}
                   2616: 		if ($i<$#lines) {
                   2617: 		    $i++;
                   2618: 		    $lines[$i]=~
                   2619: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
                   2620: 		    $name=$1;
                   2621: 		    $value='';
                   2622: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
                   2623: 			$fname=$1;
                   2624: 			if 
                   2625:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
                   2626: 				$fmime=$1;
                   2627: 				$i++;
                   2628: 			    } else {
                   2629: 				$fmime='';
                   2630: 			    }
                   2631: 		    } else {
                   2632: 			$fname='';
                   2633: 			$fmime='';
                   2634: 		    }
                   2635: 		    $i++;
                   2636: 		}
                   2637: 	    } else {
                   2638: 		$value.=$lines[$i]."\n";
                   2639: 	    }
                   2640: 	}
                   2641:     }
                   2642:     $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
                   2643:     $r->method_number(M_GET);
                   2644:     $r->method('GET');
                   2645:     $r->headers_in->unset('Content-length');
                   2646: }
                   2647: 
1.112     bowersj2 2648: =pod
                   2649: 
                   2650: =item * get_unprocessed_cgi($query,$possible_names)
                   2651: 
                   2652: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   2653: $query.  The parameters listed in $possible_names (an array reference),
                   2654: will be set in $ENV{'form.name'} if they do not already exist.
                   2655: 
                   2656: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   2657: $possible_names is an ref to an array of form element names.  As an example:
                   2658: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2659: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
                   2660: 
                   2661: =cut
1.1       albertel 2662: 
1.6       albertel 2663: sub get_unprocessed_cgi {
1.25      albertel 2664:   my ($query,$possible_names)= @_;
1.26      matthew  2665:   # $Apache::lonxml::debug=1;
1.16      harris41 2666:   foreach (split(/&/,$query)) {
1.6       albertel 2667:     my ($name, $value) = split(/=/,$_);
1.25      albertel 2668:     $name = &Apache::lonnet::unescape($name);
                   2669:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   2670:       $value =~ tr/+/ /;
                   2671:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   2672:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 2673:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 2674:     }
1.16      harris41 2675:   }
1.6       albertel 2676: }
                   2677: 
1.112     bowersj2 2678: =pod
                   2679: 
                   2680: =item * cacheheader() 
                   2681: 
                   2682: returns cache-controlling header code
                   2683: 
                   2684: =cut
                   2685: 
1.7       albertel 2686: sub cacheheader {
1.23      www      2687:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.8       albertel 2688:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.7       albertel 2689:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
                   2690:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   2691:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
                   2692:   return $output;
                   2693: }
                   2694: 
1.112     bowersj2 2695: =pod
                   2696: 
                   2697: =item * no_cache($r) 
                   2698: 
                   2699: specifies header code to not have cache
                   2700: 
                   2701: =cut
                   2702: 
1.9       albertel 2703: sub no_cache {
                   2704:   my ($r) = @_;
1.23      www      2705:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.24      albertel 2706:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.9       albertel 2707:   $r->no_cache(1);
                   2708:   $r->header_out("Pragma" => "no-cache");
1.24      albertel 2709:   #$r->header_out("Expires" => $date);
1.123     www      2710: }
                   2711: 
                   2712: sub content_type {
1.181     albertel 2713:     my ($r,$type,$charset) = @_;
                   2714:     unless ($charset) {
                   2715: 	$charset=&Apache::lonlocal::current_encoding;
                   2716:     }
                   2717:     if ($charset) { $type.='; charset='.$charset; }
                   2718:     if ($r) {
                   2719: 	$r->content_type($type);
                   2720:     } else {
                   2721: 	print("Content-type: $type\n\n");
                   2722:     }
1.9       albertel 2723: }
1.25      albertel 2724: 
1.112     bowersj2 2725: =pod
                   2726: 
                   2727: =item * add_to_env($name,$value) 
                   2728: 
                   2729: adds $name to the %ENV hash with value
                   2730: $value, if $name already exists, the entry is converted to an array
                   2731: reference and $value is added to the array.
                   2732: 
                   2733: =cut
                   2734: 
1.25      albertel 2735: sub add_to_env {
                   2736:   my ($name,$value)=@_;
1.28      albertel 2737:   if (defined($ENV{$name})) {
1.27      albertel 2738:     if (ref($ENV{$name})) {
1.25      albertel 2739:       #already have multiple values
                   2740:       push(@{ $ENV{$name} },$value);
                   2741:     } else {
                   2742:       #first time seeing multiple values, convert hash entry to an arrayref
                   2743:       my $first=$ENV{$name};
                   2744:       undef($ENV{$name});
                   2745:       push(@{ $ENV{$name} },$first,$value);
                   2746:     }
                   2747:   } else {
                   2748:     $ENV{$name}=$value;
                   2749:   }
1.31      albertel 2750: }
1.149     albertel 2751: 
                   2752: =pod
                   2753: 
                   2754: =item * get_env_multiple($name) 
                   2755: 
                   2756: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
                   2757: values may be defined and end up as an array ref.
                   2758: 
                   2759: returns an array of values
                   2760: 
                   2761: =cut
                   2762: 
                   2763: sub get_env_multiple {
                   2764:     my ($name) = @_;
                   2765:     my @values;
                   2766:     if (defined($ENV{$name})) {
                   2767:         # exists is it an array
                   2768:         if (ref($ENV{$name})) {
                   2769:             @values=@{ $ENV{$name} };
                   2770:         } else {
                   2771:             $values[0]=$ENV{$name};
                   2772:         }
                   2773:     }
                   2774:     return(@values);
                   2775: }
                   2776: 
1.31      albertel 2777: 
1.41      ng       2778: =pod
1.45      matthew  2779: 
                   2780: =back 
1.41      ng       2781: 
1.112     bowersj2 2782: =head1 CSV Upload/Handling functions
1.38      albertel 2783: 
1.41      ng       2784: =over 4
                   2785: 
1.112     bowersj2 2786: =item * upfile_store($r)
1.41      ng       2787: 
                   2788: Store uploaded file, $r should be the HTTP Request object,
                   2789: needs $ENV{'form.upfile'}
                   2790: returns $datatoken to be put into hidden field
                   2791: 
                   2792: =cut
1.31      albertel 2793: 
                   2794: sub upfile_store {
                   2795:     my $r=shift;
                   2796:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   2797:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   2798:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   2799:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   2800: 
                   2801:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   2802: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   2803:     {
1.158     raeburn  2804:         my $datafile = $r->dir_config('lonDaemons').
                   2805:                            '/tmp/'.$datatoken.'.tmp';
                   2806:         if ( open(my $fh,">$datafile") ) {
                   2807:             print $fh $ENV{'form.upfile'};
                   2808:             close($fh);
                   2809:         }
1.31      albertel 2810:     }
                   2811:     return $datatoken;
                   2812: }
                   2813: 
1.56      matthew  2814: =pod
                   2815: 
1.112     bowersj2 2816: =item * load_tmp_file($r)
1.41      ng       2817: 
                   2818: Load uploaded file from tmp, $r should be the HTTP Request object,
                   2819: needs $ENV{'form.datatoken'},
                   2820: sets $ENV{'form.upfile'} to the contents of the file
                   2821: 
                   2822: =cut
1.31      albertel 2823: 
                   2824: sub load_tmp_file {
                   2825:     my $r=shift;
                   2826:     my @studentdata=();
                   2827:     {
1.158     raeburn  2828:         my $studentfile = $r->dir_config('lonDaemons').
                   2829:                               '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
                   2830:         if ( open(my $fh,"<$studentfile") ) {
                   2831:             @studentdata=<$fh>;
                   2832:             close($fh);
                   2833:         }
1.31      albertel 2834:     }
                   2835:     $ENV{'form.upfile'}=join('',@studentdata);
                   2836: }
                   2837: 
1.56      matthew  2838: =pod
                   2839: 
1.112     bowersj2 2840: =item * upfile_record_sep()
1.41      ng       2841: 
                   2842: Separate uploaded file into records
                   2843: returns array of records,
                   2844: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   2845: 
                   2846: =cut
1.31      albertel 2847: 
                   2848: sub upfile_record_sep {
                   2849:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2850:     } else {
                   2851: 	return split(/\n/,$ENV{'form.upfile'});
                   2852:     }
                   2853: }
                   2854: 
1.56      matthew  2855: =pod
                   2856: 
1.112     bowersj2 2857: =item * record_sep($record)
1.41      ng       2858: 
                   2859: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   2860: 
                   2861: =cut
                   2862: 
1.31      albertel 2863: sub record_sep {
                   2864:     my $record=shift;
                   2865:     my %components=();
                   2866:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   2867:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   2868:         my $i=0;
                   2869:         foreach (split(/\s+/,$record)) {
                   2870:             my $field=$_;
                   2871:             $field=~s/^(\"|\')//;
                   2872:             $field=~s/(\"|\')$//;
                   2873:             $components{$i}=$field;
                   2874:             $i++;
                   2875:         }
                   2876:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   2877:         my $i=0;
1.171     matthew  2878:         foreach (split(/\t/,$record)) {
1.31      albertel 2879:             my $field=$_;
                   2880:             $field=~s/^(\"|\')//;
                   2881:             $field=~s/(\"|\')$//;
                   2882:             $components{$i}=$field;
                   2883:             $i++;
                   2884:         }
                   2885:     } else {
                   2886:         my @allfields=split(/\,/,$record);
                   2887:         my $i=0;
                   2888:         my $j;
                   2889:         for ($j=0;$j<=$#allfields;$j++) {
                   2890:             my $field=$allfields[$j];
                   2891:             if ($field=~/^\s*(\"|\')/) {
                   2892: 		my $delimiter=$1;
                   2893:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   2894: 		    $j++;
                   2895: 		    $field.=','.$allfields[$j];
                   2896: 		}
                   2897:                 $field=~s/^\s*$delimiter//;
                   2898:                 $field=~s/$delimiter\s*$//;
                   2899:             }
                   2900:             $components{$i}=$field;
                   2901: 	    $i++;
                   2902:         }
                   2903:     }
                   2904:     return %components;
                   2905: }
                   2906: 
1.144     matthew  2907: ######################################################
                   2908: ######################################################
                   2909: 
1.56      matthew  2910: =pod
                   2911: 
1.112     bowersj2 2912: =item * upfile_select_html()
1.41      ng       2913: 
1.144     matthew  2914: Return HTML code to select a file from the users machine and specify 
                   2915: the file type.
1.41      ng       2916: 
                   2917: =cut
                   2918: 
1.144     matthew  2919: ######################################################
                   2920: ######################################################
1.31      albertel 2921: sub upfile_select_html {
1.144     matthew  2922:     my %Types = (
                   2923:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
                   2924:                  space => &mt('Space separated'),
                   2925:                  tab   => &mt('Tabulator separated'),
                   2926: #                 xml   => &mt('HTML/XML'),
                   2927:                  );
                   2928:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   2929:         '<br />Type: <select name="upfiletype">';
                   2930:     foreach my $type (sort(keys(%Types))) {
                   2931:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   2932:     }
                   2933:     $Str .= "</select>\n";
                   2934:     return $Str;
1.31      albertel 2935: }
                   2936: 
1.144     matthew  2937: ######################################################
                   2938: ######################################################
                   2939: 
1.56      matthew  2940: =pod
                   2941: 
1.112     bowersj2 2942: =item * csv_print_samples($r,$records)
1.41      ng       2943: 
                   2944: Prints a table of sample values from each column uploaded $r is an
                   2945: Apache Request ref, $records is an arrayref from
                   2946: &Apache::loncommon::upfile_record_sep
                   2947: 
                   2948: =cut
                   2949: 
1.144     matthew  2950: ######################################################
                   2951: ######################################################
1.31      albertel 2952: sub csv_print_samples {
                   2953:     my ($r,$records) = @_;
                   2954:     my (%sone,%stwo,%sthree);
                   2955:     %sone=&record_sep($$records[0]);
                   2956:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   2957:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  2958:     #
                   2959:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
                   2960:     foreach (sort({$a <=> $b} keys(%sone))) { 
                   2961:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
1.31      albertel 2962:     $r->print('</tr>');
                   2963:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   2964: 	$r->print('<tr>');
                   2965: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   2966: 	    $r->print('<td>');
                   2967: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   2968: 	    $r->print('</td>');
                   2969: 	}
                   2970: 	$r->print('</tr>');
                   2971:     }
                   2972:     $r->print('</tr></table><br />'."\n");
                   2973: }
                   2974: 
1.144     matthew  2975: ######################################################
                   2976: ######################################################
                   2977: 
1.56      matthew  2978: =pod
                   2979: 
1.112     bowersj2 2980: =item * csv_print_select_table($r,$records,$d)
1.41      ng       2981: 
                   2982: Prints a table to create associations between values and table columns.
1.144     matthew  2983: 
1.41      ng       2984: $r is an Apache Request ref,
                   2985: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  2986: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       2987: 
                   2988: =cut
                   2989: 
1.144     matthew  2990: ######################################################
                   2991: ######################################################
1.31      albertel 2992: sub csv_print_select_table {
                   2993:     my ($r,$records,$d) = @_;
                   2994:     my $i=0;my %sone;
                   2995:     %sone=&record_sep($$records[0]);
1.144     matthew  2996:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   2997: 	     '<table border="2"><tr>'.
                   2998:               '<th>'.&mt('Attribute').'</th>'.
                   2999:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.31      albertel 3000:     foreach (@$d) {
1.174     matthew  3001: 	my ($value,$display,$defaultcol)=@{ $_ };
1.31      albertel 3002: 	$r->print('<tr><td>'.$display.'</td>');
                   3003: 
                   3004: 	$r->print('<td><select name=f'.$i.
1.32      matthew  3005: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3006: 	$r->print('<option value="none"></option>');
                   3007: 	foreach (sort({$a <=> $b} keys(%sone))) {
1.174     matthew  3008: 	    $r->print('<option value="'.$_.'"'.
                   3009:                       ($_ eq $defaultcol ? ' selected ' : '').
                   3010:                       '>Column '.($_+1).'</option>');
1.31      albertel 3011: 	}
                   3012: 	$r->print('</select></td></tr>'."\n");
                   3013: 	$i++;
                   3014:     }
                   3015:     $i--;
                   3016:     return $i;
                   3017: }
1.56      matthew  3018: 
1.144     matthew  3019: ######################################################
                   3020: ######################################################
                   3021: 
1.56      matthew  3022: =pod
1.31      albertel 3023: 
1.112     bowersj2 3024: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       3025: 
                   3026: Prints a table of sample values from the upload and can make associate samples to internal names.
                   3027: 
                   3028: $r is an Apache Request ref,
                   3029: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   3030: $d is an array of 2 element arrays (internal name, displayed name)
                   3031: 
                   3032: =cut
                   3033: 
1.144     matthew  3034: ######################################################
                   3035: ######################################################
1.31      albertel 3036: sub csv_samples_select_table {
                   3037:     my ($r,$records,$d) = @_;
                   3038:     my %sone; my %stwo; my %sthree;
                   3039:     my $i=0;
1.144     matthew  3040:     #
                   3041:     $r->print('<table border=2><tr><th>'.
                   3042:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.31      albertel 3043:     %sone=&record_sep($$records[0]);
                   3044:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   3045:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1.144     matthew  3046:     #
1.31      albertel 3047:     foreach (sort keys %sone) {
1.144     matthew  3048: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  3049: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 3050: 	foreach (@$d) {
1.174     matthew  3051: 	    my ($value,$display,$defaultcol)=@{ $_ };
                   3052: 	    $r->print('<option value="'.$value.'"'.
                   3053:                       ($i eq $defaultcol ? ' selected ':'').'>'.
                   3054:                       $display.'</option>');
1.31      albertel 3055: 	}
                   3056: 	$r->print('</select></td><td>');
                   3057: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   3058: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   3059: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   3060: 	$r->print('</td></tr>');
                   3061: 	$i++;
                   3062:     }
                   3063:     $i--;
                   3064:     return($i);
1.115     matthew  3065: }
                   3066: 
1.144     matthew  3067: ######################################################
                   3068: ######################################################
                   3069: 
1.115     matthew  3070: =pod
                   3071: 
                   3072: =item clean_excel_name($name)
                   3073: 
                   3074: Returns a replacement for $name which does not contain any illegal characters.
                   3075: 
                   3076: =cut
                   3077: 
1.144     matthew  3078: ######################################################
                   3079: ######################################################
1.115     matthew  3080: sub clean_excel_name {
                   3081:     my ($name) = @_;
                   3082:     $name =~ s/[:\*\?\/\\]//g;
                   3083:     if (length($name) > 31) {
                   3084:         $name = substr($name,0,31);
                   3085:     }
                   3086:     return $name;
1.25      albertel 3087: }
1.84      albertel 3088: 
1.85      albertel 3089: =pod
                   3090: 
1.112     bowersj2 3091: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 3092: 
                   3093: Returns either 1 or undef
                   3094: 
                   3095: 1 if the part is to be hidden, undef if it is to be shown
                   3096: 
                   3097: Arguments are:
                   3098: 
                   3099: $id the id of the part to be checked
                   3100: $symb, optional the symb of the resource to check
                   3101: $udom, optional the domain of the user to check for
                   3102: $uname, optional the username of the user to check for
                   3103: 
                   3104: =cut
1.84      albertel 3105: 
                   3106: sub check_if_partid_hidden {
                   3107:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 3108:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 3109: 					 $symb,$udom,$uname);
1.141     albertel 3110:     my $truth=1;
                   3111:     #if the string starts with !, then the list is the list to show not hide
                   3112:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 3113:     my @hiddenlist=split(/,/,$hiddenparts);
                   3114:     foreach my $checkid (@hiddenlist) {
1.141     albertel 3115: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 3116:     }
1.141     albertel 3117:     return !$truth;
1.84      albertel 3118: }
1.127     matthew  3119: 
1.138     matthew  3120: 
                   3121: ############################################################
                   3122: ############################################################
                   3123: 
                   3124: =pod
                   3125: 
1.157     matthew  3126: =back 
                   3127: 
1.138     matthew  3128: =head1 cgi-bin script and graphing routines
                   3129: 
1.157     matthew  3130: =over 4
                   3131: 
1.138     matthew  3132: =item get_cgi_id
                   3133: 
                   3134: Inputs: none
                   3135: 
                   3136: Returns an id which can be used to pass environment variables
                   3137: to various cgi-bin scripts.  These environment variables will
                   3138: be removed from the users environment after a given time by
                   3139: the routine &Apache::lonnet::transfer_profile_to_env.
                   3140: 
                   3141: =cut
                   3142: 
                   3143: ############################################################
                   3144: ############################################################
1.152     albertel 3145: my $uniq=0;
1.136     matthew  3146: sub get_cgi_id {
1.154     albertel 3147:     $uniq=($uniq+1)%100000;
1.152     albertel 3148:     return (time.'_'.$uniq);
1.136     matthew  3149: }
                   3150: 
1.127     matthew  3151: ############################################################
                   3152: ############################################################
                   3153: 
                   3154: =pod
                   3155: 
1.134     matthew  3156: =item DrawBarGraph
1.127     matthew  3157: 
1.138     matthew  3158: Facilitates the plotting of data in a (stacked) bar graph.
                   3159: Puts plot definition data into the users environment in order for 
                   3160: graph.png to plot it.  Returns an <img> tag for the plot.
                   3161: The bars on the plot are labeled '1','2',...,'n'.
                   3162: 
                   3163: Inputs:
                   3164: 
                   3165: =over 4
                   3166: 
                   3167: =item $Title: string, the title of the plot
                   3168: 
                   3169: =item $xlabel: string, text describing the X-axis of the plot
                   3170: 
                   3171: =item $ylabel: string, text describing the Y-axis of the plot
                   3172: 
                   3173: =item $Max: scalar, the maximum Y value to use in the plot
                   3174: If $Max is < any data point, the graph will not be rendered.
                   3175: 
1.140     matthew  3176: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  3177: they are plotted.  If undefined, default values will be used.
                   3178: 
1.178     matthew  3179: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   3180: 
1.138     matthew  3181: =item @Values: An array of array references.  Each array reference holds data
                   3182: to be plotted in a stacked bar chart.
                   3183: 
                   3184: =back
                   3185: 
                   3186: Returns:
                   3187: 
                   3188: An <img> tag which references graph.png and the appropriate identifying
                   3189: information for the plot.
                   3190: 
1.127     matthew  3191: =cut
                   3192: 
                   3193: ############################################################
                   3194: ############################################################
1.134     matthew  3195: sub DrawBarGraph {
1.178     matthew  3196:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  3197:     #
                   3198:     if (! defined($colors)) {
                   3199:         $colors = ['#33ff00', 
                   3200:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   3201:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   3202:                   ]; 
                   3203:     }
1.127     matthew  3204:     #
1.136     matthew  3205:     my $identifier = &get_cgi_id();
                   3206:     my $id = 'cgi.'.$identifier;        
1.129     matthew  3207:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  3208:         return '';
                   3209:     }
1.129     matthew  3210:     my $NumBars = scalar(@{$Values[0]});
                   3211:     my %ValuesHash;
                   3212:     my $NumSets=1;
                   3213:     foreach my $array (@Values) {
                   3214:         next if (! ref($array));
1.136     matthew  3215:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  3216:             join(',',@$array);
1.129     matthew  3217:     }
1.127     matthew  3218:     #
1.136     matthew  3219:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
                   3220:     if ($NumBars < 10) {
                   3221:         $width = 120+$NumBars*15;
                   3222:         $xskip = 1;
                   3223:         $bar_width = 15;
                   3224:     } elsif ($NumBars <= 25) {
                   3225:         $width = 120+$NumBars*11;
                   3226:         $xskip = 5;
                   3227:         $bar_width = 8;
                   3228:     } elsif ($NumBars <= 50) {
                   3229:         $width = 120+$NumBars*8;
                   3230:         $xskip = 5;
                   3231:         $bar_width = 4;
                   3232:     } else {
                   3233:         $width = 120+$NumBars*8;
                   3234:         $xskip = 5;
                   3235:         $bar_width = 4;
                   3236:     }
                   3237:     #
                   3238:     my @Labels;
1.178     matthew  3239:     if (defined($labels)) {
                   3240:         @Labels = @$labels;
                   3241:     } else {
                   3242:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   3243:             push (@Labels,$i+1);
                   3244:         }
1.136     matthew  3245:     }
                   3246:     #
1.137     matthew  3247:     $Max = 1 if ($Max < 1);
                   3248:     if ( int($Max) < $Max ) {
                   3249:         $Max++;
                   3250:         $Max = int($Max);
                   3251:     }
1.127     matthew  3252:     $Title  = '' if (! defined($Title));
                   3253:     $xlabel = '' if (! defined($xlabel));
                   3254:     $ylabel = '' if (! defined($ylabel));
1.136     matthew  3255:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
                   3256:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
                   3257:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
1.137     matthew  3258:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  3259:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   3260:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   3261:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   3262:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3263:     $ValuesHash{$id.'.height'}   = $height;
                   3264:     $ValuesHash{$id.'.width'}    = $width;
                   3265:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   3266:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   3267:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  3268:     #
1.137     matthew  3269:     &Apache::lonnet::appenv(%ValuesHash);
                   3270:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3271: }
                   3272: 
                   3273: ############################################################
                   3274: ############################################################
                   3275: 
                   3276: =pod
                   3277: 
                   3278: =item DrawXYGraph
                   3279: 
1.138     matthew  3280: Facilitates the plotting of data in an XY graph.
                   3281: Puts plot definition data into the users environment in order for 
                   3282: graph.png to plot it.  Returns an <img> tag for the plot.
                   3283: 
                   3284: Inputs:
                   3285: 
                   3286: =over 4
                   3287: 
                   3288: =item $Title: string, the title of the plot
                   3289: 
                   3290: =item $xlabel: string, text describing the X-axis of the plot
                   3291: 
                   3292: =item $ylabel: string, text describing the Y-axis of the plot
                   3293: 
                   3294: =item $Max: scalar, the maximum Y value to use in the plot
                   3295: If $Max is < any data point, the graph will not be rendered.
                   3296: 
                   3297: =item $colors: Array ref containing the hex color codes for the data to be 
                   3298: plotted in.  If undefined, default values will be used.
                   3299: 
                   3300: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3301: 
                   3302: =item $Ydata: Array ref containing Array refs.  
1.185     www      3303: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  3304: 
                   3305: =item %Values: hash indicating or overriding any default values which are 
                   3306: passed to graph.png.  
                   3307: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3308: 
                   3309: =back
                   3310: 
                   3311: Returns:
                   3312: 
                   3313: An <img> tag which references graph.png and the appropriate identifying
                   3314: information for the plot.
                   3315: 
1.137     matthew  3316: =cut
                   3317: 
                   3318: ############################################################
                   3319: ############################################################
                   3320: sub DrawXYGraph {
                   3321:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   3322:     #
                   3323:     # Create the identifier for the graph
                   3324:     my $identifier = &get_cgi_id();
                   3325:     my $id = 'cgi.'.$identifier;
                   3326:     #
                   3327:     $Title  = '' if (! defined($Title));
                   3328:     $xlabel = '' if (! defined($xlabel));
                   3329:     $ylabel = '' if (! defined($ylabel));
                   3330:     my %ValuesHash = 
                   3331:         (
                   3332:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3333:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3334:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3335:          $id.'.y_max_value'=> $Max,
                   3336:          $id.'.labels'     => join(',',@$Xlabels),
                   3337:          $id.'.PlotType'   => 'XY',
                   3338:          );
                   3339:     #
                   3340:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3341:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3342:     }
                   3343:     #
                   3344:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   3345:         return '';
                   3346:     }
                   3347:     my $NumSets=1;
1.138     matthew  3348:     foreach my $array (@{$Ydata}){
1.137     matthew  3349:         next if (! ref($array));
                   3350:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   3351:     }
1.138     matthew  3352:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  3353:     #
                   3354:     # Deal with other parameters
                   3355:     while (my ($key,$value) = each(%Values)) {
                   3356:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  3357:     }
                   3358:     #
1.136     matthew  3359:     &Apache::lonnet::appenv(%ValuesHash);
                   3360:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   3361: }
                   3362: 
                   3363: ############################################################
                   3364: ############################################################
                   3365: 
                   3366: =pod
                   3367: 
1.138     matthew  3368: =item DrawXYYGraph
                   3369: 
                   3370: Facilitates the plotting of data in an XY graph with two Y axes.
                   3371: Puts plot definition data into the users environment in order for 
                   3372: graph.png to plot it.  Returns an <img> tag for the plot.
                   3373: 
                   3374: Inputs:
                   3375: 
                   3376: =over 4
                   3377: 
                   3378: =item $Title: string, the title of the plot
                   3379: 
                   3380: =item $xlabel: string, text describing the X-axis of the plot
                   3381: 
                   3382: =item $ylabel: string, text describing the Y-axis of the plot
                   3383: 
                   3384: =item $colors: Array ref containing the hex color codes for the data to be 
                   3385: plotted in.  If undefined, default values will be used.
                   3386: 
                   3387: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   3388: 
                   3389: =item $Ydata1: The first data set
                   3390: 
                   3391: =item $Min1: The minimum value of the left Y-axis
                   3392: 
                   3393: =item $Max1: The maximum value of the left Y-axis
                   3394: 
                   3395: =item $Ydata2: The second data set
                   3396: 
                   3397: =item $Min2: The minimum value of the right Y-axis
                   3398: 
                   3399: =item $Max2: The maximum value of the left Y-axis
                   3400: 
                   3401: =item %Values: hash indicating or overriding any default values which are 
                   3402: passed to graph.png.  
                   3403: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   3404: 
                   3405: =back
                   3406: 
                   3407: Returns:
                   3408: 
                   3409: An <img> tag which references graph.png and the appropriate identifying
                   3410: information for the plot.
1.136     matthew  3411: 
                   3412: =cut
                   3413: 
                   3414: ############################################################
                   3415: ############################################################
1.137     matthew  3416: sub DrawXYYGraph {
                   3417:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   3418:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  3419:     #
                   3420:     # Create the identifier for the graph
                   3421:     my $identifier = &get_cgi_id();
                   3422:     my $id = 'cgi.'.$identifier;
                   3423:     #
                   3424:     $Title  = '' if (! defined($Title));
                   3425:     $xlabel = '' if (! defined($xlabel));
                   3426:     $ylabel = '' if (! defined($ylabel));
                   3427:     my %ValuesHash = 
                   3428:         (
                   3429:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   3430:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   3431:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   3432:          $id.'.labels' => join(',',@$Xlabels),
                   3433:          $id.'.PlotType' => 'XY',
                   3434:          $id.'.NumSets' => 2,
1.137     matthew  3435:          $id.'.two_axes' => 1,
                   3436:          $id.'.y1_max_value' => $Max1,
                   3437:          $id.'.y1_min_value' => $Min1,
                   3438:          $id.'.y2_max_value' => $Max2,
                   3439:          $id.'.y2_min_value' => $Min2,
1.136     matthew  3440:          );
                   3441:     #
1.137     matthew  3442:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   3443:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   3444:     }
                   3445:     #
                   3446:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   3447:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  3448:         return '';
                   3449:     }
                   3450:     my $NumSets=1;
1.137     matthew  3451:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  3452:         next if (! ref($array));
                   3453:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  3454:     }
                   3455:     #
                   3456:     # Deal with other parameters
                   3457:     while (my ($key,$value) = each(%Values)) {
                   3458:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  3459:     }
                   3460:     #
                   3461:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 3462:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  3463: }
                   3464: 
                   3465: ############################################################
                   3466: ############################################################
                   3467: 
                   3468: =pod
                   3469: 
1.157     matthew  3470: =back 
                   3471: 
1.139     matthew  3472: =head1 Statistics helper routines?  
                   3473: 
                   3474: Bad place for them but what the hell.
                   3475: 
1.157     matthew  3476: =over 4
                   3477: 
1.139     matthew  3478: =item &chartlink
                   3479: 
                   3480: Returns a link to the chart for a specific student.  
                   3481: 
                   3482: Inputs:
                   3483: 
                   3484: =over 4
                   3485: 
                   3486: =item $linktext: The text of the link
                   3487: 
                   3488: =item $sname: The students username
                   3489: 
                   3490: =item $sdomain: The students domain
                   3491: 
                   3492: =back
                   3493: 
1.157     matthew  3494: =back
                   3495: 
1.139     matthew  3496: =cut
                   3497: 
                   3498: ############################################################
                   3499: ############################################################
                   3500: sub chartlink {
                   3501:     my ($linktext, $sname, $sdomain) = @_;
                   3502:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
                   3503:         '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
                   3504:         '&chartoutputmode='.HTML::Entities::encode('html, with all links').
                   3505:        '">'.$linktext.'</a>';
1.153     matthew  3506: }
                   3507: 
                   3508: #######################################################
                   3509: #######################################################
                   3510: 
                   3511: =pod
                   3512: 
                   3513: =head1 Course Environment Routines
1.157     matthew  3514: 
                   3515: =over 4
1.153     matthew  3516: 
                   3517: =item &restore_course_settings 
                   3518: 
                   3519: =item &store_course_settings
                   3520: 
                   3521: Restores/Store indicated form parameters from the course environment.
                   3522: Will not overwrite existing values of the form parameters.
                   3523: 
                   3524: Inputs: 
                   3525: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   3526: 
                   3527: a hash ref describing the data to be stored.  For example:
                   3528:    
                   3529: %Save_Parameters = ('Status' => 'scalar',
                   3530:     'chartoutputmode' => 'scalar',
                   3531:     'chartoutputdata' => 'scalar',
                   3532:     'Section' => 'array',
                   3533:     'StudentData' => 'array',
                   3534:     'Maps' => 'array');
                   3535: 
                   3536: Returns: both routines return nothing
                   3537: 
                   3538: =cut
                   3539: 
                   3540: #######################################################
                   3541: #######################################################
                   3542: sub store_course_settings {
                   3543:     # save to the environment
                   3544:     # appenv the same items, just to be safe
                   3545:     my $courseid = $ENV{'request.course.id'};
                   3546:     my $coursedom = $ENV{'course.'.$courseid.'.domain'};
                   3547:     my ($prefix,$Settings) = @_;
                   3548:     my %SaveHash;
                   3549:     my %AppHash;
                   3550:     while (my ($setting,$type) = each(%$Settings)) {
1.176     albertel 3551:         my $basename = 'internal.'.$prefix.'.'.$setting;
1.153     matthew  3552:         my $envname = 'course.'.$courseid.'.'.$basename;
                   3553:         if (exists($ENV{'form.'.$setting})) {
                   3554:             # Save this value away
                   3555:             if ($type eq 'scalar' &&
                   3556:                 (! exists($ENV{$envname}) || 
                   3557:                  $ENV{$envname} ne $ENV{'form.'.$setting})) {
                   3558:                 $SaveHash{$basename} = $ENV{'form.'.$setting};
                   3559:                 $AppHash{$envname}   = $ENV{'form.'.$setting};
                   3560:             } elsif ($type eq 'array') {
                   3561:                 my $stored_form;
                   3562:                 if (ref($ENV{'form.'.$setting})) {
                   3563:                     $stored_form = join(',',
                   3564:                                         map {
                   3565:                                             &Apache::lonnet::escape($_);
                   3566:                                         } sort(@{$ENV{'form.'.$setting}}));
                   3567:                 } else {
                   3568:                     $stored_form = 
                   3569:                         &Apache::lonnet::escape($ENV{'form.'.$setting});
                   3570:                 }
                   3571:                 # Determine if the array contents are the same.
                   3572:                 if ($stored_form ne $ENV{$envname}) {
                   3573:                     $SaveHash{$basename} = $stored_form;
                   3574:                     $AppHash{$envname}   = $stored_form;
                   3575:                 }
                   3576:             }
                   3577:         }
                   3578:     }
                   3579:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
                   3580:                                           $coursedom,
                   3581:                                           $ENV{'course.'.$courseid.'.num'});
                   3582:     if ($put_result !~ /^(ok|delayed)/) {
                   3583:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   3584:                                  'got error:'.$put_result);
                   3585:     }
                   3586:     # Make sure these settings stick around in this session, too
                   3587:     &Apache::lonnet::appenv(%AppHash);
                   3588:     return;
                   3589: }
                   3590: 
                   3591: sub restore_course_settings {
                   3592:     my $courseid = $ENV{'request.course.id'};
                   3593:     my ($prefix,$Settings) = @_;
                   3594:     while (my ($setting,$type) = each(%$Settings)) {
                   3595:         next if (exists($ENV{'form.'.$setting}));
1.176     albertel 3596:         my $envname = 'course.'.$courseid.'.internal.'.$prefix.
1.153     matthew  3597:             '.'.$setting;
                   3598:         if (exists($ENV{$envname})) {
                   3599:             if ($type eq 'scalar') {
                   3600:                 $ENV{'form.'.$setting} = $ENV{$envname};
                   3601:             } elsif ($type eq 'array') {
                   3602:                 $ENV{'form.'.$setting} = [ 
                   3603:                                            map { 
                   3604:                                                &Apache::lonnet::unescape($_); 
                   3605:                                            } split(',',$ENV{$envname})
                   3606:                                            ];
                   3607:             }
                   3608:         }
                   3609:     }
1.127     matthew  3610: }
                   3611: 
                   3612: ############################################################
                   3613: ############################################################
1.154     albertel 3614: 
                   3615: sub propath {
                   3616:     my ($udom,$uname)=@_;
                   3617:     $udom=~s/\W//g;
                   3618:     $uname=~s/\W//g;
                   3619:     my $subdir=$uname.'__';
                   3620:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3621:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3622:     return $proname;
1.156     albertel 3623: } 
                   3624: 
                   3625: sub icon {
                   3626:     my ($file)=@_;
1.168     albertel 3627:     my $curfext = (split(/\./,$file))[-1];
                   3628:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 3629:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 3630:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   3631: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   3632: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3633: 	            $curfext.".gif") {
                   3634: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   3635: 		$curfext.".gif";
                   3636: 	}
                   3637:     }
                   3638:     return $iconname;
1.154     albertel 3639: } 
1.84      albertel 3640: 
1.41      ng       3641: =pod
                   3642: 
                   3643: =back
                   3644: 
1.112     bowersj2 3645: =cut
1.41      ng       3646: 
1.112     bowersj2 3647: 1;
                   3648: __END__;
1.41      ng       3649: 

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