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

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

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