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

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

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