File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.553: download - view: text, annotated - select for diffs
Wed Jul 18 01:46:07 2007 UTC (16 years, 10 months ago) by banghart
Branches: MAIN
CVS tags: HEAD
	Remove logthis debugging stuff.

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

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