File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.525: download - view: text, annotated - select for diffs
Mon Apr 16 23:25:04 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- bug2622 string response

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

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