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

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

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