File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.566: download - view: text, annotated - select for diffs
Thu Aug 23 21:54:40 2007 UTC (16 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#5377 don't create a course if cloning rights check fails

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

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