File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.514: download - view: text, annotated - select for diffs
Thu Mar 8 01:58:44 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminating the domain hash globals in favor of functional access

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

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