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

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

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