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

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

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