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

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

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