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

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

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