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

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

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