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

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

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