File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.583: download - view: text, annotated - select for diffs
Tue Sep 11 20:40:23 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- remove duplication from language list
- accept more than two language possibilities from the browser

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

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