File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.444: download - view: text, annotated - select for diffs
Fri Aug 11 22:00:07 2006 UTC (17 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_99_3, HEAD
- prep work for BUG#4965 move course creation routines and cloning
  routines for use external to webserver

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

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