File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.467: download - view: text, annotated - select for diffs
Wed Nov 1 22:22:31 2006 UTC (17 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #4072: Add a reply-to field to notification messages.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.467 2006/11/01 22:22:31 www Exp $
    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: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonlocal;
   63: use HTML::Entities;
   64: use Apache::lonhtmlcommon();
   65: use Apache::loncoursedata();
   66: use Apache::lontexconvert();
   67: use Apache::lonclonecourse();
   68: use LONCAPA;
   69: 
   70: my $readit;
   71: 
   72: ##
   73: ## Global Variables
   74: ##
   75: 
   76: # ----------------------------------------------- Filetypes/Languages/Copyright
   77: my %language;
   78: my %supported_language;
   79: my %cprtag;
   80: my %scprtag;
   81: my %fe; my %fd; my %fm;
   82: my %category_extensions;
   83: 
   84: # ---------------------------------------------- Designs
   85: 
   86: my %designhash;
   87: 
   88: # ---------------------------------------------- Thesaurus variables
   89: #
   90: # %Keywords:
   91: #      A hash used by &keyword to determine if a word is considered a keyword.
   92: # $thesaurus_db_file 
   93: #      Scalar containing the full path to the thesaurus database.
   94: 
   95: my %Keywords;
   96: my $thesaurus_db_file;
   97: 
   98: #
   99: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  100: # thesaurus.tab, and filecategories.tab.
  101: #
  102: BEGIN {
  103:     # Variable initialization
  104:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  105:     #
  106:     unless ($readit) {
  107: # ------------------------------------------------------------------- languages
  108:     {
  109:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  110:                                    '/language.tab';
  111:         if ( open(my $fh,"<$langtabfile") ) {
  112:             while (my $line = <$fh>) {
  113:                 next if ($line=~/^\#/);
  114:                 chomp($line);
  115:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  116:                 $language{$key}=$val.' - '.$enc;
  117:                 if ($sup) {
  118:                     $supported_language{$key}=$sup;
  119:                 }
  120:             }
  121:             close($fh);
  122:         }
  123:     }
  124: # ------------------------------------------------------------------ copyrights
  125:     {
  126:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  127:                                   '/copyright.tab';
  128:         if ( open (my $fh,"<$copyrightfile") ) {
  129:             while (my $line = <$fh>) {
  130:                 next if ($line=~/^\#/);
  131:                 chomp($line);
  132:                 my ($key,$val)=(split(/\s+/,$line,2));
  133:                 $cprtag{$key}=$val;
  134:             }
  135:             close($fh);
  136:         }
  137:     }
  138: # ----------------------------------------------------------- source copyrights
  139:     {
  140:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  141:                                   '/source_copyright.tab';
  142:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  143:             while (my $line = <$fh>) {
  144:                 next if ($line =~ /^\#/);
  145:                 chomp($line);
  146:                 my ($key,$val)=(split(/\s+/,$line,2));
  147:                 $scprtag{$key}=$val;
  148:             }
  149:             close($fh);
  150:         }
  151:     }
  152: 
  153: # -------------------------------------------------------------- domain designs
  154: 
  155:     my $filename;
  156:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  157:     opendir(DIR,$designdir);
  158:     while ($filename=readdir(DIR)) {
  159: 	if ($filename!~/\.tab$/) { next; }
  160: 	my ($domain)=($filename=~/^(\w+)\./);
  161: 	{
  162: 	    my $designfile = $designdir.'/'.$filename;
  163: 	    if ( open (my $fh,"<$designfile") ) {
  164: 		while (my $line = <$fh>) {
  165: 		    next if ($line =~ /^\#/);
  166: 		    chomp($line);
  167: 		    my ($key,$val)=(split(/\=/,$line));
  168: 		    if ($val) { $designhash{$domain.'.'.$key}=$val; }
  169: 		}
  170: 		close($fh);
  171: 	    }
  172: 	}
  173: 
  174:     }
  175:     closedir(DIR);
  176: 
  177: 
  178: # ------------------------------------------------------------- file categories
  179:     {
  180:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  181:                                   '/filecategories.tab';
  182:         if ( open (my $fh,"<$categoryfile") ) {
  183: 	    while (my $line = <$fh>) {
  184: 		next if ($line =~ /^\#/);
  185: 		chomp($line);
  186:                 my ($extension,$category)=(split(/\s+/,$line,2));
  187:                 push @{$category_extensions{lc($category)}},$extension;
  188:             }
  189:             close($fh);
  190:         }
  191: 
  192:     }
  193: # ------------------------------------------------------------------ file types
  194:     {
  195:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  196:                '/filetypes.tab';
  197:         if ( open (my $fh,"<$typesfile") ) {
  198:             while (my $line = <$fh>) {
  199: 		next if ($line =~ /^\#/);
  200: 		chomp($line);
  201:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  202:                 if ($descr ne '') {
  203:                     $fe{$ending}=lc($emb);
  204:                     $fd{$ending}=$descr;
  205:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  206:                 }
  207:             }
  208:             close($fh);
  209:         }
  210:     }
  211:     &Apache::lonnet::logthis(
  212:               "<font color=yellow>INFO: Read file types</font>");
  213:     $readit=1;
  214:     }  # end of unless($readit) 
  215:     
  216: }
  217: 
  218: ###############################################################
  219: ##           HTML and Javascript Helper Functions            ##
  220: ###############################################################
  221: 
  222: =pod 
  223: 
  224: =head1 HTML and Javascript Functions
  225: 
  226: =over 4
  227: 
  228: =item * browser_and_searcher_javascript ()
  229: 
  230: X<browsing, javascript>X<searching, javascript>Returns a string
  231: containing javascript with two functions, C<openbrowser> and
  232: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  233: tags.
  234: 
  235: =item * openbrowser(formname,elementname,only,omit) [javascript]
  236: 
  237: inputs: formname, elementname, only, omit
  238: 
  239: formname and elementname indicate the name of the html form and name of
  240: the element that the results of the browsing selection are to be placed in. 
  241: 
  242: Specifying 'only' will restrict the browser to displaying only files
  243: with the given extension.  Can be a comma separated list.
  244: 
  245: Specifying 'omit' will restrict the browser to NOT displaying files
  246: with the given extension.  Can be a comma separated list.
  247: 
  248: =item * opensearcher(formname, elementname) [javascript]
  249: 
  250: Inputs: formname, elementname
  251: 
  252: formname and elementname specify the name of the html form and the name
  253: of the element the selection from the search results will be placed in.
  254: 
  255: =cut
  256: 
  257: sub browser_and_searcher_javascript {
  258:     my ($mode)=@_;
  259:     if (!defined($mode)) { $mode='edit'; }
  260:     my $resurl=&escape_single(&lastresurl());
  261:     return <<END;
  262: // <!-- BEGIN LON-CAPA Internal
  263:     var editbrowser = null;
  264:     function openbrowser(formname,elementname,only,omit,titleelement) {
  265:         var url = '$resurl/?';
  266:         if (editbrowser == null) {
  267:             url += 'launch=1&';
  268:         }
  269:         url += 'catalogmode=interactive&';
  270:         url += 'mode=$mode&';
  271:         url += 'form=' + formname + '&';
  272:         if (only != null) {
  273:             url += 'only=' + only + '&';
  274:         } else {
  275:             url += 'only=&';
  276: 	}
  277:         if (omit != null) {
  278:             url += 'omit=' + omit + '&';
  279:         } else {
  280:             url += 'omit=&';
  281: 	}
  282:         if (titleelement != null) {
  283:             url += 'titleelement=' + titleelement + '&';
  284:         } else {
  285: 	    url += 'titleelement=&';
  286: 	}
  287:         url += 'element=' + elementname + '';
  288:         var title = 'Browser';
  289:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  290:         options += ',width=700,height=600';
  291:         editbrowser = open(url,title,options,'1');
  292:         editbrowser.focus();
  293:     }
  294:     var editsearcher;
  295:     function opensearcher(formname,elementname,titleelement) {
  296:         var url = '/adm/searchcat?';
  297:         if (editsearcher == null) {
  298:             url += 'launch=1&';
  299:         }
  300:         url += 'catalogmode=interactive&';
  301:         url += 'mode=$mode&';
  302:         url += 'form=' + formname + '&';
  303:         if (titleelement != null) {
  304:             url += 'titleelement=' + titleelement + '&';
  305:         } else {
  306: 	    url += 'titleelement=&';
  307: 	}
  308:         url += 'element=' + elementname + '';
  309:         var title = 'Search';
  310:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  311:         options += ',width=700,height=600';
  312:         editsearcher = open(url,title,options,'1');
  313:         editsearcher.focus();
  314:     }
  315: // END LON-CAPA Internal -->
  316: END
  317: }
  318: 
  319: sub lastresurl {
  320:     if ($env{'environment.lastresurl'}) {
  321: 	return $env{'environment.lastresurl'}
  322:     } else {
  323: 	return '/res';
  324:     }
  325: }
  326: 
  327: sub storeresurl {
  328:     my $resurl=&Apache::lonnet::clutter(shift);
  329:     unless ($resurl=~/^\/res/) { return 0; }
  330:     $resurl=~s/\/$//;
  331:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  332:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  333:     return 1;
  334: }
  335: 
  336: sub studentbrowser_javascript {
  337:    unless (
  338:             (($env{'request.course.id'}) && 
  339:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  340: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  341: 					  '/'.$env{'request.course.sec'})
  342: 	      ))
  343:          || ($env{'request.role'}=~/^(au|dc|su)/)
  344:           ) { return ''; }  
  345:    return (<<'ENDSTDBRW');
  346: <script type="text/javascript" language="Javascript" >
  347:     var stdeditbrowser;
  348:     function openstdbrowser(formname,uname,udom,roleflag) {
  349:         var url = '/adm/pickstudent?';
  350:         var filter;
  351:         eval('filter=document.'+formname+'.'+uname+'.value;');
  352:         if (filter != null) {
  353:            if (filter != '') {
  354:                url += 'filter='+filter+'&';
  355: 	   }
  356:         }
  357:         url += 'form=' + formname + '&unameelement='+uname+
  358:                                     '&udomelement='+udom;
  359: 	if (roleflag) { url+="&roles=1"; }
  360:         var title = 'Student_Browser';
  361:         var options = 'scrollbars=1,resizable=1,menubar=0';
  362:         options += ',width=700,height=600';
  363:         stdeditbrowser = open(url,title,options,'1');
  364:         stdeditbrowser.focus();
  365:     }
  366: </script>
  367: ENDSTDBRW
  368: }
  369: 
  370: sub selectstudent_link {
  371:    my ($form,$unameele,$udomele)=@_;
  372:    if ($env{'request.course.id'}) {  
  373:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  374: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  375: 					'/'.$env{'request.course.sec'})) {
  376: 	   return '';
  377:        }
  378:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  379:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  380:    }
  381:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  382:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  383:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  384:    }
  385:    return '';
  386: }
  387: 
  388: sub coursebrowser_javascript {
  389:     my ($domainfilter)=@_;
  390:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  391:    return (<<ENDSTDBRW);
  392: <script type="text/javascript" language="Javascript" >
  393:     var stdeditbrowser;
  394:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  395:         var url = '/adm/pickcourse?';
  396:         var filter;
  397:         if (filter != null) {
  398:            if (filter != '') {
  399:                url += 'filter='+filter+'&';
  400: 	   }
  401:         }
  402:         var domainfilter='$domainfilter';
  403:         if (domainfilter != null) {
  404:            if (domainfilter != '') {
  405:                url += 'domainfilter='+domainfilter+'&';
  406: 	   }
  407:         }
  408:         url += 'form=' + formname + '&cnumelement='+uname+
  409: 	                            '&cdomelement='+udom+
  410:                                     '&cnameelement='+desc;
  411:         if (extra_element !=null && extra_element != '' && formname == 'rolechoice') {
  412:             url += '&roleelement='+extra_element;
  413:             if (domainfilter == null || domainfilter == '') {
  414:                 url += '&domainfilter='+extra_element;
  415:             }
  416:         }
  417:         if (multflag !=null && multflag != '') {
  418:             url += '&multiple='+multflag;
  419:         }
  420:         if (crstype == 'Course/Group') {
  421:             if (formname == 'cu') {
  422:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  423:                 if (crstype == "") {
  424:                     alert("$crs_or_grp_alert");
  425:                     return;
  426:                 }
  427:             }
  428:         }
  429:         if (crstype !=null && crstype != '') {
  430:             url += '&type='+crstype;
  431:         }
  432:         var title = 'Course_Browser';
  433:         var options = 'scrollbars=1,resizable=1,menubar=0';
  434:         options += ',width=700,height=600';
  435:         stdeditbrowser = open(url,title,options,'1');
  436:         stdeditbrowser.focus();
  437:     }
  438: </script>
  439: ENDSTDBRW
  440: }
  441: 
  442: sub selectcourse_link {
  443:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  444:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  445:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select [_1]',$selecttype)."</a>";
  446: }
  447: 
  448: sub check_uncheck_jscript {
  449:     my $jscript = <<"ENDSCRT";
  450: function checkAll(field) {
  451:     if (field.length > 0) {
  452:         for (i = 0; i < field.length; i++) {
  453:             field[i].checked = true ;
  454:         }
  455:     } else {
  456:         field.checked = true
  457:     }
  458: }
  459:  
  460: function uncheckAll(field) {
  461:     if (field.length > 0) {
  462:         for (i = 0; i < field.length; i++) {
  463:             field[i].checked = false ;
  464:         }     } else {
  465:         field.checked = false ;
  466:     }
  467: }
  468: ENDSCRT
  469:     return $jscript;
  470: }
  471: 
  472: 
  473: =pod
  474: 
  475: =item * linked_select_forms(...)
  476: 
  477: linked_select_forms returns a string containing a <script></script> block
  478: and html for two <select> menus.  The select menus will be linked in that
  479: changing the value of the first menu will result in new values being placed
  480: in the second menu.  The values in the select menu will appear in alphabetical
  481: order.
  482: 
  483: linked_select_forms takes the following ordered inputs:
  484: 
  485: =over 4
  486: 
  487: =item * $formname, the name of the <form> tag
  488: 
  489: =item * $middletext, the text which appears between the <select> tags
  490: 
  491: =item * $firstdefault, the default value for the first menu
  492: 
  493: =item * $firstselectname, the name of the first <select> tag
  494: 
  495: =item * $secondselectname, the name of the second <select> tag
  496: 
  497: =item * $hashref, a reference to a hash containing the data for the menus.
  498: 
  499: =back 
  500: 
  501: Below is an example of such a hash.  Only the 'text', 'default', and 
  502: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  503: values for the first select menu.  The text that coincides with the 
  504: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  505: and text for the second menu are given in the hash pointed to by 
  506: $menu{$choice1}->{'select2'}.  
  507: 
  508:  my %menu = ( A1 => { text =>"Choice A1" ,
  509:                        default => "B3",
  510:                        select2 => { 
  511:                            B1 => "Choice B1",
  512:                            B2 => "Choice B2",
  513:                            B3 => "Choice B3",
  514:                            B4 => "Choice B4"
  515:                            }
  516:                    },
  517:                A2 => { text =>"Choice A2" ,
  518:                        default => "C2",
  519:                        select2 => { 
  520:                            C1 => "Choice C1",
  521:                            C2 => "Choice C2",
  522:                            C3 => "Choice C3"
  523:                            }
  524:                    },
  525:                A3 => { text =>"Choice A3" ,
  526:                        default => "D6",
  527:                        select2 => { 
  528:                            D1 => "Choice D1",
  529:                            D2 => "Choice D2",
  530:                            D3 => "Choice D3",
  531:                            D4 => "Choice D4",
  532:                            D5 => "Choice D5",
  533:                            D6 => "Choice D6",
  534:                            D7 => "Choice D7"
  535:                            }
  536:                    }
  537:                );
  538: 
  539: =cut
  540: 
  541: sub linked_select_forms {
  542:     my ($formname,
  543:         $middletext,
  544:         $firstdefault,
  545:         $firstselectname,
  546:         $secondselectname, 
  547:         $hashref
  548:         ) = @_;
  549:     my $second = "document.$formname.$secondselectname";
  550:     my $first = "document.$formname.$firstselectname";
  551:     # output the javascript to do the changing
  552:     my $result = '';
  553:     $result.="<script type=\"text/javascript\">\n";
  554:     $result.="var select2data = new Object();\n";
  555:     $" = '","';
  556:     my $debug = '';
  557:     foreach my $s1 (sort(keys(%$hashref))) {
  558:         $result.="select2data.d_$s1 = new Object();\n";        
  559:         $result.="select2data.d_$s1.def = new String('".
  560:             $hashref->{$s1}->{'default'}."');\n";
  561:         $result.="select2data.d_$s1.values = new Array(";        
  562:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  563:         $result.="\"@s2values\");\n";
  564:         $result.="select2data.d_$s1.texts = new Array(";        
  565:         my @s2texts;
  566:         foreach my $value (@s2values) {
  567:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  568:         }
  569:         $result.="\"@s2texts\");\n";
  570:     }
  571:     $"=' ';
  572:     $result.= <<"END";
  573: 
  574: function select1_changed() {
  575:     // Determine new choice
  576:     var newvalue = "d_" + $first.value;
  577:     // update select2
  578:     var values     = select2data[newvalue].values;
  579:     var texts      = select2data[newvalue].texts;
  580:     var select2def = select2data[newvalue].def;
  581:     var i;
  582:     // out with the old
  583:     for (i = 0; i < $second.options.length; i++) {
  584:         $second.options[i] = null;
  585:     }
  586:     // in with the nuclear
  587:     for (i=0;i<values.length; i++) {
  588:         $second.options[i] = new Option(values[i]);
  589:         $second.options[i].value = values[i];
  590:         $second.options[i].text = texts[i];
  591:         if (values[i] == select2def) {
  592:             $second.options[i].selected = true;
  593:         }
  594:     }
  595: }
  596: </script>
  597: END
  598:     # output the initial values for the selection lists
  599:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  600:     foreach my $value (sort(keys(%$hashref))) {
  601:         $result.="    <option value=\"$value\" ";
  602:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  603:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  604:     }
  605:     $result .= "</select>\n";
  606:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  607:     $result .= $middletext;
  608:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  609:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  610:     foreach my $value (sort(keys(%select2))) {
  611:         $result.="    <option value=\"$value\" ";        
  612:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  613:         $result.=">".&mt($select2{$value})."</option>\n";
  614:     }
  615:     $result .= "</select>\n";
  616:     #    return $debug;
  617:     return $result;
  618: }   #  end of sub linked_select_forms {
  619: 
  620: =pod
  621: 
  622: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  623: 
  624: Returns a string corresponding to an HTML link to the given help
  625: $topic, where $topic corresponds to the name of a .tex file in
  626: /home/httpd/html/adm/help/tex, with underscores replaced by
  627: spaces. 
  628: 
  629: $text will optionally be linked to the same topic, allowing you to
  630: link text in addition to the graphic. If you do not want to link
  631: text, but wish to specify one of the later parameters, pass an
  632: empty string. 
  633: 
  634: $stayOnPage is a value that will be interpreted as a boolean. If true,
  635: the link will not open a new window. If false, the link will open
  636: a new window using Javascript. (Default is false.) 
  637: 
  638: $width and $height are optional numerical parameters that will
  639: override the width and height of the popped up window, which may
  640: be useful for certain help topics with big pictures included. 
  641: 
  642: =cut
  643: 
  644: sub help_open_topic {
  645:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  646:     $text = "" if (not defined $text);
  647:     $stayOnPage = 0 if (not defined $stayOnPage);
  648:     if ($env{'browser.interface'} eq 'textual' ||
  649: 	$env{'environment.remote'} eq 'off' ) {
  650: 	$stayOnPage=1;
  651:     }
  652:     $width = 350 if (not defined $width);
  653:     $height = 400 if (not defined $height);
  654:     my $filename = $topic;
  655:     $filename =~ s/ /_/g;
  656: 
  657:     my $template = "";
  658:     my $link;
  659: 
  660:     $topic=~s/\W/\_/g;
  661: 
  662:     if (!$stayOnPage)
  663:     {
  664: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  665:     }
  666:     else
  667:     {
  668: 	$link = "/adm/help/${filename}.hlp";
  669:     }
  670: 
  671:     # Add the text
  672:     if ($text ne "")
  673:     {
  674: 	$template .= 
  675:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  676:   "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  677:     }
  678: 
  679:     # Add the graphic
  680:     my $title = &mt('Online Help');
  681:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  682:     $template .= <<"ENDTEMPLATE";
  683:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  684: ENDTEMPLATE
  685:     if ($text ne '') { $template.='</td></tr></table>' };
  686:     return $template;
  687: 
  688: }
  689: 
  690: # This is a quicky function for Latex cheatsheet editing, since it 
  691: # appears in at least four places
  692: sub helpLatexCheatsheet {
  693:     my $other = shift;
  694:     my $addOther = '';
  695:     if ($other) {
  696: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  697: 						       undef, undef, 600) .
  698: 							   '</td><td>';
  699:     }
  700:     return '<table><tr><td>'.
  701: 	$addOther .
  702: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  703: 					    undef,undef,600)
  704: 	.'</td><td>'.
  705: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  706: 					    undef,undef,600)
  707: 	.'</td></tr></table>';
  708: }
  709: 
  710: sub general_help {
  711:     my $helptopic='Student_Intro';
  712:     if ($env{'request.role'}=~/^(ca|au)/) {
  713: 	$helptopic='Authoring_Intro';
  714:     } elsif ($env{'request.role'}=~/^cc/) {
  715: 	$helptopic='Course_Coordination_Intro';
  716:     }
  717:     return $helptopic;
  718: }
  719: 
  720: sub update_help_link {
  721:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  722:     my $origurl = $ENV{'REQUEST_URI'};
  723:     $origurl=~s|^/~|/priv/|;
  724:     my $timestamp = time;
  725:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  726:         $$datum = &escape($$datum);
  727:     }
  728: 
  729:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
  730:     my $output .= <<"ENDOUTPUT";
  731: <script type="text/javascript">
  732: banner_link = '$banner_link';
  733: </script>
  734: ENDOUTPUT
  735:     return $output;
  736: }
  737: 
  738: # now just updates the help link and generates a blue icon
  739: sub help_open_menu {
  740:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  741: 	= @_;
  742:     
  743:     $stayOnPage = 0 if (not defined $stayOnPage);
  744:     if ($env{'browser.interface'} eq 'textual' ||
  745: 	$env{'environment.remote'} eq 'off' ) {
  746: 	$stayOnPage=1;
  747:     }
  748:     my $output;
  749:     if ($component_help) {
  750: 	if (!$text) {
  751: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  752: 				       $width,$height);
  753: 	} else {
  754: 	    my $help_text;
  755: 	    $help_text=&unescape($topic);
  756: 	    $output='<table><tr><td>'.
  757: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  758: 				 $width,$height).'</td></tr></table>';
  759: 	}
  760:     }
  761:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  762:     return $output.$banner_link;
  763: }
  764: 
  765: sub top_nav_help {
  766:     my ($text) = @_;
  767: 
  768:     $text = &mt($text);
  769: 
  770:     my $stayOnPage = 
  771: 	($env{'browser.interface'}  eq 'textual' ||
  772: 	 $env{'environment.remote'} eq 'off' );
  773:     my $link=  ($stayOnPage) ? "javascript:helpMenu('display')"
  774: 	                     : "javascript:helpMenu('open')";
  775:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage);
  776: 
  777:     my $title = &mt('Get help');
  778: 
  779:     return <<"END";
  780: $banner_link
  781:  <a href="$link" title="$title">$text</a>
  782: END
  783: }
  784: 
  785: sub help_menu_js {
  786:     my ($text) = @_;
  787: 
  788:     my $stayOnPage = 
  789: 	($env{'browser.interface'}  eq 'textual' ||
  790: 	 $env{'environment.remote'} eq 'off' );
  791: 
  792:     my $width = 620;
  793:     my $height = 600;
  794:     my $helptopic=&general_help();
  795:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
  796:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  797:     my $start_page =
  798:         &Apache::loncommon::start_page('Help Menu', undef,
  799: 				       {'frameset'    => 1,
  800: 					'js_ready'    => 1,
  801: 					'add_entries' => {
  802: 					    'border' => '0',
  803: 					    'rows'   => "105,*",},});
  804:     my $end_page =
  805:         &Apache::loncommon::end_page({'frameset' => 1,
  806: 				      'js_ready' => 1,});
  807: 
  808:     my $template .= <<"ENDTEMPLATE";
  809: <script type="text/javascript">
  810: // <!-- BEGIN LON-CAPA Internal
  811: // <![CDATA[
  812: var banner_link = '';
  813: function helpMenu(target) {
  814:     var caller = this;
  815:     if (target == 'open') {
  816:         var newWindow = null;
  817:         try {
  818:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  819:         }
  820:         catch(error) {
  821:             writeHelp(caller);
  822:             return;
  823:         }
  824:         if (newWindow) {
  825:             caller = newWindow;
  826:         }
  827:     }
  828:     writeHelp(caller);
  829:     return;
  830: }
  831: function writeHelp(caller) {
  832:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
  833:     caller.document.close()
  834:     caller.focus()
  835: }
  836: // ]]>
  837: // END LON-CAPA Internal -->
  838: </script>
  839: ENDTEMPLATE
  840:     return $template;
  841: }
  842: 
  843: sub help_open_bug {
  844:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  845:     unless ($env{'user.adv'}) { return ''; }
  846:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  847:     $text = "" if (not defined $text);
  848:     $stayOnPage = 0 if (not defined $stayOnPage);
  849:     if ($env{'browser.interface'} eq 'textual' ||
  850: 	$env{'environment.remote'} eq 'off' ) {
  851: 	$stayOnPage=1;
  852:     }
  853:     $width = 600 if (not defined $width);
  854:     $height = 600 if (not defined $height);
  855: 
  856:     $topic=~s/\W+/\+/g;
  857:     my $link='';
  858:     my $template='';
  859:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
  860: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
  861:     if (!$stayOnPage)
  862:     {
  863: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  864:     }
  865:     else
  866:     {
  867: 	$link = $url;
  868:     }
  869:     # Add the text
  870:     if ($text ne "")
  871:     {
  872: 	$template .= 
  873:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  874:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  875:     }
  876: 
  877:     # Add the graphic
  878:     my $title = &mt('Report a Bug');
  879:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
  880:     $template .= <<"ENDTEMPLATE";
  881:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
  882: ENDTEMPLATE
  883:     if ($text ne '') { $template.='</td></tr></table>' };
  884:     return $template;
  885: 
  886: }
  887: 
  888: sub help_open_faq {
  889:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  890:     unless ($env{'user.adv'}) { return ''; }
  891:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  892:     $text = "" if (not defined $text);
  893:     $stayOnPage = 0 if (not defined $stayOnPage);
  894:     if ($env{'browser.interface'} eq 'textual' ||
  895: 	$env{'environment.remote'} eq 'off' ) {
  896: 	$stayOnPage=1;
  897:     }
  898:     $width = 350 if (not defined $width);
  899:     $height = 400 if (not defined $height);
  900: 
  901:     $topic=~s/\W+/\+/g;
  902:     my $link='';
  903:     my $template='';
  904:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  905:     if (!$stayOnPage)
  906:     {
  907: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  908:     }
  909:     else
  910:     {
  911: 	$link = $url;
  912:     }
  913: 
  914:     # Add the text
  915:     if ($text ne "")
  916:     {
  917: 	$template .= 
  918:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
  919:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  920:     }
  921: 
  922:     # Add the graphic
  923:     my $title = &mt('View the FAQ');
  924:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
  925:     $template .= <<"ENDTEMPLATE";
  926:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
  927: ENDTEMPLATE
  928:     if ($text ne '') { $template.='</td></tr></table>' };
  929:     return $template;
  930: 
  931: }
  932: 
  933: ###############################################################
  934: ###############################################################
  935: 
  936: =pod
  937: 
  938: =item * change_content_javascript():
  939: 
  940: This and the next function allow you to create small sections of an
  941: otherwise static HTML page that you can update on the fly with
  942: Javascript, even in Netscape 4.
  943: 
  944: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
  945: must be written to the HTML page once. It will prove the Javascript
  946: function "change(name, content)". Calling the change function with the
  947: name of the section 
  948: you want to update, matching the name passed to C<changable_area>, and
  949: the new content you want to put in there, will put the content into
  950: that area.
  951: 
  952: B<Note>: Netscape 4 only reserves enough space for the changable area
  953: to contain room for the original contents. You need to "make space"
  954: for whatever changes you wish to make, and be B<sure> to check your
  955: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
  956: it's adequate for updating a one-line status display, but little more.
  957: This script will set the space to 100% width, so you only need to
  958: worry about height in Netscape 4.
  959: 
  960: Modern browsers are much less limiting, and if you can commit to the
  961: user not using Netscape 4, this feature may be used freely with
  962: pretty much any HTML.
  963: 
  964: =cut
  965: 
  966: sub change_content_javascript {
  967:     # If we're on Netscape 4, we need to use Layer-based code
  968:     if ($env{'browser.type'} eq 'netscape' &&
  969: 	$env{'browser.version'} =~ /^4\./) {
  970: 	return (<<NETSCAPE4);
  971: 	function change(name, content) {
  972: 	    doc = document.layers[name+"___escape"].layers[0].document;
  973: 	    doc.open();
  974: 	    doc.write(content);
  975: 	    doc.close();
  976: 	}
  977: NETSCAPE4
  978:     } else {
  979: 	# Otherwise, we need to use semi-standards-compliant code
  980: 	# (technically, "innerHTML" isn't standard but the equivalent
  981: 	# is really scary, and every useful browser supports it
  982: 	return (<<DOMBASED);
  983: 	function change(name, content) {
  984: 	    element = document.getElementById(name);
  985: 	    element.innerHTML = content;
  986: 	}
  987: DOMBASED
  988:     }
  989: }
  990: 
  991: =pod
  992: 
  993: =item * changable_area($name, $origContent):
  994: 
  995: This provides a "changable area" that can be modified on the fly via
  996: the Javascript code provided in C<change_content_javascript>. $name is
  997: the name you will use to reference the area later; do not repeat the
  998: same name on a given HTML page more then once. $origContent is what
  999: the area will originally contain, which can be left blank.
 1000: 
 1001: =cut
 1002: 
 1003: sub changable_area {
 1004:     my ($name, $origContent) = @_;
 1005: 
 1006:     if ($env{'browser.type'} eq 'netscape' &&
 1007: 	$env{'browser.version'} =~ /^4\./) {
 1008: 	# If this is netscape 4, we need to use the Layer tag
 1009: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1010:     } else {
 1011: 	return "<span id='$name'>$origContent</span>";
 1012:     }
 1013: }
 1014: 
 1015: =pod
 1016: 
 1017: =back
 1018: 
 1019: =head1 Excel and CSV file utility routines
 1020: 
 1021: =over 4
 1022: 
 1023: =cut
 1024: 
 1025: ###############################################################
 1026: ###############################################################
 1027: 
 1028: =pod
 1029: 
 1030: =item * csv_translate($text) 
 1031: 
 1032: Translate $text to allow it to be output as a 'comma separated values' 
 1033: format.
 1034: 
 1035: =cut
 1036: 
 1037: ###############################################################
 1038: ###############################################################
 1039: sub csv_translate {
 1040:     my $text = shift;
 1041:     $text =~ s/\"/\"\"/g;
 1042:     $text =~ s/\n/ /g;
 1043:     return $text;
 1044: }
 1045: 
 1046: ###############################################################
 1047: ###############################################################
 1048: 
 1049: =pod
 1050: 
 1051: =item * define_excel_formats
 1052: 
 1053: Define some commonly used Excel cell formats.
 1054: 
 1055: Currently supported formats:
 1056: 
 1057: =over 4
 1058: 
 1059: =item header
 1060: 
 1061: =item bold
 1062: 
 1063: =item h1
 1064: 
 1065: =item h2
 1066: 
 1067: =item h3
 1068: 
 1069: =item h4
 1070: 
 1071: =item i
 1072: 
 1073: =item date
 1074: 
 1075: =back
 1076: 
 1077: Inputs: $workbook
 1078: 
 1079: Returns: $format, a hash reference.
 1080: 
 1081: =cut
 1082: 
 1083: ###############################################################
 1084: ###############################################################
 1085: sub define_excel_formats {
 1086:     my ($workbook) = @_;
 1087:     my $format;
 1088:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1089:                                                 bottom    => 1,
 1090:                                                 align     => 'center');
 1091:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1092:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1093:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1094:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1095:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1096:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1097:     $format->{'date'} = $workbook->add_format(num_format=>
 1098:                                             'mm/dd/yyyy hh:mm:ss');
 1099:     return $format;
 1100: }
 1101: 
 1102: ###############################################################
 1103: ###############################################################
 1104: 
 1105: =pod
 1106: 
 1107: =item * create_workbook
 1108: 
 1109: Create an Excel worksheet.  If it fails, output message on the
 1110: request object and return undefs.
 1111: 
 1112: Inputs: Apache request object
 1113: 
 1114: Returns (undef) on failure, 
 1115:     Excel worksheet object, scalar with filename, and formats 
 1116:     from &Apache::loncommon::define_excel_formats on success
 1117: 
 1118: =cut
 1119: 
 1120: ###############################################################
 1121: ###############################################################
 1122: sub create_workbook {
 1123:     my ($r) = @_;
 1124:         #
 1125:     # Create the excel spreadsheet
 1126:     my $filename = '/prtspool/'.
 1127:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1128:         time.'_'.rand(1000000000).'.xls';
 1129:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1130:     if (! defined($workbook)) {
 1131:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1132:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1133:                             "This error has been logged.  ".
 1134:                             "Please alert your LON-CAPA administrator").
 1135:                   '</p>');
 1136:         return (undef);
 1137:     }
 1138:     #
 1139:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1140:     #
 1141:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1142:     return ($workbook,$filename,$format);
 1143: }
 1144: 
 1145: ###############################################################
 1146: ###############################################################
 1147: 
 1148: =pod
 1149: 
 1150: =item * create_text_file
 1151: 
 1152: Create a file to write to and eventually make available to the usre.
 1153: If file creation fails, outputs an error message on the request object and 
 1154: return undefs.
 1155: 
 1156: Inputs: Apache request object, and file suffix
 1157: 
 1158: Returns (undef) on failure, 
 1159:     Filehandle and filename on success.
 1160: 
 1161: =cut
 1162: 
 1163: ###############################################################
 1164: ###############################################################
 1165: sub create_text_file {
 1166:     my ($r,$suffix) = @_;
 1167:     if (! defined($suffix)) { $suffix = 'txt'; };
 1168:     my $fh;
 1169:     my $filename = '/prtspool/'.
 1170:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1171:         time.'_'.rand(1000000000).'.'.$suffix;
 1172:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1173:     if (! defined($fh)) {
 1174:         $r->log_error("Couldn't open $filename for output $!");
 1175:         $r->print("Problems occured in creating the output file.  ".
 1176:                   "This error has been logged.  ".
 1177:                   "Please alert your LON-CAPA administrator.");
 1178:     }
 1179:     return ($fh,$filename)
 1180: }
 1181: 
 1182: 
 1183: =pod 
 1184: 
 1185: =back
 1186: 
 1187: =cut
 1188: 
 1189: ###############################################################
 1190: ##        Home server <option> list generating code          ##
 1191: ###############################################################
 1192: 
 1193: =pod
 1194: 
 1195: =head1 Home Server option list generating code
 1196: 
 1197: =over 4
 1198: 
 1199: =item * get_domains()
 1200: 
 1201: Returns an array containing each of the domains listed in the hosts.tab
 1202: file.
 1203: 
 1204: =cut
 1205: 
 1206: #-------------------------------------------
 1207: sub get_domains {
 1208:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
 1209:     my @domains;
 1210:     my %seen;
 1211:     foreach my $dom (sort(values(%Apache::lonnet::hostdom))) {
 1212: 	push(@domains,$dom) unless $seen{$dom}++;
 1213:     }
 1214:     return @domains;
 1215: }
 1216: 
 1217: # ------------------------------------------
 1218: 
 1219: sub domain_select {
 1220:     my ($name,$value,$multiple)=@_;
 1221:     my %domains=map { 
 1222: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
 1223:     } &get_domains;
 1224:     if ($multiple) {
 1225: 	$domains{''}=&mt('Any domain');
 1226: 	return &multiple_select_form($name,$value,4,\%domains);
 1227:     } else {
 1228: 	return &select_form($name,$value,%domains);
 1229:     }
 1230: }
 1231: 
 1232: #-------------------------------------------
 1233: 
 1234: =pod
 1235: 
 1236: =item * multiple_select_form($name,$value,$size,$hash,$order)
 1237: 
 1238: Returns a string containing a <select> element int multiple mode
 1239: 
 1240: 
 1241: Args:
 1242:   $name - name of the <select> element
 1243:   $value - sclara or array ref of values that should already be selected
 1244:   $size - number of rows long the select element is
 1245:   $hash - the elements should be 'option' => 'shown text'
 1246:           (shown text should already have been &mt())
 1247:   $order - (optional) array ref of the order to show the elments in
 1248: 
 1249: =cut
 1250: 
 1251: #-------------------------------------------
 1252: sub multiple_select_form {
 1253:     my ($name,$value,$size,$hash,$order)=@_;
 1254:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1255:     my $output='';
 1256:     if (! defined($size)) {
 1257:         $size = 4;
 1258:         if (scalar(keys(%$hash))<4) {
 1259:             $size = scalar(keys(%$hash));
 1260:         }
 1261:     }
 1262:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1263:     my @order = ref($order) ? @$order
 1264:                             : sort(keys(%$hash));
 1265:     foreach my $key (@order) {
 1266:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1267:         $output.='selected="selected" ' if ($selected{$key});
 1268:         $output.='>'.$hash->{$key}."</option>\n";
 1269:     }
 1270:     $output.="</select>\n";
 1271:     return $output;
 1272: }
 1273: 
 1274: #-------------------------------------------
 1275: 
 1276: =pod
 1277: 
 1278: =item * select_form($defdom,$name,%hash)
 1279: 
 1280: Returns a string containing a <select name='$name' size='1'> form to 
 1281: allow a user to select options from a hash option_name => displayed text.  
 1282: See lonrights.pm for an example invocation and use.
 1283: 
 1284: =cut
 1285: 
 1286: #-------------------------------------------
 1287: sub select_form {
 1288:     my ($def,$name,%hash) = @_;
 1289:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1290:     my @keys;
 1291:     if (exists($hash{'select_form_order'})) {
 1292: 	@keys=@{$hash{'select_form_order'}};
 1293:     } else {
 1294: 	@keys=sort(keys(%hash));
 1295:     }
 1296:     foreach my $key (@keys) {
 1297:         $selectform.=
 1298: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1299:             ($key eq $def ? 'selected="selected" ' : '').
 1300:                 ">".&mt($hash{$key})."</option>\n";
 1301:     }
 1302:     $selectform.="</select>";
 1303:     return $selectform;
 1304: }
 1305: 
 1306: sub gradeleveldescription {
 1307:     my $gradelevel=shift;
 1308:     my %gradelevels=(0 => 'Not specified',
 1309: 		     1 => 'Grade 1',
 1310: 		     2 => 'Grade 2',
 1311: 		     3 => 'Grade 3',
 1312: 		     4 => 'Grade 4',
 1313: 		     5 => 'Grade 5',
 1314: 		     6 => 'Grade 6',
 1315: 		     7 => 'Grade 7',
 1316: 		     8 => 'Grade 8',
 1317: 		     9 => 'Grade 9',
 1318: 		     10 => 'Grade 10',
 1319: 		     11 => 'Grade 11',
 1320: 		     12 => 'Grade 12',
 1321: 		     13 => 'Grade 13',
 1322: 		     14 => '100 Level',
 1323: 		     15 => '200 Level',
 1324: 		     16 => '300 Level',
 1325: 		     17 => '400 Level',
 1326: 		     18 => 'Graduate Level');
 1327:     return &mt($gradelevels{$gradelevel});
 1328: }
 1329: 
 1330: sub select_level_form {
 1331:     my ($deflevel,$name)=@_;
 1332:     unless ($deflevel) { $deflevel=0; }
 1333:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1334:     for (my $i=0; $i<=18; $i++) {
 1335:         $selectform.="<option value=\"$i\" ".
 1336:             ($i==$deflevel ? 'selected="selected" ' : '').
 1337:                 ">".&gradeleveldescription($i)."</option>\n";
 1338:     }
 1339:     $selectform.="</select>";
 1340:     return $selectform;
 1341: }
 1342: 
 1343: #-------------------------------------------
 1344: 
 1345: =pod
 1346: 
 1347: =item * select_dom_form($defdom,$name,$includeempty)
 1348: 
 1349: Returns a string containing a <select name='$name' size='1'> form to 
 1350: allow a user to select the domain to preform an operation in.  
 1351: See loncreateuser.pm for an example invocation and use.
 1352: 
 1353: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1354: selected");
 1355: 
 1356: =cut
 1357: 
 1358: #-------------------------------------------
 1359: sub select_dom_form {
 1360:     my ($defdom,$name,$includeempty) = @_;
 1361:     my @domains = get_domains();
 1362:     if ($includeempty) { @domains=('',@domains); }
 1363:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1364:     foreach my $dom (@domains) {
 1365:         $selectdomain.="<option value=\"$dom\" ".
 1366:             ($dom eq $defdom ? 'selected="selected" ' : '').
 1367:                 ">$dom</option>\n";
 1368:     }
 1369:     $selectdomain.="</select>";
 1370:     return $selectdomain;
 1371: }
 1372: 
 1373: #-------------------------------------------
 1374: 
 1375: =pod
 1376: 
 1377: =item * get_library_servers($domain)
 1378: 
 1379: Returns a hash which contains keys like '103l3' and values like 
 1380: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
 1381: given $domain.
 1382: 
 1383: =cut
 1384: 
 1385: #-------------------------------------------
 1386: sub get_library_servers {
 1387:     my $domain = shift;
 1388:     my %library_servers;
 1389:     foreach my $hostid (keys(%Apache::lonnet::libserv)) {
 1390:         if ($Apache::lonnet::hostdom{$hostid} eq $domain) {
 1391:             $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid};
 1392:         }
 1393:     }
 1394:     return %library_servers;
 1395: }
 1396: 
 1397: #-------------------------------------------
 1398: 
 1399: =pod
 1400: 
 1401: =item * home_server_option_list($domain)
 1402: 
 1403: returns a string which contains an <option> list to be used in a 
 1404: <select> form input.  See loncreateuser.pm for an example.
 1405: 
 1406: =cut
 1407: 
 1408: #-------------------------------------------
 1409: sub home_server_option_list {
 1410:     my $domain = shift;
 1411:     my %servers = &get_library_servers($domain);
 1412:     my $result = '';
 1413:     foreach my $hostid (sort(keys(%servers))) {
 1414:         $result.=
 1415:             '<option value="'.$hostid.'">'.
 1416: 	    $hostid.' '.$servers{$hostid}."</option>\n";
 1417:     }
 1418:     return $result;
 1419: }
 1420: 
 1421: =pod
 1422: 
 1423: =back
 1424: 
 1425: =cut
 1426: 
 1427: ###############################################################
 1428: ##                  Decoding User Agent                      ##
 1429: ###############################################################
 1430: 
 1431: =pod
 1432: 
 1433: =head1 Decoding the User Agent
 1434: 
 1435: =over 4
 1436: 
 1437: =item * &decode_user_agent()
 1438: 
 1439: Inputs: $r
 1440: 
 1441: Outputs:
 1442: 
 1443: =over 4
 1444: 
 1445: =item * $httpbrowser
 1446: 
 1447: =item * $clientbrowser
 1448: 
 1449: =item * $clientversion
 1450: 
 1451: =item * $clientmathml
 1452: 
 1453: =item * $clientunicode
 1454: 
 1455: =item * $clientos
 1456: 
 1457: =back
 1458: 
 1459: =back 
 1460: 
 1461: =cut
 1462: 
 1463: ###############################################################
 1464: ###############################################################
 1465: sub decode_user_agent {
 1466:     my ($r)=@_;
 1467:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1468:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1469:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1470:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1471:     my $clientbrowser='unknown';
 1472:     my $clientversion='0';
 1473:     my $clientmathml='';
 1474:     my $clientunicode='0';
 1475:     for (my $i=0;$i<=$#browsertype;$i++) {
 1476:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1477: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1478: 	    $clientbrowser=$bname;
 1479:             $httpbrowser=~/$vreg/i;
 1480: 	    $clientversion=$1;
 1481:             $clientmathml=($clientversion>=$minv);
 1482:             $clientunicode=($clientversion>=$univ);
 1483: 	}
 1484:     }
 1485:     my $clientos='unknown';
 1486:     if (($httpbrowser=~/linux/i) ||
 1487:         ($httpbrowser=~/unix/i) ||
 1488:         ($httpbrowser=~/ux/i) ||
 1489:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1490:     if (($httpbrowser=~/vax/i) ||
 1491:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1492:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1493:     if (($httpbrowser=~/mac/i) ||
 1494:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1495:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1496:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1497:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1498:             $clientunicode,$clientos,);
 1499: }
 1500: 
 1501: ###############################################################
 1502: ##    Authentication changing form generation subroutines    ##
 1503: ###############################################################
 1504: ##
 1505: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1506: ## hash, and have reasonable default values.
 1507: ##
 1508: ##    formname = the name given in the <form> tag.
 1509: #-------------------------------------------
 1510: 
 1511: =pod
 1512: 
 1513: =head1 Authentication Routines
 1514: 
 1515: =over 4
 1516: 
 1517: =item * authform_xxxxxx
 1518: 
 1519: The authform_xxxxxx subroutines provide javascript and html forms which 
 1520: handle some of the conveniences required for authentication forms.  
 1521: This is not an optimal method, but it works.  
 1522: 
 1523: See loncreateuser.pm for invocation and use examples.
 1524: 
 1525: =over 4
 1526: 
 1527: =item * authform_header
 1528: 
 1529: =item * authform_authorwarning
 1530: 
 1531: =item * authform_nochange
 1532: 
 1533: =item * authform_kerberos
 1534: 
 1535: =item * authform_internal
 1536: 
 1537: =item * authform_filesystem
 1538: 
 1539: =back
 1540: 
 1541: =back 
 1542: 
 1543: =cut
 1544: 
 1545: #-------------------------------------------
 1546: sub authform_header{  
 1547:     my %in = (
 1548:         formname => 'cu',
 1549:         kerb_def_dom => '',
 1550:         @_,
 1551:     );
 1552:     $in{'formname'} = 'document.' . $in{'formname'};
 1553:     my $result='';
 1554: 
 1555: #---------------------------------------------- Code for upper case translation
 1556:     my $Javascript_toUpperCase;
 1557:     unless ($in{kerb_def_dom}) {
 1558:         $Javascript_toUpperCase =<<"END";
 1559:         switch (choice) {
 1560:            case 'krb': currentform.elements[choicearg].value =
 1561:                currentform.elements[choicearg].value.toUpperCase();
 1562:                break;
 1563:            default:
 1564:         }
 1565: END
 1566:     } else {
 1567:         $Javascript_toUpperCase = "";
 1568:     }
 1569: 
 1570:     my $radioval = "'nochange'";
 1571:     if (exists($in{'curr_authtype'}) &&
 1572:         defined($in{'curr_authtype'}) &&
 1573:         $in{'curr_authtype'} ne '') {
 1574:         $radioval = "'$in{'curr_authtype'}arg'";
 1575:     }
 1576:     my $argfield = 'null';
 1577:     if ( grep/^mode$/,(keys %in) ) {
 1578:         if ($in{'mode'} eq 'modifycourse')  {
 1579:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1580:                 $radioval = "'$in{'curr_authtype'}'";
 1581:             }
 1582:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1583:                 unless ($in{'curr_autharg'} eq '') {
 1584:                     $argfield = "'$in{'curr_autharg'}'";
 1585:                 }
 1586:             }
 1587:         }
 1588:     }
 1589: 
 1590:     $result.=<<"END";
 1591: var current = new Object();
 1592: current.radiovalue = $radioval;
 1593: current.argfield = $argfield;
 1594: 
 1595: function changed_radio(choice,currentform) {
 1596:     var choicearg = choice + 'arg';
 1597:     // If a radio button in changed, we need to change the argfield
 1598:     if (current.radiovalue != choice) {
 1599:         current.radiovalue = choice;
 1600:         if (current.argfield != null) {
 1601:             currentform.elements[current.argfield].value = '';
 1602:         }
 1603:         if (choice == 'nochange') {
 1604:             current.argfield = null;
 1605:         } else {
 1606:             current.argfield = choicearg;
 1607:             switch(choice) {
 1608:                 case 'krb': 
 1609:                     currentform.elements[current.argfield].value = 
 1610:                         "$in{'kerb_def_dom'}";
 1611:                 break;
 1612:               default:
 1613:                 break;
 1614:             }
 1615:         }
 1616:     }
 1617:     return;
 1618: }
 1619: 
 1620: function changed_text(choice,currentform) {
 1621:     var choicearg = choice + 'arg';
 1622:     if (currentform.elements[choicearg].value !='') {
 1623:         $Javascript_toUpperCase
 1624:         // clear old field
 1625:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1626:             currentform.elements[current.argfield].value = '';
 1627:         }
 1628:         current.argfield = choicearg;
 1629:     }
 1630:     set_auth_radio_buttons(choice,currentform);
 1631:     return;
 1632: }
 1633: 
 1634: function set_auth_radio_buttons(newvalue,currentform) {
 1635:     var i=0;
 1636:     while (i < currentform.login.length) {
 1637:         if (currentform.login[i].value == newvalue) { break; }
 1638:         i++;
 1639:     }
 1640:     if (i == currentform.login.length) {
 1641:         return;
 1642:     }
 1643:     current.radiovalue = newvalue;
 1644:     currentform.login[i].checked = true;
 1645:     return;
 1646: }
 1647: END
 1648:     return $result;
 1649: }
 1650: 
 1651: sub authform_authorwarning{
 1652:     my $result='';
 1653:     $result='<i>'.
 1654:         &mt('As a general rule, only authors or co-authors should be '.
 1655:             'filesystem authenticated '.
 1656:             '(which allows access to the server filesystem).')."</i>\n";
 1657:     return $result;
 1658: }
 1659: 
 1660: sub authform_nochange{  
 1661:     my %in = (
 1662:               formname => 'document.cu',
 1663:               kerb_def_dom => 'MSU.EDU',
 1664:               @_,
 1665:           );
 1666:     my $result = '<label>'.&mt('[_1] Do not change login data',
 1667:                      '<input type="radio" name="login" value="nochange" '.
 1668:                      'checked="checked" onclick="'.
 1669:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1670: 	    '</label>';
 1671:     return $result;
 1672: }
 1673: 
 1674: sub authform_kerberos{  
 1675:     my %in = (
 1676:               formname => 'document.cu',
 1677:               kerb_def_dom => 'MSU.EDU',
 1678:               kerb_def_auth => 'krb4',
 1679:               @_,
 1680:               );
 1681:     my ($check4,$check5,$krbarg);
 1682:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1683:        $check5 = " checked=\"on\"";
 1684:     } else {
 1685:        $check4 = " checked=\"on\"";
 1686:     }
 1687:     $krbarg = $in{'kerb_def_dom'};
 1688: 
 1689:     my $krbcheck = "";
 1690:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1691:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1692:             $krbcheck = " checked=\"on\"";
 1693:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1694:                 $krbarg = $in{'curr_autharg'};
 1695:             }
 1696:         }
 1697:     }
 1698: 
 1699:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1700:     my $result .= &mt
 1701:         ('[_1] Kerberos authenticated with domain [_2] '.
 1702:          '[_3] Version 4 [_4] Version 5 [_5]',
 1703:          '<label><input type="radio" name="login" value="krb" '.
 1704:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1705:          '</label><input type="text" size="10" name="krbarg" '.
 1706:              'value="'.$krbarg.'" '.
 1707:              'onchange="'.$jscall.'" />',
 1708:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 1709:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 1710: 	 '</label>');
 1711:     return $result;
 1712: }
 1713: 
 1714: sub authform_internal{  
 1715:     my %args = (
 1716:                 formname => 'document.cu',
 1717:                 kerb_def_dom => 'MSU.EDU',
 1718:                 @_,
 1719:                 );
 1720: 
 1721:     my $intcheck = "";
 1722:     my $intarg = 'value=""';
 1723:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1724:         if ($args{'curr_authtype'} eq 'int') {
 1725:             $intcheck = " checked=\"on\"";
 1726:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1727:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1728:             }
 1729:         }
 1730:     }
 1731: 
 1732:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1733:     my $result.=&mt
 1734:         ('[_1] Internally authenticated (with initial password [_2])',
 1735:          '<label><input type="radio" name="login" value="int" '.$intcheck.
 1736:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1737:          '</label><input type="text" size="10" name="intarg" '.$intarg.
 1738:              ' onchange="'.$jscall.'" />');
 1739:     return $result;
 1740: }
 1741: 
 1742: sub authform_local{  
 1743:     my %in = (
 1744:               formname => 'document.cu',
 1745:               kerb_def_dom => 'MSU.EDU',
 1746:               @_,
 1747:               );
 1748: 
 1749:     my $loccheck = "";
 1750:     my $locarg = 'value=""';
 1751:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1752:         if ($in{'curr_authtype'} eq 'loc') {
 1753:             $loccheck = " checked=\"on\"";
 1754:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1755:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1756:             }
 1757:         }
 1758:     }
 1759: 
 1760:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1761:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1762:                     '<label><input type="radio" name="login" value="loc" '.$loccheck.
 1763:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1764:                     '</label><input type="text" size="10" name="locarg" '.$locarg.
 1765:                         ' onchange="'.$jscall.'" />');
 1766:     return $result;
 1767: }
 1768: 
 1769: sub authform_filesystem{  
 1770:     my %in = (
 1771:               formname => 'document.cu',
 1772:               kerb_def_dom => 'MSU.EDU',
 1773:               @_,
 1774:               );
 1775:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1776:     my $result.= &mt
 1777:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1778:          '<label><input type="radio" name="login" value="fsys" '.
 1779:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1780:          '</label><input type="text" size="10" name="fsysarg" value="" '.
 1781:                   'onchange="'.$jscall.'" />');
 1782:     return $result;
 1783: }
 1784: 
 1785: ###############################################################
 1786: ##    Get Authentication Defaults for Domain                 ##
 1787: ###############################################################
 1788: 
 1789: =pod
 1790: 
 1791: =head1 Domains and Authentication
 1792: 
 1793: Returns default authentication type and an associated argument as
 1794: listed in file 'domain.tab'.
 1795: 
 1796: =over 4
 1797: 
 1798: =item * get_auth_defaults
 1799: 
 1800: get_auth_defaults($target_domain) returns the default authentication
 1801: type and an associated argument (initial password or a kerberos domain).
 1802: These values are stored in lonTabs/domain.tab
 1803: 
 1804: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1805: 
 1806: If target_domain is not found in domain.tab, returns nothing ('').
 1807: 
 1808: =cut
 1809: 
 1810: #-------------------------------------------
 1811: sub get_auth_defaults {
 1812:     my $domain=shift;
 1813:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1814: }
 1815: ###############################################################
 1816: ##   End Get Authentication Defaults for Domain              ##
 1817: ###############################################################
 1818: 
 1819: ###############################################################
 1820: ##    Get Kerberos Defaults for Domain                 ##
 1821: ###############################################################
 1822: ##
 1823: ## Returns default kerberos version and an associated argument
 1824: ## as listed in file domain.tab. If not listed, provides
 1825: ## appropriate default domain and kerberos version.
 1826: ##
 1827: #-------------------------------------------
 1828: 
 1829: =pod
 1830: 
 1831: =item * get_kerberos_defaults
 1832: 
 1833: get_kerberos_defaults($target_domain) returns the default kerberos
 1834: version and domain. If not found in domain.tabs, it defaults to
 1835: version 4 and the domain of the server.
 1836: 
 1837: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1838: 
 1839: =cut
 1840: 
 1841: #-------------------------------------------
 1842: sub get_kerberos_defaults {
 1843:     my $domain=shift;
 1844:     my ($krbdef,$krbdefdom) =
 1845:         &Apache::loncommon::get_auth_defaults($domain);
 1846:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1847:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1848:         my $krbdefdom=$1;
 1849:         $krbdefdom=~tr/a-z/A-Z/;
 1850:         $krbdef = "krb4";
 1851:     }
 1852:     return ($krbdef,$krbdefdom);
 1853: }
 1854: 
 1855: =pod
 1856: 
 1857: =back
 1858: 
 1859: =cut
 1860: 
 1861: ###############################################################
 1862: ##                Thesaurus Functions                        ##
 1863: ###############################################################
 1864: 
 1865: =pod
 1866: 
 1867: =head1 Thesaurus Functions
 1868: 
 1869: =over 4
 1870: 
 1871: =item * initialize_keywords
 1872: 
 1873: Initializes the package variable %Keywords if it is empty.  Uses the
 1874: package variable $thesaurus_db_file.
 1875: 
 1876: =cut
 1877: 
 1878: ###################################################
 1879: 
 1880: sub initialize_keywords {
 1881:     return 1 if (scalar keys(%Keywords));
 1882:     # If we are here, %Keywords is empty, so fill it up
 1883:     #   Make sure the file we need exists...
 1884:     if (! -e $thesaurus_db_file) {
 1885:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1886:                                  " failed because it does not exist");
 1887:         return 0;
 1888:     }
 1889:     #   Set up the hash as a database
 1890:     my %thesaurus_db;
 1891:     if (! tie(%thesaurus_db,'GDBM_File',
 1892:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1893:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1894:                                  $thesaurus_db_file);
 1895:         return 0;
 1896:     } 
 1897:     #  Get the average number of appearances of a word.
 1898:     my $avecount = $thesaurus_db{'average.count'};
 1899:     #  Put keywords (those that appear > average) into %Keywords
 1900:     while (my ($word,$data)=each (%thesaurus_db)) {
 1901:         my ($count,undef) = split /:/,$data;
 1902:         $Keywords{$word}++ if ($count > $avecount);
 1903:     }
 1904:     untie %thesaurus_db;
 1905:     # Remove special values from %Keywords.
 1906:     foreach my $value ('total.count','average.count') {
 1907:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 1908:     }
 1909:     return 1;
 1910: }
 1911: 
 1912: ###################################################
 1913: 
 1914: =pod
 1915: 
 1916: =item * keyword($word)
 1917: 
 1918: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1919: than the average number of times in the thesaurus database.  Calls 
 1920: &initialize_keywords
 1921: 
 1922: =cut
 1923: 
 1924: ###################################################
 1925: 
 1926: sub keyword {
 1927:     return if (!&initialize_keywords());
 1928:     my $word=lc(shift());
 1929:     $word=~s/\W//g;
 1930:     return exists($Keywords{$word});
 1931: }
 1932: 
 1933: ###############################################################
 1934: 
 1935: =pod 
 1936: 
 1937: =item * get_related_words
 1938: 
 1939: Look up a word in the thesaurus.  Takes a scalar argument and returns
 1940: an array of words.  If the keyword is not in the thesaurus, an empty array
 1941: will be returned.  The order of the words returned is determined by the
 1942: database which holds them.
 1943: 
 1944: Uses global $thesaurus_db_file.
 1945: 
 1946: =cut
 1947: 
 1948: ###############################################################
 1949: sub get_related_words {
 1950:     my $keyword = shift;
 1951:     my %thesaurus_db;
 1952:     if (! -e $thesaurus_db_file) {
 1953:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1954:                                  "failed because the file does not exist");
 1955:         return ();
 1956:     }
 1957:     if (! tie(%thesaurus_db,'GDBM_File',
 1958:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1959:         return ();
 1960:     } 
 1961:     my @Words=();
 1962:     my $count=0;
 1963:     if (exists($thesaurus_db{$keyword})) {
 1964: 	# The first element is the number of times
 1965: 	# the word appears.  We do not need it now.
 1966: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 1967: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 1968: 	my $threshold=$mostfrequentcount/10;
 1969:         foreach my $possibleword (@RelatedWords) {
 1970:             my ($word,$wordcount)=split(/\,/,$possibleword);
 1971:             if ($wordcount>$threshold) {
 1972: 		push(@Words,$word);
 1973:                 $count++;
 1974:                 if ($count>10) { last; }
 1975: 	    }
 1976:         }
 1977:     }
 1978:     untie %thesaurus_db;
 1979:     return @Words;
 1980: }
 1981: 
 1982: =pod
 1983: 
 1984: =back
 1985: 
 1986: =cut
 1987: 
 1988: # -------------------------------------------------------------- Plaintext name
 1989: =pod
 1990: 
 1991: =head1 User Name Functions
 1992: 
 1993: =over 4
 1994: 
 1995: =item * plainname($uname,$udom,$first)
 1996: 
 1997: Takes a users logon name and returns it as a string in
 1998: "first middle last generation" form 
 1999: if $first is set to 'lastname' then it returns it as
 2000: 'lastname generation, firstname middlename' if their is a lastname
 2001: 
 2002: =cut
 2003: 
 2004: 
 2005: ###############################################################
 2006: sub plainname {
 2007:     my ($uname,$udom,$first)=@_;
 2008:     my %names=&getnames($uname,$udom);
 2009:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2010: 					  $names{'middlename'},
 2011: 					  $names{'lastname'},
 2012: 					  $names{'generation'},$first);
 2013:     $name=~s/^\s+//;
 2014:     $name=~s/\s+$//;
 2015:     $name=~s/\s+/ /g;
 2016:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2017:     return $name;
 2018: }
 2019: 
 2020: # -------------------------------------------------------------------- Nickname
 2021: =pod
 2022: 
 2023: =item * nickname($uname,$udom)
 2024: 
 2025: Gets a users name and returns it as a string as
 2026: 
 2027: "&quot;nickname&quot;"
 2028: 
 2029: if the user has a nickname or
 2030: 
 2031: "first middle last generation"
 2032: 
 2033: if the user does not
 2034: 
 2035: =cut
 2036: 
 2037: sub nickname {
 2038:     my ($uname,$udom)=@_;
 2039:     my %names=&getnames($uname,$udom);
 2040:     my $name=$names{'nickname'};
 2041:     if ($name) {
 2042:        $name='&quot;'.$name.'&quot;'; 
 2043:     } else {
 2044:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2045: 	     $names{'lastname'}.' '.$names{'generation'};
 2046:        $name=~s/\s+$//;
 2047:        $name=~s/\s+/ /g;
 2048:     }
 2049:     return $name;
 2050: }
 2051: 
 2052: sub getnames {
 2053:     my ($uname,$udom)=@_;
 2054:     if ($udom eq 'public' && $uname eq 'public') {
 2055: 	return ('lastname' => &mt('Public'));
 2056:     }
 2057:     my $id=$uname.':'.$udom;
 2058:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2059:     if ($cached) {
 2060: 	return %{$names};
 2061:     } else {
 2062: 	my %loadnames=&Apache::lonnet::get('environment',
 2063:                     ['firstname','middlename','lastname','generation','nickname'],
 2064: 					 $udom,$uname);
 2065: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2066: 	return %loadnames;
 2067:     }
 2068: }
 2069: 
 2070: sub getemails {
 2071:     my ($uname,$udom)=@_;
 2072:     if ($udom eq 'public' && $uname eq 'public') {
 2073: 	return;
 2074:     }
 2075:     if (!$udom) { $udom=$env{'user.domain'}; }
 2076:     if (!$uname) { $uname=$env{'user.name'}; }
 2077:     my $id=$uname.':'.$udom;
 2078:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2079:     if ($cached) {
 2080: 	return %{$names};
 2081:     } else {
 2082: 	my %loadnames=&Apache::lonnet::get('environment',
 2083:                     			   ['notification','critnotification',
 2084: 					    'permanentemail'],
 2085: 					   $udom,$uname);
 2086: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2087: 	return %loadnames;
 2088:     }
 2089: }
 2090: 
 2091: # ------------------------------------------------------------------ Screenname
 2092: 
 2093: =pod
 2094: 
 2095: =item * screenname($uname,$udom)
 2096: 
 2097: Gets a users screenname and returns it as a string
 2098: 
 2099: =cut
 2100: 
 2101: sub screenname {
 2102:     my ($uname,$udom)=@_;
 2103:     if ($uname eq $env{'user.name'} &&
 2104: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2105:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2106:     return $names{'screenname'};
 2107: }
 2108: 
 2109: 
 2110: # ------------------------------------------------------------- Message Wrapper
 2111: 
 2112: sub messagewrapper {
 2113:     my ($link,$username,$domain,$subject,$text)=@_;
 2114:     return 
 2115:         '<a href="/adm/email?compose=individual&amp;'.
 2116:         'recname='.$username.'&amp;recdom='.$domain.
 2117: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2118:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2119: }
 2120: # --------------------------------------------------------------- Notes Wrapper
 2121: 
 2122: sub noteswrapper {
 2123:     my ($link,$un,$do)=@_;
 2124:     return 
 2125: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2126: }
 2127: # ------------------------------------------------------------- Aboutme Wrapper
 2128: 
 2129: sub aboutmewrapper {
 2130:     my ($link,$username,$domain,$target)=@_;
 2131:     if (!defined($username)  && !defined($domain)) {
 2132:         return;
 2133:     }
 2134:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2135: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2136: }
 2137: 
 2138: # ------------------------------------------------------------ Syllabus Wrapper
 2139: 
 2140: 
 2141: sub syllabuswrapper {
 2142:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2143:     if ($fontcolor) { 
 2144:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2145:     }
 2146:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2147: }
 2148: 
 2149: sub track_student_link {
 2150:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2151:     my $link ="/adm/trackstudent?";
 2152:     my $title = 'View recent activity';
 2153:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2154:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2155:         $link .= "selected_student=$sname:$sdom";
 2156:         $title .= ' of this student';
 2157:     } 
 2158:     if (defined($target) && $target !~ /^\s*$/) {
 2159:         $target = qq{target="$target"};
 2160:     } else {
 2161:         $target = '';
 2162:     }
 2163:     if ($start) { $link.='&amp;start='.$start; }
 2164:     
 2165:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2166: 	&help_open_topic('View_recent_activity');
 2167: }
 2168: 
 2169: =pod
 2170: 
 2171: =back
 2172: 
 2173: =head1 Access .tab File Data
 2174: 
 2175: =over 4
 2176: 
 2177: =item * languageids() 
 2178: 
 2179: returns list of all language ids
 2180: 
 2181: =cut
 2182: 
 2183: sub languageids {
 2184:     return sort(keys(%language));
 2185: }
 2186: 
 2187: =pod
 2188: 
 2189: =item * languagedescription() 
 2190: 
 2191: returns description of a specified language id
 2192: 
 2193: =cut
 2194: 
 2195: sub languagedescription {
 2196:     my $code=shift;
 2197:     return  ($supported_language{$code}?'* ':'').
 2198:             $language{$code}.
 2199: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2200: }
 2201: 
 2202: sub plainlanguagedescription {
 2203:     my $code=shift;
 2204:     return $language{$code};
 2205: }
 2206: 
 2207: sub supportedlanguagecode {
 2208:     my $code=shift;
 2209:     return $supported_language{$code};
 2210: }
 2211: 
 2212: =pod
 2213: 
 2214: =item * copyrightids() 
 2215: 
 2216: returns list of all copyrights
 2217: 
 2218: =cut
 2219: 
 2220: sub copyrightids {
 2221:     return sort(keys(%cprtag));
 2222: }
 2223: 
 2224: =pod
 2225: 
 2226: =item * copyrightdescription() 
 2227: 
 2228: returns description of a specified copyright id
 2229: 
 2230: =cut
 2231: 
 2232: sub copyrightdescription {
 2233:     return &mt($cprtag{shift(@_)});
 2234: }
 2235: 
 2236: =pod
 2237: 
 2238: =item * source_copyrightids() 
 2239: 
 2240: returns list of all source copyrights
 2241: 
 2242: =cut
 2243: 
 2244: sub source_copyrightids {
 2245:     return sort(keys(%scprtag));
 2246: }
 2247: 
 2248: =pod
 2249: 
 2250: =item * source_copyrightdescription() 
 2251: 
 2252: returns description of a specified source copyright id
 2253: 
 2254: =cut
 2255: 
 2256: sub source_copyrightdescription {
 2257:     return &mt($scprtag{shift(@_)});
 2258: }
 2259: 
 2260: =pod
 2261: 
 2262: =item * filecategories() 
 2263: 
 2264: returns list of all file categories
 2265: 
 2266: =cut
 2267: 
 2268: sub filecategories {
 2269:     return sort(keys(%category_extensions));
 2270: }
 2271: 
 2272: =pod
 2273: 
 2274: =item * filecategorytypes() 
 2275: 
 2276: returns list of file types belonging to a given file
 2277: category
 2278: 
 2279: =cut
 2280: 
 2281: sub filecategorytypes {
 2282:     my ($cat) = @_;
 2283:     return @{$category_extensions{lc($cat)}};
 2284: }
 2285: 
 2286: =pod
 2287: 
 2288: =item * fileembstyle() 
 2289: 
 2290: returns embedding style for a specified file type
 2291: 
 2292: =cut
 2293: 
 2294: sub fileembstyle {
 2295:     return $fe{lc(shift(@_))};
 2296: }
 2297: 
 2298: sub filemimetype {
 2299:     return $fm{lc(shift(@_))};
 2300: }
 2301: 
 2302: 
 2303: sub filecategoryselect {
 2304:     my ($name,$value)=@_;
 2305:     return &select_form($value,$name,
 2306: 			'' => &mt('Any category'),
 2307: 			map { $_,$_ } sort(keys(%category_extensions)));
 2308: }
 2309: 
 2310: =pod
 2311: 
 2312: =item * filedescription() 
 2313: 
 2314: returns description for a specified file type
 2315: 
 2316: =cut
 2317: 
 2318: sub filedescription {
 2319:     my $file_description = $fd{lc(shift())};
 2320:     $file_description =~ s:([\[\]]):~$1:g;
 2321:     return &mt($file_description);
 2322: }
 2323: 
 2324: =pod
 2325: 
 2326: =item * filedescriptionex() 
 2327: 
 2328: returns description for a specified file type with
 2329: extra formatting
 2330: 
 2331: =cut
 2332: 
 2333: sub filedescriptionex {
 2334:     my $ex=shift;
 2335:     my $file_description = $fd{lc($ex)};
 2336:     $file_description =~ s:([\[\]]):~$1:g;
 2337:     return '.'.$ex.' '.&mt($file_description);
 2338: }
 2339: 
 2340: # End of .tab access
 2341: =pod
 2342: 
 2343: =back
 2344: 
 2345: =cut
 2346: 
 2347: # ------------------------------------------------------------------ File Types
 2348: sub fileextensions {
 2349:     return sort(keys(%fe));
 2350: }
 2351: 
 2352: # ----------------------------------------------------------- Display Languages
 2353: # returns a hash with all desired display languages
 2354: #
 2355: 
 2356: sub display_languages {
 2357:     my %languages=();
 2358:     foreach my $lang (&preferred_languages()) {
 2359: 	$languages{$lang}=1;
 2360:     }
 2361:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2362:     if ($env{'form.displaylanguage'}) {
 2363: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2364: 	    $languages{$lang}=1;
 2365:         }
 2366:     }
 2367:     return %languages;
 2368: }
 2369: 
 2370: sub preferred_languages {
 2371:     my @languages=();
 2372:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2373: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2374: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2375:     }
 2376:     if ($env{'environment.languages'}) {
 2377: 	@languages=(@languages,
 2378: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2379:     }
 2380:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 2381:     if ($browser) {
 2382: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 2383:     }
 2384:     if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
 2385: 	@languages=(@languages,
 2386: 		$Apache::lonnet::domain_lang_def{$env{'user.domain'}});
 2387:     }
 2388:     if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
 2389: 	@languages=(@languages,
 2390: 		$Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
 2391:     }
 2392:     if ($Apache::lonnet::domain_lang_def{
 2393: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 2394: 	@languages=(@languages,
 2395: 		$Apache::lonnet::domain_lang_def{
 2396:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 2397:     }
 2398: # turn "en-ca" into "en-ca,en"
 2399:     my @genlanguages;
 2400:     foreach my $lang (@languages) {
 2401: 	unless ($lang=~/\w/) { next; }
 2402: 	push (@genlanguages,$lang);
 2403: 	if ($lang=~/(\-|\_)/) {
 2404: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2405: 	}
 2406:     }
 2407:     return @genlanguages;
 2408: }
 2409: 
 2410: ###############################################################
 2411: ##               Student Answer Attempts                     ##
 2412: ###############################################################
 2413: 
 2414: =pod
 2415: 
 2416: =head1 Alternate Problem Views
 2417: 
 2418: =over 4
 2419: 
 2420: =item * get_previous_attempt($symb, $username, $domain, $course,
 2421:     $getattempt, $regexp, $gradesub)
 2422: 
 2423: Return string with previous attempt on problem. Arguments:
 2424: 
 2425: =over 4
 2426: 
 2427: =item * $symb: Problem, including path
 2428: 
 2429: =item * $username: username of the desired student
 2430: 
 2431: =item * $domain: domain of the desired student
 2432: 
 2433: =item * $course: Course ID
 2434: 
 2435: =item * $getattempt: Leave blank for all attempts, otherwise put
 2436:     something
 2437: 
 2438: =item * $regexp: if string matches this regexp, the string will be
 2439:     sent to $gradesub
 2440: 
 2441: =item * $gradesub: routine that processes the string if it matches $regexp
 2442: 
 2443: =back
 2444: 
 2445: The output string is a table containing all desired attempts, if any.
 2446: 
 2447: =cut
 2448: 
 2449: sub get_previous_attempt {
 2450:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2451:   my $prevattempts='';
 2452:   no strict 'refs';
 2453:   if ($symb) {
 2454:     my (%returnhash)=
 2455:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2456:     if ($returnhash{'version'}) {
 2457:       my %lasthash=();
 2458:       my $version;
 2459:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2460:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2461: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 2462:         }
 2463:       }
 2464:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2465:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2466:       foreach my $key (sort(keys(%lasthash))) {
 2467: 	my ($ign,@parts) = split(/\./,$key);
 2468: 	if ($#parts > 0) {
 2469: 	  my $data=$parts[-1];
 2470: 	  pop(@parts);
 2471: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2472: 	} else {
 2473: 	  if ($#parts == 0) {
 2474: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2475: 	  } else {
 2476: 	    $prevattempts.='<th>'.$ign.'</th>';
 2477: 	  }
 2478: 	}
 2479:       }
 2480:       if ($getattempt eq '') {
 2481: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2482: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2483: 	    foreach my $key (sort(keys(%lasthash))) {
 2484: 	       my $value;
 2485: 	       if ($key =~ /timestamp/) {
 2486: 		  $value=scalar(localtime($returnhash{$version.':'.$key}));
 2487: 	       } else {
 2488: 		  $value=$returnhash{$version.':'.$key};
 2489: 	       }
 2490: 	       $prevattempts.='<td>'.&unescape($value).'&nbsp;</td>';   
 2491: 	    }
 2492: 	 }
 2493:       }
 2494:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2495:       foreach my $key (sort(keys(%lasthash))) {
 2496: 	my $value;
 2497: 	if ($key =~ /timestamp/) {
 2498: 	  $value=scalar(localtime($lasthash{$key}));
 2499: 	} else {
 2500: 	  $value=$lasthash{$key};
 2501: 	}
 2502: 	$value=&unescape($value);
 2503: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2504: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2505:       }
 2506:       $prevattempts.='</tr></table></td></tr></table>';
 2507:     } else {
 2508:       $prevattempts='Nothing submitted - no attempts.';
 2509:     }
 2510:   } else {
 2511:     $prevattempts='No data.';
 2512:   }
 2513: }
 2514: 
 2515: sub relative_to_absolute {
 2516:     my ($url,$output)=@_;
 2517:     my $parser=HTML::TokeParser->new(\$output);
 2518:     my $token;
 2519:     my $thisdir=$url;
 2520:     my @rlinks=();
 2521:     while ($token=$parser->get_token) {
 2522: 	if ($token->[0] eq 'S') {
 2523: 	    if ($token->[1] eq 'a') {
 2524: 		if ($token->[2]->{'href'}) {
 2525: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 2526: 		}
 2527: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 2528: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2529: 	    } elsif ($token->[1] eq 'base') {
 2530: 		$thisdir=$token->[2]->{'href'};
 2531: 	    }
 2532: 	}
 2533:     }
 2534:     $thisdir=~s-/[^/]*$--;
 2535:     foreach my $link (@rlinks) {
 2536: 	unless (($link=~/^http:\/\//i) ||
 2537: 		($link=~/^\//) ||
 2538: 		($link=~/^javascript:/i) ||
 2539: 		($link=~/^mailto:/i) ||
 2540: 		($link=~/^\#/)) {
 2541: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 2542: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 2543: 	}
 2544:     }
 2545: # -------------------------------------------------- Deal with Applet codebases
 2546:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2547:     return $output;
 2548: }
 2549: 
 2550: =pod
 2551: 
 2552: =item * get_student_view
 2553: 
 2554: show a snapshot of what student was looking at
 2555: 
 2556: =cut
 2557: 
 2558: sub get_student_view {
 2559:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 2560:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2561:   my (%form);
 2562:   my @elements=('symb','courseid','domain','username');
 2563:   foreach my $element (@elements) {
 2564:       $form{'grade_'.$element}=eval '$'.$element #'
 2565:   }
 2566:   if (defined($moreenv)) {
 2567:       %form=(%form,%{$moreenv});
 2568:   }
 2569:   if (defined($target)) { $form{'grade_target'} = $target; }
 2570:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2571:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 2572:   $userview=~s/\<body[^\>]*\>//gi;
 2573:   $userview=~s/\<\/body\>//gi;
 2574:   $userview=~s/\<html\>//gi;
 2575:   $userview=~s/\<\/html\>//gi;
 2576:   $userview=~s/\<head\>//gi;
 2577:   $userview=~s/\<\/head\>//gi;
 2578:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2579:   $userview=&relative_to_absolute($feedurl,$userview);
 2580:   return $userview;
 2581: }
 2582: 
 2583: =pod
 2584: 
 2585: =item * get_student_answers() 
 2586: 
 2587: show a snapshot of how student was answering problem
 2588: 
 2589: =cut
 2590: 
 2591: sub get_student_answers {
 2592:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2593:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2594:   my (%moreenv);
 2595:   my @elements=('symb','courseid','domain','username');
 2596:   foreach my $element (@elements) {
 2597:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 2598:   }
 2599:   $moreenv{'grade_target'}='answer';
 2600:   %moreenv=(%form,%moreenv);
 2601:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
 2602:   return $userview;
 2603: }
 2604: 
 2605: =pod
 2606: 
 2607: =item * &submlink()
 2608: 
 2609: Inputs: $text $uname $udom $symb $target
 2610: 
 2611: Returns: A link to grades.pm such as to see the SUBM view of a student
 2612: 
 2613: =cut
 2614: 
 2615: ###############################################
 2616: sub submlink {
 2617:     my ($text,$uname,$udom,$symb,$target)=@_;
 2618:     if (!($uname && $udom)) {
 2619: 	(my $cursymb, my $courseid,$udom,$uname)=
 2620: 	    &Apache::lonnet::whichuser($symb);
 2621: 	if (!$symb) { $symb=$cursymb; }
 2622:     }
 2623:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2624:     $symb=&escape($symb);
 2625:     if ($target) { $target="target=\"$target\""; }
 2626:     return '<a href="/adm/grades?&command=submission&'.
 2627: 	'symb='.$symb.'&student='.$uname.
 2628: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 2629: }
 2630: ##############################################
 2631: 
 2632: =pod
 2633: 
 2634: =item * &pgrdlink()
 2635: 
 2636: Inputs: $text $uname $udom $symb $target
 2637: 
 2638: Returns: A link to grades.pm such as to see the PGRD view of a student
 2639: 
 2640: =cut
 2641: 
 2642: ###############################################
 2643: sub pgrdlink {
 2644:     my $link=&submlink(@_);
 2645:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 2646:     return $link;
 2647: }
 2648: ##############################################
 2649: 
 2650: =pod
 2651: 
 2652: =item * &pprmlink()
 2653: 
 2654: Inputs: $text $uname $udom $symb $target
 2655: 
 2656: Returns: A link to parmset.pm such as to see the PPRM view of a
 2657: student and a specific resource
 2658: 
 2659: =cut
 2660: 
 2661: ###############################################
 2662: sub pprmlink {
 2663:     my ($text,$uname,$udom,$symb,$target)=@_;
 2664:     if (!($uname && $udom)) {
 2665: 	(my $cursymb, my $courseid,$udom,$uname)=
 2666: 	    &Apache::lonnet::whichuser($symb);
 2667: 	if (!$symb) { $symb=$cursymb; }
 2668:     }
 2669:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2670:     $symb=&escape($symb);
 2671:     if ($target) { $target="target=\"$target\""; }
 2672:     return '<a href="/adm/parmset?&command=set&'.
 2673: 	'symb='.$symb.'&uname='.$uname.
 2674: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
 2675: }
 2676: ##############################################
 2677: 
 2678: =pod
 2679: 
 2680: =back
 2681: 
 2682: =cut
 2683: 
 2684: ###############################################
 2685: 
 2686: 
 2687: sub timehash {
 2688:     my @ltime=localtime(shift);
 2689:     return ( 'seconds' => $ltime[0],
 2690:              'minutes' => $ltime[1],
 2691:              'hours'   => $ltime[2],
 2692:              'day'     => $ltime[3],
 2693:              'month'   => $ltime[4]+1,
 2694:              'year'    => $ltime[5]+1900,
 2695:              'weekday' => $ltime[6],
 2696:              'dayyear' => $ltime[7]+1,
 2697:              'dlsav'   => $ltime[8] );
 2698: }
 2699: 
 2700: sub utc_string {
 2701:     my ($date)=@_;
 2702:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 2703: }
 2704: 
 2705: sub maketime {
 2706:     my %th=@_;
 2707:     return POSIX::mktime(
 2708:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2709:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 2710: }
 2711: 
 2712: #########################################
 2713: 
 2714: sub findallcourses {
 2715:     my ($roles) = @_;
 2716:     my %roles;
 2717:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 2718:     my %courses;
 2719:     my $now=time;
 2720:     foreach my $key (keys(%env)) {
 2721: 	if ( $key=~m{^user\.role\.(\w+)\./(\w+)/(\w+)} ) {
 2722: 	    my ($role,$domain,$id) = ($1,$2,$3);
 2723: 	    next if ($role eq 'ca' || $role eq 'aa');
 2724: 	    next if (%roles && !exists($roles{$role}));
 2725: 	    my ($starttime,$endtime)=split(/\./,$env{$key});
 2726:             my $active=1;
 2727:             if ($starttime) {
 2728: 		if ($now<$starttime) { $active=0; }
 2729:             }
 2730:             if ($endtime) {
 2731:                 if ($now>$endtime) { $active=0; }
 2732:             }
 2733:             if ($active) { $courses{$domain.'_'.$id}=1; }
 2734:         }
 2735:     }
 2736:     return keys(%courses);
 2737: }
 2738: 
 2739: ###############################################
 2740: ###############################################
 2741: 
 2742: =pod
 2743: 
 2744: =head1 Domain Template Functions
 2745: 
 2746: =over 4
 2747: 
 2748: =item * &determinedomain()
 2749: 
 2750: Inputs: $domain (usually will be undef)
 2751: 
 2752: Returns: Determines which domain should be used for designs
 2753: 
 2754: =cut
 2755: 
 2756: ###############################################
 2757: sub determinedomain {
 2758:     my $domain=shift;
 2759:    if (! $domain) {
 2760:         # Determine domain if we have not been given one
 2761:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2762:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 2763:         if ($env{'request.role.domain'}) { 
 2764:             $domain=$env{'request.role.domain'}; 
 2765:         }
 2766:     }
 2767:     return $domain;
 2768: }
 2769: ###############################################
 2770: =pod
 2771: 
 2772: =item * &domainlogo()
 2773: 
 2774: Inputs: $domain (usually will be undef)
 2775: 
 2776: Returns: A link to a domain logo, if the domain logo exists.
 2777: If the domain logo does not exist, a description of the domain.
 2778: 
 2779: =cut
 2780: 
 2781: ###############################################
 2782: sub domainlogo {
 2783:     my $domain = &determinedomain(shift);    
 2784:      # See if there is a logo
 2785:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2786: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
 2787:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
 2788:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2789:         return $Apache::lonnet::domaindescription{$domain};
 2790:     } else {
 2791:         return '';
 2792:     }
 2793: }
 2794: ##############################################
 2795: 
 2796: =pod
 2797: 
 2798: =item * &designparm()
 2799: 
 2800: Inputs: $which parameter; $domain (usually will be undef)
 2801: 
 2802: Returns: value of designparamter $which
 2803: 
 2804: =cut
 2805: 
 2806: 
 2807: ##############################################
 2808: sub designparm {
 2809:     my ($which,$domain)=@_;
 2810:     if ($env{'browser.blackwhite'} eq 'on') {
 2811: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 2812: 	    return '#000000';
 2813: 	}
 2814: 	if ($which=~/\.(pgbg|sidebg)$/) {
 2815: 	    return '#FFFFFF';
 2816: 	}
 2817: 	if ($which=~/\.tabbg$/) {
 2818: 	    return '#CCCCCC';
 2819: 	}
 2820:     }
 2821:     if (exists($env{'environment.color.'.$which})) {
 2822: 	return $env{'environment.color.'.$which};
 2823:     }
 2824:     $domain=&determinedomain($domain);
 2825:     if (exists($designhash{$domain.'.'.$which})) {
 2826: 	return $designhash{$domain.'.'.$which};
 2827:     } else {
 2828:         return $designhash{'default.'.$which};
 2829:     }
 2830: }
 2831: 
 2832: ###############################################
 2833: ###############################################
 2834: 
 2835: =pod
 2836: 
 2837: =back
 2838: 
 2839: =head1 HTTP Helpers
 2840: 
 2841: =over 4
 2842: 
 2843: =item * &bodytag()
 2844: 
 2845: Returns a uniform header for LON-CAPA web pages.
 2846: 
 2847: Inputs: 
 2848: 
 2849: =over 4
 2850: 
 2851: =item * $title, A title to be displayed on the page.
 2852: 
 2853: =item * $function, the current role (can be undef).
 2854: 
 2855: =item * $addentries, extra parameters for the <body> tag.
 2856: 
 2857: =item * $bodyonly, if defined, only return the <body> tag.
 2858: 
 2859: =item * $domain, if defined, force a given domain.
 2860: 
 2861: =item * $forcereg, if page should register as content page (relevant for 
 2862:             text interface only)
 2863: 
 2864: =item * $customtitle, alternate text to use instead of $title
 2865:                       in the title box that appears, this text
 2866:                       is not auto translated like the $title is
 2867: 
 2868: =item * $notopbar, if true, keep the 'what is this' info but remove the
 2869:                    navigational links
 2870: 
 2871: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 2872: 
 2873: =item * $notitle, if true keep the nav controls, but remove the title bar
 2874: 
 2875: =item * $no_inline_link, if true and in remote mode, don't show the 
 2876:          'Switch To Inline Menu' link
 2877: 
 2878: =item * $args, optional argument valid values are
 2879:             no_auto_mt_title -> prevents &mt()ing the title arg
 2880: 
 2881: =back
 2882: 
 2883: Returns: A uniform header for LON-CAPA web pages.  
 2884: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2885: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2886: other decorations will be returned.
 2887: 
 2888: =cut
 2889: 
 2890: sub bodytag {
 2891:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 2892: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 2893: 
 2894:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 2895: 
 2896:     $function = &get_users_function() if (!$function);
 2897:     my $img =    &designparm($function.'.img',$domain);
 2898:     my $font =   &designparm($function.'.font',$domain);
 2899:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 2900: 
 2901:     my %design = ( 'style'   => 'margin-top: 0px',
 2902: 		   'bgcolor' => $pgbg,
 2903: 		   'text'    => $font,
 2904:                    'alink'   => &designparm($function.'.alink',$domain),
 2905: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 2906: 		   'link'    => &designparm($function.'.link',$domain),);
 2907:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 2908: 
 2909:  # role and realm
 2910:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 2911:     if ($role  eq 'ca') {
 2912:         my ($rdom,$rname) = ($realm =~ m-^/(\w+)/(\w+)$-);
 2913:         $realm = &plainname($rname,$rdom).':'.$rdom;
 2914:     } 
 2915: # realm
 2916:     if ($env{'request.course.id'}) {
 2917:         if ($env{'request.role'} !~ /^cr/) {
 2918:             $role = &Apache::lonnet::plaintext($role,&course_type());
 2919:         }
 2920: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 2921:     } else {
 2922:         $role = &Apache::lonnet::plaintext($role);
 2923:     }
 2924: 
 2925:     if (!$realm) { $realm='&nbsp;'; }
 2926: # Set messages
 2927:     my $messages=&domainlogo($domain);
 2928: # Port for miniserver
 2929:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2930:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2931: 
 2932:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 2933: 
 2934: # construct main body tag
 2935:     my $bodytag = "<body $extra_body_attr>".
 2936: 	&Apache::lontexconvert::init_math_support();
 2937: 
 2938:     if ($bodyonly 
 2939: 	|| ($env{'request.state'} eq 'construct' 
 2940: 	    && $env{'environment.remote'} ne 'off' )) {
 2941:         return $bodytag;
 2942:     } elsif ($env{'browser.interface'} eq 'textual') {
 2943: # Accessibility
 2944:           
 2945: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 2946: 	if (!$notitle) {
 2947: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 2948: 	}
 2949: 	return $bodytag;
 2950:     }
 2951: 
 2952:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 2953:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 2954: 	undef($role);
 2955:     } else {
 2956: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 2957:     }
 2958:     
 2959:     my $roleinfo=(<<ENDROLE);
 2960: <td class="LC_title_bar_who">
 2961: <div class="LC_title_bar_name">
 2962:     $name
 2963:     &nbsp;
 2964: </div>
 2965: <div class="LC_title_bar_role">
 2966: $role&nbsp;
 2967: </div>
 2968: <div class="LC_title_bar_realm">
 2969: $realm&nbsp;
 2970: </div>
 2971: </td>
 2972: ENDROLE
 2973: 
 2974:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 2975:     if ($customtitle) {
 2976:         $titleinfo = $customtitle;
 2977:     }
 2978:     #
 2979:     # Extra info if you are the DC
 2980:     my $dc_info = '';
 2981:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 2982:                         $env{'course.'.$env{'request.course.id'}.
 2983:                                  '.domain'}.'/'})) {
 2984:         my $cid = $env{'request.course.id'};
 2985:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 2986:         $dc_info =~ s/\s+$//;
 2987:         $dc_info = '('.$dc_info.')';
 2988:     }
 2989: 
 2990:     if ($env{'environment.remote'} eq 'off') {
 2991:         # No Remote
 2992: 	if ($env{'request.state'} eq 'construct') {
 2993: 	    $forcereg=1;
 2994: 	}
 2995: 
 2996: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 2997: 	    # this is for resources; directories have customtitle, and crumbs
 2998:             # and select recent are created in lonpubdir.pm  
 2999: 	    my ($uname,$thisdisfn)=
 3000: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 3001: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 3002: 	    $formaction=~s/\/+/\//g;
 3003: 
 3004: 	    my $parentpath = '';
 3005: 	    my $lastitem = '';
 3006: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 3007: 		$parentpath = $1;
 3008: 		$lastitem = $2;
 3009: 	    } else {
 3010: 		$lastitem = $thisdisfn;
 3011: 	    }
 3012: 	    $titleinfo = 
 3013: 		&Apache::loncommon::help_open_menu('','',3,'Authoring').
 3014: 		'<b>Construction Space</b>:&nbsp;'. 
 3015: 		'<form name="dirs" method="post" action="'.$formaction
 3016: 		.'" target="_top"><tt><b>'
 3017: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 3018: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 3019: 		.'</form>'
 3020: 		.&Apache::lonmenu::constspaceform();
 3021:         }
 3022: 
 3023:         my $titletable;
 3024: 	if (!$notitle) {
 3025: 	    $titletable =
 3026: 		'<table id="LC_title_bar">'.
 3027:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 3028: 			 '</tr></table>';
 3029: 	}
 3030: 	if ($notopbar) {
 3031: 	    $bodytag .= $titletable;
 3032: 	} else {
 3033: 	    if ($env{'request.state'} eq 'construct') {
 3034:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 3035: 							  $titletable);
 3036:             } else {
 3037:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 3038: 		    $titletable;
 3039:             }
 3040:         }
 3041:         return $bodytag;
 3042:     }
 3043: 
 3044: #
 3045: # Top frame rendering, Remote is up
 3046: #
 3047: 
 3048:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 3049:         $lonhttpdPort.$img.'" alt="'.$function.'" />';
 3050: 
 3051:     # Explicit link to get inline menu
 3052:     my $menu= ($no_inline_link?''
 3053: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 3054:     #
 3055:     if ($notitle) {
 3056: 	return $bodytag;
 3057:     }
 3058:     return(<<ENDBODY);
 3059: $bodytag
 3060: <table id="LC_title_bar" class="LC_with_remote">
 3061: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 3062:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 3063: </tr>
 3064: <tr><td>$titleinfo $dc_info $menu</td>
 3065: $roleinfo
 3066: </tr>
 3067: </table>
 3068: ENDBODY
 3069: }
 3070: 
 3071: sub make_attr_string {
 3072:     my ($register,$attr_ref) = @_;
 3073: 
 3074:     if ($attr_ref && !ref($attr_ref)) {
 3075: 	die("addentries Must be a hash ref ".
 3076: 	    join(':',caller(1))." ".
 3077: 	    join(':',caller(0))." ");
 3078:     }
 3079: 
 3080:     if ($register) {
 3081: 	my ($on_load,$on_unload);
 3082: 	foreach my $key (keys(%{$attr_ref})) {
 3083: 	    if      (lc($key) eq 'onload') {
 3084: 		$on_load.=$attr_ref->{$key}.';';
 3085: 		delete($attr_ref->{$key});
 3086: 
 3087: 	    } elsif (lc($key) eq 'onunload') {
 3088: 		$on_unload.=$attr_ref->{$key}.';';
 3089: 		delete($attr_ref->{$key});
 3090: 	    }
 3091: 	}
 3092: 	$attr_ref->{'onload'}  =
 3093: 	    &Apache::lonmenu::loadevents().  $on_load;
 3094: 	$attr_ref->{'onunload'}=
 3095: 	    &Apache::lonmenu::unloadevents().$on_unload;
 3096:     }
 3097: 
 3098: # Accessibility font enhance
 3099:     if ($env{'browser.fontenhance'} eq 'on') {
 3100: 	my $style;
 3101: 	foreach my $key (keys(%{$attr_ref})) {
 3102: 	    if (lc($key) eq 'style') {
 3103: 		$style.=$attr_ref->{$key}.';';
 3104: 		delete($attr_ref->{$key});
 3105: 	    }
 3106: 	}
 3107: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 3108:     }
 3109: 
 3110:     if ($env{'browser.blackwhite'} eq 'on') {
 3111: 	delete($attr_ref->{'font'});
 3112: 	delete($attr_ref->{'link'});
 3113: 	delete($attr_ref->{'alink'});
 3114: 	delete($attr_ref->{'vlink'});
 3115: 	delete($attr_ref->{'bgcolor'});
 3116: 	delete($attr_ref->{'background'});
 3117:     }
 3118: 
 3119:     my $attr_string;
 3120:     foreach my $attr (keys(%$attr_ref)) {
 3121: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 3122:     }
 3123:     return $attr_string;
 3124: }
 3125: 
 3126: 
 3127: ###############################################
 3128: ###############################################
 3129: 
 3130: =pod
 3131: 
 3132: =back
 3133: 
 3134: =head1 HTML Helpers
 3135: 
 3136: =over 4
 3137: 
 3138: =item * &endbodytag()
 3139: 
 3140: Returns a uniform footer for LON-CAPA web pages.
 3141: 
 3142: Inputs: none
 3143: 
 3144: =back
 3145: 
 3146: =cut
 3147: 
 3148: sub endbodytag {
 3149:     my $endbodytag='</body>';
 3150:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 3151:     if ( exists( $env{'internal.head.redirect'} ) ) {
 3152: 	$endbodytag=
 3153: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
 3154: 	    &mt('Continue').'</a>'.
 3155: 	    $endbodytag;
 3156:     }
 3157:     return $endbodytag;
 3158: }
 3159: 
 3160: =pod
 3161: 
 3162: =over 4
 3163: 
 3164: =item * &standard_css()
 3165: 
 3166: Returns a style sheet
 3167: 
 3168: Inputs: (all optional)
 3169:             domain         -> force to color decorate a page for a specific
 3170:                                domain
 3171:             function       -> force usage of a specific rolish color scheme
 3172:             bgcolor        -> override the default page bgcolor
 3173: 
 3174: =back
 3175: 
 3176: =cut
 3177: 
 3178: sub standard_css {
 3179:     my ($function,$domain,$bgcolor) = @_;
 3180:     $function  = &get_users_function() if (!$function);
 3181:     my $img    = &designparm($function.'.img',   $domain);
 3182:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 3183:     my $font   = &designparm($function.'.font',  $domain);
 3184:     my $sidebg = &designparm($function.'.sidebg',$domain);
 3185:     my $pgbg_or_bgcolor =
 3186: 	         $bgcolor ||
 3187: 	         &designparm($function.'.pgbg',  $domain);
 3188:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 3189:     my $alink  = &designparm($function.'.alink', $domain);
 3190:     my $vlink  = &designparm($function.'.vlink', $domain);
 3191:     my $link   = &designparm($function.'.link',  $domain);
 3192: 
 3193:     my $sans                 = 'Arial,Helvetica,sans-serif';
 3194:     my $mono                 = 'monospace';
 3195:     my $data_table_head      = $tabbg;
 3196:     my $data_table_light     = '#EEEEEE';
 3197:     my $data_table_dark      = '#DDD';
 3198:     my $data_table_darker    = '#CCC';
 3199:     my $data_table_highlight = '#FFFF00';
 3200:     my $mail_new             = '#FFBB77';
 3201:     my $mail_new_hover       = '#DD9955';
 3202:     my $mail_read            = '#BBBB77';
 3203:     my $mail_read_hover      = '#999944';
 3204:     my $mail_replied         = '#AAAA88';
 3205:     my $mail_replied_hover   = '#888855';
 3206:     my $mail_other           = '#99BBBB';
 3207:     my $mail_other_hover     = '#669999';
 3208:     my $table_header         = '#DDDDDD';
 3209: 
 3210:     my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
 3211: 	                                              : '0px 3px 0px 4px';
 3212: 
 3213:     return <<END;
 3214: h1, h2, h3, th { font-family: $sans }
 3215: a:focus { color: red; background: yellow } 
 3216: table.thinborder { border-collapse: collapse; }
 3217: table.thinborder tr th {  border-style: solid; border-width: 1px; background: $tabbg;}
 3218: table.thinborder tr td { border-style: solid; border-width: 1px}
 3219: 
 3220: form, .inline { display: inline; }
 3221: .center { text-align: center; }
 3222: .LC_filename {font-family: $mono;}
 3223: .LC_error {
 3224:   color: red;
 3225:   font-size: larger;
 3226: }
 3227: .LC_warning,
 3228: .LC_diff_removed {
 3229:   color: red;
 3230: }
 3231: .LC_success,
 3232: .LC_diff_added {
 3233:   color: green;
 3234: }
 3235: .LC_icon {
 3236:   border: 0px;
 3237: }
 3238: 
 3239: table.LC_pastsubmission {
 3240:   border: 1px solid black;
 3241:   margin: 2px;
 3242: }
 3243: 
 3244: table#LC_top_nav, table#LC_menubuttons {
 3245:   width: 100%;
 3246:   background: $pgbg;
 3247:   border: 2px;
 3248:   border-collapse: separate;
 3249:   padding: 0px;
 3250: }
 3251: 
 3252: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
 3253: table#LC_title_bar.LC_with_remote {
 3254:   width: 100%;
 3255:   border-color: $pgbg;
 3256:   border-style: solid;
 3257:   border-width: $border;
 3258: 
 3259:   background: $pgbg;
 3260:   font-family: $sans;
 3261:   border-collapse: collapse;
 3262:   padding: 0px;
 3263: }
 3264: 
 3265: table.LC_docs_path {
 3266:   width: 100%;
 3267:   border: 0;
 3268:   background: $pgbg;
 3269:   font-family: $sans;
 3270:   border-collapse: collapse;
 3271:   padding: 0px;
 3272: }
 3273: 
 3274: table#LC_title_bar td {
 3275:   background: $tabbg;
 3276: }
 3277: table#LC_title_bar td.LC_title_bar_who {
 3278:   background: $tabbg;
 3279:   color: $font;
 3280:   font: small $sans;
 3281:   text-align: right;
 3282: }
 3283: span.LC_title_bar_title {
 3284:   font: bold x-large $sans;
 3285: }
 3286: table#LC_title_bar td.LC_title_bar_domain_logo {
 3287:   background: $sidebg;
 3288:   text-align: right;
 3289:   padding: 0px;
 3290: }
 3291: table#LC_title_bar td.LC_title_bar_role_logo {
 3292:   background: $sidebg;
 3293:   padding: 0px;
 3294: }
 3295: 
 3296: table#LC_menubuttons_mainmenu {
 3297:   background: $pgbg;
 3298:   border: 0px;
 3299:   border-spacing: 1px;
 3300:   padding: 0px 1px;
 3301:   margin: 0px;
 3302:   border-collapse: separate;
 3303: }
 3304: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 3305:   border: 0px;
 3306: }
 3307: table#LC_top_nav td {
 3308:   background: $tabbg;
 3309:   border: 0px;
 3310:   font-size: small;
 3311: }
 3312: table#LC_top_nav td a, div#LC_top_nav a {
 3313:   color: $font;
 3314:   font-family: $sans;
 3315: }
 3316: table#LC_top_nav td.LC_top_nav_logo {
 3317:   background: $tabbg;
 3318:   text-align: left;
 3319:   white-space: nowrap;
 3320:   width: 31px;
 3321: }
 3322: table#LC_top_nav td.LC_top_nav_logo img {
 3323:   border: 0px;
 3324:   vertical-align: bottom;
 3325: }
 3326: table#LC_top_nav td.LC_top_nav_exit,
 3327: table#LC_top_nav td.LC_top_nav_help {
 3328:   width: 2.0em;
 3329: }
 3330: table#LC_top_nav td.LC_top_nav_login {
 3331:   width: 4.0em;
 3332:   text-align: center;
 3333: }
 3334: table.LC_breadcrumbs td, table.LC_docs_path td  {
 3335:   background: $tabbg;
 3336:   color: $font;
 3337:   font-family: $sans;
 3338:   font-size: smaller;
 3339: }
 3340: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 3341: table.LC_docs_path td.LC_docs_path_component {
 3342:   background: $tabbg;
 3343:   color: $font;
 3344:   font-family: $sans;
 3345:   font-size: larger;
 3346:   text-align: right;
 3347: }
 3348: td.LC_table_cell_checkbox {
 3349:   text-align: center;
 3350: }
 3351: 
 3352: .LC_menubuttons_inline_text {
 3353:   color: $font;
 3354:   font-family: $sans;
 3355:   font-size: smaller;
 3356: }
 3357: 
 3358: td.LC_menubuttons_text {
 3359:   color: $font;
 3360:   font-family: $sans;
 3361: }
 3362: td.LC_menubuttons_img {
 3363:   background: $tabbg;
 3364: }
 3365: .LC_current_location {
 3366:   font-family: $sans;
 3367:   background: $tabbg;
 3368: }
 3369: .LC_new_mail {
 3370:   font-family: $sans;
 3371:   font-weight: bold;
 3372: }
 3373: 
 3374: table.LC_aboutme_port {
 3375:   border: 0px;
 3376:   border-collapse: collapse;
 3377:   border-spacing: 0px;
 3378: }
 3379: table.LC_data_table, table.LC_mail_list {
 3380:   border: 1px solid #000000;
 3381:   border-collapse: separate;
 3382:   border-spacing: 1px;
 3383: }
 3384: .LC_data_table_dense {
 3385:   font-size: small;
 3386: }
 3387: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
 3388:   font-weight: bold;
 3389:   background-color: $data_table_head;
 3390:   font-size: smaller;
 3391: }
 3392: table.LC_data_table tr td, 
 3393: table.LC_aboutme_port tr td {
 3394:   background-color: $data_table_light;
 3395:   padding: 2px;
 3396: }
 3397: table.LC_data_table tr.LC_even_row td,
 3398: table.LC_aboutme_port tr.LC_even_row td {
 3399:   background-color: $data_table_dark;
 3400: }
 3401: table.LC_data_table tr.LC_data_table_highlight td {
 3402:   background-color: $data_table_darker;
 3403: }
 3404: table.LC_data_table tr.LC_empty_row td,
 3405: table.LC_whatsnew tr.LC_empty_row td {
 3406:   background-color: #FFFFFF;
 3407:   font-weight: bold;
 3408:   font-style: italic;
 3409:   text-align: center;
 3410:   padding: 8px;
 3411: }
 3412: table.LC_whatsnew tr.LC_empty_row td {
 3413:   padding: 4ex
 3414: }
 3415: 
 3416: 
 3417: table.LC_whatsnew {
 3418: }
 3419: 
 3420: table.LC_whatsnew tr th,
 3421: table.LC_whatsnew tr.LC_info_row td {
 3422:   background-color: #CCC;
 3423:   font-weight: bold;
 3424:   font-size: small;
 3425:   text-align: right;
 3426: }
 3427: table.LC_whatsnew tr td {
 3428:   background-color: #FFF;
 3429:   font-size: small;
 3430:   text-align: right;
 3431: }
 3432: table.LC_whatsnew tr td.LC_first_item {
 3433:   text-align: left;
 3434: }
 3435: 
 3436: table.LC_whatsnew tr.LC_odd_row td {
 3437:   background-color: #EEE;
 3438: }
 3439: 
 3440: table.LC_calendar {
 3441:   border: 1px solid #000000;
 3442:   border-collapse: collapse;
 3443: }
 3444: table.LC_calendar_pickdate {
 3445:   font-size: xx-small;
 3446: }
 3447: table.LC_calendar tr td {
 3448:   border: 1px solid #000000;
 3449:   vertical-align: top;
 3450: }
 3451: table.LC_calendar tr td.LC_calendar_day_empty {
 3452:   background-color: $data_table_dark;
 3453: }
 3454: table.LC_calendar tr td.LC_calendar_day_current {
 3455:   background-color: $data_table_highlight;
 3456: }
 3457: 
 3458: table.LC_mail_list tr.LC_mail_new {
 3459:   background-color: $mail_new;
 3460: }
 3461: table.LC_mail_list tr.LC_mail_new:hover {
 3462:   background-color: $mail_new_hover;
 3463: }
 3464: table.LC_mail_list tr.LC_mail_read {
 3465:   background-color: $mail_read;
 3466: }
 3467: table.LC_mail_list tr.LC_mail_read:hover {
 3468:   background-color: $mail_read_hover;
 3469: }
 3470: table.LC_mail_list tr.LC_mail_replied {
 3471:   background-color: $mail_replied;
 3472: }
 3473: table.LC_mail_list tr.LC_mail_replied:hover {
 3474:   background-color: $mail_replied_hover;
 3475: }
 3476: table.LC_mail_list tr.LC_mail_other {
 3477:   background-color: $mail_other;
 3478: }
 3479: table.LC_mail_list tr.LC_mail_other:hover {
 3480:   background-color: $mail_other_hover;
 3481: }
 3482: 
 3483: table#LC_portfolio_actions {
 3484:   width: auto;
 3485:   background: $pgbg;
 3486:   border: 0px;
 3487:   border-spacing: 2px 2px;
 3488:   padding: 0px;
 3489:   margin: 0px;
 3490:   border-collapse: separate;
 3491: }
 3492: table#LC_portfolio_actions td.LC_label {
 3493:   background: $tabbg;
 3494:   text-align: right;
 3495: }
 3496: table#LC_portfolio_actions td.LC_value {
 3497:   background: $tabbg;
 3498: }
 3499: 
 3500: table#LC_cstr_controls {
 3501:   width: 100%;
 3502:   border-collapse: collapse;
 3503: }
 3504: table#LC_cstr_controls tr td {
 3505:   border: 4px solid $pgbg;
 3506:   padding: 4px;
 3507:   text-align: center;
 3508:   background: $tabbg;
 3509: }
 3510: table#LC_cstr_controls tr th {
 3511:   border: 4px solid $pgbg;
 3512:   background: $table_header;
 3513:   text-align: center;
 3514:   font-family: $sans;
 3515:   font-size: smaller;
 3516: }
 3517: 
 3518: table#LC_browser {
 3519:  
 3520: }
 3521: table#LC_browser tr th {
 3522:   background: $table_header;
 3523: }
 3524: table#LC_browser tr td {
 3525:   padding: 2px;
 3526: }
 3527: table#LC_browser tr.LC_browser_file,
 3528: table#LC_browser tr.LC_browser_file_published {
 3529:   background: #CCFF88;
 3530: }
 3531: table#LC_browser tr.LC_browser_file_locked,
 3532: table#LC_browser tr.LC_browser_file_unpublished {
 3533:   background: #FFAA99;
 3534: }
 3535: table#LC_browser tr.LC_browser_file_obsolete {
 3536:   background: #AAAAAA;
 3537: }
 3538: table#LC_browser tr.LC_browser_file_modified,
 3539: table#LC_browser tr.LC_browser_file_metamodified {
 3540:   background: #FFFF77;
 3541: }
 3542: table#LC_browser tr.LC_browser_folder {
 3543:   background: #CCCCFF;
 3544: }
 3545: span.LC_current_location {
 3546:   font-size: x-large;
 3547:   background: $pgbg;
 3548: }
 3549: 
 3550: span.LC_parm_menu_item {
 3551:   font-size: larger;
 3552:   font-family: $sans;
 3553: }
 3554: span.LC_parm_scope_all {
 3555:   color: red;
 3556: }
 3557: span.LC_parm_scope_folder {
 3558:   color: green;
 3559: }
 3560: span.LC_parm_scope_resource {
 3561:   color: orange;
 3562: }
 3563: span.LC_parm_part {
 3564:   color: blue;
 3565: }
 3566: span.LC_parm_folder, span.LC_parm_symb {
 3567:   font-size: x-small;
 3568:   font-family: $mono;
 3569:   color: #AAAAAA;
 3570: }
 3571: 
 3572: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 3573: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 3574:   border: 1px solid black;
 3575:   border-collapse: collapse;
 3576: }
 3577: table.LC_parm_overview_restrictions td {
 3578:   border-width: 1px 4px 1px 4px;
 3579:   border-style: solid;
 3580:   border-color: $pgbg;
 3581:   text-align: center;
 3582: }
 3583: table.LC_parm_overview_restrictions th {
 3584:   background: $tabbg;
 3585:   border-width: 1px 4px 1px 4px;
 3586:   border-style: solid;
 3587:   border-color: $pgbg;
 3588: }
 3589: table#LC_helpmenu {
 3590:   border: 0px;
 3591:   height: 55px;
 3592:   border-spacing: 0px;
 3593: }
 3594: 
 3595: table#LC_helpmenu fieldset legend {
 3596:   font-size: larger;
 3597:   font-weight: bold;
 3598: }
 3599: table#LC_helpmenu_links {
 3600:   width: 100%;
 3601:   border: 1px solid black;
 3602:   background: $pgbg;
 3603:   padding: 0px;
 3604:   border-spacing: 1px;
 3605: }
 3606: table#LC_helpmenu_links tr td {
 3607:   padding: 1px;
 3608:   background: $tabbg;
 3609:   text-align: center;
 3610:   font-weight: bold;
 3611: }
 3612: 
 3613: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 3614: table#LC_helpmenu_links a:active {
 3615:   text-decoration: none;
 3616:   color: $font;
 3617: }
 3618: table#LC_helpmenu_links a:hover {
 3619:   text-decoration: underline;
 3620:   color: $vlink;
 3621: }
 3622: 
 3623: .LC_chrt_popup_exists {
 3624:   border: 1px solid #339933;
 3625:   margin: -1px;
 3626: }
 3627: .LC_chrt_popup_up {
 3628:   border: 1px solid yellow;
 3629:   margin: -1px;
 3630: }
 3631: .LC_chrt_popup {
 3632:   border: 1px solid #8888FF;
 3633:   background: #CCCCFF;
 3634: }
 3635: 
 3636: table.LC_pick_box {
 3637:   width: 100%;
 3638:   border-collapse: separate;
 3639:   background: white;
 3640:   border: 1px solid black;
 3641:   border-spacing: 1px;
 3642: }
 3643: table.LC_pick_box td.LC_pick_box_title {
 3644:   background: $tabbg;
 3645:   font-weight: bold;
 3646:   text-align: right;
 3647:   width: 184px;
 3648:   padding: 8px;
 3649: }
 3650: table.LC_pick_box td.LC_pick_box_separator {
 3651:   padding: 0px;
 3652:   height: 1px;
 3653:   background: black;
 3654: }
 3655: table.LC_pick_box td.LC_pick_box_submit {
 3656:   text-align: right;
 3657: }
 3658: 
 3659: table.LC_group_priv_box {
 3660:   background: white;
 3661:   border: 1px solid black;
 3662:   border-spacing: 1px;
 3663: }
 3664: table.LC_group_priv_box td.LC_pick_box_title {
 3665:   background: $tabbg;
 3666:   font-weight: bold;
 3667:   text-align: right;
 3668:   width: 184px;
 3669: }
 3670: table.LC_group_priv_box td.LC_groups_fixed {
 3671:   background: $data_table_light;
 3672:   text-align: center;
 3673: }
 3674: table.LC_group_priv_box td.LC_groups_optional {
 3675:   background: $data_table_dark;
 3676:   text-align: center;
 3677: }
 3678: table.LC_group_priv_box td.LC_groups_functionality {
 3679:   background: $data_table_darker;
 3680:   text-align: center;
 3681:   font-weight: bold;
 3682: }
 3683: table.LC_group_priv td {
 3684:   text-align: left;
 3685:   padding: 0px;
 3686: }
 3687: 
 3688: table.LC_notify_front_page {
 3689:   background: white;
 3690:   border: 1px solid black;
 3691:   padding: 8px;
 3692: }
 3693: table.LC_notify_front_page td {
 3694:   padding: 8px;
 3695: }
 3696: .LC_navbuttons {
 3697:   margin: 2ex 0ex 2ex 0ex;
 3698: }
 3699: .LC_topic_bar {
 3700:   font-family: $sans;
 3701:   font-weight: bold;
 3702:   width: 100%;
 3703:   background: $tabbg;
 3704:   vertical-align: middle;
 3705:   margin: 2ex 0ex 2ex 0ex;
 3706: }
 3707: .LC_topic_bar span {
 3708:   vertical-align: middle;
 3709: }
 3710: .LC_topic_bar img {
 3711:   vertical-align: bottom;
 3712: }
 3713: table.LC_course_group_status {
 3714:   margin: 20px;
 3715: }
 3716: table.LC_status_selector td {
 3717:   vertical-align: top;
 3718:   text-align: center;
 3719:   padding: 4px;
 3720: }
 3721: table.LC_descriptive_input td.LC_description {
 3722:   vertical-align: top;
 3723:   text-align: right;
 3724:   font-weight: bold;
 3725: }
 3726: 
 3727: END
 3728: }
 3729: 
 3730: =pod
 3731: 
 3732: =over 4
 3733: 
 3734: =item * &headtag()
 3735: 
 3736: Returns a uniform footer for LON-CAPA web pages.
 3737: 
 3738: Inputs: $title - optional title for the head
 3739:         $head_extra - optional extra HTML to put inside the <head>
 3740:         $args - optional arguments
 3741:             force_register - if is true call registerurl so the remote is 
 3742:                              informed
 3743:             redirect       -> array ref of
 3744:                                    1- seconds before redirect occurs
 3745:                                    2- url to redirect to
 3746:                                    3- whether the side effect should occur
 3747:                            (side effect of setting 
 3748:                                $env{'internal.head.redirect'} to the url 
 3749:                                redirected too)
 3750:             domain         -> force to color decorate a page for a specific
 3751:                                domain
 3752:             function       -> force usage of a specific rolish color scheme
 3753:             bgcolor        -> override the default page bgcolor
 3754:             no_auto_mt_title
 3755:                            -> prevent &mt()ing the title arg
 3756: 
 3757: =back
 3758: 
 3759: =cut
 3760: 
 3761: sub headtag {
 3762:     my ($title,$head_extra,$args) = @_;
 3763:     
 3764:     my $function = $args->{'function'} || &get_users_function();
 3765:     my $domain   = $args->{'domain'}   || &determinedomain();
 3766:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 3767:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 3768: 		   $Apache::lonnet::perlvar{'lonVersion'},
 3769: 		   #time(),
 3770: 		   $env{'environment.color.timestamp'},
 3771: 		   $function,$domain,$bgcolor);
 3772: 
 3773:     $url = '/adm/css/'.&escape($url).'.css';
 3774: 
 3775:     my $result =
 3776: 	'<head>'.
 3777: 	&font_settings();
 3778: 
 3779:     if (!$args->{'frameset'}) {
 3780: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 3781:     }
 3782:     if ($args->{'force_register'}) {
 3783: 	$result .= &Apache::lonmenu::registerurl(1);
 3784:     }
 3785:     if (!$args->{'no_nav_bar'} 
 3786: 	&& !$args->{'only_body'}
 3787: 	&& !$args->{'frameset'}) {
 3788: 	$result .= &help_menu_js();
 3789:     }
 3790: 
 3791:     if (ref($args->{'redirect'})) {
 3792: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 3793: 	$url = &Apache::lonenc::check_encrypt($url);
 3794: 	if (!$inhibit_continue) {
 3795: 	    $env{'internal.head.redirect'} = $url;
 3796: 	}
 3797: 	$result.=<<ADDMETA
 3798: <meta http-equiv="pragma" content="no-cache" />
 3799: <meta http-equiv="Refresh" content="$time; url=$url" />
 3800: ADDMETA
 3801:     }
 3802:     if (!defined($title)) {
 3803: 	$title = 'The LearningOnline Network with CAPA';
 3804:     }
 3805:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 3806:     $result .= '<title> LON-CAPA '.$title.'</title>'
 3807: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 3808: 	.$head_extra;
 3809:     return $result;
 3810: }
 3811: 
 3812: =pod
 3813: 
 3814: =over 4
 3815: 
 3816: =item * &font_settings()
 3817: 
 3818: Returns neccessary <meta> to set the proper encoding
 3819: 
 3820: Inputs: none
 3821: 
 3822: =back
 3823: 
 3824: =cut
 3825: 
 3826: sub font_settings {
 3827:     my $headerstring='';
 3828:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
 3829: 	$headerstring.=
 3830: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
 3831:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 3832: 	$headerstring.=
 3833: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 3834:     }
 3835:     return $headerstring;
 3836: }
 3837: 
 3838: =pod
 3839: 
 3840: =over 4
 3841: 
 3842: =item * &xml_begin()
 3843: 
 3844: Returns the needed doctype and <html>
 3845: 
 3846: Inputs: none
 3847: 
 3848: =back
 3849: 
 3850: =cut
 3851: 
 3852: sub xml_begin {
 3853:     my $output='';
 3854: 
 3855:     &Apache::lonhtmlcommon::init_htmlareafields();
 3856: 
 3857:     if ($env{'browser.mathml'}) {
 3858: 	$output='<?xml version="1.0"?>'
 3859:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 3860: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 3861:             
 3862: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
 3863: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
 3864:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 3865: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 3866:     } else {
 3867: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 3868:     }
 3869:     return $output;
 3870: }
 3871: 
 3872: =pod
 3873: 
 3874: =over 4
 3875: 
 3876: =item * &endheadtag()
 3877: 
 3878: Returns a uniform </head> for LON-CAPA web pages.
 3879: 
 3880: Inputs: none
 3881: 
 3882: =back
 3883: 
 3884: =cut
 3885: 
 3886: sub endheadtag {
 3887:     return '</head>';
 3888: }
 3889: 
 3890: =pod
 3891: 
 3892: =over 4
 3893: 
 3894: =item * &head()
 3895: 
 3896: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 3897: 
 3898: Inputs: $title - optional title for the page
 3899:         $head_extra - optional extra HTML to put inside the <head>
 3900: 
 3901: =back
 3902: 
 3903: =cut
 3904: 
 3905: sub head {
 3906:     my ($title,$head_extra,$args) = @_;
 3907:     return &headtag($title,$head_extra,$args).&endheadtag();
 3908: }
 3909: 
 3910: =pod
 3911: 
 3912: =over 4
 3913: 
 3914: =item * &start_page()
 3915: 
 3916: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 3917: 
 3918: Inputs: $title - optional title for the page
 3919:         $head_extra - optional extra HTML to incude inside the <head>
 3920:         $args - additional optional args supported are:
 3921:                   only_body      -> is true will set &bodytag() onlybodytag
 3922:                                     arg on
 3923:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
 3924:                   add_entries    -> additional attributes to add to the  <body>
 3925:                   domain         -> force to color decorate a page for a 
 3926:                                     specific domain
 3927:                   function       -> force usage of a specific rolish color
 3928:                                     scheme
 3929:                   redirect       -> see &headtag()
 3930:                   bgcolor        -> override the default page bg color
 3931:                   js_ready       -> return a string ready for being used in 
 3932:                                     a javascript writeln
 3933:                   html_encode    -> return a string ready for being used in 
 3934:                                     a html attribute
 3935:                   force_register -> if is true will turn on the &bodytag()
 3936:                                     $forcereg arg
 3937:                   body_title     -> alternate text to use instead of $title
 3938:                                     in the title box that appears, this text
 3939:                                     is not auto translated like the $title is
 3940:                   frameset       -> if true will start with a <frameset>
 3941:                                     rather than <body>
 3942:                   no_title       -> if true the title bar won't be shown
 3943:                   skip_phases    -> hash ref of 
 3944:                                     head -> skip the <html><head> generation
 3945:                                     body -> skip all <body> generation
 3946: 
 3947:                   no_inline_link -> if true and in remote mode, don't show the 
 3948:                                     'Switch To Inline Menu' link
 3949: 
 3950:                   no_auto_mt_title -> prevent &mt()ing the title arg
 3951: 
 3952: =back
 3953: 
 3954: =cut
 3955: 
 3956: sub start_page {
 3957:     my ($title,$head_extra,$args) = @_;
 3958:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 3959:     my %head_args;
 3960:     foreach my $arg ('redirect','force_register','domain','function',
 3961: 		     'bgcolor','frameset','no_nav_bar','only_body',
 3962: 		     'no_auto_mt_title') {
 3963: 	if (defined($args->{$arg})) {
 3964: 	    $head_args{$arg} = $args->{$arg};
 3965: 	}
 3966:     }
 3967: 
 3968:     $env{'internal.start_page'}++;
 3969:     my $result;
 3970:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 3971: 	$result.=
 3972: 	    &xml_begin().
 3973: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 3974:     }
 3975:     
 3976:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 3977: 	if ($args->{'frameset'}) {
 3978: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 3979: 						$args->{'add_entries'});
 3980: 	    $result .= "\n<frameset $attr_string>\n";
 3981: 	} else {
 3982: 	    $result .=
 3983: 		&bodytag($title, 
 3984: 			 $args->{'function'},       $args->{'add_entries'},
 3985: 			 $args->{'only_body'},      $args->{'domain'},
 3986: 			 $args->{'force_register'}, $args->{'body_title'},
 3987: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 3988: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 3989: 			 $args);
 3990: 	}
 3991:     }
 3992: 
 3993:     if ($args->{'js_ready'}) {
 3994: 	$result = &js_ready($result);
 3995:     }
 3996:     if ($args->{'html_encode'}) {
 3997: 	$result = &html_encode($result);
 3998:     }
 3999:     return $result;
 4000: }
 4001: 
 4002: 
 4003: =pod
 4004: 
 4005: =over 4
 4006: 
 4007: =item * &head()
 4008: 
 4009: Returns a complete </body></html> section for LON-CAPA web pages.
 4010: 
 4011: Inputs:         $args - additional optional args supported are:
 4012:                  js_ready     -> return a string ready for being used in 
 4013:                                  a javascript writeln
 4014:                  html_encode  -> return a string ready for being used in 
 4015:                                  a html attribute
 4016:                  frameset     -> if true will start with a <frameset>
 4017:                                  rather than <body>
 4018: 
 4019: =cut
 4020: 
 4021: sub end_page {
 4022:     my ($args) = @_;
 4023:     $env{'internal.end_page'}++;
 4024:     my $result;
 4025:     if ($args->{'discussion'}) {
 4026: 	my ($target,$parser);
 4027: 	if (ref($args->{'discussion'})) {
 4028: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 4029: 				$args->{'discussion'}{'parser'});
 4030: 	}
 4031: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 4032:     }
 4033: 
 4034:     if ($args->{'frameset'}) {
 4035: 	$result .= '</frameset>';
 4036:     } else {
 4037: 	$result .= &endbodytag();
 4038:     }
 4039:     $result .= "\n</html>";
 4040: 
 4041:     if ($args->{'js_ready'}) {
 4042: 	$result = &js_ready($result);
 4043:     }
 4044: 
 4045:     if ($args->{'html_encode'}) {
 4046: 	$result = &html_encode($result);
 4047:     }
 4048: 
 4049:     return $result;
 4050: }
 4051: 
 4052: sub html_encode {
 4053:     my ($result) = @_;
 4054: 
 4055:     $result = &HTML::Entities::encode($result,'<>&"');
 4056:     
 4057:     return $result;
 4058: }
 4059: sub js_ready {
 4060:     my ($result) = @_;
 4061: 
 4062:     $result =~ s/[\n\r]/ /xmsg;
 4063:     $result =~ s/\\/\\\\/xmsg;
 4064:     $result =~ s/'/\\'/xmsg;
 4065:     $result =~ s{</}{<\\/}xmsg;
 4066:     
 4067:     return $result;
 4068: }
 4069: 
 4070: sub validate_page {
 4071:     if (  exists($env{'internal.start_page'})
 4072: 	  &&     $env{'internal.start_page'} > 1) {
 4073: 	&Apache::lonnet::logthis('start_page called multiple times '.
 4074: 				 $env{'internal.start_page'}.' '.
 4075: 				 $ENV{'request.filename'});
 4076:     }
 4077:     if (  exists($env{'internal.end_page'})
 4078: 	  &&     $env{'internal.end_page'} > 1) {
 4079: 	&Apache::lonnet::logthis('end_page called multiple times '.
 4080: 				 $env{'internal.end_page'}.' '.
 4081: 				 $env{'request.filename'});
 4082:     }
 4083:     if (     exists($env{'internal.start_page'})
 4084: 	&& ! exists($env{'internal.end_page'})) {
 4085: 	&Apache::lonnet::logthis('start_page called without end_page '.
 4086: 				 $env{'request.filename'});
 4087:     }
 4088:     if (   ! exists($env{'internal.start_page'})
 4089: 	&&   exists($env{'internal.end_page'})) {
 4090: 	&Apache::lonnet::logthis('end_page called without start_page'.
 4091: 				 $env{'request.filename'});
 4092:     }
 4093: }
 4094: 
 4095: sub simple_error_page {
 4096:     my ($r,$title,$msg) = @_;
 4097:     my $page =
 4098: 	&Apache::loncommon::start_page($title).
 4099: 	&mt($msg).
 4100: 	&Apache::loncommon::end_page();
 4101:     if (ref($r)) {
 4102: 	$r->print($page);
 4103: 	return;
 4104:     }
 4105:     return $page;
 4106: }
 4107: 
 4108: {
 4109:     my $row_count;
 4110:     sub start_data_table {
 4111: 	my ($add_class) = @_;
 4112: 	my $css_class = (join(' ','LC_data_table',$add_class));
 4113: 	undef($row_count);
 4114: 	return '<table class="'.$css_class.'">'."\n";
 4115:     }
 4116: 
 4117:     sub end_data_table {
 4118: 	undef($row_count);
 4119: 	return '</table>'."\n";;
 4120:     }
 4121: 
 4122:     sub start_data_table_row {
 4123: 	my ($add_class) = @_;
 4124: 	$row_count++;
 4125: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
 4126: 	$css_class = (join(' ',$css_class,$add_class));
 4127: 	return  '<tr class="'.$css_class.'">'."\n";;
 4128:     }
 4129: 
 4130:     sub end_data_table_row {
 4131: 	return '</tr>'."\n";;
 4132:     }
 4133: 
 4134:     sub start_data_table_empty_row {
 4135: 	$row_count++;
 4136: 	return  '<tr class="LC_empty_row" >'."\n";;
 4137:     }
 4138: 
 4139:     sub end_data_table_empty_row {
 4140: 	return '</tr>'."\n";;
 4141:     }
 4142: 
 4143:     sub start_data_table_header_row {
 4144: 	return  '<tr class="LC_header_row">'."\n";;
 4145:     }
 4146: 
 4147:     sub end_data_table_header_row {
 4148: 	return '</tr>'."\n";;
 4149:     }
 4150: }
 4151: 
 4152: ###############################################
 4153: 
 4154: =pod
 4155: 
 4156: =item * &get_users_function()
 4157: 
 4158: Used by &bodytag to determine the current users primary role.
 4159: Returns either 'student','coordinator','admin', or 'author'.
 4160: 
 4161: =cut
 4162: 
 4163: ###############################################
 4164: sub get_users_function {
 4165:     my $function = 'student';
 4166:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 4167:         $function='coordinator';
 4168:     }
 4169:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 4170:         $function='admin';
 4171:     }
 4172:     if (($env{'request.role'}=~/^(au|ca)/) ||
 4173:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 4174:         $function='author';
 4175:     }
 4176:     return $function;
 4177: }
 4178: 
 4179: ###############################################
 4180: 
 4181: =pod
 4182: 
 4183: =item * &check_user_status
 4184: 
 4185: Determines current status of supplied role for a
 4186: specific user. Roles can be active, previous or future.
 4187: 
 4188: Inputs: 
 4189: user's domain, user's username, course's domain,
 4190: course's number, optional section ID.
 4191: 
 4192: Outputs:
 4193: role status: active, previous or future. 
 4194: 
 4195: =cut
 4196: 
 4197: sub check_user_status {
 4198:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 4199:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 4200:     my @uroles = keys %userinfo;
 4201:     my $srchstr;
 4202:     my $active_chk = 'none';
 4203:     my $now = time;
 4204:     if (@uroles > 0) {
 4205:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 4206:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 4207:         } else {
 4208:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 4209:         }
 4210:         if (grep/^\Q$srchstr\E$/,@uroles) {
 4211:             my $role_end = 0;
 4212:             my $role_start = 0;
 4213:             $active_chk = 'active';
 4214:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 4215:                 $role_end = $1;
 4216:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 4217:                     $role_start = $1;
 4218:                 }
 4219:             }
 4220:             if ($role_start > 0) {
 4221:                 if ($now < $role_start) {
 4222:                     $active_chk = 'future';
 4223:                 }
 4224:             }
 4225:             if ($role_end > 0) {
 4226:                 if ($now > $role_end) {
 4227:                     $active_chk = 'previous';
 4228:                 }
 4229:             }
 4230:         }
 4231:     }
 4232:     return $active_chk;
 4233: }
 4234: 
 4235: ###############################################
 4236: 
 4237: =pod
 4238: 
 4239: =item * &get_sections()
 4240: 
 4241: Determines all the sections for a course including
 4242: sections with students and sections containing other roles.
 4243: Incoming parameters: 
 4244: 
 4245: 1. domain
 4246: 2. course number 
 4247: 3. reference to array containing roles for which sections should 
 4248: be gathered (optional).
 4249: 4. reference to array containing status types for which sections 
 4250: should be gathered (optional).
 4251: 
 4252: If the third argument is undefined, sections are gathered for any role. 
 4253: If the fourth argument is undefined, sections are gathered for any status.
 4254: Permissible values are 'active' or 'future' or 'previous'.
 4255:  
 4256: Returns section hash (keys are section IDs, values are
 4257: number of users in each section), subject to the
 4258: optional roles filter, optional status filter 
 4259: 
 4260: =cut
 4261: 
 4262: ###############################################
 4263: sub get_sections {
 4264:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 4265:     if (!defined($cdom) || !defined($cnum)) {
 4266:         my $cid =  $env{'request.course.id'};
 4267: 
 4268: 	return if (!defined($cid));
 4269: 
 4270:         $cdom = $env{'course.'.$cid.'.domain'};
 4271:         $cnum = $env{'course.'.$cid.'.num'};
 4272:     }
 4273: 
 4274:     my %sectioncount;
 4275:     my $now = time;
 4276: 
 4277:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 4278: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 4279: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 4280: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 4281:         my $start_index = &Apache::loncoursedata::CL_START();
 4282:         my $end_index = &Apache::loncoursedata::CL_END();
 4283:         my $status;
 4284: 	while (my ($student,$data) = each(%$classlist)) {
 4285: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 4286: 				                     $data->[$status_index],
 4287:                                                      $data->[$start_index],
 4288:                                                      $data->[$end_index]);
 4289:             if ($stu_status eq 'Active') {
 4290:                 $status = 'active';
 4291:             } elsif ($end < $now) {
 4292:                 $status = 'previous';
 4293:             } elsif ($start > $now) {
 4294:                 $status = 'future';
 4295:             } 
 4296: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 4297:                 if ((!defined($possible_status)) || (($status ne '') && 
 4298:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 4299: 		    $sectioncount{$section}++;
 4300:                 }
 4301: 	    }
 4302: 	}
 4303:     }
 4304:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4305:     foreach my $user (sort(keys(%courseroles))) {
 4306: 	if ($user !~ /^(\w{2})/) { next; }
 4307: 	my ($role) = ($user =~ /^(\w{2})/);
 4308: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 4309: 	my ($section,$status);
 4310: 	if ($role eq 'cr' &&
 4311: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 4312: 	    $section=$1;
 4313: 	}
 4314: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 4315: 	if (!defined($section) || $section eq '-1') { next; }
 4316:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 4317:         if ($end == -1 && $start == -1) {
 4318:             next; #deleted role
 4319:         }
 4320:         if (!defined($possible_status)) { 
 4321:             $sectioncount{$section}++;
 4322:         } else {
 4323:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 4324:                 $status = 'active';
 4325:             } elsif ($end < $now) {
 4326:                 $status = 'future';
 4327:             } elsif ($start > $now) {
 4328:                 $status = 'previous';
 4329:             }
 4330:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 4331:                 $sectioncount{$section}++;
 4332:             }
 4333:         }
 4334:     }
 4335:     return %sectioncount;
 4336: }
 4337: 
 4338: ###############################################
 4339: 
 4340: =pod
 4341: 
 4342: =item * &get_course_users()
 4343: 
 4344: Retrieves usernames:domains for users in the specified course
 4345: with specific role(s), and access status. 
 4346: 
 4347: Incoming parameters:
 4348: 1. course domain
 4349: 2. course number
 4350: 3. access status: users must have - either active, 
 4351: previous, future, or all.
 4352: 4. reference to array of permissible roles
 4353: 5. reference to array of section restrictions (optional)
 4354: 6. reference to results object (hash of hashes).
 4355: 7. reference to optional userdata hash
 4356: Keys of top level hash are roles.
 4357: Keys of inner hashes are username:domain, with 
 4358: values set to access type.
 4359: Optional userdata hash returns an array with arguments in the 
 4360: same order as loncoursedata::get_classlist() for student data.
 4361: 
 4362: Entries for end, start, section and status are blank because
 4363: of the possibility of multiple values for non-student roles.
 4364: 
 4365: =cut
 4366: 
 4367: ###############################################
 4368: 
 4369: sub get_course_users {
 4370:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
 4371:     my %idx = ();
 4372:     my %seclists;
 4373: 
 4374:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 4375:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 4376:     $idx{end} = &Apache::loncoursedata::CL_END();
 4377:     $idx{start} = &Apache::loncoursedata::CL_START();
 4378:     $idx{id} = &Apache::loncoursedata::CL_ID();
 4379:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 4380:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 4381:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 4382: 
 4383:     if (grep(/^st$/,@{$roles})) {
 4384:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 4385:         my $now = time;
 4386:         foreach my $student (keys(%{$classlist})) {
 4387:             my $match = 0;
 4388:             my $secmatch = 0;
 4389:             my $section = $$classlist{$student}[$idx{section}];
 4390:             if ($section eq '') {
 4391:                 $section = 'none';
 4392:             }
 4393:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 4394:                 if (grep(/^all$/,@{$sections})) {
 4395:                     $secmatch = 1;
 4396:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 4397:                     if (grep(/^none$/,@{$sections})) {
 4398:                         $secmatch = 1;
 4399:                     }
 4400:                 } else {  
 4401: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 4402: 		        $secmatch = 1;
 4403:                     }
 4404: 		}
 4405:                 if (!$secmatch) {
 4406:                     next;
 4407:                 }
 4408:             }
 4409:             push(@{$seclists{$student}},$section); 
 4410:             if (defined($$types{'active'})) {
 4411:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 4412:                     push(@{$$users{st}{$student}},'active');
 4413:                     $match = 1;
 4414:                 }
 4415:             }
 4416:             if (defined($$types{'previous'})) {
 4417:                 if ($$classlist{$student}[$idx{end}] <= $now) {
 4418:                     push(@{$$users{st}{$student}},'previous');
 4419:                     $match = 1;
 4420:                 }
 4421:             }
 4422:             if (defined($$types{'future'})) {
 4423:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
 4424:                     push(@{$$users{st}{$student}},'future');
 4425:                     $match = 1;
 4426:                 }
 4427:             }
 4428:             if ($match && ref($userdata) eq 'HASH') {
 4429:                 $$userdata{$student} = $$classlist{$student};
 4430:             }
 4431:         }
 4432:     }
 4433:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 4434:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4435:         my $now = time;
 4436:         foreach my $person (sort(keys(%coursepersonnel))) {
 4437:             my $match = 0;
 4438:             my $secmatch = 0;
 4439:             my $status;
 4440:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 4441:             $user =~ s/:$//;
 4442:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 4443:             if ($end == -1 || $start == -1) {
 4444:                 next;
 4445:             }
 4446:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 4447:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 4448:                 my ($uname,$udom) = split(/:/,$user);
 4449:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 4450:                     if (grep(/^all$/,@{$sections})) {
 4451:                         $secmatch = 1;
 4452:                     } elsif ($usec eq '') {
 4453:                         if (grep(/^none$/,@{$sections})) {
 4454:                             $secmatch = 1;
 4455:                         }
 4456:                     } else {
 4457:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 4458:                             $secmatch = 1;
 4459:                         }
 4460:                     }
 4461:                     if (!$secmatch) {
 4462:                         next;
 4463:                     }
 4464:                 }
 4465:                 if ($usec eq '') {
 4466:                     $usec = 'none';
 4467:                 }
 4468:                 if ($uname ne '' && $udom ne '') {
 4469:                     if ($end < $now) {
 4470:                         $status = 'previous';
 4471:                     } elsif ($start > $now) {
 4472:                         $status = 'future';
 4473:                     } else {
 4474:                         $status = 'active';
 4475:                     }
 4476:                     foreach my $type (keys(%{$types})) { 
 4477:                         if ($status eq $type) {
 4478:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 4479:                                 push(@{$$users{$role}{$user}},$type);
 4480:                             }
 4481:                             $match = 1;
 4482:                         }
 4483:                     }
 4484:                     if (($match) && (ref($userdata) eq 'HASH')) {
 4485:                         if (!exists($$userdata{$uname.':'.$udom})) {
 4486: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 4487:                         }
 4488:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 4489:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 4490:                         }
 4491:                     }
 4492:                 }
 4493:             }
 4494:         }
 4495:         if (grep(/^ow$/,@{$roles})) {
 4496:             if ((defined($cdom)) && (defined($cnum))) {
 4497:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 4498:                 if ( defined($csettings{'internal.courseowner'}) ) {
 4499:                     my $owner = $csettings{'internal.courseowner'};
 4500:                     if ($owner !~ /^[^:]+:[^:]+$/) {
 4501:                         $owner = $owner.':'.$cdom;
 4502:                     }
 4503:                     @{$$users{'ow'}{$owner}} = 'any';
 4504:                     if (defined($userdata) && 
 4505: 			!exists($$userdata{$owner.':'.$cdom})) {
 4506: 			&get_user_info($cdom,$owner,\%idx,$userdata);
 4507:                         if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
 4508:                             push(@{$seclists{$owner.':'.$cdom}},'none');
 4509:                         }
 4510: 		    }
 4511:                 }
 4512:             }
 4513:         }
 4514:         foreach my $user (keys(%seclists)) {
 4515:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 4516:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 4517:         }
 4518:     }
 4519:     return;
 4520: }
 4521: 
 4522: sub get_user_info {
 4523:     my ($udom,$uname,$idx,$userdata) = @_;
 4524:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 4525: 	&plainname($uname,$udom,'lastname');
 4526:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 4527:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 4528:     return;
 4529: }
 4530: 
 4531: sub get_secgrprole_info {
 4532:     my ($cdom,$cnum,$needroles,$type)  = @_;
 4533:     my %sections_count = &get_sections($cdom,$cnum);
 4534:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 4535:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 4536:     my @groups = sort(keys(%curr_groups));
 4537:     my $allroles = [];
 4538:     my $rolehash;
 4539:     my $accesshash = {
 4540:                      active => 'Currently has access',
 4541:                      future => 'Will have future access',
 4542:                      previous => 'Previously had access',
 4543:                   };
 4544:     if ($needroles) {
 4545:         $rolehash = {'all' => 'all'};
 4546:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 4547: 	if (&Apache::lonnet::error(%user_roles)) {
 4548: 	    undef(%user_roles);
 4549: 	}
 4550:         foreach my $item (keys(%user_roles)) {
 4551:             my ($role)=split(/\:/,$item,2);
 4552:             if ($role eq 'cr') { next; }
 4553:             if ($role =~ /^cr/) {
 4554:                 $$rolehash{$role} = (split('/',$role))[3];
 4555:             } else {
 4556:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 4557:             }
 4558:         }
 4559:         foreach my $key (sort(keys(%{$rolehash}))) {
 4560:             push(@{$allroles},$key);
 4561:         }
 4562:         push (@{$allroles},'st');
 4563:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 4564:     }
 4565:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 4566: }
 4567: 
 4568: =pod
 4569: 
 4570: =item * get_unprocessed_cgi($query,$possible_names)
 4571: 
 4572: Modify the %env hash to contain unprocessed CGI form parameters held in
 4573: $query.  The parameters listed in $possible_names (an array reference),
 4574: will be set in $env{'form.name'} if they do not already exist.
 4575: 
 4576: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 4577: $possible_names is an ref to an array of form element names.  As an example:
 4578: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 4579: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 4580: 
 4581: =cut
 4582: 
 4583: sub get_unprocessed_cgi {
 4584:   my ($query,$possible_names)= @_;
 4585:   # $Apache::lonxml::debug=1;
 4586:   foreach my $pair (split(/&/,$query)) {
 4587:     my ($name, $value) = split(/=/,$pair);
 4588:     $name = &unescape($name);
 4589:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 4590:       $value =~ tr/+/ /;
 4591:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4592:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 4593:     }
 4594:   }
 4595: }
 4596: 
 4597: =pod
 4598: 
 4599: =item * cacheheader() 
 4600: 
 4601: returns cache-controlling header code
 4602: 
 4603: =cut
 4604: 
 4605: sub cacheheader {
 4606:     unless ($env{'request.method'} eq 'GET') { return ''; }
 4607:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 4608:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 4609:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 4610:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 4611:     return $output;
 4612: }
 4613: 
 4614: =pod
 4615: 
 4616: =item * no_cache($r) 
 4617: 
 4618: specifies header code to not have cache
 4619: 
 4620: =cut
 4621: 
 4622: sub no_cache {
 4623:     my ($r) = @_;
 4624:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 4625: 	$env{'request.method'} ne 'GET') { return ''; }
 4626:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 4627:     $r->no_cache(1);
 4628:     $r->header_out("Expires" => $date);
 4629:     $r->header_out("Pragma" => "no-cache");
 4630: }
 4631: 
 4632: sub content_type {
 4633:     my ($r,$type,$charset) = @_;
 4634:     if ($r) {
 4635: 	#  Note that printout.pl calls this with undef for $r.
 4636: 	&no_cache($r);
 4637:     }
 4638:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 4639:     unless ($charset) {
 4640: 	$charset=&Apache::lonlocal::current_encoding;
 4641:     }
 4642:     if ($charset) { $type.='; charset='.$charset; }
 4643:     if ($r) {
 4644: 	$r->content_type($type);
 4645:     } else {
 4646: 	print("Content-type: $type\n\n");
 4647:     }
 4648: }
 4649: 
 4650: =pod
 4651: 
 4652: =item * add_to_env($name,$value) 
 4653: 
 4654: adds $name to the %env hash with value
 4655: $value, if $name already exists, the entry is converted to an array
 4656: reference and $value is added to the array.
 4657: 
 4658: =cut
 4659: 
 4660: sub add_to_env {
 4661:   my ($name,$value)=@_;
 4662:   if (defined($env{$name})) {
 4663:     if (ref($env{$name})) {
 4664:       #already have multiple values
 4665:       push(@{ $env{$name} },$value);
 4666:     } else {
 4667:       #first time seeing multiple values, convert hash entry to an arrayref
 4668:       my $first=$env{$name};
 4669:       undef($env{$name});
 4670:       push(@{ $env{$name} },$first,$value);
 4671:     }
 4672:   } else {
 4673:     $env{$name}=$value;
 4674:   }
 4675: }
 4676: 
 4677: =pod
 4678: 
 4679: =item * get_env_multiple($name) 
 4680: 
 4681: gets $name from the %env hash, it seemlessly handles the cases where multiple
 4682: values may be defined and end up as an array ref.
 4683: 
 4684: returns an array of values
 4685: 
 4686: =cut
 4687: 
 4688: sub get_env_multiple {
 4689:     my ($name) = @_;
 4690:     my @values;
 4691:     if (defined($env{$name})) {
 4692:         # exists is it an array
 4693:         if (ref($env{$name})) {
 4694:             @values=@{ $env{$name} };
 4695:         } else {
 4696:             $values[0]=$env{$name};
 4697:         }
 4698:     }
 4699:     return(@values);
 4700: }
 4701: 
 4702: 
 4703: =pod
 4704: 
 4705: =back
 4706: 
 4707: =head1 CSV Upload/Handling functions
 4708: 
 4709: =over 4
 4710: 
 4711: =item * upfile_store($r)
 4712: 
 4713: Store uploaded file, $r should be the HTTP Request object,
 4714: needs $env{'form.upfile'}
 4715: returns $datatoken to be put into hidden field
 4716: 
 4717: =cut
 4718: 
 4719: sub upfile_store {
 4720:     my $r=shift;
 4721:     $env{'form.upfile'}=~s/\r/\n/gs;
 4722:     $env{'form.upfile'}=~s/\f/\n/gs;
 4723:     $env{'form.upfile'}=~s/\n+/\n/gs;
 4724:     $env{'form.upfile'}=~s/\n+$//gs;
 4725: 
 4726:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 4727: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 4728:     {
 4729:         my $datafile = $r->dir_config('lonDaemons').
 4730:                            '/tmp/'.$datatoken.'.tmp';
 4731:         if ( open(my $fh,">$datafile") ) {
 4732:             print $fh $env{'form.upfile'};
 4733:             close($fh);
 4734:         }
 4735:     }
 4736:     return $datatoken;
 4737: }
 4738: 
 4739: =pod
 4740: 
 4741: =item * load_tmp_file($r)
 4742: 
 4743: Load uploaded file from tmp, $r should be the HTTP Request object,
 4744: needs $env{'form.datatoken'},
 4745: sets $env{'form.upfile'} to the contents of the file
 4746: 
 4747: =cut
 4748: 
 4749: sub load_tmp_file {
 4750:     my $r=shift;
 4751:     my @studentdata=();
 4752:     {
 4753:         my $studentfile = $r->dir_config('lonDaemons').
 4754:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 4755:         if ( open(my $fh,"<$studentfile") ) {
 4756:             @studentdata=<$fh>;
 4757:             close($fh);
 4758:         }
 4759:     }
 4760:     $env{'form.upfile'}=join('',@studentdata);
 4761: }
 4762: 
 4763: =pod
 4764: 
 4765: =item * upfile_record_sep()
 4766: 
 4767: Separate uploaded file into records
 4768: returns array of records,
 4769: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 4770: 
 4771: =cut
 4772: 
 4773: sub upfile_record_sep {
 4774:     if ($env{'form.upfiletype'} eq 'xml') {
 4775:     } else {
 4776: 	my @records;
 4777: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 4778: 	    if ($line=~/^\s*$/) { next; }
 4779: 	    push(@records,$line);
 4780: 	}
 4781: 	return @records;
 4782:     }
 4783: }
 4784: 
 4785: =pod
 4786: 
 4787: =item * record_sep($record)
 4788: 
 4789: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 4790: 
 4791: =cut
 4792: 
 4793: sub takeleft {
 4794:     my $index=shift;
 4795:     return substr('0000'.$index,-4,4);
 4796: }
 4797: 
 4798: sub record_sep {
 4799:     my $record=shift;
 4800:     my %components=();
 4801:     if ($env{'form.upfiletype'} eq 'xml') {
 4802:     } elsif ($env{'form.upfiletype'} eq 'space') {
 4803:         my $i=0;
 4804:         foreach my $field (split(/\s+/,$record)) {
 4805:             $field=~s/^(\"|\')//;
 4806:             $field=~s/(\"|\')$//;
 4807:             $components{&takeleft($i)}=$field;
 4808:             $i++;
 4809:         }
 4810:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 4811:         my $i=0;
 4812:         foreach my $field (split(/\t/,$record)) {
 4813:             $field=~s/^(\"|\')//;
 4814:             $field=~s/(\"|\')$//;
 4815:             $components{&takeleft($i)}=$field;
 4816:             $i++;
 4817:         }
 4818:     } else {
 4819:         my @allfields=split(/\,/,$record);
 4820:         my $i=0;
 4821:         my $j;
 4822:         for ($j=0;$j<=$#allfields;$j++) {
 4823:             my $field=$allfields[$j];
 4824:             if ($field=~/^\s*(\"|\')/) {
 4825: 		my $delimiter=$1;
 4826:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 4827: 		    $j++;
 4828: 		    $field.=','.$allfields[$j];
 4829: 		}
 4830:                 $field=~s/^\s*$delimiter//;
 4831:                 $field=~s/$delimiter\s*$//;
 4832:             }
 4833:             $components{&takeleft($i)}=$field;
 4834: 	    $i++;
 4835:         }
 4836:     }
 4837:     return %components;
 4838: }
 4839: 
 4840: ######################################################
 4841: ######################################################
 4842: 
 4843: =pod
 4844: 
 4845: =item * upfile_select_html()
 4846: 
 4847: Return HTML code to select a file from the users machine and specify 
 4848: the file type.
 4849: 
 4850: =cut
 4851: 
 4852: ######################################################
 4853: ######################################################
 4854: sub upfile_select_html {
 4855:     my %Types = (
 4856:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 4857:                  space => &mt('Space separated'),
 4858:                  tab   => &mt('Tabulator separated'),
 4859: #                 xml   => &mt('HTML/XML'),
 4860:                  );
 4861:     my $Str = '<input type="file" name="upfile" size="50" />'.
 4862:         '<br />Type: <select name="upfiletype">';
 4863:     foreach my $type (sort(keys(%Types))) {
 4864:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 4865:     }
 4866:     $Str .= "</select>\n";
 4867:     return $Str;
 4868: }
 4869: 
 4870: sub get_samples {
 4871:     my ($records,$toget) = @_;
 4872:     my @samples=({});
 4873:     my $got=0;
 4874:     foreach my $rec (@$records) {
 4875: 	my %temp = &record_sep($rec);
 4876: 	if (! grep(/\S/, values(%temp))) { next; }
 4877: 	if (%temp) {
 4878: 	    $samples[$got]=\%temp;
 4879: 	    $got++;
 4880: 	    if ($got == $toget) { last; }
 4881: 	}
 4882:     }
 4883:     return \@samples;
 4884: }
 4885: 
 4886: ######################################################
 4887: ######################################################
 4888: 
 4889: =pod
 4890: 
 4891: =item * csv_print_samples($r,$records)
 4892: 
 4893: Prints a table of sample values from each column uploaded $r is an
 4894: Apache Request ref, $records is an arrayref from
 4895: &Apache::loncommon::upfile_record_sep
 4896: 
 4897: =cut
 4898: 
 4899: ######################################################
 4900: ######################################################
 4901: sub csv_print_samples {
 4902:     my ($r,$records) = @_;
 4903:     my $samples = &get_samples($records,3);
 4904: 
 4905:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 4906:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 4907:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 4908:     $r->print('</tr>');
 4909:     foreach my $hash (@$samples) {
 4910: 	$r->print('<tr>');
 4911: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4912: 	    $r->print('<td>');
 4913: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 4914: 	    $r->print('</td>');
 4915: 	}
 4916: 	$r->print('</tr>');
 4917:     }
 4918:     $r->print('</tr></table><br />'."\n");
 4919: }
 4920: 
 4921: ######################################################
 4922: ######################################################
 4923: 
 4924: =pod
 4925: 
 4926: =item * csv_print_select_table($r,$records,$d)
 4927: 
 4928: Prints a table to create associations between values and table columns.
 4929: 
 4930: $r is an Apache Request ref,
 4931: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4932: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 4933: 
 4934: =cut
 4935: 
 4936: ######################################################
 4937: ######################################################
 4938: sub csv_print_select_table {
 4939:     my ($r,$records,$d) = @_;
 4940:     my $i=0;
 4941:     my $samples = &get_samples($records,1);
 4942:     $r->print(&mt('Associate columns with student attributes.')."\n".
 4943: 	     '<table border="2"><tr>'.
 4944:               '<th>'.&mt('Attribute').'</th>'.
 4945:               '<th>'.&mt('Column').'</th></tr>'."\n");
 4946:     foreach my $array_ref (@$d) {
 4947: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 4948: 	$r->print('<tr><td>'.$display.'</td>');
 4949: 
 4950: 	$r->print('<td><select name=f'.$i.
 4951: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4952: 	$r->print('<option value="none"></option>');
 4953: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4954: 	    $r->print('<option value="'.$sample.'"'.
 4955:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 4956:                       '>Column '.($sample+1).'</option>');
 4957: 	}
 4958: 	$r->print('</select></td></tr>'."\n");
 4959: 	$i++;
 4960:     }
 4961:     $i--;
 4962:     return $i;
 4963: }
 4964: 
 4965: ######################################################
 4966: ######################################################
 4967: 
 4968: =pod
 4969: 
 4970: =item * csv_samples_select_table($r,$records,$d)
 4971: 
 4972: Prints a table of sample values from the upload and can make associate samples to internal names.
 4973: 
 4974: $r is an Apache Request ref,
 4975: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4976: $d is an array of 2 element arrays (internal name, displayed name)
 4977: 
 4978: =cut
 4979: 
 4980: ######################################################
 4981: ######################################################
 4982: sub csv_samples_select_table {
 4983:     my ($r,$records,$d) = @_;
 4984:     my $i=0;
 4985:     #
 4986:     my $samples = &get_samples($records,3);
 4987:     $r->print('<table border=2><tr><th>'.
 4988:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 4989: 
 4990:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 4991: 	$r->print('<tr><td><select name="f'.$i.'"'.
 4992: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4993: 	foreach my $option (@$d) {
 4994: 	    my ($value,$display,$defaultcol)=@{ $option };
 4995: 	    $r->print('<option value="'.$value.'"'.
 4996:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 4997:                       $display.'</option>');
 4998: 	}
 4999: 	$r->print('</select></td><td>');
 5000: 	foreach my $line (0..2) {
 5001: 	    if (defined($samples->[$line]{$key})) { 
 5002: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 5003: 	    }
 5004: 	}
 5005: 	$r->print('</td></tr>');
 5006: 	$i++;
 5007:     }
 5008:     $i--;
 5009:     return($i);
 5010: }
 5011: 
 5012: ######################################################
 5013: ######################################################
 5014: 
 5015: =pod
 5016: 
 5017: =item clean_excel_name($name)
 5018: 
 5019: Returns a replacement for $name which does not contain any illegal characters.
 5020: 
 5021: =cut
 5022: 
 5023: ######################################################
 5024: ######################################################
 5025: sub clean_excel_name {
 5026:     my ($name) = @_;
 5027:     $name =~ s/[:\*\?\/\\]//g;
 5028:     if (length($name) > 31) {
 5029:         $name = substr($name,0,31);
 5030:     }
 5031:     return $name;
 5032: }
 5033: 
 5034: =pod
 5035: 
 5036: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 5037: 
 5038: Returns either 1 or undef
 5039: 
 5040: 1 if the part is to be hidden, undef if it is to be shown
 5041: 
 5042: Arguments are:
 5043: 
 5044: $id the id of the part to be checked
 5045: $symb, optional the symb of the resource to check
 5046: $udom, optional the domain of the user to check for
 5047: $uname, optional the username of the user to check for
 5048: 
 5049: =cut
 5050: 
 5051: sub check_if_partid_hidden {
 5052:     my ($id,$symb,$udom,$uname) = @_;
 5053:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 5054: 					 $symb,$udom,$uname);
 5055:     my $truth=1;
 5056:     #if the string starts with !, then the list is the list to show not hide
 5057:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 5058:     my @hiddenlist=split(/,/,$hiddenparts);
 5059:     foreach my $checkid (@hiddenlist) {
 5060: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 5061:     }
 5062:     return !$truth;
 5063: }
 5064: 
 5065: 
 5066: ############################################################
 5067: ############################################################
 5068: 
 5069: =pod
 5070: 
 5071: =back 
 5072: 
 5073: =head1 cgi-bin script and graphing routines
 5074: 
 5075: =over 4
 5076: 
 5077: =item get_cgi_id
 5078: 
 5079: Inputs: none
 5080: 
 5081: Returns an id which can be used to pass environment variables
 5082: to various cgi-bin scripts.  These environment variables will
 5083: be removed from the users environment after a given time by
 5084: the routine &Apache::lonnet::transfer_profile_to_env.
 5085: 
 5086: =cut
 5087: 
 5088: ############################################################
 5089: ############################################################
 5090: my $uniq=0;
 5091: sub get_cgi_id {
 5092:     $uniq=($uniq+1)%100000;
 5093:     return (time.'_'.$$.'_'.$uniq);
 5094: }
 5095: 
 5096: ############################################################
 5097: ############################################################
 5098: 
 5099: =pod
 5100: 
 5101: =item DrawBarGraph
 5102: 
 5103: Facilitates the plotting of data in a (stacked) bar graph.
 5104: Puts plot definition data into the users environment in order for 
 5105: graph.png to plot it.  Returns an <img> tag for the plot.
 5106: The bars on the plot are labeled '1','2',...,'n'.
 5107: 
 5108: Inputs:
 5109: 
 5110: =over 4
 5111: 
 5112: =item $Title: string, the title of the plot
 5113: 
 5114: =item $xlabel: string, text describing the X-axis of the plot
 5115: 
 5116: =item $ylabel: string, text describing the Y-axis of the plot
 5117: 
 5118: =item $Max: scalar, the maximum Y value to use in the plot
 5119: If $Max is < any data point, the graph will not be rendered.
 5120: 
 5121: =item $colors: array ref holding the colors to be used for the data sets when
 5122: they are plotted.  If undefined, default values will be used.
 5123: 
 5124: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 5125: 
 5126: =item @Values: An array of array references.  Each array reference holds data
 5127: to be plotted in a stacked bar chart.
 5128: 
 5129: =item If the final element of @Values is a hash reference the key/value
 5130: pairs will be added to the graph definition.
 5131: 
 5132: =back
 5133: 
 5134: Returns:
 5135: 
 5136: An <img> tag which references graph.png and the appropriate identifying
 5137: information for the plot.
 5138: 
 5139: =cut
 5140: 
 5141: ############################################################
 5142: ############################################################
 5143: sub DrawBarGraph {
 5144:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 5145:     #
 5146:     if (! defined($colors)) {
 5147:         $colors = ['#33ff00', 
 5148:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 5149:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 5150:                   ]; 
 5151:     }
 5152:     my $extra_settings = {};
 5153:     if (ref($Values[-1]) eq 'HASH') {
 5154:         $extra_settings = pop(@Values);
 5155:     }
 5156:     #
 5157:     my $identifier = &get_cgi_id();
 5158:     my $id = 'cgi.'.$identifier;        
 5159:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 5160:         return '';
 5161:     }
 5162:     #
 5163:     my @Labels;
 5164:     if (defined($labels)) {
 5165:         @Labels = @$labels;
 5166:     } else {
 5167:         for (my $i=0;$i<@{$Values[0]};$i++) {
 5168:             push (@Labels,$i+1);
 5169:         }
 5170:     }
 5171:     #
 5172:     my $NumBars = scalar(@{$Values[0]});
 5173:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 5174:     my %ValuesHash;
 5175:     my $NumSets=1;
 5176:     foreach my $array (@Values) {
 5177:         next if (! ref($array));
 5178:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 5179:             join(',',@$array);
 5180:     }
 5181:     #
 5182:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 5183:     if ($NumBars < 3) {
 5184:         $width = 120+$NumBars*32;
 5185:         $xskip = 1;
 5186:         $bar_width = 30;
 5187:     } elsif ($NumBars < 5) {
 5188:         $width = 120+$NumBars*20;
 5189:         $xskip = 1;
 5190:         $bar_width = 20;
 5191:     } elsif ($NumBars < 10) {
 5192:         $width = 120+$NumBars*15;
 5193:         $xskip = 1;
 5194:         $bar_width = 15;
 5195:     } elsif ($NumBars <= 25) {
 5196:         $width = 120+$NumBars*11;
 5197:         $xskip = 5;
 5198:         $bar_width = 8;
 5199:     } elsif ($NumBars <= 50) {
 5200:         $width = 120+$NumBars*8;
 5201:         $xskip = 5;
 5202:         $bar_width = 4;
 5203:     } else {
 5204:         $width = 120+$NumBars*8;
 5205:         $xskip = 5;
 5206:         $bar_width = 4;
 5207:     }
 5208:     #
 5209:     $Max = 1 if ($Max < 1);
 5210:     if ( int($Max) < $Max ) {
 5211:         $Max++;
 5212:         $Max = int($Max);
 5213:     }
 5214:     $Title  = '' if (! defined($Title));
 5215:     $xlabel = '' if (! defined($xlabel));
 5216:     $ylabel = '' if (! defined($ylabel));
 5217:     $ValuesHash{$id.'.title'}    = &escape($Title);
 5218:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 5219:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 5220:     $ValuesHash{$id.'.y_max_value'} = $Max;
 5221:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 5222:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 5223:     $ValuesHash{$id.'.PlotType'} = 'bar';
 5224:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5225:     $ValuesHash{$id.'.height'}   = $height;
 5226:     $ValuesHash{$id.'.width'}    = $width;
 5227:     $ValuesHash{$id.'.xskip'}    = $xskip;
 5228:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 5229:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 5230:     #
 5231:     # Deal with other parameters
 5232:     while (my ($key,$value) = each(%$extra_settings)) {
 5233:         $ValuesHash{$id.'.'.$key} = $value;
 5234:     }
 5235:     #
 5236:     &Apache::lonnet::appenv(%ValuesHash);
 5237:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5238: }
 5239: 
 5240: ############################################################
 5241: ############################################################
 5242: 
 5243: =pod
 5244: 
 5245: =item DrawXYGraph
 5246: 
 5247: Facilitates the plotting of data in an XY graph.
 5248: Puts plot definition data into the users environment in order for 
 5249: graph.png to plot it.  Returns an <img> tag for the plot.
 5250: 
 5251: Inputs:
 5252: 
 5253: =over 4
 5254: 
 5255: =item $Title: string, the title of the plot
 5256: 
 5257: =item $xlabel: string, text describing the X-axis of the plot
 5258: 
 5259: =item $ylabel: string, text describing the Y-axis of the plot
 5260: 
 5261: =item $Max: scalar, the maximum Y value to use in the plot
 5262: If $Max is < any data point, the graph will not be rendered.
 5263: 
 5264: =item $colors: Array ref containing the hex color codes for the data to be 
 5265: plotted in.  If undefined, default values will be used.
 5266: 
 5267: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 5268: 
 5269: =item $Ydata: Array ref containing Array refs.  
 5270: Each of the contained arrays will be plotted as a separate curve.
 5271: 
 5272: =item %Values: hash indicating or overriding any default values which are 
 5273: passed to graph.png.  
 5274: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 5275: 
 5276: =back
 5277: 
 5278: Returns:
 5279: 
 5280: An <img> tag which references graph.png and the appropriate identifying
 5281: information for the plot.
 5282: 
 5283: =cut
 5284: 
 5285: ############################################################
 5286: ############################################################
 5287: sub DrawXYGraph {
 5288:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 5289:     #
 5290:     # Create the identifier for the graph
 5291:     my $identifier = &get_cgi_id();
 5292:     my $id = 'cgi.'.$identifier;
 5293:     #
 5294:     $Title  = '' if (! defined($Title));
 5295:     $xlabel = '' if (! defined($xlabel));
 5296:     $ylabel = '' if (! defined($ylabel));
 5297:     my %ValuesHash = 
 5298:         (
 5299:          $id.'.title'  => &escape($Title),
 5300:          $id.'.xlabel' => &escape($xlabel),
 5301:          $id.'.ylabel' => &escape($ylabel),
 5302:          $id.'.y_max_value'=> $Max,
 5303:          $id.'.labels'     => join(',',@$Xlabels),
 5304:          $id.'.PlotType'   => 'XY',
 5305:          );
 5306:     #
 5307:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 5308:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5309:     }
 5310:     #
 5311:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 5312:         return '';
 5313:     }
 5314:     my $NumSets=1;
 5315:     foreach my $array (@{$Ydata}){
 5316:         next if (! ref($array));
 5317:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 5318:     }
 5319:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 5320:     #
 5321:     # Deal with other parameters
 5322:     while (my ($key,$value) = each(%Values)) {
 5323:         $ValuesHash{$id.'.'.$key} = $value;
 5324:     }
 5325:     #
 5326:     &Apache::lonnet::appenv(%ValuesHash);
 5327:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5328: }
 5329: 
 5330: ############################################################
 5331: ############################################################
 5332: 
 5333: =pod
 5334: 
 5335: =item DrawXYYGraph
 5336: 
 5337: Facilitates the plotting of data in an XY graph with two Y axes.
 5338: Puts plot definition data into the users environment in order for 
 5339: graph.png to plot it.  Returns an <img> tag for the plot.
 5340: 
 5341: Inputs:
 5342: 
 5343: =over 4
 5344: 
 5345: =item $Title: string, the title of the plot
 5346: 
 5347: =item $xlabel: string, text describing the X-axis of the plot
 5348: 
 5349: =item $ylabel: string, text describing the Y-axis of the plot
 5350: 
 5351: =item $colors: Array ref containing the hex color codes for the data to be 
 5352: plotted in.  If undefined, default values will be used.
 5353: 
 5354: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 5355: 
 5356: =item $Ydata1: The first data set
 5357: 
 5358: =item $Min1: The minimum value of the left Y-axis
 5359: 
 5360: =item $Max1: The maximum value of the left Y-axis
 5361: 
 5362: =item $Ydata2: The second data set
 5363: 
 5364: =item $Min2: The minimum value of the right Y-axis
 5365: 
 5366: =item $Max2: The maximum value of the left Y-axis
 5367: 
 5368: =item %Values: hash indicating or overriding any default values which are 
 5369: passed to graph.png.  
 5370: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 5371: 
 5372: =back
 5373: 
 5374: Returns:
 5375: 
 5376: An <img> tag which references graph.png and the appropriate identifying
 5377: information for the plot.
 5378: 
 5379: =cut
 5380: 
 5381: ############################################################
 5382: ############################################################
 5383: sub DrawXYYGraph {
 5384:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 5385:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 5386:     #
 5387:     # Create the identifier for the graph
 5388:     my $identifier = &get_cgi_id();
 5389:     my $id = 'cgi.'.$identifier;
 5390:     #
 5391:     $Title  = '' if (! defined($Title));
 5392:     $xlabel = '' if (! defined($xlabel));
 5393:     $ylabel = '' if (! defined($ylabel));
 5394:     my %ValuesHash = 
 5395:         (
 5396:          $id.'.title'  => &escape($Title),
 5397:          $id.'.xlabel' => &escape($xlabel),
 5398:          $id.'.ylabel' => &escape($ylabel),
 5399:          $id.'.labels' => join(',',@$Xlabels),
 5400:          $id.'.PlotType' => 'XY',
 5401:          $id.'.NumSets' => 2,
 5402:          $id.'.two_axes' => 1,
 5403:          $id.'.y1_max_value' => $Max1,
 5404:          $id.'.y1_min_value' => $Min1,
 5405:          $id.'.y2_max_value' => $Max2,
 5406:          $id.'.y2_min_value' => $Min2,
 5407:          );
 5408:     #
 5409:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 5410:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 5411:     }
 5412:     #
 5413:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 5414:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 5415:         return '';
 5416:     }
 5417:     my $NumSets=1;
 5418:     foreach my $array ($Ydata1,$Ydata2){
 5419:         next if (! ref($array));
 5420:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 5421:     }
 5422:     #
 5423:     # Deal with other parameters
 5424:     while (my ($key,$value) = each(%Values)) {
 5425:         $ValuesHash{$id.'.'.$key} = $value;
 5426:     }
 5427:     #
 5428:     &Apache::lonnet::appenv(%ValuesHash);
 5429:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 5430: }
 5431: 
 5432: ############################################################
 5433: ############################################################
 5434: 
 5435: =pod
 5436: 
 5437: =back 
 5438: 
 5439: =head1 Statistics helper routines?  
 5440: 
 5441: Bad place for them but what the hell.
 5442: 
 5443: =over 4
 5444: 
 5445: =item &chartlink
 5446: 
 5447: Returns a link to the chart for a specific student.  
 5448: 
 5449: Inputs:
 5450: 
 5451: =over 4
 5452: 
 5453: =item $linktext: The text of the link
 5454: 
 5455: =item $sname: The students username
 5456: 
 5457: =item $sdomain: The students domain
 5458: 
 5459: =back
 5460: 
 5461: =back
 5462: 
 5463: =cut
 5464: 
 5465: ############################################################
 5466: ############################################################
 5467: sub chartlink {
 5468:     my ($linktext, $sname, $sdomain) = @_;
 5469:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 5470:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 5471:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 5472:        '">'.$linktext.'</a>';
 5473: }
 5474: 
 5475: #######################################################
 5476: #######################################################
 5477: 
 5478: =pod
 5479: 
 5480: =head1 Course Environment Routines
 5481: 
 5482: =over 4
 5483: 
 5484: =item &restore_course_settings 
 5485: 
 5486: =item &store_course_settings
 5487: 
 5488: Restores/Store indicated form parameters from the course environment.
 5489: Will not overwrite existing values of the form parameters.
 5490: 
 5491: Inputs: 
 5492: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 5493: 
 5494: a hash ref describing the data to be stored.  For example:
 5495:    
 5496: %Save_Parameters = ('Status' => 'scalar',
 5497:     'chartoutputmode' => 'scalar',
 5498:     'chartoutputdata' => 'scalar',
 5499:     'Section' => 'array',
 5500:     'Group' => 'array',
 5501:     'StudentData' => 'array',
 5502:     'Maps' => 'array');
 5503: 
 5504: Returns: both routines return nothing
 5505: 
 5506: =cut
 5507: 
 5508: #######################################################
 5509: #######################################################
 5510: sub store_course_settings {
 5511:     # save to the environment
 5512:     # appenv the same items, just to be safe
 5513:     my $courseid = $env{'request.course.id'};
 5514:     my $udom  = $env{'user.domain'};
 5515:     my $uname = $env{'user.name'};
 5516:     my ($prefix,$Settings) = @_;
 5517:     my %SaveHash;
 5518:     my %AppHash;
 5519:     while (my ($setting,$type) = each(%$Settings)) {
 5520:         my $basename = join('.','internal',$courseid,$prefix,$setting);
 5521:         my $envname = 'environment.'.$basename;
 5522:         if (exists($env{'form.'.$setting})) {
 5523:             # Save this value away
 5524:             if ($type eq 'scalar' &&
 5525:                 (! exists($env{$envname}) || 
 5526:                  $env{$envname} ne $env{'form.'.$setting})) {
 5527:                 $SaveHash{$basename} = $env{'form.'.$setting};
 5528:                 $AppHash{$envname}   = $env{'form.'.$setting};
 5529:             } elsif ($type eq 'array') {
 5530:                 my $stored_form;
 5531:                 if (ref($env{'form.'.$setting})) {
 5532:                     $stored_form = join(',',
 5533:                                         map {
 5534:                                             &escape($_);
 5535:                                         } sort(@{$env{'form.'.$setting}}));
 5536:                 } else {
 5537:                     $stored_form = 
 5538:                         &escape($env{'form.'.$setting});
 5539:                 }
 5540:                 # Determine if the array contents are the same.
 5541:                 if ($stored_form ne $env{$envname}) {
 5542:                     $SaveHash{$basename} = $stored_form;
 5543:                     $AppHash{$envname}   = $stored_form;
 5544:                 }
 5545:             }
 5546:         }
 5547:     }
 5548:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 5549:                                           $udom,$uname);
 5550:     if ($put_result !~ /^(ok|delayed)/) {
 5551:         &Apache::lonnet::logthis('unable to save form parameters, '.
 5552:                                  'got error:'.$put_result);
 5553:     }
 5554:     # Make sure these settings stick around in this session, too
 5555:     &Apache::lonnet::appenv(%AppHash);
 5556:     return;
 5557: }
 5558: 
 5559: sub restore_course_settings {
 5560:     my $courseid = $env{'request.course.id'};
 5561:     my ($prefix,$Settings) = @_;
 5562:     while (my ($setting,$type) = each(%$Settings)) {
 5563:         next if (exists($env{'form.'.$setting}));
 5564:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
 5565:             '.'.$setting;
 5566:         if (exists($env{$envname})) {
 5567:             if ($type eq 'scalar') {
 5568:                 $env{'form.'.$setting} = $env{$envname};
 5569:             } elsif ($type eq 'array') {
 5570:                 $env{'form.'.$setting} = [ 
 5571:                                            map { 
 5572:                                                &unescape($_); 
 5573:                                            } split(',',$env{$envname})
 5574:                                            ];
 5575:             }
 5576:         }
 5577:     }
 5578: }
 5579: 
 5580: ############################################################
 5581: ############################################################
 5582: 
 5583: sub commit_customrole {
 5584:     my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
 5585:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
 5586:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 5587:                          ($end?', ending '.localtime($end):'').': <b>'.
 5588:               &Apache::lonnet::assigncustomrole(
 5589:                  $udom,$uname,$url,$three,$four,$five,$end,$start).
 5590:                  '</b><br />';
 5591:     return $output;
 5592: }
 5593: 
 5594: sub commit_standardrole {
 5595:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
 5596:     my $output;
 5597:     my $logmsg;
 5598:     if ($three eq 'st') {
 5599:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec);
 5600:         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
 5601:             $output = "Error: $result\n"; 
 5602:         } else {
 5603:             $output = &mt('Assigning').' '.$three.' in '.$url.
 5604:                ($start?', '.&mt('starting').' '.localtime($start):'').
 5605:                ($end?', '.&mt('ending').' '.localtime($end):'').
 5606:                ': <b>'.$result.'</b><br />'.
 5607:                &mt('Add to classlist').': <b>ok</b><br />';
 5608:         }
 5609:     } else {
 5610:         $output = &mt('Assigning').' '.$three.' in '.$url.
 5611:                ($start?', '.&mt('starting').' '.localtime($start):'').
 5612:                ($end?', '.&mt('ending').' '.localtime($end):'').': <b>'.
 5613:                &Apache::lonnet::assignrole(
 5614:                    $udom,$uname,$url,$three,$end,$start).
 5615:                    '</b><br />';
 5616:     }
 5617:     return $output;
 5618: }
 5619: 
 5620: sub commit_studentrole {
 5621:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec) = @_;
 5622:     my $linefeed =  '<br />'."\n";
 5623:     my $result;
 5624:     if (defined($one) && defined($two)) {
 5625:         my $cid=$one.'_'.$two;
 5626:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 5627:         my $secchange = 0;
 5628:         my $expire_role_result;
 5629:         my $modify_section_result;
 5630:         unless ($oldsec eq '-1') {
 5631:             unless ($sec eq $oldsec) {
 5632:                 $secchange = 1;
 5633:                 my $uurl='/'.$cid;
 5634:                 $uurl=~s/\_/\//g;
 5635:                 if ($oldsec) {
 5636:                     $uurl.='/'.$oldsec;
 5637:                 }
 5638:                 $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
 5639:                 $result = $expire_role_result;
 5640:             }
 5641:         }
 5642:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 5643:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
 5644:             if ($modify_section_result =~ /^ok/) {
 5645:                 if ($secchange == 1) {
 5646:                     $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
 5647:                 } elsif ($oldsec eq '-1') {
 5648:                     $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
 5649:                 } else {
 5650:                     $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
 5651:                 }
 5652:             } else {
 5653:                 $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
 5654:             }
 5655:             $result = $modify_section_result;
 5656:         } elsif ($secchange == 1) {
 5657:             $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
 5658:         }
 5659:     } else {
 5660:         $$logmsg .= "Incomplete course id defined.  Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
 5661:         $result = "error: incomplete course id\n";
 5662:     }
 5663:     return $result;
 5664: }
 5665: 
 5666: ############################################################
 5667: ############################################################
 5668: 
 5669: sub construct_course {
 5670:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname) = @_;
 5671:     my $outcome;
 5672: 
 5673: #
 5674: # Open course
 5675: #
 5676:     my $crstype = lc($args->{'crstype'});
 5677:     my %cenv=();
 5678:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 5679:                                              $args->{'cdescr'},
 5680:                                              $args->{'curl'},
 5681:                                              $args->{'course_home'},
 5682:                                              $args->{'nonstandard'},
 5683:                                              $args->{'crscode'},
 5684:                                              $args->{'ccuname'}.':'.
 5685:                                              $args->{'ccdomain'},
 5686:                                              $args->{'crstype'});
 5687: 
 5688:     # Note: The testing routines depend on this being output; see 
 5689:     # Utils::Course. This needs to at least be output as a comment
 5690:     # if anyone ever decides to not show this, and Utils::Course::new
 5691:     # will need to be suitably modified.
 5692:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]<br />',$crstype,$$courseid);
 5693: #
 5694: # Check if created correctly
 5695: #
 5696:     ($$crsudom,$$crsunum)=($$courseid=~/^\/(\w+)\/(\w+)$/);
 5697:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 5698:     $outcome .= &mt('Created on').': '.$crsuhome.'<br>';
 5699: #
 5700: # Are we cloning?
 5701: #
 5702:     my $cloneid='';
 5703:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 5704: 	$cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 5705:         my ($clonecrsudom,$clonecrsunum)=($cloneid=~/^\/(\w+)\/(\w+)$/);
 5706: 	my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 5707: 	if ($clonehome eq 'no_host') {
 5708: 	    $outcome .=
 5709:     '<br /><font color="red">'.&mt('Attempting to clone non-existing [_1]',$crstype).' '.$cloneid.'</font>';
 5710: 	} else {
 5711: 	    $outcome .= 
 5712:     '<br /><font color="green">'.&mt('Cloning [_1] from [_2]',$crstype,$clonehome).'</font>';
 5713: 	    my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 5714: # Copy all files
 5715: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
 5716: # Restore URL
 5717: 	    $cenv{'url'}=$oldcenv{'url'};
 5718: # Restore title
 5719: 	    $cenv{'description'}=$oldcenv{'description'};
 5720: # restore grading mode
 5721: 	    if (defined($oldcenv{'grading'})) {
 5722: 		$cenv{'grading'}=$oldcenv{'grading'};
 5723: 	    }
 5724: # Mark as cloned
 5725: 	    $cenv{'clonedfrom'}=$cloneid;
 5726: 	    delete($cenv{'default_enrollment_start_date'});
 5727: 	    delete($cenv{'default_enrollment_end_date'});
 5728: 	}
 5729:     }
 5730: #
 5731: # Set environment (will override cloned, if existing)
 5732: #
 5733:     my @sections = ();
 5734:     my @xlists = ();
 5735:     if ($args->{'crstype'}) {
 5736:         $cenv{'type'}=$args->{'crstype'};
 5737:     }
 5738:     if ($args->{'crsid'}) {
 5739:         $cenv{'courseid'}=$args->{'crsid'};
 5740:     }
 5741:     if ($args->{'crscode'}) {
 5742:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 5743:     }
 5744:     if ($args->{'crsquota'} ne '') {
 5745:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 5746:     } else {
 5747:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 5748:     }
 5749:     if ($args->{'ccuname'}) {
 5750:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 5751:                                         ':'.$args->{'ccdomain'};
 5752:     } else {
 5753:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 5754:     }
 5755: 
 5756:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 5757:     if ($args->{'crssections'}) {
 5758:         $cenv{'internal.sectionnums'} = '';
 5759:         if ($args->{'crssections'} =~ m/,/) {
 5760:             @sections = split/,/,$args->{'crssections'};
 5761:         } else {
 5762:             $sections[0] = $args->{'crssections'};
 5763:         }
 5764:         if (@sections > 0) {
 5765:             foreach my $item (@sections) {
 5766:                 my ($sec,$gp) = split/:/,$item;
 5767:                 my $class = $args->{'crscode'}.$sec;
 5768:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 5769:                 $cenv{'internal.sectionnums'} .= $item.',';
 5770:                 unless ($addcheck eq 'ok') {
 5771:                     push @badclasses, $class;
 5772:                 }
 5773:             }
 5774:             $cenv{'internal.sectionnums'} =~ s/,$//;
 5775:         }
 5776:     }
 5777: # do not hide course coordinator from staff listing, 
 5778: # even if privileged
 5779:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 5780: # add crosslistings
 5781:     if ($args->{'crsxlist'}) {
 5782:         $cenv{'internal.crosslistings'}='';
 5783:         if ($args->{'crsxlist'} =~ m/,/) {
 5784:             @xlists = split/,/,$args->{'crsxlist'};
 5785:         } else {
 5786:             $xlists[0] = $args->{'crsxlist'};
 5787:         }
 5788:         if (@xlists > 0) {
 5789:             foreach my $item (@xlists) {
 5790:                 my ($xl,$gp) = split/:/,$item;
 5791:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 5792:                 $cenv{'internal.crosslistings'} .= $item.',';
 5793:                 unless ($addcheck eq 'ok') {
 5794:                     push @badclasses, $xl;
 5795:                 }
 5796:             }
 5797:             $cenv{'internal.crosslistings'} =~ s/,$//;
 5798:         }
 5799:     }
 5800:     if ($args->{'autoadds'}) {
 5801:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 5802:     }
 5803:     if ($args->{'autodrops'}) {
 5804:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 5805:     }
 5806: # check for notification of enrollment changes
 5807:     my @notified = ();
 5808:     if ($args->{'notify_owner'}) {
 5809:         if ($args->{'ccuname'} ne '') {
 5810:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 5811:         }
 5812:     }
 5813:     if ($args->{'notify_dc'}) {
 5814:         if ($uname ne '') { 
 5815:             push(@notified,$uname.'@'.$udom);
 5816:         }
 5817:     }
 5818:     if (@notified > 0) {
 5819:         my $notifylist;
 5820:         if (@notified > 1) {
 5821:             $notifylist = join(',',@notified);
 5822:         } else {
 5823:             $notifylist = $notified[0];
 5824:         }
 5825:         $cenv{'internal.notifylist'} = $notifylist;
 5826:     }
 5827:     if (@badclasses > 0) {
 5828:         my %lt=&Apache::lonlocal::texthash(
 5829:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
 5830:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 5831:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 5832:         );
 5833:         $outcome .= '<font color="red">'.$lt{'tclb'}.' ('.$cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.' ('.$lt{'adby'}.').<br /><ul>'."\n";
 5834:         foreach (@badclasses) {
 5835:             $outcome .= "<li>$_</li>\n";
 5836:         }
 5837:         $outcome .= "</ul><br /><br /></font>\n";
 5838:     }
 5839:     if ($args->{'no_end_date'}) {
 5840:         $args->{'endaccess'} = 0;
 5841:     }
 5842:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 5843:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 5844:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 5845:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 5846:     if ($args->{'showphotos'}) {
 5847:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 5848:     }
 5849:     $cenv{'internal.authtype'} = $args->{'authtype'};
 5850:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 5851:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 5852:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 5853:             $outcome .= '<font color="red" size="+1">'.
 5854:                       &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student').'</font></p>';
 5855:         }
 5856:     }
 5857:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 5858:        if ($args->{'setpolicy'}) {
 5859:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 5860:        }
 5861:        if ($args->{'setcontent'}) {
 5862:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 5863:        }
 5864:     }
 5865:     if ($args->{'reshome'}) {
 5866: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 5867: 	$cenv{'reshome'}=~s/\/+$/\//;
 5868:     }
 5869: #
 5870: # course has keyed access
 5871: #
 5872:     if ($args->{'setkeys'}) {
 5873:        $cenv{'keyaccess'}='yes';
 5874:     }
 5875: # if specified, key authority is not course, but user
 5876: # only active if keyaccess is yes
 5877:     if ($args->{'keyauth'}) {
 5878: 	$args->{'keyauth'}=~s/[^\w\@]//g;
 5879: 	if ($args->{'keyauth'}) {
 5880: 	    $cenv{'keyauth'}=$args->{'keyauth'};
 5881: 	}
 5882:     }
 5883: 
 5884:     if ($args->{'disresdis'}) {
 5885:         $cenv{'pch.roles.denied'}='st';
 5886:     }
 5887:     if ($args->{'disablechat'}) {
 5888:         $cenv{'plc.roles.denied'}='st';
 5889:     }
 5890: 
 5891:     # Record we've not yet viewed the Course Initialization Helper for this 
 5892:     # course
 5893:     $cenv{'course.helper.not.run'} = 1;
 5894:     #
 5895:     # Use new Randomseed
 5896:     #
 5897:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 5898:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 5899:     #
 5900:     # The encryption code and receipt prefix for this course
 5901:     #
 5902:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 5903:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 5904:     #
 5905:     # By default, use standard grading
 5906:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 5907: 
 5908:     $outcome .= ('<br />'.&mt('Setting environment').': '.                 
 5909:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).'<br>');
 5910: #
 5911: # Open all assignments
 5912: #
 5913:     if ($args->{'openall'}) {
 5914:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 5915:        my %storecontent = ($storeunder         => time,
 5916:                            $storeunder.'.type' => 'date_start');
 5917:        
 5918:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 5919:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).'<br>';
 5920:    }
 5921: #
 5922: # Set first page
 5923: #
 5924:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 5925: 	    || ($cloneid)) {
 5926: 	use LONCAPA::map;
 5927: 	$outcome .= &mt('Setting first resource').': ';
 5928: 
 5929: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 5930:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 5931: 
 5932:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 5933:         my $title; my $url;
 5934:         if ($args->{'firstres'} eq 'syl') {
 5935: 	    $title='Syllabus';
 5936:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 5937:         } else {
 5938:             $title='Navigate Contents';
 5939:             $url='/adm/navmaps';
 5940:         }
 5941: 
 5942:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 5943: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 5944: 
 5945: 	if ($errtext) { $fatal=2; }
 5946:         $outcome .= ($fatal?$errtext:'write ok').'<br />';
 5947:     }
 5948:     return $outcome;
 5949: }
 5950: 
 5951: ############################################################
 5952: ############################################################
 5953: 
 5954: sub course_type {
 5955:     my ($cid) = @_;
 5956:     if (!defined($cid)) {
 5957:         $cid = $env{'request.course.id'};
 5958:     }
 5959:     if (defined($env{'course.'.$cid.'.type'})) {
 5960:         return $env{'course.'.$cid.'.type'};
 5961:     } else {
 5962:         return 'Course';
 5963:     }
 5964: }
 5965: 
 5966: sub group_term {
 5967:     my $crstype = &course_type();
 5968:     my %names = (
 5969:                   'Course' => 'group',
 5970:                   'Group' => 'team',
 5971:                 );
 5972:     return $names{$crstype};
 5973: }
 5974: 
 5975: sub icon {
 5976:     my ($file)=@_;
 5977:     my $curfext = (split(/\./,$file))[-1];
 5978:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 5979:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 5980:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 5981: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 5982: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 5983: 	            $curfext.".gif") {
 5984: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 5985: 		$curfext.".gif";
 5986: 	}
 5987:     }
 5988:     return &lonhttpdurl($iconname);
 5989: } 
 5990: 
 5991: sub lonhttpdurl {
 5992:     my ($url)=@_;
 5993:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 5994:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 5995:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 5996: }
 5997: 
 5998: sub connection_aborted {
 5999:     my ($r)=@_;
 6000:     $r->print(" ");$r->rflush();
 6001:     my $c = $r->connection;
 6002:     return $c->aborted();
 6003: }
 6004: 
 6005: #    Escapes strings that may have embedded 's that will be put into
 6006: #    strings as 'strings'.
 6007: sub escape_single {
 6008:     my ($input) = @_;
 6009:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 6010:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 6011:     return $input;
 6012: }
 6013: 
 6014: #  Same as escape_single, but escape's "'s  This 
 6015: #  can be used for  "strings"
 6016: sub escape_double {
 6017:     my ($input) = @_;
 6018:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 6019:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 6020:     return $input;
 6021: }
 6022:  
 6023: #   Escapes the last element of a full URL.
 6024: sub escape_url {
 6025:     my ($url)   = @_;
 6026:     my @urlslices = split(/\//, $url,-1);
 6027:     my $lastitem = &escape(pop(@urlslices));
 6028:     return join('/',@urlslices).'/'.$lastitem;
 6029: }
 6030: 
 6031: # -------------------------------------------------------- Initliaze user login
 6032: sub init_user_environment {
 6033:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 6034:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 6035: 
 6036:     my $public=($username eq 'public' && $domain eq 'public');
 6037: 
 6038: # See if old ID present, if so, remove
 6039: 
 6040:     my ($filename,$cookie,$userroles);
 6041:     my $now=time;
 6042: 
 6043:     if ($public) {
 6044: 	my $max_public=100;
 6045: 	my $oldest;
 6046: 	my $oldest_time=0;
 6047: 	for(my $next=1;$next<=$max_public;$next++) {
 6048: 	    if (-e $lonids."/publicuser_$next.id") {
 6049: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 6050: 		if ($mtime<$oldest_time || !$oldest_time) {
 6051: 		    $oldest_time=$mtime;
 6052: 		    $oldest=$next;
 6053: 		}
 6054: 	    } else {
 6055: 		$cookie="publicuser_$next";
 6056: 		last;
 6057: 	    }
 6058: 	}
 6059: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 6060:     } else {
 6061: 	# if this isn't a robot, kill any existing non-robot sessions
 6062: 	if (!$args->{'robot'}) {
 6063: 	    opendir(DIR,$lonids);
 6064: 	    while ($filename=readdir(DIR)) {
 6065: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 6066: 		    unlink($lonids.'/'.$filename);
 6067: 		}
 6068: 	    }
 6069: 	    closedir(DIR);
 6070: 	}
 6071: # Give them a new cookie
 6072: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 6073: 		                   : $now);
 6074: 	$cookie="$username\_$id\_$domain\_$authhost";
 6075:     
 6076: # Initialize roles
 6077: 
 6078: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 6079:     }
 6080: # ------------------------------------ Check browser type and MathML capability
 6081: 
 6082:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 6083:         $clientunicode,$clientos) = &decode_user_agent($r);
 6084: 
 6085: # -------------------------------------- Any accessibility options to remember?
 6086:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 6087: 	foreach my $option ('imagesuppress','appletsuppress',
 6088: 			    'embedsuppress','fontenhance','blackwhite') {
 6089: 	    if ($form->{$option} eq 'true') {
 6090: 		&Apache::lonnet::put('environment',{$option => 'on'},
 6091: 				     $domain,$username);
 6092: 	    } else {
 6093: 		&Apache::lonnet::del('environment',[$option],
 6094: 				     $domain,$username);
 6095: 	    }
 6096: 	}
 6097:     }
 6098: # ------------------------------------------------------------- Get environment
 6099: 
 6100:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 6101:     my ($tmp) = keys(%userenv);
 6102:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6103: 	# default remote control to off
 6104: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 6105:     } else {
 6106: 	undef(%userenv);
 6107:     }
 6108:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 6109: 	$form->{'interface'}=$userenv{'interface'};
 6110:     }
 6111:     $env{'environment.remote'}=$userenv{'remote'};
 6112:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 6113: 
 6114: # --------------- Do not trust query string to be put directly into environment
 6115:     foreach my $option ('imagesuppress','appletsuppress',
 6116: 			'embedsuppress','fontenhance','blackwhite',
 6117: 			'interface','localpath','localres') {
 6118: 	$form->{$option}=~s/[\n\r\=]//gs;
 6119:     }
 6120: # --------------------------------------------------------- Write first profile
 6121: 
 6122:     {
 6123: 	my %initial_env = 
 6124: 	    ("user.name"          => $username,
 6125: 	     "user.domain"        => $domain,
 6126: 	     "user.home"          => $authhost,
 6127: 	     "browser.type"       => $clientbrowser,
 6128: 	     "browser.version"    => $clientversion,
 6129: 	     "browser.mathml"     => $clientmathml,
 6130: 	     "browser.unicode"    => $clientunicode,
 6131: 	     "browser.os"         => $clientos,
 6132: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 6133: 	     "request.course.fn"  => '',
 6134: 	     "request.course.uri" => '',
 6135: 	     "request.course.sec" => '',
 6136: 	     "request.role"       => 'cm',
 6137: 	     "request.role.adv"   => $env{'user.adv'},
 6138: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 6139: 
 6140:         if ($form->{'localpath'}) {
 6141: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 6142: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 6143:         }
 6144: 	
 6145: 	if ($public) {
 6146: 	    $initial_env{"environment.remote"} = "off";
 6147: 	}
 6148: 	if ($form->{'interface'}) {
 6149: 	    $form->{'interface'}=~s/\W//gs;
 6150: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 6151: 	    $env{'browser.interface'}=$form->{'interface'};
 6152: 	    foreach my $option ('imagesuppress','appletsuppress',
 6153: 				'embedsuppress','fontenhance','blackwhite') {
 6154: 		if (($form->{$option} eq 'true') ||
 6155: 		    ($userenv{$option} eq 'on')) {
 6156: 		    $initial_env{"browser.$option"} = "on";
 6157: 		}
 6158: 	    }
 6159: 	}
 6160: 
 6161: 	$env{'user.environment'} = "$lonids/$cookie.id";
 6162: 	
 6163: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 6164: 		 &GDBM_WRCREAT(),0640)) {
 6165: 	    &_add_to_env(\%disk_env,\%initial_env);
 6166: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 6167: 	    &_add_to_env(\%disk_env,$userroles);
 6168: 	    if (ref($args->{'extra_env'})) {
 6169: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 6170: 	    }
 6171: 	    untie(%disk_env);
 6172: 	} else {
 6173: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 6174: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 6175: 	    return 'error: '.$!;
 6176: 	}
 6177:     }
 6178:     $env{'request.role'}='cm';
 6179:     $env{'request.role.adv'}=$env{'user.adv'};
 6180:     $env{'browser.type'}=$clientbrowser;
 6181: 
 6182:     return $cookie;
 6183: 
 6184: }
 6185: 
 6186: sub _add_to_env {
 6187:     my ($idf,$env_data,$prefix) = @_;
 6188:     while (my ($key,$value) = each(%$env_data)) {
 6189: 	$idf->{$prefix.$key} = $value;
 6190: 	$env{$prefix.$key}   = $value;
 6191:     }
 6192: }
 6193: 
 6194: 
 6195: =pod
 6196: 
 6197: =back
 6198: 
 6199: =cut
 6200: 
 6201: 1;
 6202: __END__;
 6203: 

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