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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.349   ! albertel    4: # $Id: loncommon.pm,v 1.348 2006/04/22 16:26:31 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.349   ! albertel 3059:     my $data_table_head = $tabbg;
1.347     albertel 3060:     my $data_table_light = '#EEEEEE';
                   3061:     my $data_table_dark = '#DDD';
1.349   ! albertel 3062:     my $data_table_highlight = '#FFFF00';
        !          3063:     my $mail_new = '#FFBB77';
        !          3064:     my $mail_new_hover = '#DD9955';
        !          3065:     my $mail_read = '#BBBB77';
        !          3066:     my $mail_read_hover = '#999944';
        !          3067:     my $mail_replied = '#AAAA88';
        !          3068:     my $mail_replied_hover = '#888855';
        !          3069:     my $mail_other = '#99BBBB';
        !          3070:     my $mail_other_hover = '#669999';
        !          3071: 
1.343     albertel 3072:     return <<END;
                   3073: <style type="text/css">
1.345     albertel 3074: h1, h2, h3, th { font-family: $sans }
1.343     albertel 3075: a:focus { color: red; background: yellow } 
                   3076: table.thinborder { border-collapse: collapse; }
                   3077: table.thinborder tr th, table.thinborder tr td { border-style: solid; border-width: 1px}
                   3078: form, .inline { display: inline; }
                   3079: .center { text-align: center; }
                   3080: .filename {font-family: monospace;}
1.346     albertel 3081: 
                   3082: table#LC_top_nav, table#LC_menubuttons, table#LC_nav_location {
1.345     albertel 3083:   width: 100%;
                   3084:   background: $pgbg;
                   3085:   border: 0px;
                   3086:   border-spacing: 1px;
                   3087:   padding: 0px;
                   3088:   margin: 0px;
                   3089:   border-collapse: separate;
                   3090: }
1.346     albertel 3091: table#LC_menubuttons_mainmenu {
                   3092:   background: $pgbg;
                   3093:   border: 0px;
                   3094:   border-spacing: 1px;
                   3095:   padding: 0px;
                   3096:   margin: 0px;
                   3097:   border-collapse: separate;
                   3098: }
                   3099: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
                   3100:   border: 0px;
                   3101: }
1.345     albertel 3102: table#LC_top_nav td {
                   3103:   background: $tabbg;
                   3104: }
                   3105: table#LC_top_nav td a, div#LC_top_nav a {
                   3106:   color: $font;
                   3107:   font-family: $sans;
                   3108: }
1.346     albertel 3109: .LC_menubuttons_inline_text {
                   3110:   color: $font;
                   3111:   font-family: $sans;
                   3112:   font-size: smaller;
                   3113: }
                   3114: 
                   3115: td.LC_menubuttons_text {
                   3116:   color: $font;
                   3117:   font-family: $sans;
                   3118: }
                   3119: td.LC_menubuttons_img {
                   3120:   background: $tabbg;
                   3121: }
                   3122: .LC_current_location {
                   3123:   font-family: $sans;
                   3124:   background: $tabbg;
                   3125: }
                   3126: .LC_new_mail {
                   3127:   font-family: $sans;
                   3128:   font-weight: bold;
                   3129: }
1.347     albertel 3130: 
1.349   ! albertel 3131: table.LC_data_table, table.LC_mail_list {
1.347     albertel 3132:   border: 1px solid #000000;
                   3133:   border-collapse: seperate;
                   3134: }
1.349   ! albertel 3135: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
        !          3136:   font-weight: bold;
        !          3137:   background-color: $data_table_head;
1.347     albertel 3138: }
                   3139: table.LC_data_table tr td {
1.349   ! albertel 3140:   background-color: $data_table_light;
1.347     albertel 3141: }
                   3142: table.LC_data_table tr.LC_even_row td {
1.349   ! albertel 3143:   background-color: $data_table_dark;
1.347     albertel 3144: }
                   3145: table.LC_data_table tr.LC_empty td {
                   3146:   background-color: #FFFFFF;
                   3147: }
                   3148: 
1.349   ! albertel 3149: table.LC_calendar {
        !          3150:   border: 1px solid #000000;
        !          3151:   border-collapse: collapse;
        !          3152: }
        !          3153: table.LC_calendar_pickdate {
        !          3154:   font-size: xx-small;
        !          3155: }
        !          3156: table.LC_calendar tr td {
        !          3157:   border: 1px solid #000000;
        !          3158:   vertical-align: top;
        !          3159: }
        !          3160: table.LC_calendar tr td.LC_calendar_day_empty {
        !          3161:   background-color: $data_table_dark;
        !          3162: }
        !          3163: table.LC_calendar tr td.LC_calendar_day_current {
        !          3164:   background-color: $data_table_highlight;
        !          3165: }
        !          3166: 
        !          3167: table.LC_mail_list tr.LC_mail_new {
        !          3168:   background-color: $mail_new;
        !          3169: }
        !          3170: table.LC_mail_list tr.LC_mail_new:hover {
        !          3171:   background-color: $mail_new_hover;
        !          3172: }
        !          3173: table.LC_mail_list tr.LC_mail_read {
        !          3174:   background-color: $mail_read;
        !          3175: }
        !          3176: table.LC_mail_list tr.LC_mail_read:hover {
        !          3177:   background-color: $mail_read_hover;
        !          3178: }
        !          3179: table.LC_mail_list tr.LC_mail_replied {
        !          3180:   background-color: $mail_replied;
        !          3181: }
        !          3182: table.LC_mail_list tr.LC_mail_replied:hover {
        !          3183:   background-color: $mail_replied_hover;
        !          3184: }
        !          3185: table.LC_mail_list tr.LC_mail_other {
        !          3186:   background-color: $mail_other;
        !          3187: }
        !          3188: table.LC_mail_list tr.LC_mail_other:hover {
        !          3189:   background-color: $mail_other_hover;
        !          3190: }
1.343     albertel 3191: </style>
                   3192: END
                   3193: }
                   3194: 
1.306     albertel 3195: =pod
                   3196: 
                   3197: =over 4
                   3198: 
                   3199: =item * &headtag()
                   3200: 
                   3201: Returns a uniform footer for LON-CAPA web pages.
                   3202: 
1.307     albertel 3203: Inputs: $title - optional title for the head
                   3204:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 3205:         $args - optional arguments
1.319     albertel 3206:             force_register - if is true call registerurl so the remote is 
                   3207:                              informed
1.315     albertel 3208:             redirect - array ref of seconds before redirect occurs
                   3209:                                     url to redirect to
                   3210:                            (side effect of setting 
                   3211:                                $env{'internal.head.redirect'} to the url 
                   3212:                                redirected too)
1.306     albertel 3213: =back
                   3214: 
                   3215: =cut
                   3216: 
                   3217: sub headtag {
1.313     albertel 3218:     my ($title,$head_extra,$args) = @_;
1.306     albertel 3219:     
1.308     albertel 3220:     my $result =
                   3221: 	'<head>'.
1.343     albertel 3222: 	&standard_css().
1.340     albertel 3223: 	&font_settings().
1.308     albertel 3224: 	&Apache::lonhtmlcommon::htmlareaheaders();
1.319     albertel 3225: 
                   3226:     if ($args->{'force_register'}) {
                   3227: 	$result .= &Apache::lonmenu::registerurl(1);
                   3228:     }
                   3229: 
1.314     albertel 3230:     if (ref($args->{'redirect'})) {
                   3231: 	my ($time,$url) = @{$args->{'redirect'}};
1.315     albertel 3232: 	$url = &Apache::lonenc::check_encrypt($url);
                   3233: 	$env{'internal.head.redirect'} = $url;
1.313     albertel 3234: 	$result.=<<ADDMETA
                   3235: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 3236: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 3237: ADDMETA
                   3238:     }
1.306     albertel 3239:     if (!defined($title)) {
                   3240: 	$title = 'The LearningOnline Network with CAPA';
                   3241:     }
                   3242:     
1.315     albertel 3243:     $result .= '<title> LON-CAPA '.&mt($title).'</title>'.$head_extra;
1.306     albertel 3244:     return $result;
                   3245: }
                   3246: 
                   3247: =pod
                   3248: 
                   3249: =over 4
                   3250: 
1.340     albertel 3251: =item * &font_settings()
                   3252: 
                   3253: Returns neccessary <meta> to set the proper encoding
                   3254: 
                   3255: Inputs: none
                   3256: 
                   3257: =back
                   3258: 
                   3259: =cut
                   3260: 
                   3261: sub font_settings {
                   3262:     my $headerstring='';
                   3263:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
                   3264: 	$headerstring.=
                   3265: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
                   3266:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
                   3267: 	$headerstring.=
                   3268: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   3269:     }
                   3270:     return $headerstring;
                   3271: }
                   3272: 
1.341     albertel 3273: =pod
                   3274: 
                   3275: =over 4
                   3276: 
                   3277: =item * &xml_begin()
                   3278: 
                   3279: Returns the needed doctype and <html>
                   3280: 
                   3281: Inputs: none
                   3282: 
                   3283: =back
                   3284: 
                   3285: =cut
                   3286: 
                   3287: sub xml_begin {
                   3288:     my $output='';
                   3289: 
1.342     albertel 3290:     &Apache::lonhtmlcommon::init_htmlareafields();
                   3291: 
1.341     albertel 3292:     if ($env{'browser.mathml'}) {
                   3293: 	$output='<?xml version="1.0"?>'
                   3294:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   3295: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   3296:             
                   3297: #	    .'<!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">] >'
                   3298: 	    .'<!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">'
                   3299:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   3300: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   3301:     } else {
                   3302: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
                   3303:     }
                   3304:     return $output;
                   3305: }
1.340     albertel 3306: 
                   3307: =pod
                   3308: 
                   3309: =over 4
                   3310: 
1.306     albertel 3311: =item * &endheadtag()
                   3312: 
                   3313: Returns a uniform </head> for LON-CAPA web pages.
                   3314: 
                   3315: Inputs: none
                   3316: 
                   3317: =back
                   3318: 
                   3319: =cut
                   3320: 
                   3321: sub endheadtag {
                   3322:     return '</head>';
                   3323: }
                   3324: 
                   3325: =pod
                   3326: 
                   3327: =over 4
                   3328: 
                   3329: =item * &head()
                   3330: 
                   3331: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
                   3332: 
                   3333: Inputs: $title - optional title for the page
1.307     albertel 3334:         $head_extra - optional extra HTML to put inside the <head>
1.306     albertel 3335: =back
                   3336: 
                   3337: =cut
                   3338: 
                   3339: sub head {
1.325     albertel 3340:     my ($title,$head_extra,$args) = @_;
                   3341:     return &headtag($title,$head_extra,$args).&endheadtag();
1.306     albertel 3342: }
                   3343: 
                   3344: =pod
                   3345: 
                   3346: =over 4
                   3347: 
                   3348: =item * &start_page()
                   3349: 
                   3350: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   3351: 
                   3352: Inputs: $title - optional title for the page
                   3353:         $head_extra - optional extra HTML to incude inside the <head>
1.315     albertel 3354:         $args - additional optional args supported are:
1.317     albertel 3355:                   only_body      -> is true will set &bodytag() onlybodytag
                   3356:                                     arg on
                   3357:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
                   3358:                   add_entries    -> additional attributes to add to the  <body>
                   3359:                   domain         -> force to color decorate a page for a 
                   3360:                                     specific domain
                   3361:                   function       -> force usage of a specific rolish color
                   3362:                                     scheme
                   3363:                   redirect       -> see &headtag()
                   3364:                   bgcolor        -> override the default page bg color
                   3365:                   js_ready       -> return a string ready for being used in 
                   3366:                                     a javascript writeln
1.320     albertel 3367:                   html_encode    -> return a string ready for being used in 
                   3368:                                     a html attribute
1.317     albertel 3369:                   force_register -> if is true will turn on the &bodytag()
                   3370:                                     $forcereg arg
1.326     albertel 3371:                   body_title     -> alternate text to use instead of $title
                   3372:                                     in the title box that appears, this text
                   3373:                                     is not auto translated like the $title is
1.330     albertel 3374:                   frameset       -> if true will start with a <frameset>
                   3375:                                     rather than <body>
1.338     albertel 3376:                   no_title       -> if true the title bar won't be shown
                   3377:                   skip_phases    -> hash ref of 
                   3378:                                     head -> skip the <html><head> generation
                   3379:                                     body -> skip all <body> generation
1.337     albertel 3380: 
1.306     albertel 3381: =back
                   3382: 
                   3383: =cut
                   3384: 
                   3385: sub start_page {
1.309     albertel 3386:     my ($title,$head_extra,$args) = @_;
1.318     albertel 3387:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.313     albertel 3388:     my %head_args;
1.319     albertel 3389:     foreach my $arg ('redirect','force_register') {
                   3390: 	if (defined($args->{$arg})) {
1.324     raeburn  3391: 	    $head_args{$arg} = $args->{$arg};
1.319     albertel 3392: 	}
1.313     albertel 3393:     }
1.319     albertel 3394: 
1.315     albertel 3395:     $env{'internal.start_page'}++;
1.338     albertel 3396:     my $result;
                   3397:     if (! exists($args->{'skip_phases'}{'head'}) ) {
                   3398: 	$result.=
1.341     albertel 3399: 	    &xml_begin().
1.338     albertel 3400: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
                   3401:     }
                   3402:     
                   3403:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   3404: 	if ($args->{'frameset'}) {
                   3405: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   3406: 						$args->{'add_entries'});
                   3407: 	    $result .= "\n<frameset $attr_string>\n";
                   3408: 	} else {
                   3409: 	    $result .=
                   3410: 		&bodytag($title, 
                   3411: 			 $args->{'function'},       $args->{'add_entries'},
                   3412: 			 $args->{'only_body'},      $args->{'domain'},
                   3413: 			 $args->{'force_register'}, $args->{'body_title'},
                   3414: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
                   3415: 			 $args->{'no_title'});
                   3416: 	}
1.330     albertel 3417:     }
1.338     albertel 3418: 
1.315     albertel 3419:     if ($args->{'js_ready'}) {
1.317     albertel 3420: 	$result = &js_ready($result);
1.315     albertel 3421:     }
1.320     albertel 3422:     if ($args->{'html_encode'}) {
                   3423: 	$result = &html_encode($result);
                   3424:     }
1.315     albertel 3425:     return $result;
1.306     albertel 3426: }
                   3427: 
1.330     albertel 3428: 
1.306     albertel 3429: =pod
                   3430: 
                   3431: =over 4
                   3432: 
                   3433: =item * &head()
                   3434: 
                   3435: Returns a complete </body></html> section for LON-CAPA web pages.
                   3436: 
1.315     albertel 3437: Inputs:         $args - additional optional args supported are:
                   3438:                  js_ready     -> return a string ready for being used in 
                   3439:                                  a javascript writeln
1.320     albertel 3440:                  html_encode  -> return a string ready for being used in 
                   3441:                                  a html attribute
1.330     albertel 3442:                  frameset     -> if true will start with a <frameset>
                   3443:                                  rather than <body>
1.306     albertel 3444: =back
                   3445: 
                   3446: =cut
                   3447: 
                   3448: sub end_page {
1.315     albertel 3449:     my ($args) = @_;
1.318     albertel 3450:     #&Apache::lonnet::logthis("end_page ".join(':',caller(0)));
1.315     albertel 3451:     $env{'internal.end_page'}++;
1.330     albertel 3452:     my $result;
1.335     albertel 3453:     if ($args->{'discussion'}) {
                   3454: 	my ($target,$parser);
                   3455: 	if (ref($args->{'discussion'})) {
                   3456: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   3457: 				$args->{'discussion'}{'parser'});
                   3458: 	}
                   3459: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   3460:     }
                   3461: 
1.330     albertel 3462:     if ($args->{'frameset'}) {
                   3463: 	$result .= '</frameset>';
                   3464:     } else {
                   3465: 	$result .= &endbodytag();
                   3466:     }
                   3467:     $result .= "\n</html>";
                   3468: 
1.315     albertel 3469:     if ($args->{'js_ready'}) {
1.317     albertel 3470: 	$result = &js_ready($result);
1.315     albertel 3471:     }
1.335     albertel 3472: 
1.320     albertel 3473:     if ($args->{'html_encode'}) {
                   3474: 	$result = &html_encode($result);
                   3475:     }
1.335     albertel 3476: 
1.315     albertel 3477:     return $result;
                   3478: }
                   3479: 
1.320     albertel 3480: sub html_encode {
                   3481:     my ($result) = @_;
                   3482: 
1.322     albertel 3483:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 3484:     
                   3485:     return $result;
                   3486: }
1.317     albertel 3487: sub js_ready {
                   3488:     my ($result) = @_;
                   3489: 
1.323     albertel 3490:     $result =~ s/[\n\r]/ /xmsg;
                   3491:     $result =~ s/\\/\\\\/xmsg;
                   3492:     $result =~ s/'/\\'/xmsg;
                   3493:     $result =~ s{</script>}{</scrip'+'t>}xmsg;
1.317     albertel 3494:     
                   3495:     return $result;
                   3496: }
                   3497: 
1.315     albertel 3498: sub validate_page {
                   3499:     if (  exists($env{'internal.start_page'})
1.316     albertel 3500: 	  &&     $env{'internal.start_page'} > 1) {
                   3501: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 3502: 				 $env{'internal.start_page'}.' '.
1.316     albertel 3503: 				 $ENV{'request.filename'});
1.315     albertel 3504:     }
                   3505:     if (  exists($env{'internal.end_page'})
1.316     albertel 3506: 	  &&     $env{'internal.end_page'} > 1) {
                   3507: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 3508: 				 $env{'internal.end_page'}.' '.
1.316     albertel 3509: 				 $env{'request.filename'});
1.315     albertel 3510:     }
                   3511:     if (     exists($env{'internal.start_page'})
                   3512: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 3513: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   3514: 				 $env{'request.filename'});
1.315     albertel 3515:     }
                   3516:     if (   ! exists($env{'internal.start_page'})
                   3517: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 3518: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   3519: 				 $env{'request.filename'});
1.315     albertel 3520:     }
1.306     albertel 3521: }
1.315     albertel 3522: 
1.318     albertel 3523: sub simple_error_page {
                   3524:     my ($r,$title,$msg) = @_;
                   3525:     my $page =
                   3526: 	&Apache::loncommon::start_page($title).
                   3527: 	&mt($msg).
                   3528: 	&Apache::loncommon::end_page();
                   3529:     if (ref($r)) {
                   3530: 	$r->print($page);
1.327     albertel 3531: 	return;
1.318     albertel 3532:     }
                   3533:     return $page;
                   3534: }
1.347     albertel 3535: 
                   3536: {
                   3537:     my $row_count;
                   3538:     sub start_data_table {
                   3539: 	undef($row_count);
                   3540: 	return '<table class="LC_data_table">';
                   3541:     }
                   3542: 
                   3543:     sub end_data_table {
                   3544: 	undef($row_count);
                   3545: 	return '</table>';
                   3546:     }
                   3547: 
                   3548:     sub start_data_table_row {
                   3549: 	$row_count++;
                   3550: 	return  '<tr '.(($row_count % 2)?'':'class="LC_even_row"').'>';
                   3551:     }
                   3552: 
                   3553:     sub end_data_table_row {
                   3554: 	return '</tr>';
                   3555:     }
                   3556: }
                   3557: 
1.251     albertel 3558: ###############################################
1.182     matthew  3559: 
                   3560: =pod
                   3561: 
1.306     albertel 3562: =over 4
                   3563: 
1.182     matthew  3564: =item get_users_function
                   3565: 
                   3566: Used by &bodytag to determine the current users primary role.
                   3567: Returns either 'student','coordinator','admin', or 'author'.
                   3568: 
                   3569: =cut
                   3570: 
                   3571: ###############################################
                   3572: sub get_users_function {
                   3573:     my $function = 'student';
1.258     albertel 3574:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
1.182     matthew  3575:         $function='coordinator';
                   3576:     }
1.258     albertel 3577:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  3578:         $function='admin';
                   3579:     }
1.258     albertel 3580:     if (($env{'request.role'}=~/^(au|ca)/) ||
1.182     matthew  3581:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   3582:         $function='author';
                   3583:     }
                   3584:     return $function;
1.54      www      3585: }
1.99      www      3586: 
                   3587: ###############################################
                   3588: 
1.233     raeburn  3589: =pod
                   3590: 
1.274     raeburn  3591: =item check_user_status
                   3592: 
                   3593: Determines current status of supplied role for a
                   3594: specific user. Roles can be active, previous or future.
                   3595: 
                   3596: Inputs: 
                   3597: user's domain, user's username, course's domain,
                   3598: course's number, optional section/group.
                   3599: 
                   3600: Outputs:
                   3601: role status: active, previous or future. 
                   3602: 
                   3603: =cut
                   3604: 
                   3605: sub check_user_status {
                   3606:     my ($udom,$uname,$cdom,$crs,$role,$secgrp) = @_;
                   3607:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
                   3608:     my @uroles = keys %userinfo;
                   3609:     my $srchstr;
                   3610:     my $active_chk = 'none';
                   3611:     if (@uroles > 0) {
                   3612:         if (($role eq 'cc') || ($secgrp eq '') || (!defined($secgrp))) {
                   3613:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   3614:         } else {
                   3615:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$secgrp.'_'.$role;         }
                   3616:         if (grep/^$srchstr$/,@uroles) {
                   3617:             my $role_end = 0;
                   3618:             my $role_start = 0;
                   3619:             $active_chk = 'active';
                   3620:             if ($userinfo{$srchstr} =~ m/^($role)_(\d+)/) {
                   3621:                 $role_end = $2;
                   3622:                 if ($userinfo{$srchstr} =~ m/^($role)_($role_end)_(\d+)$/) {
                   3623:                     $role_start = $3;
                   3624:                 }
                   3625:             }
                   3626:             if ($role_start > 0) {
                   3627:                 if (time < $role_start) {
                   3628:                     $active_chk = 'future';
                   3629:                 }
                   3630:             }
                   3631:             if ($role_end > 0) {
                   3632:                 if (time > $role_end) {
                   3633:                     $active_chk = 'previous';
                   3634:                 }
                   3635:             }
                   3636:         }
                   3637:     }
                   3638:     return $active_chk;
                   3639: }
                   3640: 
                   3641: ###############################################
                   3642: 
                   3643: =pod
                   3644: 
1.233     raeburn  3645: =item get_sections
                   3646: 
                   3647: Determines all the sections for a course including
                   3648: sections with students and sections containing other roles.
                   3649: Incoming parameters: domain, course number, reference to 
                   3650: section hash (keys to be section/group IDs), reference to 
                   3651: array containing roles for which sections should be gathered
                   3652: (optional). If the fourth argument is undefined, sections
                   3653: are gathered for any role.
                   3654:  
                   3655: Returns number of sections.
                   3656: 
                   3657: =cut
                   3658: 
                   3659: ###############################################
                   3660: sub get_sections {
                   3661:     my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
1.240     albertel 3662:     if (!($cdom && $cnum)) { return 0; }
1.233     raeburn  3663:     my $numsections = 0;
1.240     albertel 3664: 
                   3665:     if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
1.276     albertel 3666: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 3667: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   3668: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
                   3669: 	while (my ($student,$data) = each %$classlist) {
                   3670: 	    my ($section,$status) = ($data->[$sec_index],
                   3671: 				     $data->[$status_index]);
                   3672: 	    unless ($section eq '-1' || $section =~ /^\s*$/) {
                   3673: 		if (!defined($$sectioncount{$section})) { $numsections++; }
                   3674: 		$$sectioncount{$section}++;
                   3675: 	    }
                   3676: 	}
                   3677:     }
                   3678:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   3679:     foreach my $user (sort(keys(%courseroles))) {
                   3680: 	if ($user !~ /^(\w{2})/) { next; }
                   3681: 	my ($role) = ($user =~ /^(\w{2})/);
                   3682: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
                   3683: 	my $section;
                   3684: 	if ($role eq 'cr' &&
                   3685: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   3686: 	    $section=$1;
                   3687: 	}
                   3688: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   3689: 	if (!defined($section) || $section eq '-1') { next; }
                   3690: 	if (!defined($$sectioncount{$section})) { $numsections++; } 
                   3691: 	$$sectioncount{$section}++;
1.233     raeburn  3692:     }
                   3693:     return $numsections;
                   3694: }
                   3695: 
1.274     raeburn  3696: ###############################################
1.298     raeburn  3697:                                                                                   
                   3698: =pod
                   3699:                                                                                   
                   3700: =item coursegroups
                   3701: 
                   3702: Retrieve information about groups in a course,
                   3703: 
                   3704: Input:
                   3705: 1. Reference to hash to populate with group information. 
                   3706: 2. Optional course domain
                   3707: 3. Optional course number
                   3708: 4. Optional group name
                   3709: 
                   3710: Course domain and number will be taken from user's
                   3711: environment if not supplied. Optional group name will'
                   3712: be passed to lonnet::get_coursegroups() as a regexp to
                   3713: use in the call to the dump function.
                   3714: 
                   3715: Output
                   3716: Returns number of groups in the course (subject to the
                   3717: optional group name filter).
                   3718: 
                   3719: Side effects:
                   3720: Populates the referenced curr_groups hash, with key,
                   3721: value pairs. Keys are group names, corresponding values
                   3722: are scalars containing group information in XML. This
                   3723: can be sent to &get_group_settings() to be parsed.     
                   3724: 
                   3725: =cut 
                   3726: 
                   3727: ###############################################
                   3728: 
                   3729: sub coursegroups {
                   3730:     my ($curr_groups,$cdom,$cnum,$group) = @_;
                   3731:     my $numgroups;
                   3732:     if (!defined($cdom) || !defined($cnum)) {
                   3733:         my $cid =  $env{'request.course.id'};
                   3734:         $cdom = $env{'course.'.$cid.'.domain'};
                   3735:         $cnum = $env{'course.'.$cid.'.num'};
                   3736:     }
                   3737:     %{$curr_groups} = &Apache::lonnet::get_coursegroups($cdom,$cnum,$group);
                   3738:     my ($tmp) = keys(%{$curr_groups});
                   3739:     if ($tmp=~/^error:/) {
                   3740:         unless ($tmp eq 'error: 2 tie(GDBM) Failed while attempting dump') {
                   3741:             &logthis('Error retrieving groups: '.$tmp.' in '.$cnum.':'.
                   3742:                                                                    $cdom);
                   3743:         }
                   3744:         $numgroups = 0;
                   3745:     } else {
                   3746:         $numgroups = keys(%{$curr_groups});
                   3747:     }
                   3748:     return $numgroups;
                   3749: }
                   3750: 
                   3751: ###############################################
1.274     raeburn  3752: 
1.275     raeburn  3753: =pod
1.294     raeburn  3754: 
                   3755: =item get_group_settings
                   3756: 
                   3757: Uses TokeParser to extract group information from the
                   3758: XML used to describe course groups.
                   3759: 
                   3760: Input:
1.298     raeburn  3761: Scalar containing XML  - as retrieved from &coursegroups().
1.294     raeburn  3762: 
                   3763: Output:
                   3764: Hash containing group information as key=values for (a), and
                   3765: hash of hashes for (b)
                   3766: 
                   3767: Keys (in two categories):
                   3768: (a) groupname, creator, creation, modified, startdate,enddate.
                   3769: Corresponding values are name of the group, creator of the group
                   3770: (username:domain), UNIX time for date group was created, and
                   3771: settings were last modified, and default start and end access
                   3772: times for group members.
                   3773: 
                   3774: (b) functions returned in hash of hashes.
                   3775: Outer hash key is functions.
                   3776: Inner hash keys are chat,discussion,email,files,homepage,roster.
                   3777: Corresponding values are either on or off, depending on
1.303     raeburn  3778: whether this type of functionality is available for the group.
1.294     raeburn  3779: 
                   3780: =cut
                   3781:                                                                                  
                   3782: ###############################################
                   3783: 
                   3784: sub get_group_settings {
                   3785:     my ($groupinfo)=@_;
                   3786:     my $parser=HTML::TokeParser->new(\$groupinfo);
                   3787:     my $token;
                   3788:     my $tool = '';
1.303     raeburn  3789:     my $role = '';
1.294     raeburn  3790:     my %content=();
                   3791:     while ($token=$parser->get_token) {
                   3792:         if ($token->[0] eq 'S')  {
                   3793:             my $entry=$token->[1];
1.303     raeburn  3794:             if ($entry eq 'functions' || $entry eq 'autosec') {
1.294     raeburn  3795:                 %{$content{$entry}} = ();
                   3796:                 $tool = $entry;
1.303     raeburn  3797:             } elsif ($entry eq 'role') {
                   3798:                 if ($tool eq 'autosec') {
                   3799:                     $role = $token->[2]{id};
                   3800:                 }
1.294     raeburn  3801:             } else {
                   3802:                 my $value=$parser->get_text('/'.$entry);
                   3803:                 if ($entry eq 'name') {
                   3804:                     if ($tool eq 'functions') {
                   3805:                         my $function = $token->[2]{id};
                   3806:                         $content{$tool}{$function} = $value;
                   3807:                     }
                   3808:                 } elsif ($entry eq 'groupname') {
                   3809:                     $content{$entry}=&Apache::lonnet::unescape($value);
1.303     raeburn  3810:                 } elsif (($entry eq 'roles') || ($entry eq 'types') ||
                   3811:                          ($entry eq 'sectionpick') || ($entry eq 'defpriv')) {
                   3812:                     push(@{$content{$entry}},$value);
                   3813:                 } elsif ($entry eq 'section') {
                   3814:                     if ($tool eq 'autosec'  && $role ne '') {
                   3815:                         push(@{$content{$tool}{$role}},$value);
                   3816:                     }
1.294     raeburn  3817:                 } else {
                   3818:                     $content{$entry}=$value;
                   3819:                 }
                   3820:             }
                   3821:         } elsif ($token->[0] eq 'E') {
1.303     raeburn  3822:             if ($token->[1] eq 'functions' || $token->[1] eq 'autosec') {
1.294     raeburn  3823:                 $tool = '';
1.303     raeburn  3824:             } elsif ($token->[1] eq 'role') {
                   3825:                 $role = '';
1.294     raeburn  3826:             }
1.303     raeburn  3827: 
1.294     raeburn  3828:         }
                   3829:     }
                   3830:     return %content;
                   3831: }
                   3832: 
                   3833: sub check_group_access {
                   3834:     my ($group) = @_;
                   3835:     my $access = 1;
                   3836:     my $now = time;
                   3837:     my ($start,$end) = split(/\./,$env{'user.role.gr/'.$env{'request.course,id'}.'/'.$group});
                   3838:     if (($end!=0) && ($end<$now)) { $access = 0; }
                   3839:     if (($start!=0) && ($start>$now)) { $access=0; }
                   3840:     return $access;
                   3841: }
                   3842: 
                   3843: ###############################################
                   3844: 
                   3845: =pod
1.275     raeburn  3846:                                                                                 
                   3847: =item get_course_users
                   3848:                                                                                 
                   3849: Retrieves usernames:domains for users in the specified course
                   3850: with specific role(s), and access status. 
                   3851: 
                   3852: Incoming parameters:
1.277     albertel 3853: 1. course domain
                   3854: 2. course number
                   3855: 3. access status: users must have - either active, 
1.275     raeburn  3856: previous, future, or all.
1.277     albertel 3857: 4. reference to array of permissible roles
1.288     raeburn  3858: 5. reference to array of section restrictions (optional)
                   3859: 6. reference to results object (hash of hashes).
                   3860: 7. reference to optional userdata hash
1.275     raeburn  3861: Keys of top level hash are roles.
                   3862: Keys of inner hashes are username:domain, with 
                   3863: values set to access type.
1.288     raeburn  3864: Optional userdata hash returns an array with arguments in the 
                   3865: same order as loncoursedata::get_classlist() for student data.
                   3866: 
                   3867: Entries for end, start, section and status are blank because
                   3868: of the possibility of multiple values for non-student roles.
                   3869: 
1.275     raeburn  3870: =cut
                   3871:                                                                                 
                   3872: ###############################################
                   3873:                                                                                 
                   3874: sub get_course_users {
1.288     raeburn  3875:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
                   3876:     my %idx = ();
                   3877: 
                   3878:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   3879:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   3880:     $idx{end} = &Apache::loncoursedata::CL_END();
                   3881:     $idx{start} = &Apache::loncoursedata::CL_START();
                   3882:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   3883:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   3884:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   3885:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   3886: 
1.290     albertel 3887:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 3888:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  3889:         my $now = time;
1.277     albertel 3890:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  3891:             my $match = 0;
1.291     albertel 3892:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.290     albertel 3893: 		unless(grep(/^\Q$$classlist{$student}[$idx{section}]\E$/,
                   3894: 			    @{$sections})) {
                   3895: 		    next;
                   3896: 		}
1.288     raeburn  3897:             } 
1.275     raeburn  3898:             if (defined($$types{'active'})) {
1.288     raeburn  3899:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  3900:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  3901:                     $match = 1;
1.275     raeburn  3902:                 }
                   3903:             }
                   3904:             if (defined($$types{'previous'})) {
1.288     raeburn  3905:                 if ($$classlist{$student}[$idx{end}] <= $now) {
1.275     raeburn  3906:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  3907:                     $match = 1;
1.275     raeburn  3908:                 }
                   3909:             }
                   3910:             if (defined($$types{'future'})) {
1.288     raeburn  3911:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
1.275     raeburn  3912:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  3913:                     $match = 1;
1.275     raeburn  3914:                 }
                   3915:             }
1.288     raeburn  3916:             if ($match && defined($userdata)) {
                   3917:                 $$userdata{$student} = $$classlist{$student};
                   3918:             }
1.275     raeburn  3919:         }
                   3920:     }
                   3921:     if ((@{$roles} > 0) && (@{$roles} ne "st")) {
                   3922:         my @coursepersonnel = &Apache::lonnet::getkeys('nohist_userroles',$cdom,$cnum);
                   3923:         foreach my $person (@coursepersonnel) {
1.288     raeburn  3924:             my $match = 0;
1.275     raeburn  3925:             my ($role,$user) = ($person =~ /^([^:]*):([^:]+:[^:]+)/);
                   3926:             $user =~ s/:$//;
1.290     albertel 3927:             if (($role) && (grep(/^\Q$role\E$/,@{$roles}))) {
1.288     raeburn  3928:                 my ($uname,$udom,$usec) = split(/:/,$user);
1.290     albertel 3929:                 if ($usec ne '' && (ref($sections) eq 'ARRAY') && 
                   3930: 		    @{$sections} > 0) {
                   3931: 		    unless(grep(/^\Q$usec\E$/,@{$sections})) {
                   3932: 			next;
                   3933: 		    }
1.288     raeburn  3934:                 }
1.275     raeburn  3935:                 if ($uname ne '' && $udom ne '') {
                   3936:                     my $status = &check_user_status($udom,$uname,$cdom,$cnum,$role);
1.277     albertel 3937:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  3938:                         if ($status eq $type) {
1.288     raeburn  3939:                             @{$$users{$role}{$user}} = $type;
                   3940:                             $match = 1;
                   3941:                         }
                   3942:                     }
1.290     albertel 3943:                     if ($match && defined($userdata) &&
                   3944:                         !exists($$userdata{$uname.':'.$udom})) {
                   3945: 			&get_user_info($udom,$uname,\%idx,$userdata);
1.275     raeburn  3946:                     }
                   3947:                 }
                   3948:             }
                   3949:         }
1.290     albertel 3950:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  3951:             if ((defined($cdom)) && (defined($cnum))) {
                   3952:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   3953:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   3954:                     my $owner = $csettings{'internal.courseowner'};
1.288     raeburn  3955:                     @{$$users{'ow'}{$owner.':'.$cdom}} = 'any';
1.290     albertel 3956:                     if (defined($userdata) && 
                   3957: 			!exists($$userdata{$owner.':'.$cdom})) {
                   3958: 			&get_user_info($cdom,$owner,\%idx,$userdata);
                   3959: 		    }
1.279     raeburn  3960:                 }
                   3961:             }
                   3962:         }
1.275     raeburn  3963:     }
                   3964:     return;
                   3965: }
                   3966: 
1.288     raeburn  3967: sub get_user_info {
                   3968:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 3969:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   3970: 	&plainname($uname,$udom,'lastname');
1.291     albertel 3971:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  3972:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.288     raeburn  3973:     return;
                   3974: }
1.275     raeburn  3975: 
1.112     bowersj2 3976: =pod
                   3977: 
                   3978: =item * get_unprocessed_cgi($query,$possible_names)
                   3979: 
1.258     albertel 3980: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 3981: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 3982: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 3983: 
                   3984: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   3985: $possible_names is an ref to an array of form element names.  As an example:
                   3986: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 3987: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 3988: 
                   3989: =cut
1.1       albertel 3990: 
1.6       albertel 3991: sub get_unprocessed_cgi {
1.25      albertel 3992:   my ($query,$possible_names)= @_;
1.26      matthew  3993:   # $Apache::lonxml::debug=1;
1.16      harris41 3994:   foreach (split(/&/,$query)) {
1.6       albertel 3995:     my ($name, $value) = split(/=/,$_);
1.25      albertel 3996:     $name = &Apache::lonnet::unescape($name);
                   3997:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   3998:       $value =~ tr/+/ /;
                   3999:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 4000:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 4001:     }
1.16      harris41 4002:   }
1.6       albertel 4003: }
                   4004: 
1.112     bowersj2 4005: =pod
                   4006: 
                   4007: =item * cacheheader() 
                   4008: 
                   4009: returns cache-controlling header code
                   4010: 
                   4011: =cut
                   4012: 
1.7       albertel 4013: sub cacheheader {
1.258     albertel 4014:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 4015:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   4016:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 4017:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   4018:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 4019:     return $output;
1.7       albertel 4020: }
                   4021: 
1.112     bowersj2 4022: =pod
                   4023: 
                   4024: =item * no_cache($r) 
                   4025: 
                   4026: specifies header code to not have cache
                   4027: 
                   4028: =cut
                   4029: 
1.9       albertel 4030: sub no_cache {
1.216     albertel 4031:     my ($r) = @_;
                   4032:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 4033: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 4034:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   4035:     $r->no_cache(1);
                   4036:     $r->header_out("Expires" => $date);
                   4037:     $r->header_out("Pragma" => "no-cache");
1.123     www      4038: }
                   4039: 
                   4040: sub content_type {
1.181     albertel 4041:     my ($r,$type,$charset) = @_;
1.299     foxr     4042:     if ($r) {
                   4043: 	#  Note that printout.pl calls this with undef for $r.
                   4044: 	&no_cache($r);
                   4045:     }
1.258     albertel 4046:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 4047:     unless ($charset) {
                   4048: 	$charset=&Apache::lonlocal::current_encoding;
                   4049:     }
                   4050:     if ($charset) { $type.='; charset='.$charset; }
                   4051:     if ($r) {
                   4052: 	$r->content_type($type);
                   4053:     } else {
                   4054: 	print("Content-type: $type\n\n");
                   4055:     }
1.9       albertel 4056: }
1.25      albertel 4057: 
1.112     bowersj2 4058: =pod
                   4059: 
                   4060: =item * add_to_env($name,$value) 
                   4061: 
1.258     albertel 4062: adds $name to the %env hash with value
1.112     bowersj2 4063: $value, if $name already exists, the entry is converted to an array
                   4064: reference and $value is added to the array.
                   4065: 
                   4066: =cut
                   4067: 
1.25      albertel 4068: sub add_to_env {
                   4069:   my ($name,$value)=@_;
1.258     albertel 4070:   if (defined($env{$name})) {
                   4071:     if (ref($env{$name})) {
1.25      albertel 4072:       #already have multiple values
1.258     albertel 4073:       push(@{ $env{$name} },$value);
1.25      albertel 4074:     } else {
                   4075:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 4076:       my $first=$env{$name};
                   4077:       undef($env{$name});
                   4078:       push(@{ $env{$name} },$first,$value);
1.25      albertel 4079:     }
                   4080:   } else {
1.258     albertel 4081:     $env{$name}=$value;
1.25      albertel 4082:   }
1.31      albertel 4083: }
1.149     albertel 4084: 
                   4085: =pod
                   4086: 
                   4087: =item * get_env_multiple($name) 
                   4088: 
1.258     albertel 4089: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 4090: values may be defined and end up as an array ref.
                   4091: 
                   4092: returns an array of values
                   4093: 
                   4094: =cut
                   4095: 
                   4096: sub get_env_multiple {
                   4097:     my ($name) = @_;
                   4098:     my @values;
1.258     albertel 4099:     if (defined($env{$name})) {
1.149     albertel 4100:         # exists is it an array
1.258     albertel 4101:         if (ref($env{$name})) {
                   4102:             @values=@{ $env{$name} };
1.149     albertel 4103:         } else {
1.258     albertel 4104:             $values[0]=$env{$name};
1.149     albertel 4105:         }
                   4106:     }
                   4107:     return(@values);
                   4108: }
                   4109: 
1.31      albertel 4110: 
1.41      ng       4111: =pod
1.45      matthew  4112: 
                   4113: =back 
1.41      ng       4114: 
1.112     bowersj2 4115: =head1 CSV Upload/Handling functions
1.38      albertel 4116: 
1.41      ng       4117: =over 4
                   4118: 
1.112     bowersj2 4119: =item * upfile_store($r)
1.41      ng       4120: 
                   4121: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 4122: needs $env{'form.upfile'}
1.41      ng       4123: returns $datatoken to be put into hidden field
                   4124: 
                   4125: =cut
1.31      albertel 4126: 
                   4127: sub upfile_store {
                   4128:     my $r=shift;
1.258     albertel 4129:     $env{'form.upfile'}=~s/\r/\n/gs;
                   4130:     $env{'form.upfile'}=~s/\f/\n/gs;
                   4131:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   4132:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 4133: 
1.258     albertel 4134:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   4135: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 4136:     {
1.158     raeburn  4137:         my $datafile = $r->dir_config('lonDaemons').
                   4138:                            '/tmp/'.$datatoken.'.tmp';
                   4139:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 4140:             print $fh $env{'form.upfile'};
1.158     raeburn  4141:             close($fh);
                   4142:         }
1.31      albertel 4143:     }
                   4144:     return $datatoken;
                   4145: }
                   4146: 
1.56      matthew  4147: =pod
                   4148: 
1.112     bowersj2 4149: =item * load_tmp_file($r)
1.41      ng       4150: 
                   4151: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 4152: needs $env{'form.datatoken'},
                   4153: sets $env{'form.upfile'} to the contents of the file
1.41      ng       4154: 
                   4155: =cut
1.31      albertel 4156: 
                   4157: sub load_tmp_file {
                   4158:     my $r=shift;
                   4159:     my @studentdata=();
                   4160:     {
1.158     raeburn  4161:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 4162:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  4163:         if ( open(my $fh,"<$studentfile") ) {
                   4164:             @studentdata=<$fh>;
                   4165:             close($fh);
                   4166:         }
1.31      albertel 4167:     }
1.258     albertel 4168:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 4169: }
                   4170: 
1.56      matthew  4171: =pod
                   4172: 
1.112     bowersj2 4173: =item * upfile_record_sep()
1.41      ng       4174: 
                   4175: Separate uploaded file into records
                   4176: returns array of records,
1.258     albertel 4177: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       4178: 
                   4179: =cut
1.31      albertel 4180: 
                   4181: sub upfile_record_sep {
1.258     albertel 4182:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 4183:     } else {
1.248     albertel 4184: 	my @records;
1.258     albertel 4185: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 4186: 	    if ($line=~/^\s*$/) { next; }
                   4187: 	    push(@records,$line);
                   4188: 	}
                   4189: 	return @records;
1.31      albertel 4190:     }
                   4191: }
                   4192: 
1.56      matthew  4193: =pod
                   4194: 
1.112     bowersj2 4195: =item * record_sep($record)
1.41      ng       4196: 
1.258     albertel 4197: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       4198: 
                   4199: =cut
                   4200: 
1.263     www      4201: sub takeleft {
                   4202:     my $index=shift;
                   4203:     return substr('0000'.$index,-4,4);
                   4204: }
                   4205: 
1.31      albertel 4206: sub record_sep {
                   4207:     my $record=shift;
                   4208:     my %components=();
1.258     albertel 4209:     if ($env{'form.upfiletype'} eq 'xml') {
                   4210:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 4211:         my $i=0;
                   4212:         foreach (split(/\s+/,$record)) {
                   4213:             my $field=$_;
                   4214:             $field=~s/^(\"|\')//;
                   4215:             $field=~s/(\"|\')$//;
1.263     www      4216:             $components{&takeleft($i)}=$field;
1.31      albertel 4217:             $i++;
                   4218:         }
1.258     albertel 4219:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 4220:         my $i=0;
1.171     matthew  4221:         foreach (split(/\t/,$record)) {
1.31      albertel 4222:             my $field=$_;
                   4223:             $field=~s/^(\"|\')//;
                   4224:             $field=~s/(\"|\')$//;
1.263     www      4225:             $components{&takeleft($i)}=$field;
1.31      albertel 4226:             $i++;
                   4227:         }
                   4228:     } else {
                   4229:         my @allfields=split(/\,/,$record);
                   4230:         my $i=0;
                   4231:         my $j;
                   4232:         for ($j=0;$j<=$#allfields;$j++) {
                   4233:             my $field=$allfields[$j];
                   4234:             if ($field=~/^\s*(\"|\')/) {
                   4235: 		my $delimiter=$1;
                   4236:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   4237: 		    $j++;
                   4238: 		    $field.=','.$allfields[$j];
                   4239: 		}
                   4240:                 $field=~s/^\s*$delimiter//;
                   4241:                 $field=~s/$delimiter\s*$//;
                   4242:             }
1.263     www      4243:             $components{&takeleft($i)}=$field;
1.31      albertel 4244: 	    $i++;
                   4245:         }
                   4246:     }
                   4247:     return %components;
                   4248: }
                   4249: 
1.144     matthew  4250: ######################################################
                   4251: ######################################################
                   4252: 
1.56      matthew  4253: =pod
                   4254: 
1.112     bowersj2 4255: =item * upfile_select_html()
1.41      ng       4256: 
1.144     matthew  4257: Return HTML code to select a file from the users machine and specify 
                   4258: the file type.
1.41      ng       4259: 
                   4260: =cut
                   4261: 
1.144     matthew  4262: ######################################################
                   4263: ######################################################
1.31      albertel 4264: sub upfile_select_html {
1.144     matthew  4265:     my %Types = (
                   4266:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
                   4267:                  space => &mt('Space separated'),
                   4268:                  tab   => &mt('Tabulator separated'),
                   4269: #                 xml   => &mt('HTML/XML'),
                   4270:                  );
                   4271:     my $Str = '<input type="file" name="upfile" size="50" />'.
                   4272:         '<br />Type: <select name="upfiletype">';
                   4273:     foreach my $type (sort(keys(%Types))) {
                   4274:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   4275:     }
                   4276:     $Str .= "</select>\n";
                   4277:     return $Str;
1.31      albertel 4278: }
                   4279: 
1.301     albertel 4280: sub get_samples {
                   4281:     my ($records,$toget) = @_;
                   4282:     my @samples=({});
                   4283:     my $got=0;
                   4284:     foreach my $rec (@$records) {
                   4285: 	my %temp = &record_sep($rec);
                   4286: 	if (! grep(/\S/, values(%temp))) { next; }
                   4287: 	if (%temp) {
                   4288: 	    $samples[$got]=\%temp;
                   4289: 	    $got++;
                   4290: 	    if ($got == $toget) { last; }
                   4291: 	}
                   4292:     }
                   4293:     return \@samples;
                   4294: }
                   4295: 
1.144     matthew  4296: ######################################################
                   4297: ######################################################
                   4298: 
1.56      matthew  4299: =pod
                   4300: 
1.112     bowersj2 4301: =item * csv_print_samples($r,$records)
1.41      ng       4302: 
                   4303: Prints a table of sample values from each column uploaded $r is an
                   4304: Apache Request ref, $records is an arrayref from
                   4305: &Apache::loncommon::upfile_record_sep
                   4306: 
                   4307: =cut
                   4308: 
1.144     matthew  4309: ######################################################
                   4310: ######################################################
1.31      albertel 4311: sub csv_print_samples {
                   4312:     my ($r,$records) = @_;
1.301     albertel 4313:     my $samples = &get_samples($records,3);
                   4314: 
1.144     matthew  4315:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
1.301     albertel 4316:     foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.144     matthew  4317:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
1.31      albertel 4318:     $r->print('</tr>');
1.301     albertel 4319:     foreach my $hash (@$samples) {
1.31      albertel 4320: 	$r->print('<tr>');
1.301     albertel 4321: 	foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 4322: 	    $r->print('<td>');
                   4323: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   4324: 	    $r->print('</td>');
                   4325: 	}
                   4326: 	$r->print('</tr>');
                   4327:     }
                   4328:     $r->print('</tr></table><br />'."\n");
                   4329: }
                   4330: 
1.144     matthew  4331: ######################################################
                   4332: ######################################################
                   4333: 
1.56      matthew  4334: =pod
                   4335: 
1.112     bowersj2 4336: =item * csv_print_select_table($r,$records,$d)
1.41      ng       4337: 
                   4338: Prints a table to create associations between values and table columns.
1.144     matthew  4339: 
1.41      ng       4340: $r is an Apache Request ref,
                   4341: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  4342: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       4343: 
                   4344: =cut
                   4345: 
1.144     matthew  4346: ######################################################
                   4347: ######################################################
1.31      albertel 4348: sub csv_print_select_table {
                   4349:     my ($r,$records,$d) = @_;
1.301     albertel 4350:     my $i=0;
                   4351:     my $samples = &get_samples($records,1);
1.144     matthew  4352:     $r->print(&mt('Associate columns with student attributes.')."\n".
                   4353: 	     '<table border="2"><tr>'.
                   4354:               '<th>'.&mt('Attribute').'</th>'.
                   4355:               '<th>'.&mt('Column').'</th></tr>'."\n");
1.31      albertel 4356:     foreach (@$d) {
1.174     matthew  4357: 	my ($value,$display,$defaultcol)=@{ $_ };
1.31      albertel 4358: 	$r->print('<tr><td>'.$display.'</td>');
                   4359: 
                   4360: 	$r->print('<td><select name=f'.$i.
1.32      matthew  4361: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 4362: 	$r->print('<option value="none"></option>');
1.301     albertel 4363: 	foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.174     matthew  4364: 	    $r->print('<option value="'.$_.'"'.
1.253     albertel 4365:                       ($_ eq $defaultcol ? ' selected="selected" ' : '').
1.174     matthew  4366:                       '>Column '.($_+1).'</option>');
1.31      albertel 4367: 	}
                   4368: 	$r->print('</select></td></tr>'."\n");
                   4369: 	$i++;
                   4370:     }
                   4371:     $i--;
                   4372:     return $i;
                   4373: }
1.56      matthew  4374: 
1.144     matthew  4375: ######################################################
                   4376: ######################################################
                   4377: 
1.56      matthew  4378: =pod
1.31      albertel 4379: 
1.112     bowersj2 4380: =item * csv_samples_select_table($r,$records,$d)
1.41      ng       4381: 
                   4382: Prints a table of sample values from the upload and can make associate samples to internal names.
                   4383: 
                   4384: $r is an Apache Request ref,
                   4385: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   4386: $d is an array of 2 element arrays (internal name, displayed name)
                   4387: 
                   4388: =cut
                   4389: 
1.144     matthew  4390: ######################################################
                   4391: ######################################################
1.31      albertel 4392: sub csv_samples_select_table {
                   4393:     my ($r,$records,$d) = @_;
                   4394:     my $i=0;
1.144     matthew  4395:     #
1.301     albertel 4396:     my $samples = &get_samples($records,3);
1.144     matthew  4397:     $r->print('<table border=2><tr><th>'.
                   4398:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
1.301     albertel 4399: 
                   4400:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.144     matthew  4401: 	$r->print('<tr><td><select name="f'.$i.'"'.
1.32      matthew  4402: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 4403: 	foreach my $option (@$d) {
                   4404: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  4405: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 4406:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  4407:                       $display.'</option>');
1.31      albertel 4408: 	}
                   4409: 	$r->print('</select></td><td>');
1.301     albertel 4410: 	foreach my $line (0..2) {
                   4411: 	    if (defined($samples->[$line]{$key})) { 
                   4412: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   4413: 	    }
                   4414: 	}
1.31      albertel 4415: 	$r->print('</td></tr>');
                   4416: 	$i++;
                   4417:     }
                   4418:     $i--;
                   4419:     return($i);
1.115     matthew  4420: }
                   4421: 
1.144     matthew  4422: ######################################################
                   4423: ######################################################
                   4424: 
1.115     matthew  4425: =pod
                   4426: 
                   4427: =item clean_excel_name($name)
                   4428: 
                   4429: Returns a replacement for $name which does not contain any illegal characters.
                   4430: 
                   4431: =cut
                   4432: 
1.144     matthew  4433: ######################################################
                   4434: ######################################################
1.115     matthew  4435: sub clean_excel_name {
                   4436:     my ($name) = @_;
                   4437:     $name =~ s/[:\*\?\/\\]//g;
                   4438:     if (length($name) > 31) {
                   4439:         $name = substr($name,0,31);
                   4440:     }
                   4441:     return $name;
1.25      albertel 4442: }
1.84      albertel 4443: 
1.85      albertel 4444: =pod
                   4445: 
1.112     bowersj2 4446: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 4447: 
                   4448: Returns either 1 or undef
                   4449: 
                   4450: 1 if the part is to be hidden, undef if it is to be shown
                   4451: 
                   4452: Arguments are:
                   4453: 
                   4454: $id the id of the part to be checked
                   4455: $symb, optional the symb of the resource to check
                   4456: $udom, optional the domain of the user to check for
                   4457: $uname, optional the username of the user to check for
                   4458: 
                   4459: =cut
1.84      albertel 4460: 
                   4461: sub check_if_partid_hidden {
                   4462:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 4463:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 4464: 					 $symb,$udom,$uname);
1.141     albertel 4465:     my $truth=1;
                   4466:     #if the string starts with !, then the list is the list to show not hide
                   4467:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 4468:     my @hiddenlist=split(/,/,$hiddenparts);
                   4469:     foreach my $checkid (@hiddenlist) {
1.141     albertel 4470: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 4471:     }
1.141     albertel 4472:     return !$truth;
1.84      albertel 4473: }
1.127     matthew  4474: 
1.138     matthew  4475: 
                   4476: ############################################################
                   4477: ############################################################
                   4478: 
                   4479: =pod
                   4480: 
1.157     matthew  4481: =back 
                   4482: 
1.138     matthew  4483: =head1 cgi-bin script and graphing routines
                   4484: 
1.157     matthew  4485: =over 4
                   4486: 
1.138     matthew  4487: =item get_cgi_id
                   4488: 
                   4489: Inputs: none
                   4490: 
                   4491: Returns an id which can be used to pass environment variables
                   4492: to various cgi-bin scripts.  These environment variables will
                   4493: be removed from the users environment after a given time by
                   4494: the routine &Apache::lonnet::transfer_profile_to_env.
                   4495: 
                   4496: =cut
                   4497: 
                   4498: ############################################################
                   4499: ############################################################
1.152     albertel 4500: my $uniq=0;
1.136     matthew  4501: sub get_cgi_id {
1.154     albertel 4502:     $uniq=($uniq+1)%100000;
1.280     albertel 4503:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  4504: }
                   4505: 
1.127     matthew  4506: ############################################################
                   4507: ############################################################
                   4508: 
                   4509: =pod
                   4510: 
1.134     matthew  4511: =item DrawBarGraph
1.127     matthew  4512: 
1.138     matthew  4513: Facilitates the plotting of data in a (stacked) bar graph.
                   4514: Puts plot definition data into the users environment in order for 
                   4515: graph.png to plot it.  Returns an <img> tag for the plot.
                   4516: The bars on the plot are labeled '1','2',...,'n'.
                   4517: 
                   4518: Inputs:
                   4519: 
                   4520: =over 4
                   4521: 
                   4522: =item $Title: string, the title of the plot
                   4523: 
                   4524: =item $xlabel: string, text describing the X-axis of the plot
                   4525: 
                   4526: =item $ylabel: string, text describing the Y-axis of the plot
                   4527: 
                   4528: =item $Max: scalar, the maximum Y value to use in the plot
                   4529: If $Max is < any data point, the graph will not be rendered.
                   4530: 
1.140     matthew  4531: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  4532: they are plotted.  If undefined, default values will be used.
                   4533: 
1.178     matthew  4534: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   4535: 
1.138     matthew  4536: =item @Values: An array of array references.  Each array reference holds data
                   4537: to be plotted in a stacked bar chart.
                   4538: 
1.239     matthew  4539: =item If the final element of @Values is a hash reference the key/value
                   4540: pairs will be added to the graph definition.
                   4541: 
1.138     matthew  4542: =back
                   4543: 
                   4544: Returns:
                   4545: 
                   4546: An <img> tag which references graph.png and the appropriate identifying
                   4547: information for the plot.
                   4548: 
1.127     matthew  4549: =cut
                   4550: 
                   4551: ############################################################
                   4552: ############################################################
1.134     matthew  4553: sub DrawBarGraph {
1.178     matthew  4554:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  4555:     #
                   4556:     if (! defined($colors)) {
                   4557:         $colors = ['#33ff00', 
                   4558:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   4559:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   4560:                   ]; 
                   4561:     }
1.228     matthew  4562:     my $extra_settings = {};
                   4563:     if (ref($Values[-1]) eq 'HASH') {
                   4564:         $extra_settings = pop(@Values);
                   4565:     }
1.127     matthew  4566:     #
1.136     matthew  4567:     my $identifier = &get_cgi_id();
                   4568:     my $id = 'cgi.'.$identifier;        
1.129     matthew  4569:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  4570:         return '';
                   4571:     }
1.225     matthew  4572:     #
                   4573:     my @Labels;
                   4574:     if (defined($labels)) {
                   4575:         @Labels = @$labels;
                   4576:     } else {
                   4577:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   4578:             push (@Labels,$i+1);
                   4579:         }
                   4580:     }
                   4581:     #
1.129     matthew  4582:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  4583:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  4584:     my %ValuesHash;
                   4585:     my $NumSets=1;
                   4586:     foreach my $array (@Values) {
                   4587:         next if (! ref($array));
1.136     matthew  4588:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  4589:             join(',',@$array);
1.129     matthew  4590:     }
1.127     matthew  4591:     #
1.136     matthew  4592:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  4593:     if ($NumBars < 3) {
                   4594:         $width = 120+$NumBars*32;
1.220     matthew  4595:         $xskip = 1;
1.225     matthew  4596:         $bar_width = 30;
                   4597:     } elsif ($NumBars < 5) {
                   4598:         $width = 120+$NumBars*20;
                   4599:         $xskip = 1;
                   4600:         $bar_width = 20;
1.220     matthew  4601:     } elsif ($NumBars < 10) {
1.136     matthew  4602:         $width = 120+$NumBars*15;
                   4603:         $xskip = 1;
                   4604:         $bar_width = 15;
                   4605:     } elsif ($NumBars <= 25) {
                   4606:         $width = 120+$NumBars*11;
                   4607:         $xskip = 5;
                   4608:         $bar_width = 8;
                   4609:     } elsif ($NumBars <= 50) {
                   4610:         $width = 120+$NumBars*8;
                   4611:         $xskip = 5;
                   4612:         $bar_width = 4;
                   4613:     } else {
                   4614:         $width = 120+$NumBars*8;
                   4615:         $xskip = 5;
                   4616:         $bar_width = 4;
                   4617:     }
                   4618:     #
1.137     matthew  4619:     $Max = 1 if ($Max < 1);
                   4620:     if ( int($Max) < $Max ) {
                   4621:         $Max++;
                   4622:         $Max = int($Max);
                   4623:     }
1.127     matthew  4624:     $Title  = '' if (! defined($Title));
                   4625:     $xlabel = '' if (! defined($xlabel));
                   4626:     $ylabel = '' if (! defined($ylabel));
1.136     matthew  4627:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
                   4628:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
                   4629:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
1.137     matthew  4630:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  4631:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   4632:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   4633:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   4634:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   4635:     $ValuesHash{$id.'.height'}   = $height;
                   4636:     $ValuesHash{$id.'.width'}    = $width;
                   4637:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   4638:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   4639:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  4640:     #
1.228     matthew  4641:     # Deal with other parameters
                   4642:     while (my ($key,$value) = each(%$extra_settings)) {
                   4643:         $ValuesHash{$id.'.'.$key} = $value;
                   4644:     }
                   4645:     #
1.137     matthew  4646:     &Apache::lonnet::appenv(%ValuesHash);
                   4647:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   4648: }
                   4649: 
                   4650: ############################################################
                   4651: ############################################################
                   4652: 
                   4653: =pod
                   4654: 
                   4655: =item DrawXYGraph
                   4656: 
1.138     matthew  4657: Facilitates the plotting of data in an XY graph.
                   4658: Puts plot definition data into the users environment in order for 
                   4659: graph.png to plot it.  Returns an <img> tag for the plot.
                   4660: 
                   4661: Inputs:
                   4662: 
                   4663: =over 4
                   4664: 
                   4665: =item $Title: string, the title of the plot
                   4666: 
                   4667: =item $xlabel: string, text describing the X-axis of the plot
                   4668: 
                   4669: =item $ylabel: string, text describing the Y-axis of the plot
                   4670: 
                   4671: =item $Max: scalar, the maximum Y value to use in the plot
                   4672: If $Max is < any data point, the graph will not be rendered.
                   4673: 
                   4674: =item $colors: Array ref containing the hex color codes for the data to be 
                   4675: plotted in.  If undefined, default values will be used.
                   4676: 
                   4677: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   4678: 
                   4679: =item $Ydata: Array ref containing Array refs.  
1.185     www      4680: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  4681: 
                   4682: =item %Values: hash indicating or overriding any default values which are 
                   4683: passed to graph.png.  
                   4684: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   4685: 
                   4686: =back
                   4687: 
                   4688: Returns:
                   4689: 
                   4690: An <img> tag which references graph.png and the appropriate identifying
                   4691: information for the plot.
                   4692: 
1.137     matthew  4693: =cut
                   4694: 
                   4695: ############################################################
                   4696: ############################################################
                   4697: sub DrawXYGraph {
                   4698:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   4699:     #
                   4700:     # Create the identifier for the graph
                   4701:     my $identifier = &get_cgi_id();
                   4702:     my $id = 'cgi.'.$identifier;
                   4703:     #
                   4704:     $Title  = '' if (! defined($Title));
                   4705:     $xlabel = '' if (! defined($xlabel));
                   4706:     $ylabel = '' if (! defined($ylabel));
                   4707:     my %ValuesHash = 
                   4708:         (
                   4709:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   4710:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   4711:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   4712:          $id.'.y_max_value'=> $Max,
                   4713:          $id.'.labels'     => join(',',@$Xlabels),
                   4714:          $id.'.PlotType'   => 'XY',
                   4715:          );
                   4716:     #
                   4717:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   4718:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   4719:     }
                   4720:     #
                   4721:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   4722:         return '';
                   4723:     }
                   4724:     my $NumSets=1;
1.138     matthew  4725:     foreach my $array (@{$Ydata}){
1.137     matthew  4726:         next if (! ref($array));
                   4727:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   4728:     }
1.138     matthew  4729:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  4730:     #
                   4731:     # Deal with other parameters
                   4732:     while (my ($key,$value) = each(%Values)) {
                   4733:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  4734:     }
                   4735:     #
1.136     matthew  4736:     &Apache::lonnet::appenv(%ValuesHash);
                   4737:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   4738: }
                   4739: 
                   4740: ############################################################
                   4741: ############################################################
                   4742: 
                   4743: =pod
                   4744: 
1.138     matthew  4745: =item DrawXYYGraph
                   4746: 
                   4747: Facilitates the plotting of data in an XY graph with two Y axes.
                   4748: Puts plot definition data into the users environment in order for 
                   4749: graph.png to plot it.  Returns an <img> tag for the plot.
                   4750: 
                   4751: Inputs:
                   4752: 
                   4753: =over 4
                   4754: 
                   4755: =item $Title: string, the title of the plot
                   4756: 
                   4757: =item $xlabel: string, text describing the X-axis of the plot
                   4758: 
                   4759: =item $ylabel: string, text describing the Y-axis of the plot
                   4760: 
                   4761: =item $colors: Array ref containing the hex color codes for the data to be 
                   4762: plotted in.  If undefined, default values will be used.
                   4763: 
                   4764: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   4765: 
                   4766: =item $Ydata1: The first data set
                   4767: 
                   4768: =item $Min1: The minimum value of the left Y-axis
                   4769: 
                   4770: =item $Max1: The maximum value of the left Y-axis
                   4771: 
                   4772: =item $Ydata2: The second data set
                   4773: 
                   4774: =item $Min2: The minimum value of the right Y-axis
                   4775: 
                   4776: =item $Max2: The maximum value of the left Y-axis
                   4777: 
                   4778: =item %Values: hash indicating or overriding any default values which are 
                   4779: passed to graph.png.  
                   4780: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   4781: 
                   4782: =back
                   4783: 
                   4784: Returns:
                   4785: 
                   4786: An <img> tag which references graph.png and the appropriate identifying
                   4787: information for the plot.
1.136     matthew  4788: 
                   4789: =cut
                   4790: 
                   4791: ############################################################
                   4792: ############################################################
1.137     matthew  4793: sub DrawXYYGraph {
                   4794:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   4795:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  4796:     #
                   4797:     # Create the identifier for the graph
                   4798:     my $identifier = &get_cgi_id();
                   4799:     my $id = 'cgi.'.$identifier;
                   4800:     #
                   4801:     $Title  = '' if (! defined($Title));
                   4802:     $xlabel = '' if (! defined($xlabel));
                   4803:     $ylabel = '' if (! defined($ylabel));
                   4804:     my %ValuesHash = 
                   4805:         (
                   4806:          $id.'.title'  => &Apache::lonnet::escape($Title),
                   4807:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
                   4808:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
                   4809:          $id.'.labels' => join(',',@$Xlabels),
                   4810:          $id.'.PlotType' => 'XY',
                   4811:          $id.'.NumSets' => 2,
1.137     matthew  4812:          $id.'.two_axes' => 1,
                   4813:          $id.'.y1_max_value' => $Max1,
                   4814:          $id.'.y1_min_value' => $Min1,
                   4815:          $id.'.y2_max_value' => $Max2,
                   4816:          $id.'.y2_min_value' => $Min2,
1.136     matthew  4817:          );
                   4818:     #
1.137     matthew  4819:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   4820:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   4821:     }
                   4822:     #
                   4823:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   4824:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  4825:         return '';
                   4826:     }
                   4827:     my $NumSets=1;
1.137     matthew  4828:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  4829:         next if (! ref($array));
                   4830:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  4831:     }
                   4832:     #
                   4833:     # Deal with other parameters
                   4834:     while (my ($key,$value) = each(%Values)) {
                   4835:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  4836:     }
                   4837:     #
                   4838:     &Apache::lonnet::appenv(%ValuesHash);
1.130     albertel 4839:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  4840: }
                   4841: 
                   4842: ############################################################
                   4843: ############################################################
                   4844: 
                   4845: =pod
                   4846: 
1.157     matthew  4847: =back 
                   4848: 
1.139     matthew  4849: =head1 Statistics helper routines?  
                   4850: 
                   4851: Bad place for them but what the hell.
                   4852: 
1.157     matthew  4853: =over 4
                   4854: 
1.139     matthew  4855: =item &chartlink
                   4856: 
                   4857: Returns a link to the chart for a specific student.  
                   4858: 
                   4859: Inputs:
                   4860: 
                   4861: =over 4
                   4862: 
                   4863: =item $linktext: The text of the link
                   4864: 
                   4865: =item $sname: The students username
                   4866: 
                   4867: =item $sdomain: The students domain
                   4868: 
                   4869: =back
                   4870: 
1.157     matthew  4871: =back
                   4872: 
1.139     matthew  4873: =cut
                   4874: 
                   4875: ############################################################
                   4876: ############################################################
                   4877: sub chartlink {
                   4878:     my ($linktext, $sname, $sdomain) = @_;
                   4879:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.219     albertel 4880:         '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
                   4881:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  4882:        '">'.$linktext.'</a>';
1.153     matthew  4883: }
                   4884: 
                   4885: #######################################################
                   4886: #######################################################
                   4887: 
                   4888: =pod
                   4889: 
                   4890: =head1 Course Environment Routines
1.157     matthew  4891: 
                   4892: =over 4
1.153     matthew  4893: 
                   4894: =item &restore_course_settings 
                   4895: 
                   4896: =item &store_course_settings
                   4897: 
                   4898: Restores/Store indicated form parameters from the course environment.
                   4899: Will not overwrite existing values of the form parameters.
                   4900: 
                   4901: Inputs: 
                   4902: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   4903: 
                   4904: a hash ref describing the data to be stored.  For example:
                   4905:    
                   4906: %Save_Parameters = ('Status' => 'scalar',
                   4907:     'chartoutputmode' => 'scalar',
                   4908:     'chartoutputdata' => 'scalar',
                   4909:     'Section' => 'array',
                   4910:     'StudentData' => 'array',
                   4911:     'Maps' => 'array');
                   4912: 
                   4913: Returns: both routines return nothing
                   4914: 
                   4915: =cut
                   4916: 
                   4917: #######################################################
                   4918: #######################################################
                   4919: sub store_course_settings {
                   4920:     # save to the environment
                   4921:     # appenv the same items, just to be safe
1.258     albertel 4922:     my $courseid = $env{'request.course.id'};
1.300     albertel 4923:     my $udom  = $env{'user.domain'};
                   4924:     my $uname = $env{'user.name'};
1.153     matthew  4925:     my ($prefix,$Settings) = @_;
                   4926:     my %SaveHash;
                   4927:     my %AppHash;
                   4928:     while (my ($setting,$type) = each(%$Settings)) {
1.300     albertel 4929:         my $basename = join('.','internal',$courseid,$prefix,$setting);
                   4930:         my $envname = 'environment.'.$basename;
1.258     albertel 4931:         if (exists($env{'form.'.$setting})) {
1.153     matthew  4932:             # Save this value away
                   4933:             if ($type eq 'scalar' &&
1.258     albertel 4934:                 (! exists($env{$envname}) || 
                   4935:                  $env{$envname} ne $env{'form.'.$setting})) {
                   4936:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   4937:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  4938:             } elsif ($type eq 'array') {
                   4939:                 my $stored_form;
1.258     albertel 4940:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  4941:                     $stored_form = join(',',
                   4942:                                         map {
                   4943:                                             &Apache::lonnet::escape($_);
1.258     albertel 4944:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  4945:                 } else {
                   4946:                     $stored_form = 
1.258     albertel 4947:                         &Apache::lonnet::escape($env{'form.'.$setting});
1.153     matthew  4948:                 }
                   4949:                 # Determine if the array contents are the same.
1.258     albertel 4950:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  4951:                     $SaveHash{$basename} = $stored_form;
                   4952:                     $AppHash{$envname}   = $stored_form;
                   4953:                 }
                   4954:             }
                   4955:         }
                   4956:     }
                   4957:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 4958:                                           $udom,$uname);
1.153     matthew  4959:     if ($put_result !~ /^(ok|delayed)/) {
                   4960:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   4961:                                  'got error:'.$put_result);
                   4962:     }
                   4963:     # Make sure these settings stick around in this session, too
                   4964:     &Apache::lonnet::appenv(%AppHash);
                   4965:     return;
                   4966: }
                   4967: 
                   4968: sub restore_course_settings {
1.258     albertel 4969:     my $courseid = $env{'request.course.id'};
1.153     matthew  4970:     my ($prefix,$Settings) = @_;
                   4971:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 4972:         next if (exists($env{'form.'.$setting}));
1.300     albertel 4973:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
1.153     matthew  4974:             '.'.$setting;
1.258     albertel 4975:         if (exists($env{$envname})) {
1.153     matthew  4976:             if ($type eq 'scalar') {
1.258     albertel 4977:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  4978:             } elsif ($type eq 'array') {
1.258     albertel 4979:                 $env{'form.'.$setting} = [ 
1.153     matthew  4980:                                            map { 
                   4981:                                                &Apache::lonnet::unescape($_); 
1.258     albertel 4982:                                            } split(',',$env{$envname})
1.153     matthew  4983:                                            ];
                   4984:             }
                   4985:         }
                   4986:     }
1.127     matthew  4987: }
                   4988: 
                   4989: ############################################################
                   4990: ############################################################
1.154     albertel 4991: 
                   4992: sub propath {
                   4993:     my ($udom,$uname)=@_;
                   4994:     $udom=~s/\W//g;
                   4995:     $uname=~s/\W//g;
                   4996:     my $subdir=$uname.'__';
                   4997:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4998:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   4999:     return $proname;
1.156     albertel 5000: } 
                   5001: 
                   5002: sub icon {
                   5003:     my ($file)=@_;
1.168     albertel 5004:     my $curfext = (split(/\./,$file))[-1];
                   5005:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 5006:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 5007:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   5008: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   5009: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   5010: 	            $curfext.".gif") {
                   5011: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   5012: 		$curfext.".gif";
                   5013: 	}
                   5014:     }
1.249     albertel 5015:     return &lonhttpdurl($iconname);
1.154     albertel 5016: } 
1.84      albertel 5017: 
1.215     albertel 5018: sub lonhttpdurl {
                   5019:     my ($url)=@_;
                   5020:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
                   5021:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
                   5022:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
                   5023: }
                   5024: 
1.213     albertel 5025: sub connection_aborted {
                   5026:     my ($r)=@_;
                   5027:     $r->print(" ");$r->rflush();
                   5028:     my $c = $r->connection;
                   5029:     return $c->aborted();
                   5030: }
                   5031: 
1.221     foxr     5032: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     5033: #    strings as 'strings'.
                   5034: sub escape_single {
1.221     foxr     5035:     my ($input) = @_;
1.223     albertel 5036:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     5037:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   5038:     return $input;
                   5039: }
1.223     albertel 5040: 
1.222     foxr     5041: #  Same as escape_single, but escape's "'s  This 
                   5042: #  can be used for  "strings"
                   5043: sub escape_double {
                   5044:     my ($input) = @_;
                   5045:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   5046:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   5047:     return $input;
                   5048: }
1.223     albertel 5049:  
1.222     foxr     5050: #   Escapes the last element of a full URL.
                   5051: sub escape_url {
                   5052:     my ($url)   = @_;
1.238     raeburn  5053:     my @urlslices = split(/\//, $url,-1);
1.223     albertel 5054:     my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
                   5055:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     5056: }
1.41      ng       5057: =pod
                   5058: 
                   5059: =back
                   5060: 
1.112     bowersj2 5061: =cut
1.41      ng       5062: 
1.112     bowersj2 5063: 1;
                   5064: __END__;
1.41      ng       5065: 

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