File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.633: download - view: text, annotated - select for diffs
Sun Jan 6 04:38:57 2008 UTC (16 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_0, HEAD
- "Select User" link moved to work with direct username entry form.
- Wording changes, customized to "Add single user" or "Enroll single student"
- Eliminate phrase-splitting, to facilitate localization
- Consistent word use in breadcrumbs via &singleuser_breadcrumb()
- Institutional searches disallowed for usertype (include 'Other') as searcher's type, if no type in searcher's %env.
- new CSS span: LC_cusr_subheading

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

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