File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.512: download - view: text, annotated - select for diffs
Sat Mar 3 01:33:20 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- reduce usage of libserv and host dom,
- mode the domain fetching routines to lonnet

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.