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

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

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