File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.589: download - view: text, annotated - select for diffs
Wed Sep 26 12:34:19 2007 UTC (16 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
lonwhatsnew.pm
- xhtml
- remove surplus table tags
- more CSS

loncommon.pm
- IE 7 needs border-collapse: collapse
- Full page two column format added to standard_css

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

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