File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.815: download - view: text, annotated - select for diffs
Fri May 15 09:33:22 2009 UTC (15 years ago) by tempelho
Branches: MAIN
CVS tags: HEAD
Insert a 'no role' color scheme. Color Scheme is selected after the log in.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.815 2009/05/15 09:33:22 tempelho 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 Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410:     var stdeditbrowser;
  411:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
  412:         var url = '/adm/pickstudent?';
  413:         var filter;
  414: 	if (!ignorefilter) {
  415: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  416: 	}
  417:         if (filter != null) {
  418:            if (filter != '') {
  419:                url += 'filter='+filter+'&';
  420: 	   }
  421:         }
  422:         url += 'form=' + formname + '&unameelement='+uname+
  423:                                     '&udomelement='+udom;
  424: 	if (roleflag) { url+="&roles=1"; }
  425:         if (courseadvonly) { url+="&courseadvonly=1"; }
  426:         var title = 'Student_Browser';
  427:         var options = 'scrollbars=1,resizable=1,menubar=0';
  428:         options += ',width=700,height=600';
  429:         stdeditbrowser = open(url,title,options,'1');
  430:         stdeditbrowser.focus();
  431:     }
  432: </script>
  433: ENDSTDBRW
  434: }
  435: 
  436: sub selectstudent_link {
  437:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  438:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  439:    if ($env{'request.course.id'}) {  
  440:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  441: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  442: 					'/'.$env{'request.course.sec'})) {
  443: 	   return '';
  444:        }
  445:        if ($courseadvonly)  {
  446:            $callargs .= ",'',1,1";
  447:        }
  448:        return '<span class="LC_nobreak">'.
  449:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  450:               &mt('Select User').'</a></span>';
  451:    }
  452:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  453:        $callargs .= ",1"; 
  454:        return '<span class="LC_nobreak">'.
  455:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  456:               &mt('Select User').'</a></span>';
  457:    }
  458:    return '';
  459: }
  460: 
  461: sub authorbrowser_javascript {
  462:     return <<"ENDAUTHORBRW";
  463: <script type="text/javascript" language="JavaScript">
  464: var stdeditbrowser;
  465: 
  466: function openauthorbrowser(formname,udom) {
  467:     var url = '/adm/pickauthor?';
  468:     url += 'form='+formname+'&roledom='+udom;
  469:     var title = 'Author_Browser';
  470:     var options = 'scrollbars=1,resizable=1,menubar=0';
  471:     options += ',width=700,height=600';
  472:     stdeditbrowser = open(url,title,options,'1');
  473:     stdeditbrowser.focus();
  474: }
  475: 
  476: </script>
  477: ENDAUTHORBRW
  478: }
  479: 
  480: sub coursebrowser_javascript {
  481:     my ($domainfilter,$sec_element,$formname)=@_;
  482:     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');
  483:    my $output = '
  484: <script type="text/javascript" language="JavaScript">
  485:     var stdeditbrowser;'."\n";
  486:    $output .= <<"ENDSTDBRW";
  487:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  488:         var url = '/adm/pickcourse?';
  489:         var domainfilter = '';
  490:         var formid = getFormIdByName(formname);
  491:         if (formid > -1) {
  492:             var domid = getIndexByName(formid,udom);
  493:             if (domid > -1) {
  494:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  495:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  496:                 }
  497:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  498:                     domainfilter=document.forms[formid].elements[domid].value;
  499:                 }
  500:             }
  501:         }
  502:         if (domainfilter != null) {
  503:            if (domainfilter != '') {
  504:                url += 'domainfilter='+domainfilter+'&';
  505: 	   }
  506:         }
  507:         url += 'form=' + formname + '&cnumelement='+uname+
  508: 	                            '&cdomelement='+udom+
  509:                                     '&cnameelement='+desc;
  510:         if (extra_element !=null && extra_element != '') {
  511:             if (formname == 'rolechoice' || formname == 'studentform') {
  512:                 url += '&roleelement='+extra_element;
  513:                 if (domainfilter == null || domainfilter == '') {
  514:                     url += '&domainfilter='+extra_element;
  515:                 }
  516:             }
  517:             else {
  518:                 if (formname == 'portform') {
  519:                     url += '&setroles='+extra_element;
  520:                 } else {
  521:                     if (formname == 'rules') {
  522:                         url += '&fixeddom='+extra_element; 
  523:                     }
  524:                 }
  525:             }     
  526:         }
  527:         if (multflag !=null && multflag != '') {
  528:             url += '&multiple='+multflag;
  529:         }
  530:         if (crstype == 'Course/Group') {
  531:             if (formname == 'cu') {
  532:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  533:                 if (crstype == "") {
  534:                     alert("$crs_or_grp_alert");
  535:                     return;
  536:                 }
  537:             }
  538:         }
  539:         if (crstype !=null && crstype != '') {
  540:             url += '&type='+crstype;
  541:         }
  542:         var title = 'Course_Browser';
  543:         var options = 'scrollbars=1,resizable=1,menubar=0';
  544:         options += ',width=700,height=600';
  545:         stdeditbrowser = open(url,title,options,'1');
  546:         stdeditbrowser.focus();
  547:     }
  548: 
  549:     function getFormIdByName(formname) {
  550:         for (var i=0;i<document.forms.length;i++) {
  551:             if (document.forms[i].name == formname) {
  552:                 return i;
  553:             }
  554:         }
  555:         return -1; 
  556:     }
  557: 
  558:     function getIndexByName(formid,item) {
  559:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  560:             if (document.forms[formid].elements[i].name == item) {
  561:                 return i;
  562:             }
  563:         }
  564:         return -1;
  565:     }
  566: ENDSTDBRW
  567:     if ($sec_element ne '') {
  568:         $output .= &setsec_javascript($sec_element,$formname);
  569:     }
  570:     $output .= '
  571: </script>';
  572:     return $output;
  573: }
  574: 
  575: sub setsec_javascript {
  576:     my ($sec_element,$formname) = @_;
  577:     my $setsections = qq|
  578: function setSect(sectionlist) {
  579:     var sectionsArray = new Array();
  580:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  581:         sectionsArray = sectionlist.split(",");
  582:     }
  583:     var numSections = sectionsArray.length;
  584:     document.$formname.$sec_element.length = 0;
  585:     if (numSections == 0) {
  586:         document.$formname.$sec_element.multiple=false;
  587:         document.$formname.$sec_element.size=1;
  588:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  589:     } else {
  590:         if (numSections == 1) {
  591:             document.$formname.$sec_element.multiple=false;
  592:             document.$formname.$sec_element.size=1;
  593:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  594:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  595:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  596:         } else {
  597:             for (var i=0; i<numSections; i++) {
  598:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  599:             }
  600:             document.$formname.$sec_element.multiple=true
  601:             if (numSections < 3) {
  602:                 document.$formname.$sec_element.size=numSections;
  603:             } else {
  604:                 document.$formname.$sec_element.size=3;
  605:             }
  606:             document.$formname.$sec_element.options[0].selected = false
  607:         }
  608:     }
  609: }
  610: |;
  611:     return $setsections;
  612: }
  613: 
  614: 
  615: sub selectcourse_link {
  616:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  617:    return '<span class="LC_nobreak">'
  618:          ."<a href='"
  619:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  620:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  621:          .'","'.$multflag.'","'.$selecttype.'");'
  622:          ."'>".&mt('Select Course').'</a>'
  623:          .'</span>';
  624: }
  625: 
  626: sub selectauthor_link {
  627:    my ($form,$udom)=@_;
  628:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  629:           &mt('Select Author').'</a>';
  630: }
  631: 
  632: sub check_uncheck_jscript {
  633:     my $jscript = <<"ENDSCRT";
  634: function checkAll(field) {
  635:     if (field.length > 0) {
  636:         for (i = 0; i < field.length; i++) {
  637:             field[i].checked = true ;
  638:         }
  639:     } else {
  640:         field.checked = true
  641:     }
  642: }
  643:  
  644: function uncheckAll(field) {
  645:     if (field.length > 0) {
  646:         for (i = 0; i < field.length; i++) {
  647:             field[i].checked = false ;
  648:         }
  649:     } else {
  650:         field.checked = false ;
  651:     }
  652: }
  653: ENDSCRT
  654:     return $jscript;
  655: }
  656: 
  657: sub select_timezone {
  658:    my ($name,$selected,$onchange,$includeempty)=@_;
  659:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  660:    if ($includeempty) {
  661:        $output .= '<option value=""';
  662:        if (($selected eq '') || ($selected eq 'local')) {
  663:            $output .= ' selected="selected" ';
  664:        }
  665:        $output .= '> </option>';
  666:    }
  667:    my @timezones = DateTime::TimeZone->all_names;
  668:    foreach my $tzone (@timezones) {
  669:        $output.= '<option value="'.$tzone.'"';
  670:        if ($tzone eq $selected) {
  671:            $output.=' selected="selected"';
  672:        }
  673:        $output.=">$tzone</option>\n";
  674:    }
  675:    $output.="</select>";
  676:    return $output;
  677: }
  678: 
  679: sub select_datelocale {
  680:     my ($name,$selected,$onchange,$includeempty)=@_;
  681:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  682:     if ($includeempty) {
  683:         $output .= '<option value=""';
  684:         if ($selected eq '') {
  685:             $output .= ' selected="selected" ';
  686:         }
  687:         $output .= '> </option>';
  688:     }
  689:     my (@possibles,%locale_names);
  690:     my @locales = DateTime::Locale::Catalog::Locales;
  691:     foreach my $locale (@locales) {
  692:         if (ref($locale) eq 'HASH') {
  693:             my $id = $locale->{'id'};
  694:             if ($id ne '') {
  695:                 my $en_terr = $locale->{'en_territory'};
  696:                 my $native_terr = $locale->{'native_territory'};
  697:                 my @languages = &Apache::lonlocal::preferred_languages();
  698:                 if (grep(/^en$/,@languages) || !@languages) {
  699:                     if ($en_terr ne '') {
  700:                         $locale_names{$id} = '('.$en_terr.')';
  701:                     } elsif ($native_terr ne '') {
  702:                         $locale_names{$id} = $native_terr;
  703:                     }
  704:                 } else {
  705:                     if ($native_terr ne '') {
  706:                         $locale_names{$id} = $native_terr.' ';
  707:                     } elsif ($en_terr ne '') {
  708:                         $locale_names{$id} = '('.$en_terr.')';
  709:                     }
  710:                 }
  711:                 push (@possibles,$id);
  712:             }
  713:         }
  714:     }
  715:     foreach my $item (sort(@possibles)) {
  716:         $output.= '<option value="'.$item.'"';
  717:         if ($item eq $selected) {
  718:             $output.=' selected="selected"';
  719:         }
  720:         $output.=">$item";
  721:         if ($locale_names{$item} ne '') {
  722:             $output.="  $locale_names{$item}</option>\n";
  723:         }
  724:         $output.="</option>\n";
  725:     }
  726:     $output.="</select>";
  727:     return $output;
  728: }
  729: 
  730: sub select_language {
  731:     my ($name,$selected,$includeempty) = @_;
  732:     my %langchoices;
  733:     if ($includeempty) {
  734:         %langchoices = ('' => 'No language preference');
  735:     }
  736:     foreach my $id (&languageids()) {
  737:         my $code = &supportedlanguagecode($id);
  738:         if ($code) {
  739:             $langchoices{$code} = &plainlanguagedescription($id);
  740:         }
  741:     }
  742:     return &select_form($selected,$name,%langchoices);
  743: }
  744: 
  745: =pod
  746: 
  747: =item * &linked_select_forms(...)
  748: 
  749: linked_select_forms returns a string containing a <script></script> block
  750: and html for two <select> menus.  The select menus will be linked in that
  751: changing the value of the first menu will result in new values being placed
  752: in the second menu.  The values in the select menu will appear in alphabetical
  753: order unless a defined order is provided.
  754: 
  755: linked_select_forms takes the following ordered inputs:
  756: 
  757: =over 4
  758: 
  759: =item * $formname, the name of the <form> tag
  760: 
  761: =item * $middletext, the text which appears between the <select> tags
  762: 
  763: =item * $firstdefault, the default value for the first menu
  764: 
  765: =item * $firstselectname, the name of the first <select> tag
  766: 
  767: =item * $secondselectname, the name of the second <select> tag
  768: 
  769: =item * $hashref, a reference to a hash containing the data for the menus.
  770: 
  771: =item * $menuorder, the order of values in the first menu
  772: 
  773: =back 
  774: 
  775: Below is an example of such a hash.  Only the 'text', 'default', and 
  776: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  777: values for the first select menu.  The text that coincides with the 
  778: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  779: and text for the second menu are given in the hash pointed to by 
  780: $menu{$choice1}->{'select2'}.  
  781: 
  782:  my %menu = ( A1 => { text =>"Choice A1" ,
  783:                        default => "B3",
  784:                        select2 => { 
  785:                            B1 => "Choice B1",
  786:                            B2 => "Choice B2",
  787:                            B3 => "Choice B3",
  788:                            B4 => "Choice B4"
  789:                            },
  790:                        order => ['B4','B3','B1','B2'],
  791:                    },
  792:                A2 => { text =>"Choice A2" ,
  793:                        default => "C2",
  794:                        select2 => { 
  795:                            C1 => "Choice C1",
  796:                            C2 => "Choice C2",
  797:                            C3 => "Choice C3"
  798:                            },
  799:                        order => ['C2','C1','C3'],
  800:                    },
  801:                A3 => { text =>"Choice A3" ,
  802:                        default => "D6",
  803:                        select2 => { 
  804:                            D1 => "Choice D1",
  805:                            D2 => "Choice D2",
  806:                            D3 => "Choice D3",
  807:                            D4 => "Choice D4",
  808:                            D5 => "Choice D5",
  809:                            D6 => "Choice D6",
  810:                            D7 => "Choice D7"
  811:                            },
  812:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  813:                    }
  814:                );
  815: 
  816: =cut
  817: 
  818: sub linked_select_forms {
  819:     my ($formname,
  820:         $middletext,
  821:         $firstdefault,
  822:         $firstselectname,
  823:         $secondselectname, 
  824:         $hashref,
  825:         $menuorder,
  826:         ) = @_;
  827:     my $second = "document.$formname.$secondselectname";
  828:     my $first = "document.$formname.$firstselectname";
  829:     # output the javascript to do the changing
  830:     my $result = '';
  831:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  832:     $result.="var select2data = new Object();\n";
  833:     $" = '","';
  834:     my $debug = '';
  835:     foreach my $s1 (sort(keys(%$hashref))) {
  836:         $result.="select2data.d_$s1 = new Object();\n";        
  837:         $result.="select2data.d_$s1.def = new String('".
  838:             $hashref->{$s1}->{'default'}."');\n";
  839:         $result.="select2data.d_$s1.values = new Array(";
  840:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  841:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  842:             @s2values = @{$hashref->{$s1}->{'order'}};
  843:         }
  844:         $result.="\"@s2values\");\n";
  845:         $result.="select2data.d_$s1.texts = new Array(";        
  846:         my @s2texts;
  847:         foreach my $value (@s2values) {
  848:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  849:         }
  850:         $result.="\"@s2texts\");\n";
  851:     }
  852:     $"=' ';
  853:     $result.= <<"END";
  854: 
  855: function select1_changed() {
  856:     // Determine new choice
  857:     var newvalue = "d_" + $first.value;
  858:     // update select2
  859:     var values     = select2data[newvalue].values;
  860:     var texts      = select2data[newvalue].texts;
  861:     var select2def = select2data[newvalue].def;
  862:     var i;
  863:     // out with the old
  864:     for (i = 0; i < $second.options.length; i++) {
  865:         $second.options[i] = null;
  866:     }
  867:     // in with the nuclear
  868:     for (i=0;i<values.length; i++) {
  869:         $second.options[i] = new Option(values[i]);
  870:         $second.options[i].value = values[i];
  871:         $second.options[i].text = texts[i];
  872:         if (values[i] == select2def) {
  873:             $second.options[i].selected = true;
  874:         }
  875:     }
  876: }
  877: </script>
  878: END
  879:     # output the initial values for the selection lists
  880:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  881:     my @order = sort(keys(%{$hashref}));
  882:     if (ref($menuorder) eq 'ARRAY') {
  883:         @order = @{$menuorder};
  884:     }
  885:     foreach my $value (@order) {
  886:         $result.="    <option value=\"$value\" ";
  887:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  888:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  889:     }
  890:     $result .= "</select>\n";
  891:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  892:     $result .= $middletext;
  893:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  894:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  895:     
  896:     my @secondorder = sort(keys(%select2));
  897:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  898:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  899:     }
  900:     foreach my $value (@secondorder) {
  901:         $result.="    <option value=\"$value\" ";        
  902:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  903:         $result.=">".&mt($select2{$value})."</option>\n";
  904:     }
  905:     $result .= "</select>\n";
  906:     #    return $debug;
  907:     return $result;
  908: }   #  end of sub linked_select_forms {
  909: 
  910: =pod
  911: 
  912: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  913: 
  914: Returns a string corresponding to an HTML link to the given help
  915: $topic, where $topic corresponds to the name of a .tex file in
  916: /home/httpd/html/adm/help/tex, with underscores replaced by
  917: spaces. 
  918: 
  919: $text will optionally be linked to the same topic, allowing you to
  920: link text in addition to the graphic. If you do not want to link
  921: text, but wish to specify one of the later parameters, pass an
  922: empty string. 
  923: 
  924: $stayOnPage is a value that will be interpreted as a boolean. If true,
  925: the link will not open a new window. If false, the link will open
  926: a new window using Javascript. (Default is false.) 
  927: 
  928: $width and $height are optional numerical parameters that will
  929: override the width and height of the popped up window, which may
  930: be useful for certain help topics with big pictures included. 
  931: 
  932: =cut
  933: 
  934: sub help_open_topic {
  935:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  936:     $text = "" if (not defined $text);
  937:     $stayOnPage = 0 if (not defined $stayOnPage);
  938:     $width = 350 if (not defined $width);
  939:     $height = 400 if (not defined $height);
  940:     my $filename = $topic;
  941:     $filename =~ s/ /_/g;
  942: 
  943:     my $template = "";
  944:     my $link;
  945:     
  946:     $topic=~s/\W/\_/g;
  947: 
  948:     if (!$stayOnPage) {
  949: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  950:     } else {
  951: 	$link = "/adm/help/${filename}.hlp";
  952:     }
  953: 
  954:     # Add the text
  955:     if ($text ne "") {	
  956: 	$template.='<span class="LC_help_open_topic">'
  957:                   .'<a target="_top" href="'.$link.'">'
  958:                   .$text.'</a>';
  959:     }
  960: 
  961:     # (Always) Add the graphic
  962:     my $title = &mt('Online Help');
  963:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  964:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  965:               .'<img src="'.$helpicon.'" border="0"'
  966:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  967:               .' title="'.$title.'"' 
  968:               .' /></a>';
  969:     if ($text ne "") {	
  970:         $template.='</span>';
  971:     }
  972:     return $template;
  973: 
  974: }
  975: 
  976: # This is a quicky function for Latex cheatsheet editing, since it 
  977: # appears in at least four places
  978: sub helpLatexCheatsheet {
  979:     my ($topic,$text,$not_author) = @_;
  980:     my $out;
  981:     my $addOther = '';
  982:     if ($topic) {
  983: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  984: 							       undef, undef, 600).
  985: 								   '</span> ';
  986:     }
  987:     $out = '<span>' # Start cheatsheet
  988: 	  .$addOther
  989:           .'<span>'
  990: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  991: 					       undef,undef,600)
  992: 	  .'</span> <span>'
  993: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  994: 					       undef,undef,600)
  995: 	  .'</span>';
  996:     unless ($not_author) {
  997:         $out .= ' <span>'
  998: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  999: 	                                            undef,undef,600)
 1000: 	       .'</span>';
 1001:     }
 1002:     $out .= '</span>'; # End cheatsheet
 1003:     return $out;
 1004: }
 1005: 
 1006: sub general_help {
 1007:     my $helptopic='Student_Intro';
 1008:     if ($env{'request.role'}=~/^(ca|au)/) {
 1009: 	$helptopic='Authoring_Intro';
 1010:     } elsif ($env{'request.role'}=~/^cc/) {
 1011: 	$helptopic='Course_Coordination_Intro';
 1012:     } elsif ($env{'request.role'}=~/^dc/) {
 1013:         $helptopic='Domain_Coordination_Intro';
 1014:     }
 1015:     return $helptopic;
 1016: }
 1017: 
 1018: sub update_help_link {
 1019:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1020:     my $origurl = $ENV{'REQUEST_URI'};
 1021:     $origurl=~s|^/~|/priv/|;
 1022:     my $timestamp = time;
 1023:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1024:         $$datum = &escape($$datum);
 1025:     }
 1026: 
 1027:     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";
 1028:     my $output .= <<"ENDOUTPUT";
 1029: <script type="text/javascript">
 1030: banner_link = '$banner_link';
 1031: </script>
 1032: ENDOUTPUT
 1033:     return $output;
 1034: }
 1035: 
 1036: # now just updates the help link and generates a blue icon
 1037: sub help_open_menu {
 1038:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1039: 	= @_;    
 1040:     $stayOnPage = 0 if (not defined $stayOnPage);
 1041:     # only use pop-up help (stayOnPage == 0)
 1042:     # if environment.remote is on (using remote control UI)
 1043:     if ($env{'environment.remote'} eq 'off' ) {
 1044:         $stayOnPage=1;
 1045:     }
 1046:     my $output;
 1047:     if ($component_help) {
 1048: 	if (!$text) {
 1049: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1050: 				       $width,$height);
 1051: 	} else {
 1052: 	    my $help_text;
 1053: 	    $help_text=&unescape($topic);
 1054: 	    $output='<table><tr><td>'.
 1055: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1056: 				 $width,$height).'</td></tr></table>';
 1057: 	}
 1058:     }
 1059:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1060:     return $output.$banner_link;
 1061: }
 1062: 
 1063: sub top_nav_help {
 1064:     my ($text) = @_;
 1065:     $text = &mt($text);
 1066:     my $stay_on_page = 
 1067: 	($env{'environment.remote'} eq 'off' );
 1068:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1069: 	                     : "javascript:helpMenu('open')";
 1070:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1071: 
 1072:     my $title = &mt('Get help');
 1073: 
 1074:     return <<"END";
 1075: $banner_link
 1076:  <a href="$link" title="$title">$text</a>
 1077: END
 1078: }
 1079: 
 1080: sub help_menu_js {
 1081:     my ($text) = @_;
 1082: 
 1083:     my $stayOnPage = 
 1084: 	($env{'environment.remote'} eq 'off' );
 1085: 
 1086:     my $width = 620;
 1087:     my $height = 600;
 1088:     my $helptopic=&general_help();
 1089:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1090:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1091:     my $start_page =
 1092:         &Apache::loncommon::start_page('Help Menu', undef,
 1093: 				       {'frameset'    => 1,
 1094: 					'js_ready'    => 1,
 1095: 					'add_entries' => {
 1096: 					    'border' => '0',
 1097: 					    'rows'   => "110,*",},});
 1098:     my $end_page =
 1099:         &Apache::loncommon::end_page({'frameset' => 1,
 1100: 				      'js_ready' => 1,});
 1101: 
 1102:     my $template .= <<"ENDTEMPLATE";
 1103: <script type="text/javascript">
 1104: // <!-- BEGIN LON-CAPA Internal
 1105: // <![CDATA[
 1106: var banner_link = '';
 1107: function helpMenu(target) {
 1108:     var caller = this;
 1109:     if (target == 'open') {
 1110:         var newWindow = null;
 1111:         try {
 1112:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1113:         }
 1114:         catch(error) {
 1115:             writeHelp(caller);
 1116:             return;
 1117:         }
 1118:         if (newWindow) {
 1119:             caller = newWindow;
 1120:         }
 1121:     }
 1122:     writeHelp(caller);
 1123:     return;
 1124: }
 1125: function writeHelp(caller) {
 1126:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1127:     caller.document.close()
 1128:     caller.focus()
 1129: }
 1130: // ]]>
 1131: // END LON-CAPA Internal -->
 1132: </script>
 1133: ENDTEMPLATE
 1134:     return $template;
 1135: }
 1136: 
 1137: sub help_open_bug {
 1138:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1139:     unless ($env{'user.adv'}) { return ''; }
 1140:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1141:     $text = "" if (not defined $text);
 1142:     $stayOnPage = 0 if (not defined $stayOnPage);
 1143:     if ($env{'environment.remote'} eq 'off' ) {
 1144: 	$stayOnPage=1;
 1145:     }
 1146:     $width = 600 if (not defined $width);
 1147:     $height = 600 if (not defined $height);
 1148: 
 1149:     $topic=~s/\W+/\+/g;
 1150:     my $link='';
 1151:     my $template='';
 1152:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1153: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1154:     if (!$stayOnPage)
 1155:     {
 1156: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1157:     }
 1158:     else
 1159:     {
 1160: 	$link = $url;
 1161:     }
 1162:     # Add the text
 1163:     if ($text ne "")
 1164:     {
 1165: 	$template .= 
 1166:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1167:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1168:     }
 1169: 
 1170:     # Add the graphic
 1171:     my $title = &mt('Report a Bug');
 1172:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1173:     $template .= <<"ENDTEMPLATE";
 1174:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1175: ENDTEMPLATE
 1176:     if ($text ne '') { $template.='</td></tr></table>' };
 1177:     return $template;
 1178: 
 1179: }
 1180: 
 1181: sub help_open_faq {
 1182:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1183:     unless ($env{'user.adv'}) { return ''; }
 1184:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1185:     $text = "" if (not defined $text);
 1186:     $stayOnPage = 0 if (not defined $stayOnPage);
 1187:     if ($env{'environment.remote'} eq 'off' ) {
 1188: 	$stayOnPage=1;
 1189:     }
 1190:     $width = 350 if (not defined $width);
 1191:     $height = 400 if (not defined $height);
 1192: 
 1193:     $topic=~s/\W+/\+/g;
 1194:     my $link='';
 1195:     my $template='';
 1196:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1197:     if (!$stayOnPage)
 1198:     {
 1199: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1200:     }
 1201:     else
 1202:     {
 1203: 	$link = $url;
 1204:     }
 1205: 
 1206:     # Add the text
 1207:     if ($text ne "")
 1208:     {
 1209: 	$template .= 
 1210:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1211:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1212:     }
 1213: 
 1214:     # Add the graphic
 1215:     my $title = &mt('View the FAQ');
 1216:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1217:     $template .= <<"ENDTEMPLATE";
 1218:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1219: ENDTEMPLATE
 1220:     if ($text ne '') { $template.='</td></tr></table>' };
 1221:     return $template;
 1222: 
 1223: }
 1224: 
 1225: ###############################################################
 1226: ###############################################################
 1227: 
 1228: =pod
 1229: 
 1230: =item * &change_content_javascript():
 1231: 
 1232: This and the next function allow you to create small sections of an
 1233: otherwise static HTML page that you can update on the fly with
 1234: Javascript, even in Netscape 4.
 1235: 
 1236: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1237: must be written to the HTML page once. It will prove the Javascript
 1238: function "change(name, content)". Calling the change function with the
 1239: name of the section 
 1240: you want to update, matching the name passed to C<changable_area>, and
 1241: the new content you want to put in there, will put the content into
 1242: that area.
 1243: 
 1244: B<Note>: Netscape 4 only reserves enough space for the changable area
 1245: to contain room for the original contents. You need to "make space"
 1246: for whatever changes you wish to make, and be B<sure> to check your
 1247: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1248: it's adequate for updating a one-line status display, but little more.
 1249: This script will set the space to 100% width, so you only need to
 1250: worry about height in Netscape 4.
 1251: 
 1252: Modern browsers are much less limiting, and if you can commit to the
 1253: user not using Netscape 4, this feature may be used freely with
 1254: pretty much any HTML.
 1255: 
 1256: =cut
 1257: 
 1258: sub change_content_javascript {
 1259:     # If we're on Netscape 4, we need to use Layer-based code
 1260:     if ($env{'browser.type'} eq 'netscape' &&
 1261: 	$env{'browser.version'} =~ /^4\./) {
 1262: 	return (<<NETSCAPE4);
 1263: 	function change(name, content) {
 1264: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1265: 	    doc.open();
 1266: 	    doc.write(content);
 1267: 	    doc.close();
 1268: 	}
 1269: NETSCAPE4
 1270:     } else {
 1271: 	# Otherwise, we need to use semi-standards-compliant code
 1272: 	# (technically, "innerHTML" isn't standard but the equivalent
 1273: 	# is really scary, and every useful browser supports it
 1274: 	return (<<DOMBASED);
 1275: 	function change(name, content) {
 1276: 	    element = document.getElementById(name);
 1277: 	    element.innerHTML = content;
 1278: 	}
 1279: DOMBASED
 1280:     }
 1281: }
 1282: 
 1283: =pod
 1284: 
 1285: =item * &changable_area($name,$origContent):
 1286: 
 1287: This provides a "changable area" that can be modified on the fly via
 1288: the Javascript code provided in C<change_content_javascript>. $name is
 1289: the name you will use to reference the area later; do not repeat the
 1290: same name on a given HTML page more then once. $origContent is what
 1291: the area will originally contain, which can be left blank.
 1292: 
 1293: =cut
 1294: 
 1295: sub changable_area {
 1296:     my ($name, $origContent) = @_;
 1297: 
 1298:     if ($env{'browser.type'} eq 'netscape' &&
 1299: 	$env{'browser.version'} =~ /^4\./) {
 1300: 	# If this is netscape 4, we need to use the Layer tag
 1301: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1302:     } else {
 1303: 	return "<span id='$name'>$origContent</span>";
 1304:     }
 1305: }
 1306: 
 1307: =pod
 1308: 
 1309: =item * &viewport_geometry_js 
 1310: 
 1311: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1312: 
 1313: =cut
 1314: 
 1315: 
 1316: sub viewport_geometry_js { 
 1317:     return <<"GEOMETRY";
 1318: var Geometry = {};
 1319: function init_geometry() {
 1320:     if (Geometry.init) { return };
 1321:     Geometry.init=1;
 1322:     if (window.innerHeight) {
 1323:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1324:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1325:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1326:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1327:     }
 1328:     else if (document.documentElement && document.documentElement.clientHeight) {
 1329:         Geometry.getViewportHeight =
 1330:             function() { return document.documentElement.clientHeight; };
 1331:         Geometry.getViewportWidth =
 1332:             function() { return document.documentElement.clientWidth; };
 1333: 
 1334:         Geometry.getHorizontalScroll =
 1335:             function() { return document.documentElement.scrollLeft; };
 1336:         Geometry.getVerticalScroll =
 1337:             function() { return document.documentElement.scrollTop; };
 1338:     }
 1339:     else if (document.body.clientHeight) {
 1340:         Geometry.getViewportHeight =
 1341:             function() { return document.body.clientHeight; };
 1342:         Geometry.getViewportWidth =
 1343:             function() { return document.body.clientWidth; };
 1344:         Geometry.getHorizontalScroll =
 1345:             function() { return document.body.scrollLeft; };
 1346:         Geometry.getVerticalScroll =
 1347:             function() { return document.body.scrollTop; };
 1348:     }
 1349: }
 1350: 
 1351: GEOMETRY
 1352: }
 1353: 
 1354: =pod
 1355: 
 1356: =item * &viewport_size_js()
 1357: 
 1358: 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. 
 1359: 
 1360: =cut
 1361: 
 1362: sub viewport_size_js {
 1363:     my $geometry = &viewport_geometry_js();
 1364:     return <<"DIMS";
 1365: 
 1366: $geometry
 1367: 
 1368: function getViewportDims(width,height) {
 1369:     init_geometry();
 1370:     width.value = Geometry.getViewportWidth();
 1371:     height.value = Geometry.getViewportHeight();
 1372:     return;
 1373: }
 1374: 
 1375: DIMS
 1376: }
 1377: 
 1378: =pod
 1379: 
 1380: =item * &resize_textarea_js()
 1381: 
 1382: emits the needed javascript to resize a textarea to be as big as possible
 1383: 
 1384: creates a function resize_textrea that takes two IDs first should be
 1385: the id of the element to resize, second should be the id of a div that
 1386: surrounds everything that comes after the textarea, this routine needs
 1387: to be attached to the <body> for the onload and onresize events.
 1388: 
 1389: =back
 1390: 
 1391: =cut
 1392: 
 1393: sub resize_textarea_js {
 1394:     my $geometry = &viewport_geometry_js();
 1395:     return <<"RESIZE";
 1396:     <script type="text/javascript">
 1397: $geometry
 1398: 
 1399: function getX(element) {
 1400:     var x = 0;
 1401:     while (element) {
 1402: 	x += element.offsetLeft;
 1403: 	element = element.offsetParent;
 1404:     }
 1405:     return x;
 1406: }
 1407: function getY(element) {
 1408:     var y = 0;
 1409:     while (element) {
 1410: 	y += element.offsetTop;
 1411: 	element = element.offsetParent;
 1412:     }
 1413:     return y;
 1414: }
 1415: 
 1416: 
 1417: function resize_textarea(textarea_id,bottom_id) {
 1418:     init_geometry();
 1419:     var textarea        = document.getElementById(textarea_id);
 1420:     //alert(textarea);
 1421: 
 1422:     var textarea_top    = getY(textarea);
 1423:     var textarea_height = textarea.offsetHeight;
 1424:     var bottom          = document.getElementById(bottom_id);
 1425:     var bottom_top      = getY(bottom);
 1426:     var bottom_height   = bottom.offsetHeight;
 1427:     var window_height   = Geometry.getViewportHeight();
 1428:     var fudge           = 23;
 1429:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1430:     if (new_height < 300) {
 1431: 	new_height = 300;
 1432:     }
 1433:     textarea.style.height=new_height+'px';
 1434: }
 1435: </script>
 1436: RESIZE
 1437: 
 1438: }
 1439: 
 1440: =pod
 1441: 
 1442: =head1 Excel and CSV file utility routines
 1443: 
 1444: =over 4
 1445: 
 1446: =cut
 1447: 
 1448: ###############################################################
 1449: ###############################################################
 1450: 
 1451: =pod
 1452: 
 1453: =item * &csv_translate($text) 
 1454: 
 1455: Translate $text to allow it to be output as a 'comma separated values' 
 1456: format.
 1457: 
 1458: =cut
 1459: 
 1460: ###############################################################
 1461: ###############################################################
 1462: sub csv_translate {
 1463:     my $text = shift;
 1464:     $text =~ s/\"/\"\"/g;
 1465:     $text =~ s/\n/ /g;
 1466:     return $text;
 1467: }
 1468: 
 1469: ###############################################################
 1470: ###############################################################
 1471: 
 1472: =pod
 1473: 
 1474: =item * &define_excel_formats()
 1475: 
 1476: Define some commonly used Excel cell formats.
 1477: 
 1478: Currently supported formats:
 1479: 
 1480: =over 4
 1481: 
 1482: =item header
 1483: 
 1484: =item bold
 1485: 
 1486: =item h1
 1487: 
 1488: =item h2
 1489: 
 1490: =item h3
 1491: 
 1492: =item h4
 1493: 
 1494: =item i
 1495: 
 1496: =item date
 1497: 
 1498: =back
 1499: 
 1500: Inputs: $workbook
 1501: 
 1502: Returns: $format, a hash reference.
 1503: 
 1504: =cut
 1505: 
 1506: ###############################################################
 1507: ###############################################################
 1508: sub define_excel_formats {
 1509:     my ($workbook) = @_;
 1510:     my $format;
 1511:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1512:                                                 bottom    => 1,
 1513:                                                 align     => 'center');
 1514:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1515:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1516:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1517:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1518:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1519:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1520:     $format->{'date'} = $workbook->add_format(num_format=>
 1521:                                             'mm/dd/yyyy hh:mm:ss');
 1522:     return $format;
 1523: }
 1524: 
 1525: ###############################################################
 1526: ###############################################################
 1527: 
 1528: =pod
 1529: 
 1530: =item * &create_workbook()
 1531: 
 1532: Create an Excel worksheet.  If it fails, output message on the
 1533: request object and return undefs.
 1534: 
 1535: Inputs: Apache request object
 1536: 
 1537: Returns (undef) on failure, 
 1538:     Excel worksheet object, scalar with filename, and formats 
 1539:     from &Apache::loncommon::define_excel_formats on success
 1540: 
 1541: =cut
 1542: 
 1543: ###############################################################
 1544: ###############################################################
 1545: sub create_workbook {
 1546:     my ($r) = @_;
 1547:         #
 1548:     # Create the excel spreadsheet
 1549:     my $filename = '/prtspool/'.
 1550:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1551:         time.'_'.rand(1000000000).'.xls';
 1552:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1553:     if (! defined($workbook)) {
 1554:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1555:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1556:                             "This error has been logged.  ".
 1557:                             "Please alert your LON-CAPA administrator").
 1558:                   '</p>');
 1559:         return (undef);
 1560:     }
 1561:     #
 1562:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1563:     #
 1564:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1565:     return ($workbook,$filename,$format);
 1566: }
 1567: 
 1568: ###############################################################
 1569: ###############################################################
 1570: 
 1571: =pod
 1572: 
 1573: =item * &create_text_file()
 1574: 
 1575: Create a file to write to and eventually make available to the user.
 1576: If file creation fails, outputs an error message on the request object and 
 1577: return undefs.
 1578: 
 1579: Inputs: Apache request object, and file suffix
 1580: 
 1581: Returns (undef) on failure, 
 1582:     Filehandle and filename on success.
 1583: 
 1584: =cut
 1585: 
 1586: ###############################################################
 1587: ###############################################################
 1588: sub create_text_file {
 1589:     my ($r,$suffix) = @_;
 1590:     if (! defined($suffix)) { $suffix = 'txt'; };
 1591:     my $fh;
 1592:     my $filename = '/prtspool/'.
 1593:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1594:         time.'_'.rand(1000000000).'.'.$suffix;
 1595:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1596:     if (! defined($fh)) {
 1597:         $r->log_error("Couldn't open $filename for output $!");
 1598:         $r->print(&mt('Problems occurred in creating the output file. '
 1599:                      .'This error has been logged. '
 1600:                      .'Please alert your LON-CAPA administrator.'));
 1601:     }
 1602:     return ($fh,$filename)
 1603: }
 1604: 
 1605: 
 1606: =pod 
 1607: 
 1608: =back
 1609: 
 1610: =cut
 1611: 
 1612: ###############################################################
 1613: ##        Home server <option> list generating code          ##
 1614: ###############################################################
 1615: 
 1616: # ------------------------------------------
 1617: 
 1618: sub domain_select {
 1619:     my ($name,$value,$multiple)=@_;
 1620:     my %domains=map { 
 1621: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1622:     } &Apache::lonnet::all_domains();
 1623:     if ($multiple) {
 1624: 	$domains{''}=&mt('Any domain');
 1625: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1626: 	return &multiple_select_form($name,$value,4,\%domains);
 1627:     } else {
 1628: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1629: 	return &select_form($name,$value,%domains);
 1630:     }
 1631: }
 1632: 
 1633: #-------------------------------------------
 1634: 
 1635: =pod
 1636: 
 1637: =head1 Routines for form select boxes
 1638: 
 1639: =over 4
 1640: 
 1641: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1642: 
 1643: Returns a string containing a <select> element int multiple mode
 1644: 
 1645: 
 1646: Args:
 1647:   $name - name of the <select> element
 1648:   $value - scalar or array ref of values that should already be selected
 1649:   $size - number of rows long the select element is
 1650:   $hash - the elements should be 'option' => 'shown text'
 1651:           (shown text should already have been &mt())
 1652:   $order - (optional) array ref of the order to show the elements in
 1653: 
 1654: =cut
 1655: 
 1656: #-------------------------------------------
 1657: sub multiple_select_form {
 1658:     my ($name,$value,$size,$hash,$order)=@_;
 1659:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1660:     my $output='';
 1661:     if (! defined($size)) {
 1662:         $size = 4;
 1663:         if (scalar(keys(%$hash))<4) {
 1664:             $size = scalar(keys(%$hash));
 1665:         }
 1666:     }
 1667:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1668:     my @order;
 1669:     if (ref($order) eq 'ARRAY')  {
 1670:         @order = @{$order};
 1671:     } else {
 1672:         @order = sort(keys(%$hash));
 1673:     }
 1674:     if (exists($$hash{'select_form_order'})) {
 1675:         @order = @{$$hash{'select_form_order'}};
 1676:     }
 1677:         
 1678:     foreach my $key (@order) {
 1679:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1680:         $output.='selected="selected" ' if ($selected{$key});
 1681:         $output.='>'.$hash->{$key}."</option>\n";
 1682:     }
 1683:     $output.="</select>\n";
 1684:     return $output;
 1685: }
 1686: 
 1687: #-------------------------------------------
 1688: 
 1689: =pod
 1690: 
 1691: =item * &select_form($defdom,$name,%hash)
 1692: 
 1693: Returns a string containing a <select name='$name' size='1'> form to 
 1694: allow a user to select options from a hash option_name => displayed text.  
 1695: See lonrights.pm for an example invocation and use.
 1696: 
 1697: =cut
 1698: 
 1699: #-------------------------------------------
 1700: sub select_form {
 1701:     my ($def,$name,%hash) = @_;
 1702:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1703:     my @keys;
 1704:     if (exists($hash{'select_form_order'})) {
 1705: 	@keys=@{$hash{'select_form_order'}};
 1706:     } else {
 1707: 	@keys=sort(keys(%hash));
 1708:     }
 1709:     foreach my $key (@keys) {
 1710:         $selectform.=
 1711: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1712:             ($key eq $def ? 'selected="selected" ' : '').
 1713:                 ">".&mt($hash{$key})."</option>\n";
 1714:     }
 1715:     $selectform.="</select>";
 1716:     return $selectform;
 1717: }
 1718: 
 1719: # For display filters
 1720: 
 1721: sub display_filter {
 1722:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1723:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1724:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1725: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1726: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1727: 	   '</label></span> <span class="LC_nobreak">'.
 1728:            &mt('Filter [_1]',
 1729: 	   &select_form($env{'form.displayfilter'},
 1730: 			'displayfilter',
 1731: 			('currentfolder' => 'Current folder/page',
 1732: 			 'containing' => 'Containing phrase',
 1733: 			 'none' => 'None'))).
 1734: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1735: }
 1736: 
 1737: sub gradeleveldescription {
 1738:     my $gradelevel=shift;
 1739:     my %gradelevels=(0 => 'Not specified',
 1740: 		     1 => 'Grade 1',
 1741: 		     2 => 'Grade 2',
 1742: 		     3 => 'Grade 3',
 1743: 		     4 => 'Grade 4',
 1744: 		     5 => 'Grade 5',
 1745: 		     6 => 'Grade 6',
 1746: 		     7 => 'Grade 7',
 1747: 		     8 => 'Grade 8',
 1748: 		     9 => 'Grade 9',
 1749: 		     10 => 'Grade 10',
 1750: 		     11 => 'Grade 11',
 1751: 		     12 => 'Grade 12',
 1752: 		     13 => 'Grade 13',
 1753: 		     14 => '100 Level',
 1754: 		     15 => '200 Level',
 1755: 		     16 => '300 Level',
 1756: 		     17 => '400 Level',
 1757: 		     18 => 'Graduate Level');
 1758:     return &mt($gradelevels{$gradelevel});
 1759: }
 1760: 
 1761: sub select_level_form {
 1762:     my ($deflevel,$name)=@_;
 1763:     unless ($deflevel) { $deflevel=0; }
 1764:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1765:     for (my $i=0; $i<=18; $i++) {
 1766:         $selectform.="<option value=\"$i\" ".
 1767:             ($i==$deflevel ? 'selected="selected" ' : '').
 1768:                 ">".&gradeleveldescription($i)."</option>\n";
 1769:     }
 1770:     $selectform.="</select>";
 1771:     return $selectform;
 1772: }
 1773: 
 1774: #-------------------------------------------
 1775: 
 1776: =pod
 1777: 
 1778: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1779: 
 1780: Returns a string containing a <select name='$name' size='1'> form to 
 1781: allow a user to select the domain to preform an operation in.  
 1782: See loncreateuser.pm for an example invocation and use.
 1783: 
 1784: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1785: selected");
 1786: 
 1787: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1788: 
 1789: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1790: 
 1791: =cut
 1792: 
 1793: #-------------------------------------------
 1794: sub select_dom_form {
 1795:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1796:     my $onchange;
 1797:     if ($autosubmit) {
 1798:         $onchange = ' onchange="this.form.submit()"';
 1799:     }
 1800:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1801:     if ($includeempty) { @domains=('',@domains); }
 1802:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1803:     foreach my $dom (@domains) {
 1804:         $selectdomain.="<option value=\"$dom\" ".
 1805:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1806:         if ($showdomdesc) {
 1807:             if ($dom ne '') {
 1808:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1809:                 if ($domdesc ne '') {
 1810:                     $selectdomain .= ' ('.$domdesc.')';
 1811:                 }
 1812:             } 
 1813:         }
 1814:         $selectdomain .= "</option>\n";
 1815:     }
 1816:     $selectdomain.="</select>";
 1817:     return $selectdomain;
 1818: }
 1819: 
 1820: #-------------------------------------------
 1821: 
 1822: =pod
 1823: 
 1824: =item * &home_server_form_item($domain,$name,$defaultflag)
 1825: 
 1826: input: 4 arguments (two required, two optional) - 
 1827:     $domain - domain of new user
 1828:     $name - name of form element
 1829:     $default - Value of 'default' causes a default item to be first 
 1830:                             option, and selected by default. 
 1831:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1832:                             if 1 server found, or default, if 0 found.
 1833: output: returns 2 items: 
 1834: (a) form element which contains either:
 1835:    (i) <select name="$name">
 1836:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1837:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1838:        </select>
 1839:        form item if there are multiple library servers in $domain, or
 1840:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1841:        if there is only one library server in $domain.
 1842: 
 1843: (b) number of library servers found.
 1844: 
 1845: See loncreateuser.pm for example of use.
 1846: 
 1847: =cut
 1848: 
 1849: #-------------------------------------------
 1850: sub home_server_form_item {
 1851:     my ($domain,$name,$default,$hide) = @_;
 1852:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1853:     my $result;
 1854:     my $numlib = keys(%servers);
 1855:     if ($numlib > 1) {
 1856:         $result .= '<select name="'.$name.'" />'."\n";
 1857:         if ($default) {
 1858:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1859:                        '</option>'."\n";
 1860:         }
 1861:         foreach my $hostid (sort(keys(%servers))) {
 1862:             $result.= '<option value="'.$hostid.'">'.
 1863: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1864:         }
 1865:         $result .= '</select>'."\n";
 1866:     } elsif ($numlib == 1) {
 1867:         my $hostid;
 1868:         foreach my $item (keys(%servers)) {
 1869:             $hostid = $item;
 1870:         }
 1871:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1872:                    $hostid.'" />';
 1873:                    if (!$hide) {
 1874:                        $result .= $hostid.' '.$servers{$hostid};
 1875:                    }
 1876:                    $result .= "\n";
 1877:     } elsif ($default) {
 1878:         $result .= '<input type="hidden" name="'.$name.
 1879:                    '" value="default" />';
 1880:                    if (!$hide) {
 1881:                        $result .= &mt('default');
 1882:                    }
 1883:                    $result .= "\n";
 1884:     }
 1885:     return ($result,$numlib);
 1886: }
 1887: 
 1888: =pod
 1889: 
 1890: =back 
 1891: 
 1892: =cut
 1893: 
 1894: ###############################################################
 1895: ##                  Decoding User Agent                      ##
 1896: ###############################################################
 1897: 
 1898: =pod
 1899: 
 1900: =head1 Decoding the User Agent
 1901: 
 1902: =over 4
 1903: 
 1904: =item * &decode_user_agent()
 1905: 
 1906: Inputs: $r
 1907: 
 1908: Outputs:
 1909: 
 1910: =over 4
 1911: 
 1912: =item * $httpbrowser
 1913: 
 1914: =item * $clientbrowser
 1915: 
 1916: =item * $clientversion
 1917: 
 1918: =item * $clientmathml
 1919: 
 1920: =item * $clientunicode
 1921: 
 1922: =item * $clientos
 1923: 
 1924: =back
 1925: 
 1926: =back 
 1927: 
 1928: =cut
 1929: 
 1930: ###############################################################
 1931: ###############################################################
 1932: sub decode_user_agent {
 1933:     my ($r)=@_;
 1934:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1935:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1936:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1937:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1938:     my $clientbrowser='unknown';
 1939:     my $clientversion='0';
 1940:     my $clientmathml='';
 1941:     my $clientunicode='0';
 1942:     for (my $i=0;$i<=$#browsertype;$i++) {
 1943:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1944: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1945: 	    $clientbrowser=$bname;
 1946:             $httpbrowser=~/$vreg/i;
 1947: 	    $clientversion=$1;
 1948:             $clientmathml=($clientversion>=$minv);
 1949:             $clientunicode=($clientversion>=$univ);
 1950: 	}
 1951:     }
 1952:     my $clientos='unknown';
 1953:     if (($httpbrowser=~/linux/i) ||
 1954:         ($httpbrowser=~/unix/i) ||
 1955:         ($httpbrowser=~/ux/i) ||
 1956:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1957:     if (($httpbrowser=~/vax/i) ||
 1958:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1959:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1960:     if (($httpbrowser=~/mac/i) ||
 1961:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1962:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1963:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1964:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1965:             $clientunicode,$clientos,);
 1966: }
 1967: 
 1968: ###############################################################
 1969: ##    Authentication changing form generation subroutines    ##
 1970: ###############################################################
 1971: ##
 1972: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1973: ## hash, and have reasonable default values.
 1974: ##
 1975: ##    formname = the name given in the <form> tag.
 1976: #-------------------------------------------
 1977: 
 1978: =pod
 1979: 
 1980: =head1 Authentication Routines
 1981: 
 1982: =over 4
 1983: 
 1984: =item * &authform_xxxxxx()
 1985: 
 1986: The authform_xxxxxx subroutines provide javascript and html forms which 
 1987: handle some of the conveniences required for authentication forms.  
 1988: This is not an optimal method, but it works.  
 1989: 
 1990: =over 4
 1991: 
 1992: =item * authform_header
 1993: 
 1994: =item * authform_authorwarning
 1995: 
 1996: =item * authform_nochange
 1997: 
 1998: =item * authform_kerberos
 1999: 
 2000: =item * authform_internal
 2001: 
 2002: =item * authform_filesystem
 2003: 
 2004: =back
 2005: 
 2006: See loncreateuser.pm for invocation and use examples.
 2007: 
 2008: =cut
 2009: 
 2010: #-------------------------------------------
 2011: sub authform_header{  
 2012:     my %in = (
 2013:         formname => 'cu',
 2014:         kerb_def_dom => '',
 2015:         @_,
 2016:     );
 2017:     $in{'formname'} = 'document.' . $in{'formname'};
 2018:     my $result='';
 2019: 
 2020: #---------------------------------------------- Code for upper case translation
 2021:     my $Javascript_toUpperCase;
 2022:     unless ($in{kerb_def_dom}) {
 2023:         $Javascript_toUpperCase =<<"END";
 2024:         switch (choice) {
 2025:            case 'krb': currentform.elements[choicearg].value =
 2026:                currentform.elements[choicearg].value.toUpperCase();
 2027:                break;
 2028:            default:
 2029:         }
 2030: END
 2031:     } else {
 2032:         $Javascript_toUpperCase = "";
 2033:     }
 2034: 
 2035:     my $radioval = "'nochange'";
 2036:     if (defined($in{'curr_authtype'})) {
 2037:         if ($in{'curr_authtype'} ne '') {
 2038:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2039:         }
 2040:     }
 2041:     my $argfield = 'null';
 2042:     if (defined($in{'mode'})) {
 2043:         if ($in{'mode'} eq 'modifycourse')  {
 2044:             if (defined($in{'curr_autharg'})) {
 2045:                 if ($in{'curr_autharg'} ne '') {
 2046:                     $argfield = "'$in{'curr_autharg'}'";
 2047:                 }
 2048:             }
 2049:         }
 2050:     }
 2051: 
 2052:     $result.=<<"END";
 2053: var current = new Object();
 2054: current.radiovalue = $radioval;
 2055: current.argfield = $argfield;
 2056: 
 2057: function changed_radio(choice,currentform) {
 2058:     var choicearg = choice + 'arg';
 2059:     // If a radio button in changed, we need to change the argfield
 2060:     if (current.radiovalue != choice) {
 2061:         current.radiovalue = choice;
 2062:         if (current.argfield != null) {
 2063:             currentform.elements[current.argfield].value = '';
 2064:         }
 2065:         if (choice == 'nochange') {
 2066:             current.argfield = null;
 2067:         } else {
 2068:             current.argfield = choicearg;
 2069:             switch(choice) {
 2070:                 case 'krb': 
 2071:                     currentform.elements[current.argfield].value = 
 2072:                         "$in{'kerb_def_dom'}";
 2073:                 break;
 2074:               default:
 2075:                 break;
 2076:             }
 2077:         }
 2078:     }
 2079:     return;
 2080: }
 2081: 
 2082: function changed_text(choice,currentform) {
 2083:     var choicearg = choice + 'arg';
 2084:     if (currentform.elements[choicearg].value !='') {
 2085:         $Javascript_toUpperCase
 2086:         // clear old field
 2087:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2088:             currentform.elements[current.argfield].value = '';
 2089:         }
 2090:         current.argfield = choicearg;
 2091:     }
 2092:     set_auth_radio_buttons(choice,currentform);
 2093:     return;
 2094: }
 2095: 
 2096: function set_auth_radio_buttons(newvalue,currentform) {
 2097:     var i=0;
 2098:     while (i < currentform.login.length) {
 2099:         if (currentform.login[i].value == newvalue) { break; }
 2100:         i++;
 2101:     }
 2102:     if (i == currentform.login.length) {
 2103:         return;
 2104:     }
 2105:     current.radiovalue = newvalue;
 2106:     currentform.login[i].checked = true;
 2107:     return;
 2108: }
 2109: END
 2110:     return $result;
 2111: }
 2112: 
 2113: sub authform_authorwarning{
 2114:     my $result='';
 2115:     $result='<i>'.
 2116:         &mt('As a general rule, only authors or co-authors should be '.
 2117:             'filesystem authenticated '.
 2118:             '(which allows access to the server filesystem).')."</i>\n";
 2119:     return $result;
 2120: }
 2121: 
 2122: sub authform_nochange{  
 2123:     my %in = (
 2124:               formname => 'document.cu',
 2125:               kerb_def_dom => 'MSU.EDU',
 2126:               @_,
 2127:           );
 2128:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2129:     my $result;
 2130:     if (keys(%can_assign) == 0) {
 2131:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2132:     } else {
 2133:         $result = '<label>'.&mt('[_1] Do not change login data',
 2134:                   '<input type="radio" name="login" value="nochange" '.
 2135:                   'checked="checked" onclick="'.
 2136:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2137: 	    '</label>';
 2138:     }
 2139:     return $result;
 2140: }
 2141: 
 2142: sub authform_kerberos {
 2143:     my %in = (
 2144:               formname => 'document.cu',
 2145:               kerb_def_dom => 'MSU.EDU',
 2146:               kerb_def_auth => 'krb4',
 2147:               @_,
 2148:               );
 2149:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2150:         $autharg,$jscall);
 2151:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2152:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2153:        $check5 = ' checked="checked"';
 2154:     } else {
 2155:        $check4 = ' checked="checked"';
 2156:     }
 2157:     $krbarg = $in{'kerb_def_dom'};
 2158:     if (defined($in{'curr_authtype'})) {
 2159:         if ($in{'curr_authtype'} eq 'krb') {
 2160:             $krbcheck = ' checked="checked"';
 2161:             if (defined($in{'mode'})) {
 2162:                 if ($in{'mode'} eq 'modifyuser') {
 2163:                     $krbcheck = '';
 2164:                 }
 2165:             }
 2166:             if (defined($in{'curr_kerb_ver'})) {
 2167:                 if ($in{'curr_krb_ver'} eq '5') {
 2168:                     $check5 = ' checked="checked"';
 2169:                     $check4 = '';
 2170:                 } else {
 2171:                     $check4 = ' checked="checked"';
 2172:                     $check5 = '';
 2173:                 }
 2174:             }
 2175:             if (defined($in{'curr_autharg'})) {
 2176:                 $krbarg = $in{'curr_autharg'};
 2177:             }
 2178:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2179:                 if (defined($in{'curr_autharg'})) {
 2180:                     $result = 
 2181:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2182:         $in{'curr_autharg'},$krbver);
 2183:                 } else {
 2184:                     $result =
 2185:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2186:                 }
 2187:                 return $result; 
 2188:             }
 2189:         }
 2190:     } else {
 2191:         if ($authnum == 1) {
 2192:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2193:         }
 2194:     }
 2195:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2196:         return;
 2197:     } elsif ($authtype eq '') {
 2198:         if (defined($in{'mode'})) {
 2199:             if ($in{'mode'} eq 'modifycourse') {
 2200:                 if ($authnum == 1) {
 2201:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2202:                 }
 2203:             }
 2204:         }
 2205:     }
 2206:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2207:     if ($authtype eq '') {
 2208:         $authtype = '<input type="radio" name="login" value="krb" '.
 2209:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2210:                     $krbcheck.' />';
 2211:     }
 2212:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2213:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2214:          $in{'curr_authtype'} eq 'krb5') ||
 2215:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2216:          $in{'curr_authtype'} eq 'krb4')) {
 2217:         $result .= &mt
 2218:         ('[_1] Kerberos authenticated with domain [_2] '.
 2219:          '[_3] Version 4 [_4] Version 5 [_5]',
 2220:          '<label>'.$authtype,
 2221:          '</label><input type="text" size="10" name="krbarg" '.
 2222:              'value="'.$krbarg.'" '.
 2223:              'onchange="'.$jscall.'" />',
 2224:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2225:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2226: 	 '</label>');
 2227:     } elsif ($can_assign{'krb4'}) {
 2228:         $result .= &mt
 2229:         ('[_1] Kerberos authenticated with domain [_2] '.
 2230:          '[_3] Version 4 [_4]',
 2231:          '<label>'.$authtype,
 2232:          '</label><input type="text" size="10" name="krbarg" '.
 2233:              'value="'.$krbarg.'" '.
 2234:              'onchange="'.$jscall.'" />',
 2235:          '<label><input type="hidden" name="krbver" value="4" />',
 2236:          '</label>');
 2237:     } elsif ($can_assign{'krb5'}) {
 2238:         $result .= &mt
 2239:         ('[_1] Kerberos authenticated with domain [_2] '.
 2240:          '[_3] Version 5 [_4]',
 2241:          '<label>'.$authtype,
 2242:          '</label><input type="text" size="10" name="krbarg" '.
 2243:              'value="'.$krbarg.'" '.
 2244:              'onchange="'.$jscall.'" />',
 2245:          '<label><input type="hidden" name="krbver" value="5" />',
 2246:          '</label>');
 2247:     }
 2248:     return $result;
 2249: }
 2250: 
 2251: sub authform_internal{  
 2252:     my %in = (
 2253:                 formname => 'document.cu',
 2254:                 kerb_def_dom => 'MSU.EDU',
 2255:                 @_,
 2256:                 );
 2257:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2258:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2259:     if (defined($in{'curr_authtype'})) {
 2260:         if ($in{'curr_authtype'} eq 'int') {
 2261:             if ($can_assign{'int'}) {
 2262:                 $intcheck = 'checked="checked" ';
 2263:                 if (defined($in{'mode'})) {
 2264:                     if ($in{'mode'} eq 'modifyuser') {
 2265:                         $intcheck = '';
 2266:                     }
 2267:                 }
 2268:                 if (defined($in{'curr_autharg'})) {
 2269:                     $intarg = $in{'curr_autharg'};
 2270:                 }
 2271:             } else {
 2272:                 $result = &mt('Currently internally authenticated.');
 2273:                 return $result;
 2274:             }
 2275:         }
 2276:     } else {
 2277:         if ($authnum == 1) {
 2278:             $authtype = '<input type="hidden" name="login" value="int" />';
 2279:         }
 2280:     }
 2281:     if (!$can_assign{'int'}) {
 2282:         return;
 2283:     } elsif ($authtype eq '') {
 2284:         if (defined($in{'mode'})) {
 2285:             if ($in{'mode'} eq 'modifycourse') {
 2286:                 if ($authnum == 1) {
 2287:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2288:                 }
 2289:             }
 2290:         }
 2291:     }
 2292:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2293:     if ($authtype eq '') {
 2294:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2295:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2296:     }
 2297:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2298:                $intarg.'" onchange="'.$jscall.'" />';
 2299:     $result = &mt
 2300:         ('[_1] Internally authenticated (with initial password [_2])',
 2301:          '<label>'.$authtype,'</label>'.$autharg);
 2302:     $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>';
 2303:     return $result;
 2304: }
 2305: 
 2306: sub authform_local{  
 2307:     my %in = (
 2308:               formname => 'document.cu',
 2309:               kerb_def_dom => 'MSU.EDU',
 2310:               @_,
 2311:               );
 2312:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2313:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2314:     if (defined($in{'curr_authtype'})) {
 2315:         if ($in{'curr_authtype'} eq 'loc') {
 2316:             if ($can_assign{'loc'}) {
 2317:                 $loccheck = 'checked="checked" ';
 2318:                 if (defined($in{'mode'})) {
 2319:                     if ($in{'mode'} eq 'modifyuser') {
 2320:                         $loccheck = '';
 2321:                     }
 2322:                 }
 2323:                 if (defined($in{'curr_autharg'})) {
 2324:                     $locarg = $in{'curr_autharg'};
 2325:                 }
 2326:             } else {
 2327:                 $result = &mt('Currently using local (institutional) authentication.');
 2328:                 return $result;
 2329:             }
 2330:         }
 2331:     } else {
 2332:         if ($authnum == 1) {
 2333:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2334:         }
 2335:     }
 2336:     if (!$can_assign{'loc'}) {
 2337:         return;
 2338:     } elsif ($authtype eq '') {
 2339:         if (defined($in{'mode'})) {
 2340:             if ($in{'mode'} eq 'modifycourse') {
 2341:                 if ($authnum == 1) {
 2342:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2343:                 }
 2344:             }
 2345:         }
 2346:     }
 2347:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2348:     if ($authtype eq '') {
 2349:         $authtype = '<input type="radio" name="login" value="loc" '.
 2350:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2351:                     $jscall.'" />';
 2352:     }
 2353:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2354:                $locarg.'" onchange="'.$jscall.'" />';
 2355:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2356:                   '<label>'.$authtype,'</label>'.$autharg);
 2357:     return $result;
 2358: }
 2359: 
 2360: sub authform_filesystem{  
 2361:     my %in = (
 2362:               formname => 'document.cu',
 2363:               kerb_def_dom => 'MSU.EDU',
 2364:               @_,
 2365:               );
 2366:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2367:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2368:     if (defined($in{'curr_authtype'})) {
 2369:         if ($in{'curr_authtype'} eq 'fsys') {
 2370:             if ($can_assign{'fsys'}) {
 2371:                 $fsyscheck = 'checked="checked" ';
 2372:                 if (defined($in{'mode'})) {
 2373:                     if ($in{'mode'} eq 'modifyuser') {
 2374:                         $fsyscheck = '';
 2375:                     }
 2376:                 }
 2377:             } else {
 2378:                 $result = &mt('Currently Filesystem Authenticated.');
 2379:                 return $result;
 2380:             }           
 2381:         }
 2382:     } else {
 2383:         if ($authnum == 1) {
 2384:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2385:         }
 2386:     }
 2387:     if (!$can_assign{'fsys'}) {
 2388:         return;
 2389:     } elsif ($authtype eq '') {
 2390:         if (defined($in{'mode'})) {
 2391:             if ($in{'mode'} eq 'modifycourse') {
 2392:                 if ($authnum == 1) {
 2393:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2394:                 }
 2395:             }
 2396:         }
 2397:     }
 2398:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2399:     if ($authtype eq '') {
 2400:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2401:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2402:                     $jscall.'" />';
 2403:     }
 2404:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2405:                ' onchange="'.$jscall.'" />';
 2406:     $result = &mt
 2407:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2408:          '<label><input type="radio" name="login" value="fsys" '.
 2409:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2410:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2411:                   'onchange="'.$jscall.'" />');
 2412:     return $result;
 2413: }
 2414: 
 2415: sub get_assignable_auth {
 2416:     my ($dom) = @_;
 2417:     if ($dom eq '') {
 2418:         $dom = $env{'request.role.domain'};
 2419:     }
 2420:     my %can_assign = (
 2421:                           krb4 => 1,
 2422:                           krb5 => 1,
 2423:                           int  => 1,
 2424:                           loc  => 1,
 2425:                      );
 2426:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2427:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2428:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2429:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2430:             my $context;
 2431:             if ($env{'request.role'} =~ /^au/) {
 2432:                 $context = 'author';
 2433:             } elsif ($env{'request.role'} =~ /^dc/) {
 2434:                 $context = 'domain';
 2435:             } elsif ($env{'request.course.id'}) {
 2436:                 $context = 'course';
 2437:             }
 2438:             if ($context) {
 2439:                 if (ref($authhash->{$context}) eq 'HASH') {
 2440:                    %can_assign = %{$authhash->{$context}}; 
 2441:                 }
 2442:             }
 2443:         }
 2444:     }
 2445:     my $authnum = 0;
 2446:     foreach my $key (keys(%can_assign)) {
 2447:         if ($can_assign{$key}) {
 2448:             $authnum ++;
 2449:         }
 2450:     }
 2451:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2452:         $authnum --;
 2453:     }
 2454:     return ($authnum,%can_assign);
 2455: }
 2456: 
 2457: ###############################################################
 2458: ##    Get Kerberos Defaults for Domain                 ##
 2459: ###############################################################
 2460: ##
 2461: ## Returns default kerberos version and an associated argument
 2462: ## as listed in file domain.tab. If not listed, provides
 2463: ## appropriate default domain and kerberos version.
 2464: ##
 2465: #-------------------------------------------
 2466: 
 2467: =pod
 2468: 
 2469: =item * &get_kerberos_defaults()
 2470: 
 2471: get_kerberos_defaults($target_domain) returns the default kerberos
 2472: version and domain. If not found, it defaults to version 4 and the 
 2473: domain of the server.
 2474: 
 2475: =over 4
 2476: 
 2477: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2478: 
 2479: =back
 2480: 
 2481: =back
 2482: 
 2483: =cut
 2484: 
 2485: #-------------------------------------------
 2486: sub get_kerberos_defaults {
 2487:     my $domain=shift;
 2488:     my ($krbdef,$krbdefdom);
 2489:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2490:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2491:         $krbdef = $domdefaults{'auth_def'};
 2492:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2493:     } else {
 2494:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2495:         my $krbdefdom=$1;
 2496:         $krbdefdom=~tr/a-z/A-Z/;
 2497:         $krbdef = "krb4";
 2498:     }
 2499:     return ($krbdef,$krbdefdom);
 2500: }
 2501: 
 2502: 
 2503: ###############################################################
 2504: ##                Thesaurus Functions                        ##
 2505: ###############################################################
 2506: 
 2507: =pod
 2508: 
 2509: =head1 Thesaurus Functions
 2510: 
 2511: =over 4
 2512: 
 2513: =item * &initialize_keywords()
 2514: 
 2515: Initializes the package variable %Keywords if it is empty.  Uses the
 2516: package variable $thesaurus_db_file.
 2517: 
 2518: =cut
 2519: 
 2520: ###################################################
 2521: 
 2522: sub initialize_keywords {
 2523:     return 1 if (scalar keys(%Keywords));
 2524:     # If we are here, %Keywords is empty, so fill it up
 2525:     #   Make sure the file we need exists...
 2526:     if (! -e $thesaurus_db_file) {
 2527:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2528:                                  " failed because it does not exist");
 2529:         return 0;
 2530:     }
 2531:     #   Set up the hash as a database
 2532:     my %thesaurus_db;
 2533:     if (! tie(%thesaurus_db,'GDBM_File',
 2534:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2535:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2536:                                  $thesaurus_db_file);
 2537:         return 0;
 2538:     } 
 2539:     #  Get the average number of appearances of a word.
 2540:     my $avecount = $thesaurus_db{'average.count'};
 2541:     #  Put keywords (those that appear > average) into %Keywords
 2542:     while (my ($word,$data)=each (%thesaurus_db)) {
 2543:         my ($count,undef) = split /:/,$data;
 2544:         $Keywords{$word}++ if ($count > $avecount);
 2545:     }
 2546:     untie %thesaurus_db;
 2547:     # Remove special values from %Keywords.
 2548:     foreach my $value ('total.count','average.count') {
 2549:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2550:   }
 2551:     return 1;
 2552: }
 2553: 
 2554: ###################################################
 2555: 
 2556: =pod
 2557: 
 2558: =item * &keyword($word)
 2559: 
 2560: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2561: than the average number of times in the thesaurus database.  Calls 
 2562: &initialize_keywords
 2563: 
 2564: =cut
 2565: 
 2566: ###################################################
 2567: 
 2568: sub keyword {
 2569:     return if (!&initialize_keywords());
 2570:     my $word=lc(shift());
 2571:     $word=~s/\W//g;
 2572:     return exists($Keywords{$word});
 2573: }
 2574: 
 2575: ###############################################################
 2576: 
 2577: =pod 
 2578: 
 2579: =item * &get_related_words()
 2580: 
 2581: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2582: an array of words.  If the keyword is not in the thesaurus, an empty array
 2583: will be returned.  The order of the words returned is determined by the
 2584: database which holds them.
 2585: 
 2586: Uses global $thesaurus_db_file.
 2587: 
 2588: =cut
 2589: 
 2590: ###############################################################
 2591: sub get_related_words {
 2592:     my $keyword = shift;
 2593:     my %thesaurus_db;
 2594:     if (! -e $thesaurus_db_file) {
 2595:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2596:                                  "failed because the file does not exist");
 2597:         return ();
 2598:     }
 2599:     if (! tie(%thesaurus_db,'GDBM_File',
 2600:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2601:         return ();
 2602:     } 
 2603:     my @Words=();
 2604:     my $count=0;
 2605:     if (exists($thesaurus_db{$keyword})) {
 2606: 	# The first element is the number of times
 2607: 	# the word appears.  We do not need it now.
 2608: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2609: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2610: 	my $threshold=$mostfrequentcount/10;
 2611:         foreach my $possibleword (@RelatedWords) {
 2612:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2613:             if ($wordcount>$threshold) {
 2614: 		push(@Words,$word);
 2615:                 $count++;
 2616:                 if ($count>10) { last; }
 2617: 	    }
 2618:         }
 2619:     }
 2620:     untie %thesaurus_db;
 2621:     return @Words;
 2622: }
 2623: 
 2624: =pod
 2625: 
 2626: =back
 2627: 
 2628: =cut
 2629: 
 2630: # -------------------------------------------------------------- Plaintext name
 2631: =pod
 2632: 
 2633: =head1 User Name Functions
 2634: 
 2635: =over 4
 2636: 
 2637: =item * &plainname($uname,$udom,$first)
 2638: 
 2639: Takes a users logon name and returns it as a string in
 2640: "first middle last generation" form 
 2641: if $first is set to 'lastname' then it returns it as
 2642: 'lastname generation, firstname middlename' if their is a lastname
 2643: 
 2644: =cut
 2645: 
 2646: 
 2647: ###############################################################
 2648: sub plainname {
 2649:     my ($uname,$udom,$first)=@_;
 2650:     return if (!defined($uname) || !defined($udom));
 2651:     my %names=&getnames($uname,$udom);
 2652:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2653: 					  $names{'middlename'},
 2654: 					  $names{'lastname'},
 2655: 					  $names{'generation'},$first);
 2656:     $name=~s/^\s+//;
 2657:     $name=~s/\s+$//;
 2658:     $name=~s/\s+/ /g;
 2659:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2660:     return $name;
 2661: }
 2662: 
 2663: # -------------------------------------------------------------------- Nickname
 2664: =pod
 2665: 
 2666: =item * &nickname($uname,$udom)
 2667: 
 2668: Gets a users name and returns it as a string as
 2669: 
 2670: "&quot;nickname&quot;"
 2671: 
 2672: if the user has a nickname or
 2673: 
 2674: "first middle last generation"
 2675: 
 2676: if the user does not
 2677: 
 2678: =cut
 2679: 
 2680: sub nickname {
 2681:     my ($uname,$udom)=@_;
 2682:     return if (!defined($uname) || !defined($udom));
 2683:     my %names=&getnames($uname,$udom);
 2684:     my $name=$names{'nickname'};
 2685:     if ($name) {
 2686:        $name='&quot;'.$name.'&quot;'; 
 2687:     } else {
 2688:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2689: 	     $names{'lastname'}.' '.$names{'generation'};
 2690:        $name=~s/\s+$//;
 2691:        $name=~s/\s+/ /g;
 2692:     }
 2693:     return $name;
 2694: }
 2695: 
 2696: sub getnames {
 2697:     my ($uname,$udom)=@_;
 2698:     return if (!defined($uname) || !defined($udom));
 2699:     if ($udom eq 'public' && $uname eq 'public') {
 2700: 	return ('lastname' => &mt('Public'));
 2701:     }
 2702:     my $id=$uname.':'.$udom;
 2703:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2704:     if ($cached) {
 2705: 	return %{$names};
 2706:     } else {
 2707: 	my %loadnames=&Apache::lonnet::get('environment',
 2708:                     ['firstname','middlename','lastname','generation','nickname'],
 2709: 					 $udom,$uname);
 2710: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2711: 	return %loadnames;
 2712:     }
 2713: }
 2714: 
 2715: # -------------------------------------------------------------------- getemails
 2716: 
 2717: =pod
 2718: 
 2719: =item * &getemails($uname,$udom)
 2720: 
 2721: Gets a user's email information and returns it as a hash with keys:
 2722: notification, critnotification, permanentemail
 2723: 
 2724: For notification and critnotification, values are comma-separated lists 
 2725: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2726:  
 2727: 
 2728: =cut
 2729: 
 2730: 
 2731: sub getemails {
 2732:     my ($uname,$udom)=@_;
 2733:     if ($udom eq 'public' && $uname eq 'public') {
 2734: 	return;
 2735:     }
 2736:     if (!$udom) { $udom=$env{'user.domain'}; }
 2737:     if (!$uname) { $uname=$env{'user.name'}; }
 2738:     my $id=$uname.':'.$udom;
 2739:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2740:     if ($cached) {
 2741: 	return %{$names};
 2742:     } else {
 2743: 	my %loadnames=&Apache::lonnet::get('environment',
 2744:                     			   ['notification','critnotification',
 2745: 					    'permanentemail'],
 2746: 					   $udom,$uname);
 2747: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2748: 	return %loadnames;
 2749:     }
 2750: }
 2751: 
 2752: sub flush_email_cache {
 2753:     my ($uname,$udom)=@_;
 2754:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2755:     if (!$uname) { $uname=$env{'user.name'};   }
 2756:     return if ($udom eq 'public' && $uname eq 'public');
 2757:     my $id=$uname.':'.$udom;
 2758:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2759: }
 2760: 
 2761: # -------------------------------------------------------------------- getlangs
 2762: 
 2763: =pod
 2764: 
 2765: =item * &getlangs($uname,$udom)
 2766: 
 2767: Gets a user's language preference and returns it as a hash with key:
 2768: language.
 2769: 
 2770: =cut
 2771: 
 2772: 
 2773: sub getlangs {
 2774:     my ($uname,$udom) = @_;
 2775:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2776:     if (!$uname) { $uname=$env{'user.name'};   }
 2777:     my $id=$uname.':'.$udom;
 2778:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2779:     if ($cached) {
 2780:         return %{$langs};
 2781:     } else {
 2782:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2783:                                            $udom,$uname);
 2784:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2785:         return %loadlangs;
 2786:     }
 2787: }
 2788: 
 2789: sub flush_langs_cache {
 2790:     my ($uname,$udom)=@_;
 2791:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2792:     if (!$uname) { $uname=$env{'user.name'};   }
 2793:     return if ($udom eq 'public' && $uname eq 'public');
 2794:     my $id=$uname.':'.$udom;
 2795:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2796: }
 2797: 
 2798: # ------------------------------------------------------------------ Screenname
 2799: 
 2800: =pod
 2801: 
 2802: =item * &screenname($uname,$udom)
 2803: 
 2804: Gets a users screenname and returns it as a string
 2805: 
 2806: =cut
 2807: 
 2808: sub screenname {
 2809:     my ($uname,$udom)=@_;
 2810:     if ($uname eq $env{'user.name'} &&
 2811: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2812:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2813:     return $names{'screenname'};
 2814: }
 2815: 
 2816: 
 2817: # ------------------------------------------------------------- Confirm Wrapper
 2818: =pod
 2819: 
 2820: =item confirmwrapper
 2821: 
 2822: Wrap messages about completion of operation in box
 2823: 
 2824: =cut
 2825: 
 2826: sub confirmwrapper {
 2827:     my ($message)=@_;
 2828:     if ($message) {
 2829:         return "\n".'<div class="LC_confirm_box">'."\n"
 2830:                .$message."\n"
 2831:                .'</div>'."\n";
 2832:     } else {
 2833:         return $message;
 2834:     }
 2835: }
 2836: 
 2837: # ------------------------------------------------------------- Message Wrapper
 2838: 
 2839: sub messagewrapper {
 2840:     my ($link,$username,$domain,$subject,$text)=@_;
 2841:     return 
 2842:         '<a href="/adm/email?compose=individual&amp;'.
 2843:         'recname='.$username.'&amp;recdom='.$domain.
 2844: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2845:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2846: }
 2847: 
 2848: # --------------------------------------------------------------- Notes Wrapper
 2849: 
 2850: sub noteswrapper {
 2851:     my ($link,$un,$do)=@_;
 2852:     return 
 2853: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2854: }
 2855: 
 2856: # ------------------------------------------------------------- Aboutme Wrapper
 2857: 
 2858: sub aboutmewrapper {
 2859:     my ($link,$username,$domain,$target)=@_;
 2860:     if (!defined($username)  && !defined($domain)) {
 2861:         return;
 2862:     }
 2863:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2864: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2865: }
 2866: 
 2867: # ------------------------------------------------------------ Syllabus Wrapper
 2868: 
 2869: sub syllabuswrapper {
 2870:     my ($linktext,$coursedir,$domain)=@_;
 2871:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2872: }
 2873: 
 2874: # -----------------------------------------------------------------------------
 2875: 
 2876: sub track_student_link {
 2877:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2878:     my $link ="/adm/trackstudent?";
 2879:     my $title = 'View recent activity';
 2880:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2881:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2882:         $link .= "selected_student=$sname:$sdom";
 2883:         $title .= ' of this student';
 2884:     } 
 2885:     if (defined($target) && $target !~ /^\s*$/) {
 2886:         $target = qq{target="$target"};
 2887:     } else {
 2888:         $target = '';
 2889:     }
 2890:     if ($start) { $link.='&amp;start='.$start; }
 2891:     $title = &mt($title);
 2892:     $linktext = &mt($linktext);
 2893:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2894: 	&help_open_topic('View_recent_activity');
 2895: }
 2896: 
 2897: sub slot_reservations_link {
 2898:     my ($linktext,$sname,$sdom,$target) = @_;
 2899:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2900:     my $title = 'View slot reservation history';
 2901:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2902:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2903:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2904:         $title .= ' of this student';
 2905:     }
 2906:     if (defined($target) && $target !~ /^\s*$/) {
 2907:         $target = qq{target="$target"};
 2908:     } else {
 2909:         $target = '';
 2910:     }
 2911:     $title = &mt($title);
 2912:     $linktext = &mt($linktext);
 2913:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2914: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2915: 
 2916: }
 2917: 
 2918: # ===================================================== Display a student photo
 2919: 
 2920: 
 2921: sub student_image_tag {
 2922:     my ($domain,$user)=@_;
 2923:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2924:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2925: 	return '<img src="'.$imgsrc.'" align="right" />';
 2926:     } else {
 2927: 	return '';
 2928:     }
 2929: }
 2930: 
 2931: =pod
 2932: 
 2933: =back
 2934: 
 2935: =head1 Access .tab File Data
 2936: 
 2937: =over 4
 2938: 
 2939: =item * &languageids() 
 2940: 
 2941: returns list of all language ids
 2942: 
 2943: =cut
 2944: 
 2945: sub languageids {
 2946:     return sort(keys(%language));
 2947: }
 2948: 
 2949: =pod
 2950: 
 2951: =item * &languagedescription() 
 2952: 
 2953: returns description of a specified language id
 2954: 
 2955: =cut
 2956: 
 2957: sub languagedescription {
 2958:     my $code=shift;
 2959:     return  ($supported_language{$code}?'* ':'').
 2960:             $language{$code}.
 2961: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2962: }
 2963: 
 2964: sub plainlanguagedescription {
 2965:     my $code=shift;
 2966:     return $language{$code};
 2967: }
 2968: 
 2969: sub supportedlanguagecode {
 2970:     my $code=shift;
 2971:     return $supported_language{$code};
 2972: }
 2973: 
 2974: =pod
 2975: 
 2976: =item * &copyrightids() 
 2977: 
 2978: returns list of all copyrights
 2979: 
 2980: =cut
 2981: 
 2982: sub copyrightids {
 2983:     return sort(keys(%cprtag));
 2984: }
 2985: 
 2986: =pod
 2987: 
 2988: =item * &copyrightdescription() 
 2989: 
 2990: returns description of a specified copyright id
 2991: 
 2992: =cut
 2993: 
 2994: sub copyrightdescription {
 2995:     return &mt($cprtag{shift(@_)});
 2996: }
 2997: 
 2998: =pod
 2999: 
 3000: =item * &source_copyrightids() 
 3001: 
 3002: returns list of all source copyrights
 3003: 
 3004: =cut
 3005: 
 3006: sub source_copyrightids {
 3007:     return sort(keys(%scprtag));
 3008: }
 3009: 
 3010: =pod
 3011: 
 3012: =item * &source_copyrightdescription() 
 3013: 
 3014: returns description of a specified source copyright id
 3015: 
 3016: =cut
 3017: 
 3018: sub source_copyrightdescription {
 3019:     return &mt($scprtag{shift(@_)});
 3020: }
 3021: 
 3022: =pod
 3023: 
 3024: =item * &filecategories() 
 3025: 
 3026: returns list of all file categories
 3027: 
 3028: =cut
 3029: 
 3030: sub filecategories {
 3031:     return sort(keys(%category_extensions));
 3032: }
 3033: 
 3034: =pod
 3035: 
 3036: =item * &filecategorytypes() 
 3037: 
 3038: returns list of file types belonging to a given file
 3039: category
 3040: 
 3041: =cut
 3042: 
 3043: sub filecategorytypes {
 3044:     my ($cat) = @_;
 3045:     return @{$category_extensions{lc($cat)}};
 3046: }
 3047: 
 3048: =pod
 3049: 
 3050: =item * &fileembstyle() 
 3051: 
 3052: returns embedding style for a specified file type
 3053: 
 3054: =cut
 3055: 
 3056: sub fileembstyle {
 3057:     return $fe{lc(shift(@_))};
 3058: }
 3059: 
 3060: sub filemimetype {
 3061:     return $fm{lc(shift(@_))};
 3062: }
 3063: 
 3064: 
 3065: sub filecategoryselect {
 3066:     my ($name,$value)=@_;
 3067:     return &select_form($value,$name,
 3068: 			'' => &mt('Any category'),
 3069: 			map { $_,$_ } sort(keys(%category_extensions)));
 3070: }
 3071: 
 3072: =pod
 3073: 
 3074: =item * &filedescription() 
 3075: 
 3076: returns description for a specified file type
 3077: 
 3078: =cut
 3079: 
 3080: sub filedescription {
 3081:     my $file_description = $fd{lc(shift())};
 3082:     $file_description =~ s:([\[\]]):~$1:g;
 3083:     return &mt($file_description);
 3084: }
 3085: 
 3086: =pod
 3087: 
 3088: =item * &filedescriptionex() 
 3089: 
 3090: returns description for a specified file type with
 3091: extra formatting
 3092: 
 3093: =cut
 3094: 
 3095: sub filedescriptionex {
 3096:     my $ex=shift;
 3097:     my $file_description = $fd{lc($ex)};
 3098:     $file_description =~ s:([\[\]]):~$1:g;
 3099:     return '.'.$ex.' '.&mt($file_description);
 3100: }
 3101: 
 3102: # End of .tab access
 3103: =pod
 3104: 
 3105: =back
 3106: 
 3107: =cut
 3108: 
 3109: # ------------------------------------------------------------------ File Types
 3110: sub fileextensions {
 3111:     return sort(keys(%fe));
 3112: }
 3113: 
 3114: # ----------------------------------------------------------- Display Languages
 3115: # returns a hash with all desired display languages
 3116: #
 3117: 
 3118: sub display_languages {
 3119:     my %languages=();
 3120:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3121: 	$languages{$lang}=1;
 3122:     }
 3123:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3124:     if ($env{'form.displaylanguage'}) {
 3125: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3126: 	    $languages{$lang}=1;
 3127:         }
 3128:     }
 3129:     return %languages;
 3130: }
 3131: 
 3132: sub languages {
 3133:     my ($possible_langs) = @_;
 3134:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3135:     if (!ref($possible_langs)) {
 3136: 	if( wantarray ) {
 3137: 	    return @preferred_langs;
 3138: 	} else {
 3139: 	    return $preferred_langs[0];
 3140: 	}
 3141:     }
 3142:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3143:     my @preferred_possibilities;
 3144:     foreach my $preferred_lang (@preferred_langs) {
 3145: 	if (exists($possibilities{$preferred_lang})) {
 3146: 	    push(@preferred_possibilities, $preferred_lang);
 3147: 	}
 3148:     }
 3149:     if( wantarray ) {
 3150: 	return @preferred_possibilities;
 3151:     }
 3152:     return $preferred_possibilities[0];
 3153: }
 3154: 
 3155: sub user_lang {
 3156:     my ($touname,$toudom,$fromcid) = @_;
 3157:     my @userlangs;
 3158:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3159:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3160:                     $env{'course.'.$fromcid.'.languages'}));
 3161:     } else {
 3162:         my %langhash = &getlangs($touname,$toudom);
 3163:         if ($langhash{'languages'} ne '') {
 3164:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3165:         } else {
 3166:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3167:             if ($domdefs{'lang_def'} ne '') {
 3168:                 @userlangs = ($domdefs{'lang_def'});
 3169:             }
 3170:         }
 3171:     }
 3172:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3173:     my $user_lh = Apache::localize->get_handle(@languages);
 3174:     return $user_lh;
 3175: }
 3176: 
 3177: 
 3178: ###############################################################
 3179: ##               Student Answer Attempts                     ##
 3180: ###############################################################
 3181: 
 3182: =pod
 3183: 
 3184: =head1 Alternate Problem Views
 3185: 
 3186: =over 4
 3187: 
 3188: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3189:     $getattempt, $regexp, $gradesub)
 3190: 
 3191: Return string with previous attempt on problem. Arguments:
 3192: 
 3193: =over 4
 3194: 
 3195: =item * $symb: Problem, including path
 3196: 
 3197: =item * $username: username of the desired student
 3198: 
 3199: =item * $domain: domain of the desired student
 3200: 
 3201: =item * $course: Course ID
 3202: 
 3203: =item * $getattempt: Leave blank for all attempts, otherwise put
 3204:     something
 3205: 
 3206: =item * $regexp: if string matches this regexp, the string will be
 3207:     sent to $gradesub
 3208: 
 3209: =item * $gradesub: routine that processes the string if it matches $regexp
 3210: 
 3211: =back
 3212: 
 3213: The output string is a table containing all desired attempts, if any.
 3214: 
 3215: =cut
 3216: 
 3217: sub get_previous_attempt {
 3218:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3219:   my $prevattempts='';
 3220:   no strict 'refs';
 3221:   if ($symb) {
 3222:     my (%returnhash)=
 3223:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3224:     if ($returnhash{'version'}) {
 3225:       my %lasthash=();
 3226:       my $version;
 3227:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3228:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3229: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3230:         }
 3231:       }
 3232:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3233:       $prevattempts.='<th>'.&mt('History').'</th>';
 3234:       foreach my $key (sort(keys(%lasthash))) {
 3235: 	my ($ign,@parts) = split(/\./,$key);
 3236: 	if ($#parts > 0) {
 3237: 	  my $data=$parts[-1];
 3238: 	  pop(@parts);
 3239: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3240: 	} else {
 3241: 	  if ($#parts == 0) {
 3242: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3243: 	  } else {
 3244: 	    $prevattempts.='<th>'.$ign.'</th>';
 3245: 	  }
 3246: 	}
 3247:       }
 3248:       $prevattempts.=&end_data_table_header_row();
 3249:       if ($getattempt eq '') {
 3250: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3251: 	  $prevattempts.=&start_data_table_row().
 3252: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3253: 	    foreach my $key (sort(keys(%lasthash))) {
 3254: 		my $value = &format_previous_attempt_value($key,
 3255: 							   $returnhash{$version.':'.$key});
 3256: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3257: 	    }
 3258: 	  $prevattempts.=&end_data_table_row();
 3259: 	 }
 3260:       }
 3261:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3262:       foreach my $key (sort(keys(%lasthash))) {
 3263: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3264: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3265: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3266:       }
 3267:       $prevattempts.= &end_data_table_row().&end_data_table();
 3268:     } else {
 3269:       $prevattempts=
 3270: 	  &start_data_table().&start_data_table_row().
 3271: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3272: 	  &end_data_table_row().&end_data_table();
 3273:     }
 3274:   } else {
 3275:     $prevattempts=
 3276: 	  &start_data_table().&start_data_table_row().
 3277: 	  '<td>'.&mt('No data.').'</td>'.
 3278: 	  &end_data_table_row().&end_data_table();
 3279:   }
 3280: }
 3281: 
 3282: sub format_previous_attempt_value {
 3283:     my ($key,$value) = @_;
 3284:     if ($key =~ /timestamp/) {
 3285: 	$value = &Apache::lonlocal::locallocaltime($value);
 3286:     } elsif (ref($value) eq 'ARRAY') {
 3287: 	$value = '('.join(', ', @{ $value }).')';
 3288:     } else {
 3289: 	$value = &unescape($value);
 3290:     }
 3291:     return $value;
 3292: }
 3293: 
 3294: 
 3295: sub relative_to_absolute {
 3296:     my ($url,$output)=@_;
 3297:     my $parser=HTML::TokeParser->new(\$output);
 3298:     my $token;
 3299:     my $thisdir=$url;
 3300:     my @rlinks=();
 3301:     while ($token=$parser->get_token) {
 3302: 	if ($token->[0] eq 'S') {
 3303: 	    if ($token->[1] eq 'a') {
 3304: 		if ($token->[2]->{'href'}) {
 3305: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3306: 		}
 3307: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3308: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3309: 	    } elsif ($token->[1] eq 'base') {
 3310: 		$thisdir=$token->[2]->{'href'};
 3311: 	    }
 3312: 	}
 3313:     }
 3314:     $thisdir=~s-/[^/]*$--;
 3315:     foreach my $link (@rlinks) {
 3316: 	unless (($link=~/^https?\:\/\//i) ||
 3317: 		($link=~/^\//) ||
 3318: 		($link=~/^javascript:/i) ||
 3319: 		($link=~/^mailto:/i) ||
 3320: 		($link=~/^\#/)) {
 3321: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3322: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3323: 	}
 3324:     }
 3325: # -------------------------------------------------- Deal with Applet codebases
 3326:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3327:     return $output;
 3328: }
 3329: 
 3330: =pod
 3331: 
 3332: =item * &get_student_view()
 3333: 
 3334: show a snapshot of what student was looking at
 3335: 
 3336: =cut
 3337: 
 3338: sub get_student_view {
 3339:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3340:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3341:   my (%form);
 3342:   my @elements=('symb','courseid','domain','username');
 3343:   foreach my $element (@elements) {
 3344:       $form{'grade_'.$element}=eval '$'.$element #'
 3345:   }
 3346:   if (defined($moreenv)) {
 3347:       %form=(%form,%{$moreenv});
 3348:   }
 3349:   if (defined($target)) { $form{'grade_target'} = $target; }
 3350:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3351:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3352:   $userview=~s/\<body[^\>]*\>//gi;
 3353:   $userview=~s/\<\/body\>//gi;
 3354:   $userview=~s/\<html\>//gi;
 3355:   $userview=~s/\<\/html\>//gi;
 3356:   $userview=~s/\<head\>//gi;
 3357:   $userview=~s/\<\/head\>//gi;
 3358:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3359:   $userview=&relative_to_absolute($feedurl,$userview);
 3360:   if (wantarray) {
 3361:      return ($userview,$response);
 3362:   } else {
 3363:      return $userview;
 3364:   }
 3365: }
 3366: 
 3367: sub get_student_view_with_retries {
 3368:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3369: 
 3370:     my $ok = 0;                 # True if we got a good response.
 3371:     my $content;
 3372:     my $response;
 3373: 
 3374:     # Try to get the student_view done. within the retries count:
 3375:     
 3376:     do {
 3377:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3378:          $ok      = $response->is_success;
 3379:          if (!$ok) {
 3380:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3381:          }
 3382:          $retries--;
 3383:     } while (!$ok && ($retries > 0));
 3384:     
 3385:     if (!$ok) {
 3386:        $content = '';          # On error return an empty content.
 3387:     }
 3388:     if (wantarray) {
 3389:        return ($content, $response);
 3390:     } else {
 3391:        return $content;
 3392:     }
 3393: }
 3394: 
 3395: =pod
 3396: 
 3397: =item * &get_student_answers() 
 3398: 
 3399: show a snapshot of how student was answering problem
 3400: 
 3401: =cut
 3402: 
 3403: sub get_student_answers {
 3404:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3405:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3406:   my (%moreenv);
 3407:   my @elements=('symb','courseid','domain','username');
 3408:   foreach my $element (@elements) {
 3409:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3410:   }
 3411:   $moreenv{'grade_target'}='answer';
 3412:   %moreenv=(%form,%moreenv);
 3413:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3414:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3415:   return $userview;
 3416: }
 3417: 
 3418: =pod
 3419: 
 3420: =item * &submlink()
 3421: 
 3422: Inputs: $text $uname $udom $symb $target
 3423: 
 3424: Returns: A link to grades.pm such as to see the SUBM view of a student
 3425: 
 3426: =cut
 3427: 
 3428: ###############################################
 3429: sub submlink {
 3430:     my ($text,$uname,$udom,$symb,$target)=@_;
 3431:     if (!($uname && $udom)) {
 3432: 	(my $cursymb, my $courseid,$udom,$uname)=
 3433: 	    &Apache::lonnet::whichuser($symb);
 3434: 	if (!$symb) { $symb=$cursymb; }
 3435:     }
 3436:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3437:     $symb=&escape($symb);
 3438:     if ($target) { $target="target=\"$target\""; }
 3439:     return '<a href="/adm/grades?&command=submission&'.
 3440: 	'symb='.$symb.'&student='.$uname.
 3441: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3442: }
 3443: ##############################################
 3444: 
 3445: =pod
 3446: 
 3447: =item * &pgrdlink()
 3448: 
 3449: Inputs: $text $uname $udom $symb $target
 3450: 
 3451: Returns: A link to grades.pm such as to see the PGRD view of a student
 3452: 
 3453: =cut
 3454: 
 3455: ###############################################
 3456: sub pgrdlink {
 3457:     my $link=&submlink(@_);
 3458:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3459:     return $link;
 3460: }
 3461: ##############################################
 3462: 
 3463: =pod
 3464: 
 3465: =item * &pprmlink()
 3466: 
 3467: Inputs: $text $uname $udom $symb $target
 3468: 
 3469: Returns: A link to parmset.pm such as to see the PPRM view of a
 3470: student and a specific resource
 3471: 
 3472: =cut
 3473: 
 3474: ###############################################
 3475: sub pprmlink {
 3476:     my ($text,$uname,$udom,$symb,$target)=@_;
 3477:     if (!($uname && $udom)) {
 3478: 	(my $cursymb, my $courseid,$udom,$uname)=
 3479: 	    &Apache::lonnet::whichuser($symb);
 3480: 	if (!$symb) { $symb=$cursymb; }
 3481:     }
 3482:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3483:     $symb=&escape($symb);
 3484:     if ($target) { $target="target=\"$target\""; }
 3485:     return '<a href="/adm/parmset?command=set&amp;'.
 3486: 	'symb='.$symb.'&amp;uname='.$uname.
 3487: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3488: }
 3489: ##############################################
 3490: 
 3491: =pod
 3492: 
 3493: =back
 3494: 
 3495: =cut
 3496: 
 3497: ###############################################
 3498: 
 3499: 
 3500: sub timehash {
 3501:     my ($thistime) = @_;
 3502:     my $timezone = &Apache::lonlocal::gettimezone();
 3503:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3504:                      ->set_time_zone($timezone);
 3505:     my $wday = $dt->day_of_week();
 3506:     if ($wday == 7) { $wday = 0; }
 3507:     return ( 'second' => $dt->second(),
 3508:              'minute' => $dt->minute(),
 3509:              'hour'   => $dt->hour(),
 3510:              'day'     => $dt->day_of_month(),
 3511:              'month'   => $dt->month(),
 3512:              'year'    => $dt->year(),
 3513:              'weekday' => $wday,
 3514:              'dayyear' => $dt->day_of_year(),
 3515:              'dlsav'   => $dt->is_dst() );
 3516: }
 3517: 
 3518: sub utc_string {
 3519:     my ($date)=@_;
 3520:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3521: }
 3522: 
 3523: sub maketime {
 3524:     my %th=@_;
 3525:     my ($epoch_time,$timezone,$dt);
 3526:     $timezone = &Apache::lonlocal::gettimezone();
 3527:     eval {
 3528:         $dt = DateTime->new( year   => $th{'year'},
 3529:                              month  => $th{'month'},
 3530:                              day    => $th{'day'},
 3531:                              hour   => $th{'hour'},
 3532:                              minute => $th{'minute'},
 3533:                              second => $th{'second'},
 3534:                              time_zone => $timezone,
 3535:                          );
 3536:     };
 3537:     if (!$@) {
 3538:         $epoch_time = $dt->epoch;
 3539:         if ($epoch_time) {
 3540:             return $epoch_time;
 3541:         }
 3542:     }
 3543:     return POSIX::mktime(
 3544:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3545:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3546: }
 3547: 
 3548: #########################################
 3549: 
 3550: sub findallcourses {
 3551:     my ($roles,$uname,$udom) = @_;
 3552:     my %roles;
 3553:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3554:     my %courses;
 3555:     my $now=time;
 3556:     if (!defined($uname)) {
 3557:         $uname = $env{'user.name'};
 3558:     }
 3559:     if (!defined($udom)) {
 3560:         $udom = $env{'user.domain'};
 3561:     }
 3562:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3563:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3564:         if (!%roles) {
 3565:             %roles = (
 3566:                        cc => 1,
 3567:                        in => 1,
 3568:                        ep => 1,
 3569:                        ta => 1,
 3570:                        cr => 1,
 3571:                        st => 1,
 3572:              );
 3573:         }
 3574:         foreach my $entry (keys(%roleshash)) {
 3575:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3576:             if ($trole =~ /^cr/) { 
 3577:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3578:             } else {
 3579:                 next if (!exists($roles{$trole}));
 3580:             }
 3581:             if ($tend) {
 3582:                 next if ($tend < $now);
 3583:             }
 3584:             if ($tstart) {
 3585:                 next if ($tstart > $now);
 3586:             }
 3587:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3588:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3589:             if ($secpart eq '') {
 3590:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3591:                 $sec = 'none';
 3592:                 $realsec = '';
 3593:             } else {
 3594:                 $cnum = $cnumpart;
 3595:                 ($sec,$role) = split(/_/,$secpart);
 3596:                 $realsec = $sec;
 3597:             }
 3598:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3599:         }
 3600:     } else {
 3601:         foreach my $key (keys(%env)) {
 3602: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3603:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3604: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3605: 	        next if ($role eq 'ca' || $role eq 'aa');
 3606: 	        next if (%roles && !exists($roles{$role}));
 3607: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3608:                 my $active=1;
 3609:                 if ($starttime) {
 3610: 		    if ($now<$starttime) { $active=0; }
 3611:                 }
 3612:                 if ($endtime) {
 3613:                     if ($now>$endtime) { $active=0; }
 3614:                 }
 3615:                 if ($active) {
 3616:                     if ($sec eq '') {
 3617:                         $sec = 'none';
 3618:                     }
 3619:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3620:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3621:                 }
 3622:             }
 3623:         }
 3624:     }
 3625:     return %courses;
 3626: }
 3627: 
 3628: ###############################################
 3629: 
 3630: sub blockcheck {
 3631:     my ($setters,$activity,$uname,$udom) = @_;
 3632: 
 3633:     if (!defined($udom)) {
 3634:         $udom = $env{'user.domain'};
 3635:     }
 3636:     if (!defined($uname)) {
 3637:         $uname = $env{'user.name'};
 3638:     }
 3639: 
 3640:     # If uname and udom are for a course, check for blocks in the course.
 3641: 
 3642:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3643:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3644:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3645:         return ($startblock,$endblock);
 3646:     }
 3647: 
 3648:     my $startblock = 0;
 3649:     my $endblock = 0;
 3650:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3651: 
 3652:     # If uname is for a user, and activity is course-specific, i.e.,
 3653:     # boards, chat or groups, check for blocking in current course only.
 3654: 
 3655:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3656:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3657:         foreach my $key (keys(%live_courses)) {
 3658:             if ($key ne $env{'request.course.id'}) {
 3659:                 delete($live_courses{$key});
 3660:             }
 3661:         }
 3662:     }
 3663: 
 3664:     my $otheruser = 0;
 3665:     my %own_courses;
 3666:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3667:         # Resource belongs to user other than current user.
 3668:         $otheruser = 1;
 3669:         # Gather courses for current user
 3670:         %own_courses = 
 3671:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3672:     }
 3673: 
 3674:     # Gather active course roles - course coordinator, instructor, 
 3675:     # exam proctor, ta, student, or custom role.
 3676: 
 3677:     foreach my $course (keys(%live_courses)) {
 3678:         my ($cdom,$cnum);
 3679:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3680:             $cdom = $env{'course.'.$course.'.domain'};
 3681:             $cnum = $env{'course.'.$course.'.num'};
 3682:         } else {
 3683:             ($cdom,$cnum) = split(/_/,$course); 
 3684:         }
 3685:         my $no_ownblock = 0;
 3686:         my $no_userblock = 0;
 3687:         if ($otheruser && $activity ne 'com') {
 3688:             # Check if current user has 'evb' priv for this
 3689:             if (defined($own_courses{$course})) {
 3690:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3691:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3692:                     if ($sec ne 'none') {
 3693:                         $checkrole .= '/'.$sec;
 3694:                     }
 3695:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3696:                         $no_ownblock = 1;
 3697:                         last;
 3698:                     }
 3699:                 }
 3700:             }
 3701:             # if they have 'evb' priv and are currently not playing student
 3702:             next if (($no_ownblock) &&
 3703:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3704:         }
 3705:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3706:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3707:             if ($sec ne 'none') {
 3708:                 $checkrole .= '/'.$sec;
 3709:             }
 3710:             if ($otheruser) {
 3711:                 # Resource belongs to user other than current user.
 3712:                 # Assemble privs for that user, and check for 'evb' priv.
 3713:                 my ($trole,$tdom,$tnum,$tsec);
 3714:                 my $entry = $live_courses{$course}{$sec};
 3715:                 if ($entry =~ /^cr/) {
 3716:                     ($trole,$tdom,$tnum,$tsec) = 
 3717:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3718:                 } else {
 3719:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3720:                 }
 3721:                 my ($spec,$area,$trest,%allroles,%userroles);
 3722:                 $area = '/'.$tdom.'/'.$tnum;
 3723:                 $trest = $tnum;
 3724:                 if ($tsec ne '') {
 3725:                     $area .= '/'.$tsec;
 3726:                     $trest .= '/'.$tsec;
 3727:                 }
 3728:                 $spec = $trole.'.'.$area;
 3729:                 if ($trole =~ /^cr/) {
 3730:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3731:                                                       $tdom,$spec,$trest,$area);
 3732:                 } else {
 3733:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3734:                                                        $tdom,$spec,$trest,$area);
 3735:                 }
 3736:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3737:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3738:                     if ($1) {
 3739:                         $no_userblock = 1;
 3740:                         last;
 3741:                     }
 3742:                 }
 3743:             } else {
 3744:                 # Resource belongs to current user
 3745:                 # Check for 'evb' priv via lonnet::allowed().
 3746:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3747:                     $no_ownblock = 1;
 3748:                     last;
 3749:                 }
 3750:             }
 3751:         }
 3752:         # if they have the evb priv and are currently not playing student
 3753:         next if (($no_ownblock) &&
 3754:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3755:         next if ($no_userblock);
 3756: 
 3757:         # Retrieve blocking times and identity of blocker for course
 3758:         # of specified user, unless user has 'evb' privilege.
 3759:         
 3760:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3761:         if (($start != 0) && 
 3762:             (($startblock == 0) || ($startblock > $start))) {
 3763:             $startblock = $start;
 3764:         }
 3765:         if (($end != 0)  &&
 3766:             (($endblock == 0) || ($endblock < $end))) {
 3767:             $endblock = $end;
 3768:         }
 3769:     }
 3770:     return ($startblock,$endblock);
 3771: }
 3772: 
 3773: sub get_blocks {
 3774:     my ($setters,$activity,$cdom,$cnum) = @_;
 3775:     my $startblock = 0;
 3776:     my $endblock = 0;
 3777:     my $course = $cdom.'_'.$cnum;
 3778:     $setters->{$course} = {};
 3779:     $setters->{$course}{'staff'} = [];
 3780:     $setters->{$course}{'times'} = [];
 3781:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3782:     foreach my $record (keys(%records)) {
 3783:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3784:         if ($start <= time && $end >= time) {
 3785:             my ($staff_name,$staff_dom,$title,$blocks) =
 3786:                 &parse_block_record($records{$record});
 3787:             if ($blocks->{$activity} eq 'on') {
 3788:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3789:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3790:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3791:                     $startblock = $start;
 3792:                 }
 3793:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3794:                     $endblock = $end;
 3795:                 }
 3796:             }
 3797:         }
 3798:     }
 3799:     return ($startblock,$endblock);
 3800: }
 3801: 
 3802: sub parse_block_record {
 3803:     my ($record) = @_;
 3804:     my ($setuname,$setudom,$title,$blocks);
 3805:     if (ref($record) eq 'HASH') {
 3806:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3807:         $title = &unescape($record->{'event'});
 3808:         $blocks = $record->{'blocks'};
 3809:     } else {
 3810:         my @data = split(/:/,$record,3);
 3811:         if (scalar(@data) eq 2) {
 3812:             $title = $data[1];
 3813:             ($setuname,$setudom) = split(/@/,$data[0]);
 3814:         } else {
 3815:             ($setuname,$setudom,$title) = @data;
 3816:         }
 3817:         $blocks = { 'com' => 'on' };
 3818:     }
 3819:     return ($setuname,$setudom,$title,$blocks);
 3820: }
 3821: 
 3822: sub build_block_table {
 3823:     my ($startblock,$endblock,$setters) = @_;
 3824:     my %lt = &Apache::lonlocal::texthash(
 3825:         'cacb' => 'Currently active communication blocks',
 3826:         'cour' => 'Course',
 3827:         'dura' => 'Duration',
 3828:         'blse' => 'Block set by'
 3829:     );
 3830:     my $output;
 3831:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3832:     $output .= &start_data_table();
 3833:     $output .= '
 3834: <tr>
 3835:  <th>'.$lt{'cour'}.'</th>
 3836:  <th>'.$lt{'dura'}.'</th>
 3837:  <th>'.$lt{'blse'}.'</th>
 3838: </tr>
 3839: ';
 3840:     foreach my $course (keys(%{$setters})) {
 3841:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3842:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3843:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3844:             my $fullname = &plainname($uname,$udom);
 3845:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3846:                 && $env{'user.name'} ne 'public' 
 3847:                 && $env{'user.domain'} ne 'public') {
 3848:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3849:             }
 3850:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3851:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3852:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3853:             $output .= &Apache::loncommon::start_data_table_row().
 3854:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3855:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3856:                        '<td>'.$fullname.'</td>'.
 3857:                         &Apache::loncommon::end_data_table_row();
 3858:         }
 3859:     }
 3860:     $output .= &end_data_table();
 3861: }
 3862: 
 3863: sub blocking_status {
 3864:     my ($activity,$uname,$udom) = @_;
 3865:     my %setters;
 3866:     my ($blocked,$output,$ownitem,$is_course);
 3867:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3868:     if ($startblock && $endblock) {
 3869:         $blocked = 1;
 3870:         if (wantarray) {
 3871:             my $category;
 3872:             if ($activity eq 'boards') {
 3873:                 $category = 'Discussion posts in this course';
 3874:             } elsif ($activity eq 'blogs') {
 3875:                 $category = 'Blogs';
 3876:             } elsif ($activity eq 'port') {
 3877:                 if (defined($uname) && defined($udom)) {
 3878:                     if ($uname eq $env{'user.name'} &&
 3879:                         $udom eq $env{'user.domain'}) {
 3880:                         $ownitem = 1;
 3881:                     }
 3882:                 }
 3883:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3884:                 if ($ownitem) { 
 3885:                     $category = 'Your portfolio files';  
 3886:                 } elsif ($is_course) {
 3887:                     my $coursedesc;
 3888:                     foreach my $course (keys(%setters)) {
 3889:                         my %courseinfo =
 3890:                              &Apache::lonnet::coursedescription($course);
 3891:                         $coursedesc = $courseinfo{'description'};
 3892:                     }
 3893:                     $category = "Group portfolio in the course '$coursedesc'";
 3894:                 } else {
 3895:                     $category = 'Portfolio files belonging to ';
 3896:                     if ($env{'user.name'} eq 'public' && 
 3897:                         $env{'user.domain'} eq 'public') {
 3898:                         $category .= &plainname($uname,$udom);
 3899:                     } else {
 3900:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3901:                     }
 3902:                 }
 3903:             } elsif ($activity eq 'groups') {
 3904:                 $category = 'Groups in this course';
 3905:             }
 3906:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3907:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3908:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3909:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3910:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3911:             }
 3912:         }
 3913:     }
 3914:     if (wantarray) {
 3915:         return ($blocked,$output);
 3916:     } else {
 3917:         return $blocked;
 3918:     }
 3919: }
 3920: 
 3921: ###############################################
 3922: 
 3923: sub check_ip_acc {
 3924:     my ($acc)=@_;
 3925:     &Apache::lonxml::debug("acc is $acc");
 3926:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3927:         return 1;
 3928:     }
 3929:     my $allowed=0;
 3930:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3931: 
 3932:     my $name;
 3933:     foreach my $pattern (split(',',$acc)) {
 3934:         $pattern =~ s/^\s*//;
 3935:         $pattern =~ s/\s*$//;
 3936:         if ($pattern =~ /\*$/) {
 3937:             #35.8.*
 3938:             $pattern=~s/\*//;
 3939:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3940:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3941:             #35.8.3.[34-56]
 3942:             my $low=$2;
 3943:             my $high=$3;
 3944:             $pattern=$1;
 3945:             if ($ip =~ /^\Q$pattern\E/) {
 3946:                 my $last=(split(/\./,$ip))[3];
 3947:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3948:             }
 3949:         } elsif ($pattern =~ /^\*/) {
 3950:             #*.msu.edu
 3951:             $pattern=~s/\*//;
 3952:             if (!defined($name)) {
 3953:                 use Socket;
 3954:                 my $netaddr=inet_aton($ip);
 3955:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3956:             }
 3957:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3958:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3959:             #127.0.0.1
 3960:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3961:         } else {
 3962:             #some.name.com
 3963:             if (!defined($name)) {
 3964:                 use Socket;
 3965:                 my $netaddr=inet_aton($ip);
 3966:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3967:             }
 3968:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3969:         }
 3970:         if ($allowed) { last; }
 3971:     }
 3972:     return $allowed;
 3973: }
 3974: 
 3975: ###############################################
 3976: 
 3977: =pod
 3978: 
 3979: =head1 Domain Template Functions
 3980: 
 3981: =over 4
 3982: 
 3983: =item * &determinedomain()
 3984: 
 3985: Inputs: $domain (usually will be undef)
 3986: 
 3987: Returns: Determines which domain should be used for designs
 3988: 
 3989: =cut
 3990: 
 3991: ###############################################
 3992: sub determinedomain {
 3993:     my $domain=shift;
 3994:     if (! $domain) {
 3995:         # Determine domain if we have not been given one
 3996:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3997:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3998:         if ($env{'request.role.domain'}) { 
 3999:             $domain=$env{'request.role.domain'}; 
 4000:         }
 4001:     }
 4002:     return $domain;
 4003: }
 4004: ###############################################
 4005: 
 4006: sub devalidate_domconfig_cache {
 4007:     my ($udom)=@_;
 4008:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4009: }
 4010: 
 4011: # ---------------------- Get domain configuration for a domain
 4012: sub get_domainconf {
 4013:     my ($udom) = @_;
 4014:     my $cachetime=1800;
 4015:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4016:     if (defined($cached)) { return %{$result}; }
 4017: 
 4018:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4019: 					     ['login','rolecolors'],$udom);
 4020:     my (%designhash,%legacy);
 4021:     if (keys(%domconfig) > 0) {
 4022:         if (ref($domconfig{'login'}) eq 'HASH') {
 4023:             if (keys(%{$domconfig{'login'}})) {
 4024:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4025:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4026:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4027:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4028:                                 $domconfig{'login'}{$key}{$img};
 4029:                         }
 4030:                     } else {
 4031:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4032:                     }
 4033:                 }
 4034:             } else {
 4035:                 $legacy{'login'} = 1;
 4036:             }
 4037:         } else {
 4038:             $legacy{'login'} = 1;
 4039:         }
 4040:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4041:             if (keys(%{$domconfig{'rolecolors'}})) {
 4042:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4043:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4044:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4045:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4046:                         }
 4047:                     }
 4048:                 }
 4049:             } else {
 4050:                 $legacy{'rolecolors'} = 1;
 4051:             }
 4052:         } else {
 4053:             $legacy{'rolecolors'} = 1;
 4054:         }
 4055:         if (keys(%legacy) > 0) {
 4056:             my %legacyhash = &get_legacy_domconf($udom);
 4057:             foreach my $item (keys(%legacyhash)) {
 4058:                 if ($item =~ /^\Q$udom\E\.login/) {
 4059:                     if ($legacy{'login'}) { 
 4060:                         $designhash{$item} = $legacyhash{$item};
 4061:                     }
 4062:                 } else {
 4063:                     if ($legacy{'rolecolors'}) {
 4064:                         $designhash{$item} = $legacyhash{$item};
 4065:                     }
 4066:                 }
 4067:             }
 4068:         }
 4069:     } else {
 4070:         %designhash = &get_legacy_domconf($udom); 
 4071:     }
 4072:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4073: 				  $cachetime);
 4074:     return %designhash;
 4075: }
 4076: 
 4077: sub get_legacy_domconf {
 4078:     my ($udom) = @_;
 4079:     my %legacyhash;
 4080:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4081:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4082:     if (-e $designfile) {
 4083:         if ( open (my $fh,"<$designfile") ) {
 4084:             while (my $line = <$fh>) {
 4085:                 next if ($line =~ /^\#/);
 4086:                 chomp($line);
 4087:                 my ($key,$val)=(split(/\=/,$line));
 4088:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4089:             }
 4090:             close($fh);
 4091:         }
 4092:     }
 4093:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4094:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4095:     }
 4096:     return %legacyhash;
 4097: }
 4098: 
 4099: =pod
 4100: 
 4101: =item * &domainlogo()
 4102: 
 4103: Inputs: $domain (usually will be undef)
 4104: 
 4105: Returns: A link to a domain logo, if the domain logo exists.
 4106: If the domain logo does not exist, a description of the domain.
 4107: 
 4108: =cut
 4109: 
 4110: ###############################################
 4111: sub domainlogo {
 4112:     my $domain = &determinedomain(shift);
 4113:     my %designhash = &get_domainconf($domain);    
 4114:     # See if there is a logo
 4115:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4116:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4117:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4118: 	    if ($imgsrc =~ m{^/res/}) {
 4119: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4120: 		&Apache::lonnet::repcopy($local_name);
 4121: 	    }
 4122: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4123:         } 
 4124:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4125:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4126:         return &Apache::lonnet::domain($domain,'description');
 4127:     } else {
 4128:         return '';
 4129:     }
 4130: }
 4131: ##############################################
 4132: 
 4133: =pod
 4134: 
 4135: =item * &designparm()
 4136: 
 4137: Inputs: $which parameter; $domain (usually will be undef)
 4138: 
 4139: Returns: value of designparamter $which
 4140: 
 4141: =cut
 4142: 
 4143: 
 4144: ##############################################
 4145: sub designparm {
 4146:     my ($which,$domain)=@_;
 4147:     if ($env{'browser.blackwhite'} eq 'on') {
 4148: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4149: 	    return '#000000';
 4150: 	}
 4151: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4152: 	    return '#FFFFFF';
 4153: 	}
 4154: 	if ($which=~/\.tabbg$/) {
 4155: 	    return '#CCCCCC';
 4156: 	}
 4157:     }
 4158:     if (exists($env{'environment.color.'.$which})) {
 4159: 	return $env{'environment.color.'.$which};
 4160:     }
 4161:     $domain=&determinedomain($domain);
 4162:     my %domdesign = &get_domainconf($domain);
 4163:     my $output;
 4164:     if ($domdesign{$domain.'.'.$which} ne '') {
 4165: 	$output = $domdesign{$domain.'.'.$which};
 4166:     } else {
 4167:         $output = $defaultdesign{$which};
 4168:     }
 4169:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4170:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4171:         if ($output =~ m{^/(adm|res)/}) {
 4172: 	    if ($output =~ m{^/res/}) {
 4173: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4174: 		&Apache::lonnet::repcopy($local_name);
 4175: 	    }
 4176:             $output = &lonhttpdurl($output);
 4177:         }
 4178:     }
 4179:     return $output;
 4180: }
 4181: 
 4182: ###############################################
 4183: ###############################################
 4184: 
 4185: =pod
 4186: 
 4187: =back
 4188: 
 4189: =head1 HTML Helpers
 4190: 
 4191: =over 4
 4192: 
 4193: =item * &bodytag()
 4194: 
 4195: Returns a uniform header for LON-CAPA web pages.
 4196: 
 4197: Inputs: 
 4198: 
 4199: =over 4
 4200: 
 4201: =item * $title, A title to be displayed on the page.
 4202: 
 4203: =item * $function, the current role (can be undef).
 4204: 
 4205: =item * $addentries, extra parameters for the <body> tag.
 4206: 
 4207: =item * $bodyonly, if defined, only return the <body> tag.
 4208: 
 4209: =item * $domain, if defined, force a given domain.
 4210: 
 4211: =item * $forcereg, if page should register as content page (relevant for 
 4212:             text interface only)
 4213: 
 4214: =item * $customtitle, alternate text to use instead of $title
 4215:                       in the title box that appears, this text
 4216:                       is not auto translated like the $title is
 4217: 
 4218: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4219:                      navigational links
 4220: 
 4221: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4222: 
 4223: =item * $notitle, if true keep the nav controls, but remove the title bar
 4224: 
 4225: =item * $no_inline_link, if true and in remote mode, don't show the 
 4226:          'Switch To Inline Menu' link
 4227: 
 4228: =item * $args, optional argument valid values are
 4229:             no_auto_mt_title -> prevents &mt()ing the title arg
 4230:             inherit_jsmath -> when creating popup window in a page,
 4231:                               should it have jsmath forced on by the
 4232:                               current page
 4233: 
 4234: =back
 4235: 
 4236: Returns: A uniform header for LON-CAPA web pages.  
 4237: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4238: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4239: other decorations will be returned.
 4240: 
 4241: =cut
 4242: 
 4243: sub bodytag {
 4244:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4245:         $no_nav_bar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4246: 
 4247:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4248: 
 4249:     $function = &get_users_function() if (!$function);
 4250:     my $img =    &designparm($function.'.img',$domain);
 4251:     my $font =   &designparm($function.'.font',$domain);
 4252:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4253: 
 4254:     my %design = ( 'style'   => 'margin-top: 0',
 4255: 		   'bgcolor' => $pgbg,
 4256: 		   'text'    => $font,
 4257:                    'alink'   => &designparm($function.'.alink',$domain),
 4258: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4259: 		   'link'    => &designparm($function.'.link',$domain),);
 4260:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4261: 
 4262:  # role and realm
 4263:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4264:     if ($role  eq 'ca') {
 4265:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4266:         $realm = &plainname($rname,$rdom);
 4267:     } 
 4268: # realm
 4269:     if ($env{'request.course.id'}) {
 4270:         if ($env{'request.role'} !~ /^cr/) {
 4271:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4272:         }
 4273: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4274:     } else {
 4275:         $role = &Apache::lonnet::plaintext($role);
 4276:     }
 4277: 
 4278:     if (!$realm) { $realm='&nbsp;'; }
 4279: # Set messages
 4280:     my $messages=&domainlogo($domain);
 4281: 
 4282:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4283: 
 4284: # construct main body tag
 4285:     my $bodytag = "<body $extra_body_attr>".
 4286: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4287: 
 4288:     if ($bodyonly) {
 4289:         return $bodytag;
 4290:     } 
 4291: 
 4292:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4293:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4294: 	undef($role);
 4295:     } else {
 4296: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4297:     }
 4298:     
 4299:     my $roleinfo=(<<ENDROLE);
 4300: <td class="LC_title_bar_who">
 4301: <div class="LC_title_bar_name">
 4302:     $name
 4303:     &nbsp;
 4304: </div>
 4305: <div class="LC_title_bar_role">
 4306: $role&nbsp;
 4307: </div>
 4308: <div class="LC_title_bar_realm">
 4309: $realm&nbsp;
 4310: </div>
 4311: </td>
 4312: ENDROLE
 4313: 
 4314:     my $titleinfo = '<h1>'.$title.'</h1>';
 4315:     if ($customtitle) {
 4316:         $titleinfo = $customtitle;
 4317:     }
 4318:     #
 4319:     # Extra info if you are the DC
 4320:     my $dc_info = '';
 4321:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4322:                         $env{'course.'.$env{'request.course.id'}.
 4323:                                  '.domain'}.'/'})) {
 4324:         my $cid = $env{'request.course.id'};
 4325:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4326:         $dc_info =~ s/\s+$//;
 4327:         $dc_info = '('.$dc_info.')';
 4328:     }
 4329: 
 4330:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4331:         # No Remote
 4332: 	if ($env{'request.state'} eq 'construct') {
 4333: 	    $forcereg=1;
 4334: 	}
 4335: 
 4336: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4337: 	    # this is for resources; directories have customtitle, and crumbs
 4338:             # and select recent are created in lonpubdir.pm  
 4339: 	    my ($uname,$thisdisfn)=
 4340: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4341: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4342: 	    $formaction=~s/\/+/\//g;
 4343: 
 4344: 	    my $parentpath = '';
 4345: 	    my $lastitem = '';
 4346: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4347: 		$parentpath = $1;
 4348: 		$lastitem = $2;
 4349: 	    } else {
 4350: 		$lastitem = $thisdisfn;
 4351: 	    }
 4352: 	    $titleinfo = 
 4353: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4354: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4355: 		.'<form name="dirs" method="post" action="'.$formaction
 4356: 		.'" target="_top"><tt><b>'
 4357: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4358: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4359: 		.'</form>'
 4360: 		.&Apache::lonmenu::constspaceform();
 4361:         }
 4362: 
 4363:         my $titletable;
 4364: 	if (!$notitle) {
 4365: 	    $titletable =
 4366: 		'<table id="LC_title_bar">'.
 4367:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4368: 			 '</tr></table>';
 4369: 	}
 4370: 	if ($no_nav_bar) {
 4371: 	    $bodytag .= $titletable;
 4372: 	} else {
 4373:         $bodytag .= qq|<div id="LC_nav_bar">$name ($role)<br />
 4374:             <em>$realm</em> $dc_info</div>|;
 4375: 	    if ($env{'request.state'} eq 'construct') {
 4376:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4377: 							  $titletable);
 4378:             } else {
 4379:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4380: 		    $titletable;
 4381:             }
 4382:         }
 4383:         return $bodytag;
 4384:     }
 4385: 
 4386: #
 4387: # Top frame rendering, Remote is up
 4388: #
 4389: 
 4390:     my $imgsrc = $img;
 4391:     if ($img =~ /^\/adm/) {
 4392:         $imgsrc = &lonhttpdurl($img);
 4393:     }
 4394:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4395: 
 4396:     # Explicit link to get inline menu
 4397:     my $menu= ($no_inline_link?''
 4398: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4399:     #
 4400:     if ($notitle) {
 4401: 	return $bodytag;
 4402:     }
 4403:     return(<<ENDBODY);
 4404: $bodytag
 4405: <table id="LC_title_bar" class="LC_with_remote">
 4406: <tr><td>$upperleft</td>
 4407:     <td>$messages&nbsp;</td>
 4408: </tr>
 4409: <tr><td>$titleinfo $dc_info $menu</td>
 4410: $roleinfo
 4411: </tr>
 4412: </table>
 4413: ENDBODY
 4414: }
 4415: 
 4416: sub make_attr_string {
 4417:     my ($register,$attr_ref) = @_;
 4418: 
 4419:     if ($attr_ref && !ref($attr_ref)) {
 4420: 	die("addentries Must be a hash ref ".
 4421: 	    join(':',caller(1))." ".
 4422: 	    join(':',caller(0))." ");
 4423:     }
 4424: 
 4425:     if ($register) {
 4426: 	my ($on_load,$on_unload);
 4427: 	foreach my $key (keys(%{$attr_ref})) {
 4428: 	    if      (lc($key) eq 'onload') {
 4429: 		$on_load.=$attr_ref->{$key}.';';
 4430: 		delete($attr_ref->{$key});
 4431: 
 4432: 	    } elsif (lc($key) eq 'onunload') {
 4433: 		$on_unload.=$attr_ref->{$key}.';';
 4434: 		delete($attr_ref->{$key});
 4435: 	    }
 4436: 	}
 4437: 	$attr_ref->{'onload'}  =
 4438: 	    &Apache::lonmenu::loadevents().  $on_load;
 4439: 	$attr_ref->{'onunload'}=
 4440: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4441:     }
 4442: 
 4443: # Accessibility font enhance
 4444:     if ($env{'browser.fontenhance'} eq 'on') {
 4445: 	my $style;
 4446: 	foreach my $key (keys(%{$attr_ref})) {
 4447: 	    if (lc($key) eq 'style') {
 4448: 		$style.=$attr_ref->{$key}.';';
 4449: 		delete($attr_ref->{$key});
 4450: 	    }
 4451: 	}
 4452: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4453:     }
 4454: 
 4455:     if ($env{'browser.blackwhite'} eq 'on') {
 4456: 	delete($attr_ref->{'font'});
 4457: 	delete($attr_ref->{'link'});
 4458: 	delete($attr_ref->{'alink'});
 4459: 	delete($attr_ref->{'vlink'});
 4460: 	delete($attr_ref->{'bgcolor'});
 4461: 	delete($attr_ref->{'background'});
 4462:     }
 4463: 
 4464:     my $attr_string;
 4465:     foreach my $attr (keys(%$attr_ref)) {
 4466: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4467:     }
 4468:     return $attr_string;
 4469: }
 4470: 
 4471: 
 4472: ###############################################
 4473: ###############################################
 4474: 
 4475: =pod
 4476: 
 4477: =item * &endbodytag()
 4478: 
 4479: Returns a uniform footer for LON-CAPA web pages.
 4480: 
 4481: Inputs: 1 - optional reference to an args hash
 4482: If in the hash, key for noredirectlink has a value which evaluates to true,
 4483: a 'Continue' link is not displayed if the page contains an
 4484: internal redirect in the <head></head> section,
 4485: i.e., $env{'internal.head.redirect'} exists   
 4486: 
 4487: =cut
 4488: 
 4489: sub endbodytag {
 4490:     my ($args) = @_;
 4491:     my $endbodytag='</body>';
 4492:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4493:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4494:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4495: 	    $endbodytag=
 4496: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4497: 	        &mt('Continue').'</a>'.
 4498: 	        $endbodytag;
 4499:         }
 4500:     }
 4501:     return $endbodytag;
 4502: }
 4503: 
 4504: =pod
 4505: 
 4506: =item * &standard_css()
 4507: 
 4508: Returns a style sheet
 4509: 
 4510: Inputs: (all optional)
 4511:             domain         -> force to color decorate a page for a specific
 4512:                                domain
 4513:             function       -> force usage of a specific rolish color scheme
 4514:             bgcolor        -> override the default page bgcolor
 4515: 
 4516: =cut
 4517: 
 4518: sub standard_css {
 4519:     my ($function,$domain,$bgcolor) = @_;
 4520:     $function  = &get_users_function() if (!$function);
 4521:     my $img    = &designparm($function.'.img',   $domain);
 4522:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4523:     my $font   = &designparm($function.'.font',  $domain);
 4524:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4525: #second colour for later usage
 4526:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4527:     my $pgbg_or_bgcolor =
 4528: 	         $bgcolor ||
 4529: 	         &designparm($function.'.pgbg',  $domain);
 4530:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4531:     my $alink  = &designparm($function.'.alink', $domain);
 4532:     my $vlink  = &designparm($function.'.vlink', $domain);
 4533:     my $link   = &designparm($function.'.link',  $domain);
 4534: 
 4535:     my $loginbg = &designparm('login.sidebg',$domain);
 4536:     my $bgcol = &designparm('login.bgcol',$domain);
 4537:     my $textcol = &designparm('login.textcol',$domain);
 4538: 
 4539:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4540:     my $mono                 = 'monospace';
 4541:     my $data_table_head      = $tabbg;
 4542:     my $data_table_light     = '#EEEEEE';
 4543:     my $data_table_dark      = '#DDDDDD';
 4544:     my $data_table_darker    = '#CCCCCC';
 4545:     my $data_table_highlight = '#FFFF00';
 4546:     my $mail_new             = '#FFBB77';
 4547:     my $mail_new_hover       = '#DD9955';
 4548:     my $mail_read            = '#BBBB77';
 4549:     my $mail_read_hover      = '#999944';
 4550:     my $mail_replied         = '#AAAA88';
 4551:     my $mail_replied_hover   = '#888855';
 4552:     my $mail_other           = '#99BBBB';
 4553:     my $mail_other_hover     = '#669999';
 4554:     my $table_header         = '#DDDDDD';
 4555:     my $feedback_link_bg     = '#BBBBBB';
 4556:     my $lg_border_color	     = '#C8C8C8';
 4557: 
 4558:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4559: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4560: 	                                                 : '0 3px 0 4px';
 4561: 
 4562: 
 4563:     return <<END;
 4564: body {
 4565:    font-family: $sans;
 4566:    line-height:130%;
 4567:    font-size:0.83em;
 4568:    color:$font;
 4569: }
 4570: 
 4571: a:link, a:visited { 
 4572:   font-size:100%; 
 4573: }
 4574: 
 4575: a:focus { 
 4576:   color: red;
 4577:   background: yellow 
 4578: }
 4579: 
 4580: form, .inline { 
 4581:    display: inline; 
 4582: }
 4583: 
 4584: .LC_right {
 4585:    text-align:right;
 4586: }
 4587: 
 4588: .LC_middle {
 4589:    vertical-align:middle;
 4590: }
 4591: 
 4592: /* just for tests */
 4593: .LC_400Box {width:400px; }
 4594: /* end */
 4595: 
 4596: .LC_filename {
 4597:   font-family: $mono;
 4598:   white-space:pre;
 4599: }
 4600: 
 4601: .LC_fileicon {
 4602:   border: none;
 4603:   height: 1.3em;
 4604:   vertical-align: text-bottom;
 4605:   margin-right: 0.3em;
 4606:   text-decoration:none;
 4607: }
 4608: 
 4609: .LC_error {
 4610:   color: red;
 4611:   font-size: larger;
 4612: }
 4613: 
 4614: .LC_warning,
 4615: .LC_diff_removed {
 4616:   color: red;
 4617: }
 4618: 
 4619: .LC_info,
 4620: .LC_success,
 4621: .LC_diff_added {
 4622:   color: green;
 4623: }
 4624: 
 4625: div.LC_confirm_box {
 4626:   background-color: #FAFAFA;
 4627:   border: 1px solid $lg_border_color;
 4628:   margin-right: 0;
 4629:   padding: 5px;
 4630: }
 4631: 
 4632: div.LC_confirm_box .LC_error img,
 4633: div.LC_confirm_box .LC_success img {
 4634:   vertical-align: middle;
 4635: }
 4636: 
 4637: .LC_icon {
 4638:   border: none;
 4639:   vertical-align: middle;
 4640: }
 4641: 
 4642: .LC_docs_spacer {
 4643:   width: 25px;
 4644:   height: 1px;
 4645:   border: none;
 4646: }
 4647: 
 4648: .LC_internal_info {
 4649:   color: #999999;
 4650: }
 4651: 
 4652: .LC_discussion {
 4653:    background: $tabbg;
 4654:    border: 1px solid black;
 4655:    margin: 2px;
 4656: }
 4657: 
 4658: .LC_disc_action_links_bar {
 4659:    background: $tabbg;
 4660:    font-family: $sans;
 4661:    border: none;
 4662:    margin: 4px;
 4663: }
 4664: 
 4665: .LC_disc_action_left {
 4666:    text-align: left;
 4667: }
 4668: 
 4669: .LC_disc_action_right {
 4670:    text-align: right;
 4671: }
 4672: 
 4673: .LC_disc_new_item {
 4674:    background: white;
 4675:    border: 2px solid red;
 4676:    margin: 2px;
 4677: }
 4678: 
 4679: .LC_disc_old_item {
 4680:    background: white;
 4681:    border: 1px solid black;
 4682:    margin: 2px;
 4683: }
 4684: 
 4685: table.LC_pastsubmission {
 4686:   border: 1px solid black;
 4687:   margin: 2px;
 4688: }
 4689: 
 4690: table#LC_top_nav,
 4691: table#LC_menubuttons,
 4692: table#LC_nav_location {
 4693:   width: 100%;
 4694:   background: $pgbg;
 4695:   border: 2px;
 4696:   border-collapse: separate;
 4697:   padding: 0;
 4698: }
 4699: 
 4700: table#LC_title_bar a {
 4701:   color: $fontmenu;
 4702: }
 4703:     
 4704: table#LC_title_bar {
 4705:   /*display: none;*/
 4706: }
 4707: 
 4708: table#LC_title_bar,
 4709: table.LC_breadcrumbs,
 4710: table#LC_title_bar.LC_with_remote {
 4711:   width: 100%;
 4712:   border-color: $pgbg;
 4713:   border-style: solid;
 4714:   border-width: $border;
 4715:   background: $pgbg;
 4716:   color: $fontmenu;
 4717:   font-family: $sans;
 4718:   border-collapse: collapse;
 4719:   padding: 0;
 4720: }
 4721: 
 4722: table.LC_docs_path {
 4723:   width: 100%;
 4724:   border: 0;
 4725:   background: $pgbg;
 4726:   font-family: $sans;
 4727:   border-collapse: collapse;
 4728:   padding: 0;
 4729: }
 4730: 
 4731: table#LC_title_bar td {
 4732:   background: $tabbg;
 4733: }
 4734: 
 4735: table#LC_title_bar .LC_title_bar_who {
 4736:   background: $tabbg;
 4737:   color: $fontmenu;
 4738:   font: small $sans;
 4739:   text-align: right;
 4740:   margin: 0;
 4741: }
 4742: 
 4743: table#LC_title_bar .LC_title_bar_name {
 4744:   margin: 0;
 4745: }
 4746: 
 4747: table#LC_title_bar .LC_title_bar_role {
 4748:   margin: 0;
 4749: }
 4750: 
 4751: table#LC_title_bar .LC_title_bar_realm {
 4752:   margin: 0;
 4753: }
 4754: 
 4755: span.LC_metadata {
 4756:   font-family: $sans;
 4757: }
 4758: 
 4759: table#LC_menubuttons img{
 4760:   border: none;
 4761: }
 4762: 
 4763: table#LC_top_nav td {
 4764:   background: $tabbg;
 4765:   border: none;
 4766:   font-size: small;
 4767:   vertical-align:top;
 4768:   padding:2px 5px 2px 5px;
 4769: }
 4770: 
 4771: table#LC_top_nav td a,
 4772: div#LC_top_nav a {
 4773:   color: $font;
 4774:   font-family: $sans;
 4775: }
 4776: 
 4777: table#LC_top_nav td.LC_top_nav_logo {
 4778:   background: $tabbg;
 4779:   text-align: left;
 4780:   white-space: nowrap;
 4781:   width: 31px;
 4782: }
 4783: 
 4784: table#LC_top_nav td.LC_top_nav_logo img {
 4785:   border: none;
 4786:   vertical-align: bottom;
 4787: }
 4788: 
 4789: table#LC_top_nav td.LC_top_nav_exit,
 4790: table#LC_top_nav td.LC_top_nav_help {
 4791:   width: 2.0em;
 4792: }
 4793: 
 4794: table#LC_top_nav td.LC_top_nav_login {
 4795:   width: 4.0em;
 4796:   text-align: center;
 4797: }
 4798: 
 4799: table.LC_breadcrumbs td,
 4800: table.LC_docs_path td  {
 4801:   background: $tabbg;
 4802:   color: $fontmenu;
 4803:   font-family: $sans;
 4804:   font-size: smaller;
 4805: }
 4806: 
 4807: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4808: table.LC_docs_path td.LC_docs_path_component {
 4809:   background: $tabbg;
 4810:   color: $fontmenu;
 4811:   font-family: $sans;
 4812:   font-size: larger;
 4813:   text-align: right;
 4814: }
 4815: 
 4816: td.LC_table_cell_checkbox {
 4817:   text-align: center;
 4818: }
 4819: 
 4820: table#LC_mainmenu td.LC_mainmenu_column {
 4821:     vertical-align: top;
 4822: }
 4823: 
 4824: .LC_fontsize_small {
 4825:  font-size: 70%;
 4826: }
 4827: 
 4828: .LC_fontsize_medium {
 4829:  font-size: 85%;
 4830: }
 4831: 
 4832: .LC_fontsize_large {
 4833:  font-size: 120%;
 4834: }
 4835: 
 4836: .LC_menubuttons_inline_text {
 4837:   color: $font;
 4838:   font-family: $sans;
 4839:   font-size: 90%;
 4840:   padding-left:3px;
 4841: }
 4842: 
 4843: .LC_menubuttons_link {
 4844:   text-decoration: none;
 4845: }
 4846: 
 4847: .LC_menubuttons_category {
 4848:   color: $font;
 4849:   background: $pgbg;
 4850:   font-family: $sans;
 4851:   font-size: larger;
 4852:   font-weight: bold;
 4853: }
 4854: 
 4855: td.LC_menubuttons_text {
 4856:  	color: $font;
 4857: }
 4858: 
 4859: .LC_current_location {
 4860:   font-family: $sans;
 4861:   background: $tabbg;
 4862: }
 4863: 
 4864: .LC_new_mail {
 4865:   font-family: $sans;
 4866:   background: $tabbg;
 4867:   font-weight: bold;
 4868: }
 4869: 
 4870: .LC_preferences_labeltext {
 4871:   font-family: $sans;
 4872:   text-align: right;
 4873: }
 4874: 
 4875: .LC_roleslog_note {
 4876:   font-size: small;
 4877: }
 4878: 
 4879: .LC_mail_functions {
 4880:     font-weight: bold;
 4881: }
 4882: 
 4883: table.LC_data_table,
 4884: table.LC_mail_list {
 4885:   border: 1px solid #000000;
 4886:   border-collapse: separate;
 4887:   border-spacing: 1px;
 4888:   background: $pgbg;
 4889: }
 4890: 
 4891: .LC_data_table_dense {
 4892:   font-size: small;
 4893: }
 4894: 
 4895: table.LC_nested_outer {
 4896:   border: 1px solid #000000;
 4897:   border-collapse: collapse;
 4898:   border-spacing: 0;
 4899:   width: 100%;
 4900: }
 4901: 
 4902: table.LC_nested {
 4903:   border: none;
 4904:   border-collapse: collapse;
 4905:   border-spacing: 0;
 4906:   width: 100%;
 4907: }
 4908: 
 4909: table.LC_data_table tr th, 
 4910: table.LC_calendar tr th, 
 4911: table.LC_mail_list tr th,
 4912: table.LC_prior_tries tr th {
 4913:   font-weight: bold;
 4914:   background-color: $data_table_head;
 4915:   color:$fontmenu;
 4916:   font-size:90%;
 4917: }
 4918: 
 4919: table.LC_data_table tr.LC_info_row > td {
 4920:   background-color: #CCCCCC;
 4921:   font-weight: bold;
 4922:   text-align: left;
 4923: }
 4924: 
 4925: table.LC_data_table tr.LC_odd_row > td,
 4926: table.LC_pick_box tr > td.LC_odd_row {
 4927:   background-color: $data_table_light;
 4928:   padding: 2px;
 4929: }
 4930: 
 4931: table.LC_data_table tr.LC_even_row > td,
 4932: table.LC_pick_box tr > td.LC_even_row {
 4933:   background-color: $data_table_dark;
 4934:   padding: 2px;
 4935: }
 4936: 
 4937: table.LC_data_table tr.LC_data_table_highlight td {
 4938:   background-color: $data_table_darker;
 4939: }
 4940: 
 4941: table.LC_data_table tr td.LC_leftcol_header {
 4942:   background-color: $data_table_head;
 4943:   font-weight: bold;
 4944: }
 4945: 
 4946: table.LC_data_table tr.LC_empty_row td,
 4947: table.LC_nested tr.LC_empty_row td {
 4948:   background-color: #FFFFFF;
 4949:   font-weight: bold;
 4950:   font-style: italic;
 4951:   text-align: center;
 4952:   padding: 8px;
 4953: }
 4954: 
 4955: table.LC_nested tr.LC_empty_row td {
 4956:   padding: 4ex
 4957: }
 4958: 
 4959: table.LC_nested_outer tr th {
 4960:   font-weight: bold;
 4961:   color:$fontmenu;
 4962:   background-color: $data_table_head;
 4963:   font-size: small;
 4964:   border-bottom: 1px solid #000000;
 4965: }
 4966: 
 4967: table.LC_nested_outer tr td.LC_subheader {
 4968:   background-color: $data_table_head;
 4969:   font-weight: bold;
 4970:   font-size: small;
 4971:   border-bottom: 1px solid #000000;
 4972:   text-align: right;
 4973: }
 4974: 
 4975: table.LC_nested tr.LC_info_row td {
 4976:   background-color: #CCCCCC;
 4977:   font-weight: bold;
 4978:   font-size: small;
 4979:   text-align: center;
 4980: }
 4981: 
 4982: table.LC_nested tr.LC_info_row td.LC_left_item,
 4983: table.LC_nested_outer tr th.LC_left_item {
 4984:   text-align: left;
 4985: }
 4986: 
 4987: table.LC_nested td {
 4988:   background-color: #FFFFFF;
 4989:   font-size: small;
 4990: }
 4991: 
 4992: table.LC_nested_outer tr th.LC_right_item,
 4993: table.LC_nested tr.LC_info_row td.LC_right_item,
 4994: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4995: table.LC_nested tr td.LC_right_item {
 4996:   text-align: right;
 4997: }
 4998: 
 4999: table.LC_nested tr.LC_odd_row td {
 5000:   background-color: #EEEEEE;
 5001: }
 5002: 
 5003: table.LC_createuser {
 5004: }
 5005: 
 5006: table.LC_createuser tr.LC_section_row td {
 5007:   font-size: small;
 5008: }
 5009: 
 5010: table.LC_createuser tr.LC_info_row td  {
 5011:   background-color: #CCCCCC;
 5012:   font-weight: bold;
 5013:   text-align: center;
 5014: }
 5015: 
 5016: table.LC_calendar {
 5017:   border: 1px solid #000000;
 5018:   border-collapse: collapse;
 5019: }
 5020: 
 5021: table.LC_calendar_pickdate {
 5022:   font-size: xx-small;
 5023: }
 5024: 
 5025: table.LC_calendar tr td {
 5026:   border: 1px solid #000000;
 5027:   vertical-align: top;
 5028: }
 5029: 
 5030: table.LC_calendar tr td.LC_calendar_day_empty {
 5031:   background-color: $data_table_dark;
 5032: }
 5033: 
 5034: table.LC_calendar tr td.LC_calendar_day_current {
 5035:   background-color: $data_table_highlight;
 5036: }
 5037: 
 5038: table.LC_mail_list tr.LC_mail_new {
 5039:   background-color: $mail_new;
 5040: }
 5041: 
 5042: table.LC_mail_list tr.LC_mail_new:hover {
 5043:   background-color: $mail_new_hover;
 5044: }
 5045: 
 5046: table.LC_mail_list tr.LC_mail_even {
 5047: }
 5048: 
 5049: table.LC_mail_list tr.LC_mail_odd {
 5050: }
 5051: 
 5052: table.LC_mail_list tr.LC_mail_read {
 5053:   background-color: $mail_read;
 5054: }
 5055: 
 5056: table.LC_mail_list tr.LC_mail_read:hover {
 5057:   background-color: $mail_read_hover;
 5058: }
 5059: 
 5060: table.LC_mail_list tr.LC_mail_replied {
 5061:   background-color: $mail_replied;
 5062: }
 5063: 
 5064: table.LC_mail_list tr.LC_mail_replied:hover {
 5065:   background-color: $mail_replied_hover;
 5066: }
 5067: 
 5068: table.LC_mail_list tr.LC_mail_other {
 5069:   background-color: $mail_other;
 5070: }
 5071: 
 5072: table.LC_mail_list tr.LC_mail_other:hover {
 5073:   background-color: $mail_other_hover;
 5074: }
 5075: 
 5076: table.LC_data_table tr > td.LC_browser_file,
 5077: table.LC_data_table tr > td.LC_browser_file_published {
 5078:   background: #CCFF88;
 5079: }
 5080: 
 5081: table.LC_data_table tr > td.LC_browser_file_locked,
 5082: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5083:   background: #FFAA99;
 5084: }
 5085: 
 5086: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5087:   background: #AAAAAA;
 5088: }
 5089: 
 5090: table.LC_data_table tr > td.LC_browser_file_modified,
 5091: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5092:   background: #FFFF77;
 5093: }
 5094: 
 5095: table.LC_data_table tr.LC_browser_folder > td {
 5096:   background: #CCCCFF;
 5097: }
 5098: 
 5099: table.LC_data_table tr > td.LC_roles_is {
 5100: /*  background: #77FF77; */
 5101: }
 5102: 
 5103: table.LC_data_table tr > td.LC_roles_future {
 5104:   background: #FFFF77;
 5105: }
 5106: 
 5107: table.LC_data_table tr > td.LC_roles_will {
 5108:   background: #FFAA77;
 5109: }
 5110: 
 5111: table.LC_data_table tr > td.LC_roles_expired {
 5112:   background: #FF7777;
 5113: }
 5114: 
 5115: table.LC_data_table tr > td.LC_roles_will_not {
 5116:   background: #AAFF77;
 5117: }
 5118: 
 5119: table.LC_data_table tr > td.LC_roles_selected {
 5120:   background: #11CC55;
 5121: }
 5122: 
 5123: span.LC_current_location {
 5124:   font-size:larger;
 5125:   background: $pgbg;
 5126: }
 5127: 
 5128: span.LC_parm_menu_item {
 5129:   font-size: larger;
 5130:   font-family: $sans;
 5131: }
 5132: 
 5133: span.LC_parm_scope_all {
 5134:   color: red;
 5135: }
 5136: 
 5137: span.LC_parm_scope_folder {
 5138:   color: green;
 5139: }
 5140: 
 5141: span.LC_parm_scope_resource {
 5142:   color: orange;
 5143: }
 5144: 
 5145: span.LC_parm_part {
 5146:   color: blue;
 5147: }
 5148: 
 5149: span.LC_parm_folder, span.LC_parm_symb {
 5150:   font-size: x-small;
 5151:   font-family: $mono;
 5152:   color: #AAAAAA;
 5153: }
 5154: 
 5155: td.LC_parm_overview_level_menu,
 5156: td.LC_parm_overview_map_menu,
 5157: td.LC_parm_overview_parm_selectors,
 5158: td.LC_parm_overview_restrictions  {
 5159:   border: 1px solid black;
 5160:   border-collapse: collapse;
 5161: }
 5162: 
 5163: table.LC_parm_overview_restrictions td {
 5164:   border-width: 1px 4px 1px 4px;
 5165:   border-style: solid;
 5166:   border-color: $pgbg;
 5167:   text-align: center;
 5168: }
 5169: 
 5170: table.LC_parm_overview_restrictions th {
 5171:   background: $tabbg;
 5172:   border-width: 1px 4px 1px 4px;
 5173:   border-style: solid;
 5174:   border-color: $pgbg;
 5175: }
 5176: 
 5177: table#LC_helpmenu {
 5178:   border: none;
 5179:   height: 55px;
 5180:   border-spacing: 0;
 5181: }
 5182: 
 5183: table#LC_helpmenu fieldset legend {
 5184:   font-size: larger;
 5185:   font-weight: bold;
 5186: }
 5187: 
 5188: table#LC_helpmenu_links {
 5189:   width: 100%;
 5190:   border: 1px solid black;
 5191:   background: $pgbg;
 5192:   padding: 0;
 5193:   border-spacing: 1px;
 5194: }
 5195: 
 5196: table#LC_helpmenu_links tr td {
 5197:   padding: 1px;
 5198:   background: $tabbg;
 5199:   text-align: center;
 5200:   font-weight: bold;
 5201: }
 5202: 
 5203: table#LC_helpmenu_links a:link,
 5204: table#LC_helpmenu_links a:visited,
 5205: table#LC_helpmenu_links a:active {
 5206:   text-decoration: none;
 5207:   color: $font;
 5208: }
 5209: 
 5210: table#LC_helpmenu_links a:hover {
 5211:   text-decoration: underline;
 5212:   color: $vlink;
 5213: }
 5214: 
 5215: .LC_chrt_popup_exists {
 5216:   border: 1px solid #339933;
 5217:   margin: -1px;
 5218: }
 5219: 
 5220: .LC_chrt_popup_up {
 5221:   border: 1px solid yellow;
 5222:   margin: -1px;
 5223: }
 5224: 
 5225: .LC_chrt_popup {
 5226:   border: 1px solid #8888FF;
 5227:   background: #CCCCFF;
 5228: }
 5229: 
 5230: table.LC_pick_box {
 5231:   border-collapse: separate;
 5232:   background: white;
 5233:   border: 1px solid black;
 5234:   border-spacing: 1px;
 5235: }
 5236: 
 5237: table.LC_pick_box td.LC_pick_box_title {
 5238:   background: $tabbg;
 5239:   font-weight: bold;
 5240:   text-align: right;
 5241:   vertical-align: top;
 5242:   width: 184px;
 5243:   padding: 8px;
 5244: }
 5245: 
 5246: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5247:   background: $tabbg;
 5248:   font-weight: bold;
 5249:   text-align: right;
 5250:   width: 350px;
 5251:   padding: 8px;
 5252: }
 5253: 
 5254: table.LC_pick_box td.LC_pick_box_value {
 5255:   text-align: left;
 5256:   padding: 8px;
 5257: }
 5258: 
 5259: table.LC_pick_box td.LC_pick_box_select {
 5260:   text-align: left;
 5261:   padding: 8px;
 5262: }
 5263: 
 5264: table.LC_pick_box td.LC_pick_box_separator {
 5265:   padding: 0;
 5266:   height: 1px;
 5267:   background: black;
 5268: }
 5269: 
 5270: table.LC_pick_box td.LC_pick_box_submit {
 5271:   text-align: right;
 5272: }
 5273: 
 5274: table.LC_pick_box td.LC_evenrow_value {
 5275:   text-align: left;
 5276:   padding: 8px;
 5277:   background-color: $data_table_light;
 5278: }
 5279: 
 5280: table.LC_pick_box td.LC_oddrow_value {
 5281:   text-align: left;
 5282:   padding: 8px;
 5283:   background-color: $data_table_light;
 5284: }
 5285: 
 5286: table.LC_helpform_receipt {
 5287:   width: 620px;
 5288:   border-collapse: separate;
 5289:   background: white;
 5290:   border: 1px solid black;
 5291:   border-spacing: 1px;
 5292: }
 5293: 
 5294: table.LC_helpform_receipt td.LC_pick_box_title {
 5295:   background: $tabbg;
 5296:   font-weight: bold;
 5297:   text-align: right;
 5298:   width: 184px;
 5299:   padding: 8px;
 5300: }
 5301: 
 5302: table.LC_helpform_receipt td.LC_evenrow_value {
 5303:   text-align: left;
 5304:   padding: 8px;
 5305:   background-color: $data_table_light;
 5306: }
 5307: 
 5308: table.LC_helpform_receipt td.LC_oddrow_value {
 5309:   text-align: left;
 5310:   padding: 8px;
 5311:   background-color: $data_table_light;
 5312: }
 5313: 
 5314: table.LC_helpform_receipt td.LC_pick_box_separator {
 5315:   padding: 0;
 5316:   height: 1px;
 5317:   background: black;
 5318: }
 5319: 
 5320: span.LC_helpform_receipt_cat {
 5321:   font-weight: bold;
 5322: }
 5323: 
 5324: table.LC_group_priv_box {
 5325:   background: white;
 5326:   border: 1px solid black;
 5327:   border-spacing: 1px;
 5328: }
 5329: 
 5330: table.LC_group_priv_box td.LC_pick_box_title {
 5331:   background: $tabbg;
 5332:   font-weight: bold;
 5333:   text-align: right;
 5334:   width: 184px;
 5335: }
 5336: 
 5337: table.LC_group_priv_box td.LC_groups_fixed {
 5338:   background: $data_table_light;
 5339:   text-align: center;
 5340: }
 5341: 
 5342: table.LC_group_priv_box td.LC_groups_optional {
 5343:   background: $data_table_dark;
 5344:   text-align: center;
 5345: }
 5346: 
 5347: table.LC_group_priv_box td.LC_groups_functionality {
 5348:   background: $data_table_darker;
 5349:   text-align: center;
 5350:   font-weight: bold;
 5351: }
 5352: 
 5353: table.LC_group_priv td {
 5354:   text-align: left;
 5355:   padding: 0;
 5356: }
 5357: 
 5358: table.LC_notify_front_page {
 5359:   background: white;
 5360:   border: 1px solid black;
 5361:   padding: 8px;
 5362: }
 5363: 
 5364: table.LC_notify_front_page td {
 5365:   padding: 8px;
 5366: }
 5367: 
 5368: .LC_navbuttons {
 5369:   margin: 2ex 0ex 2ex 0ex;
 5370: }
 5371: 
 5372: .LC_topic_bar {
 5373:   font-family: $sans;
 5374:   font-weight: bold;
 5375:   width: 100%;
 5376:   background: $tabbg;
 5377:   vertical-align: middle;
 5378:   margin: 2ex 0ex 2ex 0ex;
 5379:   padding: 3px;
 5380: }
 5381: 
 5382: .LC_topic_bar span {
 5383:   vertical-align: middle;
 5384: }
 5385: 
 5386: .LC_topic_bar img {
 5387:   vertical-align: bottom;
 5388: }
 5389: 
 5390: table.LC_course_group_status {
 5391:   margin: 20px;
 5392: }
 5393: 
 5394: table.LC_status_selector td {
 5395:   vertical-align: top;
 5396:   text-align: center;
 5397:   padding: 4px;
 5398: }
 5399: 
 5400: div.LC_feedback_link {
 5401:   clear: both;
 5402:   background: white;
 5403:   width: 100%;
 5404: }
 5405: 
 5406: span.LC_feedback_link {
 5407:   background: $feedback_link_bg;
 5408:   font-size: larger;
 5409: }
 5410: 
 5411: span.LC_message_link {
 5412:   background: $feedback_link_bg;
 5413:   font-size: larger;
 5414:   position: absolute;
 5415:   right: 1em;
 5416: }
 5417: 
 5418: table.LC_prior_tries {
 5419:   border: 1px solid #000000;
 5420:   border-collapse: separate;
 5421:   border-spacing: 1px;
 5422: }
 5423: 
 5424: table.LC_prior_tries td {
 5425:   padding: 2px;
 5426: }
 5427: 
 5428: .LC_answer_correct {
 5429:   background: lightgreen;
 5430:   font-family: $sans;
 5431:   color: darkgreen;
 5432:   padding: 6px;
 5433: }
 5434: 
 5435: .LC_answer_charged_try {
 5436:   background: #FFAAAA;
 5437:   font-family: $sans;
 5438:   color: darkred;
 5439:   padding: 6px;
 5440: }
 5441: 
 5442: .LC_answer_not_charged_try,
 5443: .LC_answer_no_grade,
 5444: .LC_answer_late {
 5445:   background: lightyellow;
 5446:   font-family: $sans;
 5447:   color: black;
 5448:   padding: 6px;
 5449: }
 5450: 
 5451: .LC_answer_previous {
 5452:   background: lightblue;
 5453:   font-family: $sans;
 5454:   color: darkblue;
 5455:   padding: 6px;
 5456: }
 5457: 
 5458: .LC_answer_no_message {
 5459:   background: #FFFFFF;
 5460:   font-family: $sans;
 5461:   color: black;
 5462:   padding: 6px;
 5463: }
 5464: 
 5465: .LC_answer_unknown {
 5466:   background: orange;
 5467:   font-family: $sans;
 5468:   color: black;
 5469:   padding: 6px;
 5470: }
 5471: 
 5472: span.LC_prior_numerical,
 5473: span.LC_prior_string,
 5474: span.LC_prior_custom,
 5475: span.LC_prior_reaction,
 5476: span.LC_prior_math {
 5477:   font-family: monospace;
 5478:   white-space: pre;
 5479: }
 5480: 
 5481: span.LC_prior_string {
 5482:   font-family: monospace;
 5483:   white-space: pre;
 5484: }
 5485: 
 5486: table.LC_prior_option {
 5487:   width: 100%;
 5488:   border-collapse: collapse;
 5489: }
 5490: 
 5491: table.LC_prior_rank, 
 5492: table.LC_prior_match {
 5493:   border-collapse: collapse;
 5494: }
 5495: 
 5496: table.LC_prior_option tr td,
 5497: table.LC_prior_rank tr td,
 5498: table.LC_prior_match tr td {
 5499:   border: 1px solid #000000;
 5500: }
 5501: 
 5502: td.LC_nobreak,
 5503: span.LC_nobreak {
 5504:   white-space: nowrap;
 5505: }
 5506: 
 5507: span.LC_cusr_emph {
 5508:   font-style: italic;
 5509: }
 5510: 
 5511: span.LC_cusr_subheading {
 5512:   font-weight: normal;
 5513:   font-size: 85%;
 5514: }
 5515: 
 5516: table.LC_docs_documents {
 5517:   background: #BBBBBB;
 5518:   border-width: 0;
 5519:   border-collapse: collapse;
 5520: }
 5521: 
 5522: table.LC_docs_documents td.LC_docs_document {
 5523:   border: 2px solid black;
 5524:   padding: 4px;
 5525: }
 5526: 
 5527: .LC_docs_entry_move {
 5528:   border: none;
 5529:   border-collapse: collapse;
 5530: }
 5531: 
 5532: .LC_docs_entry_move td {
 5533:   border: 2px solid #BBBBBB;
 5534:   background: #DDDDDD;
 5535: }
 5536: 
 5537: .LC_docs_editor td.LC_docs_entry_commands {
 5538:   background: #DDDDDD;
 5539:   font-size: x-small;
 5540: }
 5541: 
 5542: .LC_docs_copy {
 5543:   color: #000099;
 5544: }
 5545: 
 5546: .LC_docs_cut {
 5547:   color: #550044;
 5548: }
 5549: 
 5550: .LC_docs_rename {
 5551:   color: #009900;
 5552: }
 5553: 
 5554: .LC_docs_remove {
 5555:   color: #990000;
 5556: }
 5557: 
 5558: .LC_docs_reinit_warn,
 5559: .LC_docs_ext_edit {
 5560:   font-size: x-small;
 5561: }
 5562: 
 5563: .LC_docs_editor td.LC_docs_entry_title,
 5564: .LC_docs_editor td.LC_docs_entry_icon {
 5565:   background: #FFFFBB;
 5566: }
 5567: 
 5568: .LC_docs_editor td.LC_docs_entry_parameter {
 5569:   background: #BBBBFF;
 5570:   font-size: x-small;
 5571:   white-space: nowrap;
 5572: }
 5573: 
 5574: table.LC_docs_adddocs td,
 5575: table.LC_docs_adddocs th {
 5576:   border: 1px solid #BBBBBB;
 5577:   padding: 4px;
 5578:   background: #DDDDDD;
 5579: }
 5580: 
 5581: table.LC_sty_begin {
 5582:   background: #BBFFBB;
 5583: }
 5584: 
 5585: table.LC_sty_end {
 5586:   background: #FFBBBB;
 5587: }
 5588: 
 5589: table.LC_double_column {
 5590:   border-width: 0;
 5591:   border-collapse: collapse;
 5592:   width: 100%;
 5593:   padding: 2px;
 5594: }
 5595: 
 5596: table.LC_double_column tr td.LC_left_col {
 5597:   top: 2px;
 5598:   left: 2px;
 5599:   width: 47%;
 5600:   vertical-align: top;
 5601: }
 5602: 
 5603: table.LC_double_column tr td.LC_right_col {
 5604:   top: 2px;
 5605:   right: 2px;
 5606:   width: 47%;
 5607:   vertical-align: top;
 5608: }
 5609: 
 5610: span.LC_role_level {
 5611:   font-weight: bold;
 5612: }
 5613: 
 5614: div.LC_left_float {
 5615:   float: left;
 5616:   padding-right: 5%;
 5617:   padding-bottom: 4px;
 5618: }
 5619: 
 5620: div.LC_clear_float_header {
 5621:   padding-bottom: 2px;
 5622: }
 5623: 
 5624: div.LC_clear_float_footer {
 5625:   padding-top: 10px;
 5626:   clear: both;
 5627: }
 5628: 
 5629: div.LC_grade_show_user {
 5630:   margin-top: 20px;
 5631:   border: 1px solid black;
 5632: }
 5633: 
 5634: div.LC_grade_user_name {
 5635:   background: #DDDDEE;
 5636:   border-bottom: 1px solid black;
 5637:   font-weight: bold;
 5638:   font-size: large;
 5639: }
 5640: 
 5641: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5642:   background: #DDEEDD;
 5643: }
 5644: 
 5645: div.LC_grade_show_problem,
 5646: div.LC_grade_submissions,
 5647: div.LC_grade_message_center,
 5648: div.LC_grade_info_links,
 5649: div.LC_grade_assign {
 5650:   margin: 5px;
 5651:   width: 99%;
 5652:   background: #FFFFFF;
 5653: }
 5654: 
 5655: div.LC_grade_show_problem_header,
 5656: div.LC_grade_submissions_header,
 5657: div.LC_grade_message_center_header,
 5658: div.LC_grade_assign_header {
 5659:   font-weight: bold;
 5660:   font-size: large;
 5661: }
 5662: 
 5663: div.LC_grade_show_problem_problem,
 5664: div.LC_grade_submissions_body,
 5665: div.LC_grade_message_center_body,
 5666: div.LC_grade_assign_body {
 5667:   border: 1px solid black;
 5668:   width: 99%;
 5669:   background: #FFFFFF;
 5670: }
 5671: 
 5672: span.LC_grade_check_note {
 5673:   font-weight: normal;
 5674:   font-size: medium;
 5675:   display: inline;
 5676:   position: absolute;
 5677:   right: 1em;
 5678: }
 5679: 
 5680: table.LC_scantron_action {
 5681:   width: 100%;
 5682: }
 5683: 
 5684: table.LC_scantron_action tr th {
 5685:   font-weight:bold;
 5686:   font-style:normal;
 5687: }
 5688: 
 5689: .LC_edit_problem_header,
 5690: div.LC_edit_problem_footer {
 5691:   font-weight: normal;
 5692:   font-size:  medium;
 5693:   margin: 2px;
 5694: }
 5695: 
 5696: div.LC_edit_problem_header,
 5697: div.LC_edit_problem_header div,
 5698: div.LC_edit_problem_footer,
 5699: div.LC_edit_problem_footer div,
 5700: div.LC_edit_problem_editxml_header,
 5701: div.LC_edit_problem_editxml_header div {
 5702:   margin-top: 5px;
 5703: }
 5704: 
 5705: div.LC_edit_problem_header_edit_row {
 5706:   background: $tabbg;
 5707:   padding: 3px;
 5708:   margin-bottom: 5px;
 5709: }
 5710: 
 5711: div.LC_edit_problem_header_title {
 5712:   font-weight: bold;
 5713:   font-size: larger;
 5714:   background: $tabbg;
 5715:   padding: 3px;
 5716: }
 5717: 
 5718: table.LC_edit_problem_header_title {
 5719:   font-size: larger;
 5720:   font-weight:  bold;
 5721:   width: 100%;
 5722:   border-color: $pgbg;
 5723:   border-style: solid;
 5724:   border-width: $border;
 5725:   background: $tabbg;
 5726:   border-collapse: collapse;
 5727:   padding: 0;
 5728: }
 5729: 
 5730: div.LC_edit_problem_discards {
 5731:   float: left;
 5732:   padding-bottom: 5px;
 5733: }
 5734: 
 5735: div.LC_edit_problem_saves {
 5736:   float: right;
 5737:   padding-bottom: 5px;
 5738: }
 5739: 
 5740: hr.LC_edit_problem_divide {
 5741:   clear: both;
 5742:   color: $tabbg;
 5743:   background-color: $tabbg;
 5744:   height: 3px;
 5745:   border: none;
 5746: }
 5747: 
 5748: img.stift{
 5749:   border-width: 0;
 5750:   vertical-align: middle;
 5751: }
 5752: 
 5753: table#LC_mainmenu{
 5754:  margin-top:10px;
 5755:  width:80%;
 5756: }
 5757: 
 5758: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5759:   vertical-align: top;
 5760:   width: 45%;
 5761: }
 5762: 
 5763: .LC_mainmenu_fieldset_category {
 5764:   color: $font;
 5765:   background: $pgbg;
 5766:   font-family: $sans;
 5767:   font-size: small;
 5768:   font-weight: bold;
 5769: }
 5770: 
 5771: div.LC_createcourse {
 5772:     margin: 10px 10px 10px 10px;
 5773: }
 5774: 
 5775: /* ---- Remove when done ----
 5776: # The following styles is part of the redesign of LON-CAPA and are
 5777: # subject to change during this project.
 5778: # Don't rely on their current functionality as they might be 
 5779: # changed or removed.
 5780: # --------------------------*/
 5781: 
 5782: a:hover,
 5783: ol.LC_smallMenu a:hover,
 5784: ol#LC_MenuBreadcrumbs a:hover,
 5785: ol#LC_PathBreadcrumbs a:hover,
 5786: ul#LC_TabMainMenuContent a:hover,
 5787: .LC_FormSectionClearButton input:hover
 5788: ul.LC_TabContent   li:hover a {
 5789: 	color:#BF2317;
 5790:         text-decoration:none;
 5791: }
 5792: 
 5793: h1 {
 5794: 	padding: 0;
 5795: 	line-height:130%;
 5796: }
 5797: 
 5798: h2,h3,h4,h5,h6 {
 5799: 	margin: 5px 0 5px 0;
 5800: 	padding: 0;
 5801: 	line-height:130%;
 5802: }
 5803: 
 5804: .LC_hcell {
 5805:         padding:3px 15px 3px 15px;
 5806:         margin: 0;
 5807: 	background-color:$tabbg;
 5808: 	color:$fontmenu;
 5809: 	border-bottom:solid 1px $lg_border_color;
 5810: }
 5811: 
 5812: .LC_noBorder {
 5813:         border: 0;
 5814: }
 5815: 
 5816: 
 5817: /* Main Header with discription of Person, Course, etc. */
 5818: 
 5819: .LC_Right {
 5820:         float: right;
 5821:         margin: 0;
 5822:         padding: 0;
 5823: }
 5824: 
 5825: .LC_FormSectionClearButton input {
 5826:         background-color:transparent;
 5827:         border: none;
 5828:         cursor:pointer;
 5829:         text-decoration:underline;
 5830: }
 5831: 
 5832: .LC_help_open_topic {
 5833:         color: #FFFFFF;
 5834:         background-color: #EEEEFF;
 5835:         margin: 1px;
 5836:         padding: 4px;
 5837:         border: 1px solid #000033;
 5838:         white-space: nowrap;
 5839: /*		vertical-align: middle; */
 5840: }
 5841: 
 5842: dl,ul,div,fieldset {
 5843: 	margin: 10px 10px 10px 0;
 5844: /*	overflow: hidden; */
 5845: }
 5846: 
 5847: #LC_nav_bar {
 5848:     float: left;
 5849:     margin: 0;
 5850: }
 5851: 
 5852: #LC_nav_bar em{
 5853:     font-weight: bold;
 5854:     font-style: normal;
 5855: }
 5856: 
 5857: ol.LC_smallMenu {
 5858:     float: right;
 5859: }
 5860: 
 5861: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5862: 	margin: 0;
 5863: }
 5864: 
 5865: ol.LC_smallMenu li {
 5866: 	display: inline;
 5867: 	padding: 5px 5px 0 10px;
 5868: 	vertical-align: top;
 5869: }
 5870: 
 5871: ol.LC_smallMenu li img {
 5872: 	vertical-align: bottom;
 5873: }
 5874: 
 5875: ol.LC_smallMenu a {
 5876: 	font-size: 90%;
 5877: 	color: RGB(80, 80, 80);
 5878: 	text-decoration: none;
 5879: }
 5880: 
 5881: ul#LC_TabMainMenuContent {
 5882:     clear: both;
 5883:     color: $fontmenu;
 5884:     background: $tabbg;
 5885:     list-style: none;
 5886:     padding: 0;
 5887:     margin: 0;
 5888:     float:left;
 5889:     width: 100%;
 5890: }
 5891: 
 5892: ul#LC_TabMainMenuContent li {
 5893:     float: left;
 5894:     font-weight: bold;
 5895:     line-height: 1.8em;
 5896:     padding: 0 0.8em; 
 5897:     border-right: 1px solid black;
 5898:     display: inline;
 5899:     vertical-align: middle;
 5900: }
 5901: 
 5902: ul.LC_TabContent ,
 5903: ul.LC_TabContentBigger {
 5904: 	display:block;
 5905: 	list-style:none;
 5906: 	margin: 0;
 5907: 	padding: 0;
 5908: }
 5909: 
 5910: ul.LC_TabContent li,
 5911: ul.LC_TabContentBigger li {
 5912: 	display: inline;
 5913: 	border-right: solid 1px $lg_border_color;
 5914: 	float:left;
 5915: 	line-height:140%;
 5916: 	white-space:nowrap;
 5917: }
 5918: 
 5919: ul#LC_TabMainMenuContent li a {
 5920:     color: $fontmenu;
 5921: 	text-decoration: none;
 5922: }
 5923: 
 5924: ul.LC_TabContent {
 5925: 	min-height:1.6em;
 5926: }
 5927: 
 5928: ul.LC_TabContent li {
 5929: 	vertical-align:middle;
 5930: 	padding: 0 10px 0 10px;
 5931: 	background-color:$tabbg;
 5932: 	border-bottom:solid 1px $lg_border_color;
 5933: }
 5934: 
 5935: ul.LC_TabContent li a, ul.LC_TabContent li {
 5936: 	color:rgb(47,47,47);
 5937: 	text-decoration:none;
 5938: 	font-size:95%;
 5939: 	font-weight:bold;
 5940: 	padding-right: 16px;
 5941: }
 5942: 
 5943: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
 5944:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5945: 	border-bottom:solid 1px #FFFFFF;
 5946: 	padding-right: 16px;
 5947: }
 5948: 
 5949: ul.LC_TabContentBigger li {
 5950: 	vertical-align:bottom;
 5951: 	border-top:solid 1px $lg_border_color;
 5952: 	border-left:solid 1px $lg_border_color;
 5953: 	padding:5px 10px 5px 10px;
 5954: 	margin-left:2px;
 5955: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5956: }
 5957: 
 5958: ul.LC_TabContentBigger li:hover, 
 5959: ul.LC_TabContentBigger li.active {
 5960: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5961: }
 5962: 
 5963: ul.LC_TabContentBigger li, 
 5964: ul.LC_TabContentBigger li a {
 5965: 	font-size:110%;
 5966: 	font-weight:bold;
 5967: }
 5968: 
 5969: ol#LC_MenuBreadcrumbs, 
 5970: ol#LC_PathBreadcrumbs, 
 5971: ul.LC_CourseBreadcrumbs {
 5972: 	border-top: solid 1px RGB(255, 255, 255);
 5973: 	height: 20px;
 5974: 	line-height: 20px;
 5975: 	vertical-align: bottom;
 5976: 	margin: 0 0 30px 0;
 5977: 	padding-left: 10px;
 5978: 	list-style-position: inside;
 5979: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5980: }
 5981: 
 5982: ol#LC_MenuBreadcrumbs li, 
 5983: ol#LC_PathBreadcrumbs li, 
 5984: ul.LC_CourseBreadcrumbs li {
 5985: /*
 5986: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5987: */
 5988: 	display: inline;
 5989: 	padding: 0 0 0 10px;
 5990: /*	vertical-align: bottom; */
 5991: 	overflow:hidden;
 5992: }
 5993: 
 5994: ol#LC_MenuBreadcrumbs li a, ul.LC_CourseBreadcrumbs li a {
 5995: 	text-decoration: none;
 5996: 	font-size:90%;
 5997: }
 5998: 
 5999: ol#LC_PathBreadcrumbs li a {
 6000: 	text-decoration:none;
 6001: 	font-size:100%;
 6002: 	font-weight:bold;
 6003: }
 6004: 
 6005: .LC_BoxPadding {
 6006: 	padding: 10px;
 6007: }
 6008: 
 6009: .LC_ContentBoxSpecial {
 6010: 	border: solid 1px $lg_border_color;
 6011: }
 6012: 
 6013: .LC_ContentBoxSpecialContactInfo {
 6014: 	border: solid 1px $lg_border_color;
 6015: 	max-width:25%;
 6016: 	min-width:25%;
 6017: }
 6018: 
 6019: .LC_AboutMe_Image {
 6020: 	float:left;
 6021: 	margin-right:10px;
 6022: }
 6023: 
 6024: .LC_Clear_AboutMe_Image {
 6025: 	clear:left;
 6026: }
 6027: 
 6028: dl.LC_ListStyleClean dt {
 6029: 	padding-right: 5px;
 6030: 	display: table-header-group;
 6031: }
 6032: 
 6033: dl.LC_ListStyleClean dd {
 6034: 	display: table-row;
 6035: }
 6036: 
 6037: .LC_ListStyleClean,
 6038: .LC_ListStyleSimple,
 6039: .LC_ListStyleNormal,
 6040: .LC_ListStyle_Border,
 6041: .LC_ListStyleSpecial {
 6042: 	/*display:block;	*/
 6043: 	list-style-position: inside;
 6044: 	list-style-type: none;
 6045: 	overflow: hidden;
 6046: 	padding: 0;
 6047: }
 6048: 
 6049: .LC_ListStyleSimple li,
 6050: .LC_ListStyleSimple dd,
 6051: .LC_ListStyleNormal li,
 6052: .LC_ListStyleNormal dd,
 6053: .LC_ListStyleSpecial li,
 6054: .LC_ListStyleSpecial dd {
 6055: 	margin: 0;
 6056: 	padding: 5px 5px 5px 10px;
 6057: 	clear: both;
 6058: }
 6059: 
 6060: .LC_ListStyleClean li,
 6061: .LC_ListStyleClean dd {
 6062: 	padding-top: 0;
 6063: 	padding-bottom: 0;
 6064: }
 6065: 
 6066: .LC_ListStyleSimple dd,
 6067: .LC_ListStyleSimple li {
 6068: 	border-bottom: solid 1px $lg_border_color;
 6069: }
 6070: 
 6071: .LC_ListStyleSpecial li,
 6072: .LC_ListStyleSpecial dd {
 6073: 	list-style-type: none;
 6074: 	background-color: RGB(220, 220, 220);
 6075: 	margin-bottom: 4px;
 6076: }
 6077: 
 6078: table.LC_SimpleTable {
 6079: 	margin:5px;
 6080: 	border:solid 1px $lg_border_color;
 6081: }
 6082: 
 6083: table.LC_SimpleTable tr {
 6084: 	padding: 0;
 6085: 	border:solid 1px $lg_border_color;
 6086: }
 6087: 
 6088: table.LC_SimpleTable thead {
 6089: 	 background:rgb(220,220,220);
 6090: }
 6091: 
 6092: div.LC_columnSection {
 6093: 	display: block;
 6094: 	clear: both;
 6095: 	overflow: hidden;
 6096: 	margin: 0;
 6097: }
 6098: 
 6099: div.LC_columnSection>* {
 6100: 	float: left;
 6101: 	margin: 10px 20px 10px 0;
 6102: 	overflow:hidden;
 6103: }
 6104: 
 6105: .ContentBoxSpecialTemplate {
 6106:         border: solid 1px $lg_border_color;
 6107: }
 6108: 
 6109: .ContentBoxTemplate {
 6110:         padding:10px;
 6111: }
 6112: 
 6113: div.LC_columnSection > .ContentBoxTemplate,
 6114: div.LC_columnSection > .ContentBoxSpecialTemplate {
 6115:         width: 600px;
 6116: }
 6117: 
 6118: .clear {
 6119: 	clear: both;
 6120: 	line-height: 0;
 6121: 	font-size: 0;
 6122: 	height: 0;
 6123: }
 6124: 
 6125: .LC_loginpage_container {
 6126: 	text-align:left;
 6127: 	margin : 0 auto;
 6128: 	width:90%;
 6129: 	padding: 10px;
 6130: 	height: auto;
 6131: 	background-color:#FFFFFF;
 6132: 	border:1px solid #CCCCCC;
 6133: }
 6134: 
 6135: 
 6136: .LC_loginpage_loginContainer {
 6137: 	float:left;
 6138: 	width: 182px;
 6139: 	padding: 2px;
 6140: 	border:1px solid #CCCCCC;
 6141: 	background-color:$loginbg;
 6142: }
 6143: 
 6144: .LC_loginpage_loginContainer h2 {
 6145: 	margin-top: 0;
 6146: 	display:block;
 6147: 	background:$bgcol;
 6148: 	color:$textcol;
 6149: 	padding-left:5px;
 6150: }
 6151: 
 6152: .LC_loginpage_loginInfo {
 6153: 	float:left;
 6154: 	width:182px;
 6155: 	border:1px solid #CCCCCC;
 6156: 	padding:2px;
 6157: }
 6158: 
 6159: .LC_loginpage_space {
 6160: 	clear: both;
 6161: 	margin-bottom: 20px;
 6162: 	border-bottom: 1px solid #CCCCCC;
 6163: }
 6164: 
 6165: .LC_loginpage_floatLeft {
 6166: 	float: left;
 6167: 	width: 200px;
 6168: 	margin: 0;
 6169: }
 6170: 
 6171: table em {
 6172: 	font-weight: bold;
 6173: 	font-style: normal;
 6174: }
 6175: 
 6176: table.LC_tableBrowseRes,
 6177: table.LC_tableOfContent {
 6178:         border:none;
 6179: 	border-spacing: 1;
 6180: 	padding: 3px;
 6181: 	background-color: #FFFFFF;
 6182: 	font-size: 90%;
 6183: }
 6184: 
 6185: table.LC_tableOfContent{
 6186:     border-collapse: collapse;
 6187: }
 6188: 
 6189: table.LC_tableBrowseRes a,
 6190: table.LC_tableOfContent a {
 6191:         background-color: transparent;
 6192: 	text-decoration: none;
 6193: }
 6194: 
 6195: table.LC_tableBrowseRes tr.LC_trOdd,
 6196: table.LC_tableOfContent tr.LC_trOdd{
 6197: 	background-color: #EEEEEE;
 6198: }
 6199: 
 6200: table.LC_tableOfContent img {
 6201: 	border: none;
 6202: 	height: 1.3em;
 6203: 	vertical-align: text-bottom;
 6204: 	margin-right: 0.3em;
 6205: }
 6206: 
 6207: a#LC_content_toolbar_firsthomework {
 6208: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 6209: }
 6210: 
 6211: a#LC_content_toolbar_launchnav {
 6212: 	background-image:url(/res/adm/pages/start-navigation.gif);
 6213: }
 6214: 
 6215: a#LC_content_toolbar_closenav {
 6216: 	background-image:url(/res/adm/pages/close-navigation.gif);
 6217: }
 6218: 
 6219: a#LC_content_toolbar_everything {
 6220: 	background-image:url(/res/adm/pages/show-all.gif);
 6221: }
 6222: 
 6223: a#LC_content_toolbar_uncompleted {
 6224: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6225: }
 6226: 
 6227: #LC_content_toolbar_clearbubbles {
 6228: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6229: }
 6230: 
 6231: a#LC_content_toolbar_changefolder {
 6232: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6233: }
 6234: 
 6235: a#LC_content_toolbar_changefolder_toggled {
 6236: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 6237: }
 6238: 
 6239: ul#LC_toolbar li a:hover {
 6240: 	background-position: bottom center;
 6241: }
 6242: 
 6243: ul#LC_toolbar {
 6244: 	padding: 0;
 6245: 	margin: 2px;
 6246: 	list-style:none;
 6247: 	position:relative;
 6248: 	background-color:white;
 6249: }
 6250: 
 6251: ul#LC_toolbar li {
 6252: 	border:1px solid white;
 6253: 	padding: 0;
 6254: 	margin: 0;
 6255:         float: left;
 6256: 	display:inline;
 6257: 	vertical-align:middle;
 6258: } 
 6259: 
 6260: 
 6261: a.LC_toolbarItem {
 6262: 	display:block;
 6263: 	padding: 0;
 6264: 	margin: 0;
 6265: 	height: 32px;
 6266: 	width: 32px;
 6267: 	color:white;
 6268: 	border: none;
 6269: 	background-repeat:no-repeat;
 6270: 	background-color:transparent;
 6271: }
 6272: 
 6273: ul.LC_functionslist li {
 6274:   float: left;
 6275:   white-space: nowrap;
 6276:   height: 35px; /* at least as high as heighest list item */
 6277:   margin: 0 15px 15px 10px;
 6278: }
 6279: 
 6280: 
 6281: END
 6282: }
 6283: 
 6284: =pod
 6285: 
 6286: =item * &headtag()
 6287: 
 6288: Returns a uniform footer for LON-CAPA web pages.
 6289: 
 6290: Inputs: $title - optional title for the head
 6291:         $head_extra - optional extra HTML to put inside the <head>
 6292:         $args - optional arguments
 6293:             force_register - if is true call registerurl so the remote is 
 6294:                              informed
 6295:             redirect       -> array ref of
 6296:                                    1- seconds before redirect occurs
 6297:                                    2- url to redirect to
 6298:                                    3- whether the side effect should occur
 6299:                            (side effect of setting 
 6300:                                $env{'internal.head.redirect'} to the url 
 6301:                                redirected too)
 6302:             domain         -> force to color decorate a page for a specific
 6303:                                domain
 6304:             function       -> force usage of a specific rolish color scheme
 6305:             bgcolor        -> override the default page bgcolor
 6306:             no_auto_mt_title
 6307:                            -> prevent &mt()ing the title arg
 6308: 
 6309: =cut
 6310: 
 6311: sub headtag {
 6312:     my ($title,$head_extra,$args) = @_;
 6313:     
 6314:     my $function = $args->{'function'} || &get_users_function();
 6315:     my $domain   = $args->{'domain'}   || &determinedomain();
 6316:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6317:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6318: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6319: 		   #time(),
 6320: 		   $env{'environment.color.timestamp'},
 6321: 		   $function,$domain,$bgcolor);
 6322: 
 6323:     $url = '/adm/css/'.&escape($url).'.css';
 6324: 
 6325:     my $result =
 6326: 	'<head>'.
 6327: 	&font_settings();
 6328: 
 6329:     if (!$args->{'frameset'}) {
 6330: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6331:     }
 6332:     if ($args->{'force_register'}) {
 6333: 	$result .= &Apache::lonmenu::registerurl(1);
 6334:     }
 6335:     if (!$args->{'no_nav_bar'} 
 6336: 	&& !$args->{'only_body'}
 6337: 	&& !$args->{'frameset'}) {
 6338: 	$result .= &help_menu_js();
 6339:     }
 6340: 
 6341:     if (ref($args->{'redirect'})) {
 6342: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6343: 	$url = &Apache::lonenc::check_encrypt($url);
 6344: 	if (!$inhibit_continue) {
 6345: 	    $env{'internal.head.redirect'} = $url;
 6346: 	}
 6347: 	$result.=<<ADDMETA
 6348: <meta http-equiv="pragma" content="no-cache" />
 6349: <meta http-equiv="Refresh" content="$time; url=$url" />
 6350: ADDMETA
 6351:     }
 6352:     if (!defined($title)) {
 6353: 	$title = 'The LearningOnline Network with CAPA';
 6354:     }
 6355:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6356:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6357: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6358: 	.$head_extra;
 6359:     return $result;
 6360: }
 6361: 
 6362: =pod
 6363: 
 6364: =item * &font_settings()
 6365: 
 6366: Returns neccessary <meta> to set the proper encoding
 6367: 
 6368: Inputs: none
 6369: 
 6370: =cut
 6371: 
 6372: sub font_settings {
 6373:     my $headerstring='';
 6374:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6375: 	$headerstring.=
 6376: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6377:     }
 6378:     return $headerstring;
 6379: }
 6380: 
 6381: =pod
 6382: 
 6383: =item * &xml_begin()
 6384: 
 6385: Returns the needed doctype and <html>
 6386: 
 6387: Inputs: none
 6388: 
 6389: =cut
 6390: 
 6391: sub xml_begin {
 6392:     my $output='';
 6393: 
 6394:     if ($env{'internal.start_page'}==1) {
 6395: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6396:     }
 6397: 
 6398:     if ($env{'browser.mathml'}) {
 6399: 	$output='<?xml version="1.0"?>'
 6400:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6401: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6402:             
 6403: #	    .'<!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">] >'
 6404: 	    .'<!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">'
 6405:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6406: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6407:     } else {
 6408: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6409:     }
 6410:     return $output;
 6411: }
 6412: 
 6413: =pod
 6414: 
 6415: =item * &endheadtag()
 6416: 
 6417: Returns a uniform </head> for LON-CAPA web pages.
 6418: 
 6419: Inputs: none
 6420: 
 6421: =cut
 6422: 
 6423: sub endheadtag {
 6424:     return '</head>';
 6425: }
 6426: 
 6427: =pod
 6428: 
 6429: =item * &head()
 6430: 
 6431: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6432: 
 6433: Inputs:
 6434: 
 6435: =over 4
 6436: 
 6437: $title - optional title for the page
 6438: 
 6439: $head_extra - optional extra HTML to put inside the <head>
 6440: 
 6441: =back
 6442: 
 6443: =cut
 6444: 
 6445: sub head {
 6446:     my ($title,$head_extra,$args) = @_;
 6447:     return &headtag($title,$head_extra,$args).&endheadtag();
 6448: }
 6449: 
 6450: =pod
 6451: 
 6452: =item * &start_page()
 6453: 
 6454: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6455: 
 6456: Inputs:
 6457: 
 6458: =over 4
 6459: 
 6460: $title - optional title for the page
 6461: 
 6462: $head_extra - optional extra HTML to incude inside the <head>
 6463: 
 6464: $args - additional optional args supported are:
 6465: 
 6466: =over 8
 6467: 
 6468:              only_body      -> is true will set &bodytag() onlybodytag
 6469:                                     arg on
 6470:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6471:              add_entries    -> additional attributes to add to the  <body>
 6472:              domain         -> force to color decorate a page for a 
 6473:                                     specific domain
 6474:              function       -> force usage of a specific rolish color
 6475:                                     scheme
 6476:              redirect       -> see &headtag()
 6477:              bgcolor        -> override the default page bg color
 6478:              js_ready       -> return a string ready for being used in 
 6479:                                     a javascript writeln
 6480:              html_encode    -> return a string ready for being used in 
 6481:                                     a html attribute
 6482:              force_register -> if is true will turn on the &bodytag()
 6483:                                     $forcereg arg
 6484:              body_title     -> alternate text to use instead of $title
 6485:                                     in the title box that appears, this text
 6486:                                     is not auto translated like the $title is
 6487:              frameset       -> if true will start with a <frameset>
 6488:                                     rather than <body>
 6489:              no_title       -> if true the title bar won't be shown
 6490:              skip_phases    -> hash ref of 
 6491:                                     head -> skip the <html><head> generation
 6492:                                     body -> skip all <body> generation
 6493:              no_inline_link -> if true and in remote mode, don't show the 
 6494:                                     'Switch To Inline Menu' link
 6495:              no_auto_mt_title -> prevent &mt()ing the title arg
 6496:              inherit_jsmath -> when creating popup window in a page,
 6497:                                     should it have jsmath forced on by the
 6498:                                     current page
 6499: 
 6500: =back
 6501: 
 6502: =back
 6503: 
 6504: =cut
 6505: 
 6506: sub start_page {
 6507:     my ($title,$head_extra,$args) = @_;
 6508:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6509:     my %head_args;
 6510:     foreach my $arg ('redirect','force_register','domain','function',
 6511: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6512: 		     'no_auto_mt_title') {
 6513: 	if (defined($args->{$arg})) {
 6514: 	    $head_args{$arg} = $args->{$arg};
 6515: 	}
 6516:     }
 6517: 
 6518:     $env{'internal.start_page'}++;
 6519:     my $result;
 6520:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6521: 	$result.=
 6522: 	    &xml_begin().
 6523: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6524:     }
 6525:     
 6526:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6527: 	if ($args->{'frameset'}) {
 6528: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6529: 						$args->{'add_entries'});
 6530: 	    $result .= "\n<frameset $attr_string>\n";
 6531: 	} else {
 6532: 	    $result .=
 6533: 		&bodytag($title, 
 6534: 			 $args->{'function'},       $args->{'add_entries'},
 6535: 			 $args->{'only_body'},      $args->{'domain'},
 6536: 			 $args->{'force_register'}, $args->{'body_title'},
 6537: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6538: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6539: 			 $args);
 6540: 	}
 6541:     }
 6542: 
 6543:     if ($args->{'js_ready'}) {
 6544: 		$result = &js_ready($result);
 6545:     }
 6546:     if ($args->{'html_encode'}) {
 6547: 		$result = &html_encode($result);
 6548:     }
 6549: 
 6550:     # Preparation for new and consistent functionlist at top of screen
 6551:     # if ($args->{'functionlist'}) {
 6552:     #            $result .= &build_functionlist();
 6553:     #}
 6554: 
 6555:     # Don't add anything more if only_body wanted
 6556:     return $result if $args->{'only_body'};
 6557: 
 6558:     #Breadcrumbs
 6559:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6560: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6561: 		#if any br links exists, add them to the breadcrumbs
 6562: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6563: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6564: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6565: 			}
 6566: 		}
 6567: 
 6568: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6569: 		if(exists($args->{'bread_crumbs_component'})){
 6570: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6571: 		}else{
 6572: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6573: 		}
 6574:     }
 6575:     return $result;
 6576: }
 6577: 
 6578: 
 6579: =pod
 6580: 
 6581: =item * &head()
 6582: 
 6583: Returns a complete </body></html> section for LON-CAPA web pages.
 6584: 
 6585: Inputs:         $args - additional optional args supported are:
 6586:                  js_ready     -> return a string ready for being used in 
 6587:                                  a javascript writeln
 6588:                  html_encode  -> return a string ready for being used in 
 6589:                                  a html attribute
 6590:                  frameset     -> if true will start with a <frameset>
 6591:                                  rather than <body>
 6592:                  dicsussion   -> if true will get discussion from
 6593:                                   lonxml::xmlend
 6594:                                  (you can pass the target and parser arguments
 6595:                                   through optional 'target' and 'parser' args
 6596:                                   to this routine)
 6597: 
 6598: =cut
 6599: 
 6600: sub end_page {
 6601:     my ($args) = @_;
 6602:     $env{'internal.end_page'}++;
 6603:     my $result;
 6604:     if ($args->{'discussion'}) {
 6605: 	my ($target,$parser);
 6606: 	if (ref($args->{'discussion'})) {
 6607: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6608: 				$args->{'discussion'}{'parser'});
 6609: 	}
 6610: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6611:     }
 6612: 
 6613:     if ($args->{'frameset'}) {
 6614: 	$result .= '</frameset>';
 6615:     } else {
 6616: 	$result .= &endbodytag($args);
 6617:     }
 6618:     $result .= "\n</html>";
 6619: 
 6620:     if ($args->{'js_ready'}) {
 6621: 	$result = &js_ready($result);
 6622:     }
 6623: 
 6624:     if ($args->{'html_encode'}) {
 6625: 	$result = &html_encode($result);
 6626:     }
 6627: 
 6628:     return $result;
 6629: }
 6630: 
 6631: sub html_encode {
 6632:     my ($result) = @_;
 6633: 
 6634:     $result = &HTML::Entities::encode($result,'<>&"');
 6635:     
 6636:     return $result;
 6637: }
 6638: sub js_ready {
 6639:     my ($result) = @_;
 6640: 
 6641:     $result =~ s/[\n\r]/ /xmsg;
 6642:     $result =~ s/\\/\\\\/xmsg;
 6643:     $result =~ s/'/\\'/xmsg;
 6644:     $result =~ s{</}{<\\/}xmsg;
 6645:     
 6646:     return $result;
 6647: }
 6648: 
 6649: sub validate_page {
 6650:     if (  exists($env{'internal.start_page'})
 6651: 	  &&     $env{'internal.start_page'} > 1) {
 6652: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6653: 				 $env{'internal.start_page'}.' '.
 6654: 				 $ENV{'request.filename'});
 6655:     }
 6656:     if (  exists($env{'internal.end_page'})
 6657: 	  &&     $env{'internal.end_page'} > 1) {
 6658: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6659: 				 $env{'internal.end_page'}.' '.
 6660: 				 $env{'request.filename'});
 6661:     }
 6662:     if (     exists($env{'internal.start_page'})
 6663: 	&& ! exists($env{'internal.end_page'})) {
 6664: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6665: 				 $env{'request.filename'});
 6666:     }
 6667:     if (   ! exists($env{'internal.start_page'})
 6668: 	&&   exists($env{'internal.end_page'})) {
 6669: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6670: 				 $env{'request.filename'});
 6671:     }
 6672: }
 6673: 
 6674: sub simple_error_page {
 6675:     my ($r,$title,$msg) = @_;
 6676:     my $page =
 6677: 	&Apache::loncommon::start_page($title).
 6678: 	&mt($msg).
 6679: 	&Apache::loncommon::end_page();
 6680:     if (ref($r)) {
 6681: 	$r->print($page);
 6682: 	return;
 6683:     }
 6684:     return $page;
 6685: }
 6686: 
 6687: {
 6688:     my @row_count;
 6689:     sub start_data_table {
 6690: 	my ($add_class) = @_;
 6691: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6692: 	unshift(@row_count,0);
 6693: 	return '<table class="'.$css_class.'">'."\n";
 6694:     }
 6695: 
 6696:     sub end_data_table {
 6697: 	shift(@row_count);
 6698: 	return '</table>'."\n";;
 6699:     }
 6700: 
 6701:     sub start_data_table_row {
 6702: 	my ($add_class) = @_;
 6703: 	$row_count[0]++;
 6704: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6705: 	$css_class = (join(' ',$css_class,$add_class));
 6706: 	return  '<tr class="'.$css_class.'">'."\n";;
 6707:     }
 6708:     
 6709:     sub continue_data_table_row {
 6710: 	my ($add_class) = @_;
 6711: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6712: 	$css_class = (join(' ',$css_class,$add_class));
 6713: 	return  '<tr class="'.$css_class.'">'."\n";;
 6714:     }
 6715: 
 6716:     sub end_data_table_row {
 6717: 	return '</tr>'."\n";;
 6718:     }
 6719: 
 6720:     sub start_data_table_empty_row {
 6721: #	$row_count[0]++;
 6722: 	return  '<tr class="LC_empty_row" >'."\n";;
 6723:     }
 6724: 
 6725:     sub end_data_table_empty_row {
 6726: 	return '</tr>'."\n";;
 6727:     }
 6728: 
 6729:     sub start_data_table_header_row {
 6730: 	return  '<tr class="LC_header_row">'."\n";;
 6731:     }
 6732: 
 6733:     sub end_data_table_header_row {
 6734: 	return '</tr>'."\n";;
 6735:     }
 6736: }
 6737: 
 6738: =pod
 6739: 
 6740: =item * &inhibit_menu_check($arg)
 6741: 
 6742: Checks for a inhibitmenu state and generates output to preserve it
 6743: 
 6744: Inputs:         $arg - can be any of
 6745:                      - undef - in which case the return value is a string 
 6746:                                to add  into arguments list of a uri
 6747:                      - 'input' - in which case the return value is a HTML
 6748:                                  <form> <input> field of type hidden to
 6749:                                  preserve the value
 6750:                      - a url - in which case the return value is the url with
 6751:                                the neccesary cgi args added to preserve the
 6752:                                inhibitmenu state
 6753:                      - a ref to a url - no return value, but the string is
 6754:                                         updated to include the neccessary cgi
 6755:                                         args to preserve the inhibitmenu state
 6756: 
 6757: =cut
 6758: 
 6759: sub inhibit_menu_check {
 6760:     my ($arg) = @_;
 6761:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6762:     if ($arg eq 'input') {
 6763: 	if ($env{'form.inhibitmenu'}) {
 6764: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6765: 	} else {
 6766: 	    return
 6767: 	}
 6768:     }
 6769:     if ($env{'form.inhibitmenu'}) {
 6770: 	if (ref($arg)) {
 6771: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6772: 	} elsif ($arg eq '') {
 6773: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6774: 	} else {
 6775: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6776: 	}
 6777:     }
 6778:     if (!ref($arg)) {
 6779: 	return $arg;
 6780:     }
 6781: }
 6782: 
 6783: ###############################################
 6784: 
 6785: =pod
 6786: 
 6787: =back
 6788: 
 6789: =head1 User Information Routines
 6790: 
 6791: =over 4
 6792: 
 6793: =item * &get_users_function()
 6794: 
 6795: Used by &bodytag to determine the current users primary role.
 6796: Returns either 'student','coordinator','admin', or 'author'.
 6797: 
 6798: =cut
 6799: 
 6800: ###############################################
 6801: sub get_users_function {
 6802:     my $function = 'norole';
 6803:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6804:         $function='coordinator';
 6805:     }
 6806:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6807:         $function='admin';
 6808:     }
 6809:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6810:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6811:         $function='author';
 6812:     }
 6813:     return $function;
 6814: }
 6815: 
 6816: ###############################################
 6817: 
 6818: =pod
 6819: 
 6820: =item * &check_user_status()
 6821: 
 6822: Determines current status of supplied role for a
 6823: specific user. Roles can be active, previous or future.
 6824: 
 6825: Inputs: 
 6826: user's domain, user's username, course's domain,
 6827: course's number, optional section ID.
 6828: 
 6829: Outputs:
 6830: role status: active, previous or future. 
 6831: 
 6832: =cut
 6833: 
 6834: sub check_user_status {
 6835:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6836:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6837:     my @uroles = keys %userinfo;
 6838:     my $srchstr;
 6839:     my $active_chk = 'none';
 6840:     my $now = time;
 6841:     if (@uroles > 0) {
 6842:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6843:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6844:         } else {
 6845:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6846:         }
 6847:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6848:             my $role_end = 0;
 6849:             my $role_start = 0;
 6850:             $active_chk = 'active';
 6851:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6852:                 $role_end = $1;
 6853:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6854:                     $role_start = $1;
 6855:                 }
 6856:             }
 6857:             if ($role_start > 0) {
 6858:                 if ($now < $role_start) {
 6859:                     $active_chk = 'future';
 6860:                 }
 6861:             }
 6862:             if ($role_end > 0) {
 6863:                 if ($now > $role_end) {
 6864:                     $active_chk = 'previous';
 6865:                 }
 6866:             }
 6867:         }
 6868:     }
 6869:     return $active_chk;
 6870: }
 6871: 
 6872: ###############################################
 6873: 
 6874: =pod
 6875: 
 6876: =item * &get_sections()
 6877: 
 6878: Determines all the sections for a course including
 6879: sections with students and sections containing other roles.
 6880: Incoming parameters: 
 6881: 
 6882: 1. domain
 6883: 2. course number 
 6884: 3. reference to array containing roles for which sections should 
 6885: be gathered (optional).
 6886: 4. reference to array containing status types for which sections 
 6887: should be gathered (optional).
 6888: 
 6889: If the third argument is undefined, sections are gathered for any role. 
 6890: If the fourth argument is undefined, sections are gathered for any status.
 6891: Permissible values are 'active' or 'future' or 'previous'.
 6892:  
 6893: Returns section hash (keys are section IDs, values are
 6894: number of users in each section), subject to the
 6895: optional roles filter, optional status filter 
 6896: 
 6897: =cut
 6898: 
 6899: ###############################################
 6900: sub get_sections {
 6901:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6902:     if (!defined($cdom) || !defined($cnum)) {
 6903:         my $cid =  $env{'request.course.id'};
 6904: 
 6905: 	return if (!defined($cid));
 6906: 
 6907:         $cdom = $env{'course.'.$cid.'.domain'};
 6908:         $cnum = $env{'course.'.$cid.'.num'};
 6909:     }
 6910: 
 6911:     my %sectioncount;
 6912:     my $now = time;
 6913: 
 6914:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6915: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6916: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6917: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6918:         my $start_index = &Apache::loncoursedata::CL_START();
 6919:         my $end_index = &Apache::loncoursedata::CL_END();
 6920:         my $status;
 6921: 	while (my ($student,$data) = each(%$classlist)) {
 6922: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6923: 				                     $data->[$status_index],
 6924:                                                      $data->[$start_index],
 6925:                                                      $data->[$end_index]);
 6926:             if ($stu_status eq 'Active') {
 6927:                 $status = 'active';
 6928:             } elsif ($end < $now) {
 6929:                 $status = 'previous';
 6930:             } elsif ($start > $now) {
 6931:                 $status = 'future';
 6932:             } 
 6933: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6934:                 if ((!defined($possible_status)) || (($status ne '') && 
 6935:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6936: 		    $sectioncount{$section}++;
 6937:                 }
 6938: 	    }
 6939: 	}
 6940:     }
 6941:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6942:     foreach my $user (sort(keys(%courseroles))) {
 6943: 	if ($user !~ /^(\w{2})/) { next; }
 6944: 	my ($role) = ($user =~ /^(\w{2})/);
 6945: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6946: 	my ($section,$status);
 6947: 	if ($role eq 'cr' &&
 6948: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6949: 	    $section=$1;
 6950: 	}
 6951: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6952: 	if (!defined($section) || $section eq '-1') { next; }
 6953:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6954:         if ($end == -1 && $start == -1) {
 6955:             next; #deleted role
 6956:         }
 6957:         if (!defined($possible_status)) { 
 6958:             $sectioncount{$section}++;
 6959:         } else {
 6960:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6961:                 $status = 'active';
 6962:             } elsif ($end < $now) {
 6963:                 $status = 'future';
 6964:             } elsif ($start > $now) {
 6965:                 $status = 'previous';
 6966:             }
 6967:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6968:                 $sectioncount{$section}++;
 6969:             }
 6970:         }
 6971:     }
 6972:     return %sectioncount;
 6973: }
 6974: 
 6975: ###############################################
 6976: 
 6977: =pod
 6978: 
 6979: =item * &get_course_users()
 6980: 
 6981: Retrieves usernames:domains for users in the specified course
 6982: with specific role(s), and access status. 
 6983: 
 6984: Incoming parameters:
 6985: 1. course domain
 6986: 2. course number
 6987: 3. access status: users must have - either active, 
 6988: previous, future, or all.
 6989: 4. reference to array of permissible roles
 6990: 5. reference to array of section restrictions (optional)
 6991: 6. reference to results object (hash of hashes).
 6992: 7. reference to optional userdata hash
 6993: 8. reference to optional statushash
 6994: 9. flag if privileged users (except those set to unhide in
 6995:    course settings) should be excluded    
 6996: Keys of top level results hash are roles.
 6997: Keys of inner hashes are username:domain, with 
 6998: values set to access type.
 6999: Optional userdata hash returns an array with arguments in the 
 7000: same order as loncoursedata::get_classlist() for student data.
 7001: 
 7002: Optional statushash returns
 7003: 
 7004: Entries for end, start, section and status are blank because
 7005: of the possibility of multiple values for non-student roles.
 7006: 
 7007: =cut
 7008: 
 7009: ###############################################
 7010: 
 7011: sub get_course_users {
 7012:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7013:     my %idx = ();
 7014:     my %seclists;
 7015: 
 7016:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7017:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7018:     $idx{end} = &Apache::loncoursedata::CL_END();
 7019:     $idx{start} = &Apache::loncoursedata::CL_START();
 7020:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7021:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7022:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7023:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7024: 
 7025:     if (grep(/^st$/,@{$roles})) {
 7026:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7027:         my $now = time;
 7028:         foreach my $student (keys(%{$classlist})) {
 7029:             my $match = 0;
 7030:             my $secmatch = 0;
 7031:             my $section = $$classlist{$student}[$idx{section}];
 7032:             my $status = $$classlist{$student}[$idx{status}];
 7033:             if ($section eq '') {
 7034:                 $section = 'none';
 7035:             }
 7036:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7037:                 if (grep(/^all$/,@{$sections})) {
 7038:                     $secmatch = 1;
 7039:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7040:                     if (grep(/^none$/,@{$sections})) {
 7041:                         $secmatch = 1;
 7042:                     }
 7043:                 } else {  
 7044: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7045: 		        $secmatch = 1;
 7046:                     }
 7047: 		}
 7048:                 if (!$secmatch) {
 7049:                     next;
 7050:                 }
 7051:             }
 7052:             if (defined($$types{'active'})) {
 7053:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7054:                     push(@{$$users{st}{$student}},'active');
 7055:                     $match = 1;
 7056:                 }
 7057:             }
 7058:             if (defined($$types{'previous'})) {
 7059:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7060:                     push(@{$$users{st}{$student}},'previous');
 7061:                     $match = 1;
 7062:                 }
 7063:             }
 7064:             if (defined($$types{'future'})) {
 7065:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7066:                     push(@{$$users{st}{$student}},'future');
 7067:                     $match = 1;
 7068:                 }
 7069:             }
 7070:             if ($match) {
 7071:                 push(@{$seclists{$student}},$section);
 7072:                 if (ref($userdata) eq 'HASH') {
 7073:                     $$userdata{$student} = $$classlist{$student};
 7074:                 }
 7075:                 if (ref($statushash) eq 'HASH') {
 7076:                     $statushash->{$student}{'st'}{$section} = $status;
 7077:                 }
 7078:             }
 7079:         }
 7080:     }
 7081:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7082:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7083:         my $now = time;
 7084:         my %displaystatus = ( previous => 'Expired',
 7085:                               active   => 'Active',
 7086:                               future   => 'Future',
 7087:                             );
 7088:         my %nothide;
 7089:         if ($hidepriv) {
 7090:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7091:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7092:                 if ($user !~ /:/) {
 7093:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7094:                 } else {
 7095:                     $nothide{$user} = 1;
 7096:                 }
 7097:             }
 7098:         }
 7099:         foreach my $person (sort(keys(%coursepersonnel))) {
 7100:             my $match = 0;
 7101:             my $secmatch = 0;
 7102:             my $status;
 7103:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7104:             $user =~ s/:$//;
 7105:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7106:             if ($end == -1 || $start == -1) {
 7107:                 next;
 7108:             }
 7109:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7110:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7111:                 my ($uname,$udom) = split(/:/,$user);
 7112:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7113:                     if (grep(/^all$/,@{$sections})) {
 7114:                         $secmatch = 1;
 7115:                     } elsif ($usec eq '') {
 7116:                         if (grep(/^none$/,@{$sections})) {
 7117:                             $secmatch = 1;
 7118:                         }
 7119:                     } else {
 7120:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7121:                             $secmatch = 1;
 7122:                         }
 7123:                     }
 7124:                     if (!$secmatch) {
 7125:                         next;
 7126:                     }
 7127:                 }
 7128:                 if ($usec eq '') {
 7129:                     $usec = 'none';
 7130:                 }
 7131:                 if ($uname ne '' && $udom ne '') {
 7132:                     if ($hidepriv) {
 7133:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7134:                             (!$nothide{$uname.':'.$udom})) {
 7135:                             next;
 7136:                         }
 7137:                     }
 7138:                     if ($end > 0 && $end < $now) {
 7139:                         $status = 'previous';
 7140:                     } elsif ($start > $now) {
 7141:                         $status = 'future';
 7142:                     } else {
 7143:                         $status = 'active';
 7144:                     }
 7145:                     foreach my $type (keys(%{$types})) { 
 7146:                         if ($status eq $type) {
 7147:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7148:                                 push(@{$$users{$role}{$user}},$type);
 7149:                             }
 7150:                             $match = 1;
 7151:                         }
 7152:                     }
 7153:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7154:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7155: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7156:                         }
 7157:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7158:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7159:                         }
 7160:                         if (ref($statushash) eq 'HASH') {
 7161:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7162:                         }
 7163:                     }
 7164:                 }
 7165:             }
 7166:         }
 7167:         if (grep(/^ow$/,@{$roles})) {
 7168:             if ((defined($cdom)) && (defined($cnum))) {
 7169:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7170:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7171:                     my $owner = $csettings{'internal.courseowner'};
 7172:                     next if ($owner eq '');
 7173:                     my ($ownername,$ownerdom);
 7174:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7175:                         $ownername = $1;
 7176:                         $ownerdom = $2;
 7177:                     } else {
 7178:                         $ownername = $owner;
 7179:                         $ownerdom = $cdom;
 7180:                         $owner = $ownername.':'.$ownerdom;
 7181:                     }
 7182:                     @{$$users{'ow'}{$owner}} = 'any';
 7183:                     if (defined($userdata) && 
 7184: 			!exists($$userdata{$owner})) {
 7185: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7186:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7187:                             push(@{$seclists{$owner}},'none');
 7188:                         }
 7189:                         if (ref($statushash) eq 'HASH') {
 7190:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7191:                         }
 7192: 		    }
 7193:                 }
 7194:             }
 7195:         }
 7196:         foreach my $user (keys(%seclists)) {
 7197:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7198:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7199:         }
 7200:     }
 7201:     return;
 7202: }
 7203: 
 7204: sub get_user_info {
 7205:     my ($udom,$uname,$idx,$userdata) = @_;
 7206:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7207: 	&plainname($uname,$udom,'lastname');
 7208:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7209:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7210:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7211:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7212:     return;
 7213: }
 7214: 
 7215: ###############################################
 7216: 
 7217: =pod
 7218: 
 7219: =item * &get_user_quota()
 7220: 
 7221: Retrieves quota assigned for storage of portfolio files for a user  
 7222: 
 7223: Incoming parameters:
 7224: 1. user's username
 7225: 2. user's domain
 7226: 
 7227: Returns:
 7228: 1. Disk quota (in Mb) assigned to student.
 7229: 2. (Optional) Type of setting: custom or default
 7230:    (individually assigned or default for user's 
 7231:    institutional status).
 7232: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7233:    or student - types as defined in localenroll::inst_usertypes 
 7234:    for user's domain, which determines default quota for user.
 7235: 4. (Optional) - Default quota which would apply to the user.
 7236: 
 7237: If a value has been stored in the user's environment, 
 7238: it will return that, otherwise it returns the maximal default
 7239: defined for the user's instituional status(es) in the domain.
 7240: 
 7241: =cut
 7242: 
 7243: ###############################################
 7244: 
 7245: 
 7246: sub get_user_quota {
 7247:     my ($uname,$udom) = @_;
 7248:     my ($quota,$quotatype,$settingstatus,$defquota);
 7249:     if (!defined($udom)) {
 7250:         $udom = $env{'user.domain'};
 7251:     }
 7252:     if (!defined($uname)) {
 7253:         $uname = $env{'user.name'};
 7254:     }
 7255:     if (($udom eq '' || $uname eq '') ||
 7256:         ($udom eq 'public') && ($uname eq 'public')) {
 7257:         $quota = 0;
 7258:         $quotatype = 'default';
 7259:         $defquota = 0; 
 7260:     } else {
 7261:         my $inststatus;
 7262:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7263:             $quota = $env{'environment.portfolioquota'};
 7264:             $inststatus = $env{'environment.inststatus'};
 7265:         } else {
 7266:             my %userenv = 
 7267:                 &Apache::lonnet::get('environment',['portfolioquota',
 7268:                                      'inststatus'],$udom,$uname);
 7269:             my ($tmp) = keys(%userenv);
 7270:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7271:                 $quota = $userenv{'portfolioquota'};
 7272:                 $inststatus = $userenv{'inststatus'};
 7273:             } else {
 7274:                 undef(%userenv);
 7275:             }
 7276:         }
 7277:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7278:         if ($quota eq '') {
 7279:             $quota = $defquota;
 7280:             $quotatype = 'default';
 7281:         } else {
 7282:             $quotatype = 'custom';
 7283:         }
 7284:     }
 7285:     if (wantarray) {
 7286:         return ($quota,$quotatype,$settingstatus,$defquota);
 7287:     } else {
 7288:         return $quota;
 7289:     }
 7290: }
 7291: 
 7292: ###############################################
 7293: 
 7294: =pod
 7295: 
 7296: =item * &default_quota()
 7297: 
 7298: Retrieves default quota assigned for storage of user portfolio files,
 7299: given an (optional) user's institutional status.
 7300: 
 7301: Incoming parameters:
 7302: 1. domain
 7303: 2. (Optional) institutional status(es).  This is a : separated list of 
 7304:    status types (e.g., faculty, staff, student etc.)
 7305:    which apply to the user for whom the default is being retrieved.
 7306:    If the institutional status string in undefined, the domain
 7307:    default quota will be returned. 
 7308: 
 7309: Returns:
 7310: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7311: 2. (Optional) institutional type which determined the value of the
 7312:    default quota.
 7313: 
 7314: If a value has been stored in the domain's configuration db,
 7315: it will return that, otherwise it returns 20 (for backwards 
 7316: compatibility with domains which have not set up a configuration
 7317: db file; the original statically defined portfolio quota was 20 Mb). 
 7318: 
 7319: If the user's status includes multiple types (e.g., staff and student),
 7320: the largest default quota which applies to the user determines the
 7321: default quota returned.
 7322: 
 7323: =back
 7324: 
 7325: =cut
 7326: 
 7327: ###############################################
 7328: 
 7329: 
 7330: sub default_quota {
 7331:     my ($udom,$inststatus) = @_;
 7332:     my ($defquota,$settingstatus);
 7333:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7334:                                             ['quotas'],$udom);
 7335:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7336:         if ($inststatus ne '') {
 7337:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7338:             foreach my $item (@statuses) {
 7339:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7340:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7341:                         if ($defquota eq '') {
 7342:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7343:                             $settingstatus = $item;
 7344:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7345:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7346:                             $settingstatus = $item;
 7347:                         }
 7348:                     }
 7349:                 } else {
 7350:                     if ($quotahash{'quotas'}{$item} ne '') {
 7351:                         if ($defquota eq '') {
 7352:                             $defquota = $quotahash{'quotas'}{$item};
 7353:                             $settingstatus = $item;
 7354:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7355:                             $defquota = $quotahash{'quotas'}{$item};
 7356:                             $settingstatus = $item;
 7357:                         }
 7358:                     }
 7359:                 }
 7360:             }
 7361:         }
 7362:         if ($defquota eq '') {
 7363:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7364:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7365:             } else {
 7366:                 $defquota = $quotahash{'quotas'}{'default'};
 7367:             }
 7368:             $settingstatus = 'default';
 7369:         }
 7370:     } else {
 7371:         $settingstatus = 'default';
 7372:         $defquota = 20;
 7373:     }
 7374:     if (wantarray) {
 7375:         return ($defquota,$settingstatus);
 7376:     } else {
 7377:         return $defquota;
 7378:     }
 7379: }
 7380: 
 7381: sub get_secgrprole_info {
 7382:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7383:     my %sections_count = &get_sections($cdom,$cnum);
 7384:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7385:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7386:     my @groups = sort(keys(%curr_groups));
 7387:     my $allroles = [];
 7388:     my $rolehash;
 7389:     my $accesshash = {
 7390:                      active => 'Currently has access',
 7391:                      future => 'Will have future access',
 7392:                      previous => 'Previously had access',
 7393:                   };
 7394:     if ($needroles) {
 7395:         $rolehash = {'all' => 'all'};
 7396:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7397: 	if (&Apache::lonnet::error(%user_roles)) {
 7398: 	    undef(%user_roles);
 7399: 	}
 7400:         foreach my $item (keys(%user_roles)) {
 7401:             my ($role)=split(/\:/,$item,2);
 7402:             if ($role eq 'cr') { next; }
 7403:             if ($role =~ /^cr/) {
 7404:                 $$rolehash{$role} = (split('/',$role))[3];
 7405:             } else {
 7406:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7407:             }
 7408:         }
 7409:         foreach my $key (sort(keys(%{$rolehash}))) {
 7410:             push(@{$allroles},$key);
 7411:         }
 7412:         push (@{$allroles},'st');
 7413:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7414:     }
 7415:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7416: }
 7417: 
 7418: sub user_picker {
 7419:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7420:     my $currdom = $dom;
 7421:     my %curr_selected = (
 7422:                         srchin => 'dom',
 7423:                         srchby => 'lastname',
 7424:                       );
 7425:     my $srchterm;
 7426:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7427:         if ($srch->{'srchby'} ne '') {
 7428:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7429:         }
 7430:         if ($srch->{'srchin'} ne '') {
 7431:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7432:         }
 7433:         if ($srch->{'srchtype'} ne '') {
 7434:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7435:         }
 7436:         if ($srch->{'srchdomain'} ne '') {
 7437:             $currdom = $srch->{'srchdomain'};
 7438:         }
 7439:         $srchterm = $srch->{'srchterm'};
 7440:     }
 7441:     my %lt=&Apache::lonlocal::texthash(
 7442:                     'usr'       => 'Search criteria',
 7443:                     'doma'      => 'Domain/institution to search',
 7444:                     'uname'     => 'username',
 7445:                     'lastname'  => 'last name',
 7446:                     'lastfirst' => 'last name, first name',
 7447:                     'crs'       => 'in this course',
 7448:                     'dom'       => 'in selected LON-CAPA domain', 
 7449:                     'alc'       => 'all LON-CAPA',
 7450:                     'instd'     => 'in institutional directory for selected domain',
 7451:                     'exact'     => 'is',
 7452:                     'contains'  => 'contains',
 7453:                     'begins'    => 'begins with',
 7454:                     'youm'      => "You must include some text to search for.",
 7455:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7456:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7457:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7458:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7459:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7460:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7461:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7462:                                        );
 7463:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7464:     my $srchinsel = ' <select name="srchin">';
 7465: 
 7466:     my @srchins = ('crs','dom','alc','instd');
 7467: 
 7468:     foreach my $option (@srchins) {
 7469:         # FIXME 'alc' option unavailable until 
 7470:         #       loncreateuser::print_user_query_page()
 7471:         #       has been completed.
 7472:         next if ($option eq 'alc');
 7473:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7474:         if ($curr_selected{'srchin'} eq $option) {
 7475:             $srchinsel .= ' 
 7476:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7477:         } else {
 7478:             $srchinsel .= '
 7479:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7480:         }
 7481:     }
 7482:     $srchinsel .= "\n  </select>\n";
 7483: 
 7484:     my $srchbysel =  ' <select name="srchby">';
 7485:     foreach my $option ('lastname','lastfirst','uname') {
 7486:         if ($curr_selected{'srchby'} eq $option) {
 7487:             $srchbysel .= '
 7488:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7489:         } else {
 7490:             $srchbysel .= '
 7491:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7492:          }
 7493:     }
 7494:     $srchbysel .= "\n  </select>\n";
 7495: 
 7496:     my $srchtypesel = ' <select name="srchtype">';
 7497:     foreach my $option ('begins','contains','exact') {
 7498:         if ($curr_selected{'srchtype'} eq $option) {
 7499:             $srchtypesel .= '
 7500:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7501:         } else {
 7502:             $srchtypesel .= '
 7503:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7504:         }
 7505:     }
 7506:     $srchtypesel .= "\n  </select>\n";
 7507: 
 7508:     my ($newuserscript,$new_user_create);
 7509: 
 7510:     if ($forcenewuser) {
 7511:         if (ref($srch) eq 'HASH') {
 7512:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7513:                 if ($cancreate) {
 7514:                     $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>';
 7515:                 } else {
 7516:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7517:                     my %usertypetext = (
 7518:                         official   => 'institutional',
 7519:                         unofficial => 'non-institutional',
 7520:                     );
 7521:                     $new_user_create = '<p class="LC_warning">'
 7522:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7523:                                       .' '
 7524:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7525:                                           ,'<a href="'.$helplink.'">','</a>')
 7526:                                       .'</p><br />';
 7527:                 }
 7528:             }
 7529:         }
 7530: 
 7531:         $newuserscript = <<"ENDSCRIPT";
 7532: 
 7533: function setSearch(createnew,callingForm) {
 7534:     if (createnew == 1) {
 7535:         for (var i=0; i<callingForm.srchby.length; i++) {
 7536:             if (callingForm.srchby.options[i].value == 'uname') {
 7537:                 callingForm.srchby.selectedIndex = i;
 7538:             }
 7539:         }
 7540:         for (var i=0; i<callingForm.srchin.length; i++) {
 7541:             if ( callingForm.srchin.options[i].value == 'dom') {
 7542: 		callingForm.srchin.selectedIndex = i;
 7543:             }
 7544:         }
 7545:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7546:             if (callingForm.srchtype.options[i].value == 'exact') {
 7547:                 callingForm.srchtype.selectedIndex = i;
 7548:             }
 7549:         }
 7550:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7551:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7552:                 callingForm.srchdomain.selectedIndex = i;
 7553:             }
 7554:         }
 7555:     }
 7556: }
 7557: ENDSCRIPT
 7558: 
 7559:     }
 7560: 
 7561:     my $output = <<"END_BLOCK";
 7562: <script type="text/javascript">
 7563: function validateEntry(callingForm) {
 7564: 
 7565:     var checkok = 1;
 7566:     var srchin;
 7567:     for (var i=0; i<callingForm.srchin.length; i++) {
 7568: 	if ( callingForm.srchin[i].checked ) {
 7569: 	    srchin = callingForm.srchin[i].value;
 7570: 	}
 7571:     }
 7572: 
 7573:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7574:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7575:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7576:     var srchterm =  callingForm.srchterm.value;
 7577:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7578:     var msg = "";
 7579: 
 7580:     if (srchterm == "") {
 7581:         checkok = 0;
 7582:         msg += "$lt{'youm'}\\n";
 7583:     }
 7584: 
 7585:     if (srchtype== 'begins') {
 7586:         if (srchterm.length < 2) {
 7587:             checkok = 0;
 7588:             msg += "$lt{'thte'}\\n";
 7589:         }
 7590:     }
 7591: 
 7592:     if (srchtype== 'contains') {
 7593:         if (srchterm.length < 3) {
 7594:             checkok = 0;
 7595:             msg += "$lt{'thet'}\\n";
 7596:         }
 7597:     }
 7598:     if (srchin == 'instd') {
 7599:         if (srchdomain == '') {
 7600:             checkok = 0;
 7601:             msg += "$lt{'yomc'}\\n";
 7602:         }
 7603:     }
 7604:     if (srchin == 'dom') {
 7605:         if (srchdomain == '') {
 7606:             checkok = 0;
 7607:             msg += "$lt{'ymcd'}\\n";
 7608:         }
 7609:     }
 7610:     if (srchby == 'lastfirst') {
 7611:         if (srchterm.indexOf(",") == -1) {
 7612:             checkok = 0;
 7613:             msg += "$lt{'whus'}\\n";
 7614:         }
 7615:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7616:             checkok = 0;
 7617:             msg += "$lt{'whse'}\\n";
 7618:         }
 7619:     }
 7620:     if (checkok == 0) {
 7621:         alert("$lt{'thfo'}\\n"+msg);
 7622:         return;
 7623:     }
 7624:     if (checkok == 1) {
 7625:         callingForm.submit();
 7626:     }
 7627: }
 7628: 
 7629: $newuserscript
 7630: 
 7631: </script>
 7632: 
 7633: $new_user_create
 7634: 
 7635: <table>
 7636:  <tr>
 7637:   <td>$lt{'doma'}:</td>
 7638:   <td>$domform</td>
 7639:   </td>
 7640:  </tr>
 7641:  <tr>
 7642:   <td>$lt{'usr'}:</td>
 7643:   <td>$srchbysel
 7644:       $srchtypesel 
 7645:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7646:       $srchinsel 
 7647:   </td>
 7648:  </tr>
 7649: </table>
 7650: <br />
 7651: END_BLOCK
 7652: 
 7653:     return $output;
 7654: }
 7655: 
 7656: sub user_rule_check {
 7657:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7658:     my $response;
 7659:     if (ref($usershash) eq 'HASH') {
 7660:         foreach my $user (keys(%{$usershash})) {
 7661:             my ($uname,$udom) = split(/:/,$user);
 7662:             next if ($udom eq '' || $uname eq '');
 7663:             my ($id,$newuser);
 7664:             if (ref($usershash->{$user}) eq 'HASH') {
 7665:                 $newuser = $usershash->{$user}->{'newuser'};
 7666:                 $id = $usershash->{$user}->{'id'};
 7667:             }
 7668:             my $inst_response;
 7669:             if (ref($checks) eq 'HASH') {
 7670:                 if (defined($checks->{'username'})) {
 7671:                     ($inst_response,%{$inst_results->{$user}}) = 
 7672:                         &Apache::lonnet::get_instuser($udom,$uname);
 7673:                 } elsif (defined($checks->{'id'})) {
 7674:                     ($inst_response,%{$inst_results->{$user}}) =
 7675:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7676:                 }
 7677:             } else {
 7678:                 ($inst_response,%{$inst_results->{$user}}) =
 7679:                     &Apache::lonnet::get_instuser($udom,$uname);
 7680:                 return;
 7681:             }
 7682:             if (!$got_rules->{$udom}) {
 7683:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7684:                                                   ['usercreation'],$udom);
 7685:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7686:                     foreach my $item ('username','id') {
 7687:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7688:                             $$curr_rules{$udom}{$item} = 
 7689:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7690:                         }
 7691:                     }
 7692:                 }
 7693:                 $got_rules->{$udom} = 1;  
 7694:             }
 7695:             foreach my $item (keys(%{$checks})) {
 7696:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7697:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7698:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7699:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7700:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7701:                                 if ($rule_check{$rule}) {
 7702:                                     $$rulematch{$user}{$item} = $rule;
 7703:                                     if ($inst_response eq 'ok') {
 7704:                                         if (ref($inst_results) eq 'HASH') {
 7705:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7706:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7707:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7708:                                                 }
 7709:                                             }
 7710:                                         }
 7711:                                     }
 7712:                                     last;
 7713:                                 }
 7714:                             }
 7715:                         }
 7716:                     }
 7717:                 }
 7718:             }
 7719:         }
 7720:     }
 7721:     return;
 7722: }
 7723: 
 7724: sub user_rule_formats {
 7725:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7726:     my %text = ( 
 7727:                  'username' => 'Usernames',
 7728:                  'id'       => 'IDs',
 7729:                );
 7730:     my $output;
 7731:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7732:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7733:         if (@{$ruleorder} > 0) {
 7734:             $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>';
 7735:             foreach my $rule (@{$ruleorder}) {
 7736:                 if (ref($curr_rules) eq 'ARRAY') {
 7737:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7738:                         if (ref($rules->{$rule}) eq 'HASH') {
 7739:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7740:                                         $rules->{$rule}{'desc'}.'</li>';
 7741:                         }
 7742:                     }
 7743:                 }
 7744:             }
 7745:             $output .= '</ul>';
 7746:         }
 7747:     }
 7748:     return $output;
 7749: }
 7750: 
 7751: sub instrule_disallow_msg {
 7752:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7753:     my $response;
 7754:     my %text = (
 7755:                   item   => 'username',
 7756:                   items  => 'usernames',
 7757:                   match  => 'matches',
 7758:                   do     => 'does',
 7759:                   action => 'a username',
 7760:                   one    => 'one',
 7761:                );
 7762:     if ($count > 1) {
 7763:         $text{'item'} = 'usernames';
 7764:         $text{'match'} ='match';
 7765:         $text{'do'} = 'do';
 7766:         $text{'action'} = 'usernames',
 7767:         $text{'one'} = 'ones';
 7768:     }
 7769:     if ($checkitem eq 'id') {
 7770:         $text{'items'} = 'IDs';
 7771:         $text{'item'} = 'ID';
 7772:         $text{'action'} = 'an ID';
 7773:         if ($count > 1) {
 7774:             $text{'item'} = 'IDs';
 7775:             $text{'action'} = 'IDs';
 7776:         }
 7777:     }
 7778:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
 7779:     if ($mode eq 'upload') {
 7780:         if ($checkitem eq 'username') {
 7781:             $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'}.");
 7782:         } elsif ($checkitem eq 'id') {
 7783:             $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 Student/Employee ID field.");
 7784:         }
 7785:     } elsif ($mode eq 'selfcreate') {
 7786:         if ($checkitem eq 'id') {
 7787:             $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.");
 7788:         }
 7789:     } else {
 7790:         if ($checkitem eq 'username') {
 7791:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7792:         } elsif ($checkitem eq 'id') {
 7793:             $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.");
 7794:         }
 7795:     }
 7796:     return $response;
 7797: }
 7798: 
 7799: sub personal_data_fieldtitles {
 7800:     my %fieldtitles = &Apache::lonlocal::texthash (
 7801:                         id => 'Student/Employee ID',
 7802:                         permanentemail => 'E-mail address',
 7803:                         lastname => 'Last Name',
 7804:                         firstname => 'First Name',
 7805:                         middlename => 'Middle Name',
 7806:                         generation => 'Generation',
 7807:                         gen => 'Generation',
 7808:                         inststatus => 'Affiliation',
 7809:                    );
 7810:     return %fieldtitles;
 7811: }
 7812: 
 7813: sub sorted_inst_types {
 7814:     my ($dom) = @_;
 7815:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7816:     my $othertitle = &mt('All users');
 7817:     if ($env{'request.course.id'}) {
 7818:         $othertitle  = &mt('Any users');
 7819:     }
 7820:     my @types;
 7821:     if (ref($order) eq 'ARRAY') {
 7822:         @types = @{$order};
 7823:     }
 7824:     if (@types == 0) {
 7825:         if (ref($usertypes) eq 'HASH') {
 7826:             @types = sort(keys(%{$usertypes}));
 7827:         }
 7828:     }
 7829:     if (keys(%{$usertypes}) > 0) {
 7830:         $othertitle = &mt('Other users');
 7831:     }
 7832:     return ($othertitle,$usertypes,\@types);
 7833: }
 7834: 
 7835: sub get_institutional_codes {
 7836:     my ($settings,$allcourses,$LC_code) = @_;
 7837: # Get complete list of course sections to update
 7838:     my @currsections = ();
 7839:     my @currxlists = ();
 7840:     my $coursecode = $$settings{'internal.coursecode'};
 7841: 
 7842:     if ($$settings{'internal.sectionnums'} ne '') {
 7843:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7844:     }
 7845: 
 7846:     if ($$settings{'internal.crosslistings'} ne '') {
 7847:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7848:     }
 7849: 
 7850:     if (@currxlists > 0) {
 7851:         foreach (@currxlists) {
 7852:             if (m/^([^:]+):(\w*)$/) {
 7853:                 unless (grep/^$1$/,@{$allcourses}) {
 7854:                     push @{$allcourses},$1;
 7855:                     $$LC_code{$1} = $2;
 7856:                 }
 7857:             }
 7858:         }
 7859:     }
 7860:  
 7861:     if (@currsections > 0) {
 7862:         foreach (@currsections) {
 7863:             if (m/^(\w+):(\w*)$/) {
 7864:                 my $sec = $coursecode.$1;
 7865:                 my $lc_sec = $2;
 7866:                 unless (grep/^$sec$/,@{$allcourses}) {
 7867:                     push @{$allcourses},$sec;
 7868:                     $$LC_code{$sec} = $lc_sec;
 7869:                 }
 7870:             }
 7871:         }
 7872:     }
 7873:     return;
 7874: }
 7875: 
 7876: =pod
 7877: 
 7878: =head1 Slot Helpers
 7879: 
 7880: =over 4
 7881: 
 7882: =item * sorted_slots()
 7883: 
 7884: Sorts an array of slot names in order of slot start time (earliest first). 
 7885: 
 7886: Inputs:
 7887: 
 7888: =over 4
 7889: 
 7890: slotsarr  - Reference to array of unsorted slot names.
 7891: 
 7892: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7893: 
 7894: =back
 7895: 
 7896: Returns:
 7897: 
 7898: =over 4
 7899: 
 7900: sorted   - An array of slot names sorted by the start time of the slot.
 7901: 
 7902: =back
 7903: 
 7904: =back
 7905: 
 7906: =cut
 7907: 
 7908: 
 7909: sub sorted_slots {
 7910:     my ($slotsarr,$slots) = @_;
 7911:     my @sorted;
 7912:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7913:         @sorted =
 7914:             sort {
 7915:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7916:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7917:                      }
 7918:                      if (ref($slots->{$a})) { return -1;}
 7919:                      if (ref($slots->{$b})) { return 1;}
 7920:                      return 0;
 7921:                  } @{$slotsarr};
 7922:     }
 7923:     return @sorted;
 7924: }
 7925: 
 7926: 
 7927: =pod
 7928: 
 7929: =head1 HTTP Helpers
 7930: 
 7931: =over 4
 7932: 
 7933: =item * &get_unprocessed_cgi($query,$possible_names)
 7934: 
 7935: Modify the %env hash to contain unprocessed CGI form parameters held in
 7936: $query.  The parameters listed in $possible_names (an array reference),
 7937: will be set in $env{'form.name'} if they do not already exist.
 7938: 
 7939: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7940: $possible_names is an ref to an array of form element names.  As an example:
 7941: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7942: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7943: 
 7944: =cut
 7945: 
 7946: sub get_unprocessed_cgi {
 7947:   my ($query,$possible_names)= @_;
 7948:   # $Apache::lonxml::debug=1;
 7949:   foreach my $pair (split(/&/,$query)) {
 7950:     my ($name, $value) = split(/=/,$pair);
 7951:     $name = &unescape($name);
 7952:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7953:       $value =~ tr/+/ /;
 7954:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7955:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7956:     }
 7957:   }
 7958: }
 7959: 
 7960: =pod
 7961: 
 7962: =item * &cacheheader() 
 7963: 
 7964: returns cache-controlling header code
 7965: 
 7966: =cut
 7967: 
 7968: sub cacheheader {
 7969:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7970:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7971:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7972:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7973:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7974:     return $output;
 7975: }
 7976: 
 7977: =pod
 7978: 
 7979: =item * &no_cache($r) 
 7980: 
 7981: specifies header code to not have cache
 7982: 
 7983: =cut
 7984: 
 7985: sub no_cache {
 7986:     my ($r) = @_;
 7987:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7988: 	$env{'request.method'} ne 'GET') { return ''; }
 7989:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7990:     $r->no_cache(1);
 7991:     $r->header_out("Expires" => $date);
 7992:     $r->header_out("Pragma" => "no-cache");
 7993: }
 7994: 
 7995: sub content_type {
 7996:     my ($r,$type,$charset) = @_;
 7997:     if ($r) {
 7998: 	#  Note that printout.pl calls this with undef for $r.
 7999: 	&no_cache($r);
 8000:     }
 8001:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8002:     unless ($charset) {
 8003: 	$charset=&Apache::lonlocal::current_encoding;
 8004:     }
 8005:     if ($charset) { $type.='; charset='.$charset; }
 8006:     if ($r) {
 8007: 	$r->content_type($type);
 8008:     } else {
 8009: 	print("Content-type: $type\n\n");
 8010:     }
 8011: }
 8012: 
 8013: =pod
 8014: 
 8015: =item * &add_to_env($name,$value) 
 8016: 
 8017: adds $name to the %env hash with value
 8018: $value, if $name already exists, the entry is converted to an array
 8019: reference and $value is added to the array.
 8020: 
 8021: =cut
 8022: 
 8023: sub add_to_env {
 8024:   my ($name,$value)=@_;
 8025:   if (defined($env{$name})) {
 8026:     if (ref($env{$name})) {
 8027:       #already have multiple values
 8028:       push(@{ $env{$name} },$value);
 8029:     } else {
 8030:       #first time seeing multiple values, convert hash entry to an arrayref
 8031:       my $first=$env{$name};
 8032:       undef($env{$name});
 8033:       push(@{ $env{$name} },$first,$value);
 8034:     }
 8035:   } else {
 8036:     $env{$name}=$value;
 8037:   }
 8038: }
 8039: 
 8040: =pod
 8041: 
 8042: =item * &get_env_multiple($name) 
 8043: 
 8044: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8045: values may be defined and end up as an array ref.
 8046: 
 8047: returns an array of values
 8048: 
 8049: =cut
 8050: 
 8051: sub get_env_multiple {
 8052:     my ($name) = @_;
 8053:     my @values;
 8054:     if (defined($env{$name})) {
 8055:         # exists is it an array
 8056:         if (ref($env{$name})) {
 8057:             @values=@{ $env{$name} };
 8058:         } else {
 8059:             $values[0]=$env{$name};
 8060:         }
 8061:     }
 8062:     return(@values);
 8063: }
 8064: 
 8065: sub ask_for_embedded_content {
 8066:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8067:     my $upload_output = '
 8068:    <form name="upload_embedded" action="'.$actionurl.'"
 8069:                   method="post" enctype="multipart/form-data">';
 8070:     $upload_output .= $state;
 8071:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8072: 
 8073:     my $num = 0;
 8074:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8075:         $upload_output .= &start_data_table_row().
 8076:             '<td>'.$embed_file.'</td><td>';
 8077:         if ($args->{'ignore_remote_references'}
 8078:             && $embed_file =~ m{^\w+://}) {
 8079:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8080:         } elsif ($args->{'error_on_invalid_names'}
 8081:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8082: 
 8083:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8084: 
 8085:         } else {
 8086:             $upload_output .='
 8087:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8088:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8089:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8090:             $upload_output .=
 8091:                 "\n\t\t".
 8092:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8093:                 $attrib.'" />';
 8094:             if (exists($$codebase{$embed_file})) {
 8095:                 $upload_output .=
 8096:                     "\n\t\t".
 8097:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8098:                     &escape($$codebase{$embed_file}).'" />';
 8099:             }
 8100:         }
 8101:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8102:         $num++;
 8103:     }
 8104:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8105:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8106:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8107:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8108:    </form>';
 8109:     return $upload_output;
 8110: }
 8111: 
 8112: sub upload_embedded {
 8113:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8114:         $current_disk_usage) = @_;
 8115:     my $output;
 8116:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8117:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8118:         my $orig_uploaded_filename =
 8119:             $env{'form.embedded_item_'.$i.'.filename'};
 8120: 
 8121:         $env{'form.embedded_orig_'.$i} =
 8122:             &unescape($env{'form.embedded_orig_'.$i});
 8123:         my ($path,$fname) =
 8124:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8125:         # no path, whole string is fname
 8126:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8127: 
 8128:         $path = $env{'form.currentpath'}.$path;
 8129:         $fname = &Apache::lonnet::clean_filename($fname);
 8130:         # See if there is anything left
 8131:         next if ($fname eq '');
 8132: 
 8133:         # Check if file already exists as a file or directory.
 8134:         my ($state,$msg);
 8135:         if ($context eq 'portfolio') {
 8136:             my $port_path = $dirpath;
 8137:             if ($group ne '') {
 8138:                 $port_path = "groups/$group/$port_path";
 8139:             }
 8140:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8141:                                               $dir_root,$port_path,$disk_quota,
 8142:                                               $current_disk_usage,$uname,$udom);
 8143:             if ($state eq 'will_exceed_quota'
 8144:                 || $state eq 'file_locked'
 8145:                 || $state eq 'file_exists' ) {
 8146:                 $output .= $msg;
 8147:                 next;
 8148:             }
 8149:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8150:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8151:             if ($state eq 'exists') {
 8152:                 $output .= $msg;
 8153:                 next;
 8154:             }
 8155:         }
 8156:         # Check if extension is valid
 8157:         if (($fname =~ /\.(\w+)$/) &&
 8158:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8159:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8160:             next;
 8161:         } elsif (($fname =~ /\.(\w+)$/) &&
 8162:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8163:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8164:             next;
 8165:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8166:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8167:             next;
 8168:         }
 8169: 
 8170:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8171:         if ($context eq 'portfolio') {
 8172:             my $result=
 8173:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8174:                                                 $dirpath.$path);
 8175:             if ($result !~ m|^/uploaded/|) {
 8176:                 $output .= '<span class="LC_error">'
 8177:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8178:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8179:                       .'</span><br />';
 8180:                 next;
 8181:             } else {
 8182:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8183:                            $path.$fname.'</span>').'</p>';     
 8184:             }
 8185:         } else {
 8186: # Save the file
 8187:             my $target = $env{'form.embedded_item_'.$i};
 8188:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8189:             my $dest = $fullpath.$fname;
 8190:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8191:             my @parts=split(/\//,$fullpath);
 8192:             my $count;
 8193:             my $filepath = $dir_root;
 8194:             for ($count=4;$count<=$#parts;$count++) {
 8195:                 $filepath .= "/$parts[$count]";
 8196:                 if ((-e $filepath)!=1) {
 8197:                     mkdir($filepath,0770);
 8198:                 }
 8199:             }
 8200:             my $fh;
 8201:             if (!open($fh,'>'.$dest)) {
 8202:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8203:                 $output .= '<span class="LC_error">'.
 8204:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8205:                            '</span><br />';
 8206:             } else {
 8207:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8208:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8209:                     $output .= '<span class="LC_error">'.
 8210:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8211:                               '</span><br />';
 8212:                 } else {
 8213:                     if ($context eq 'testbank') {
 8214:                         $output .= &mt('Embedded file uploaded successfully:').
 8215:                                    '&nbsp;<a href="'.$url.'">'.
 8216:                                    $orig_uploaded_filename.'</a><br />';
 8217:                     } else {
 8218:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8219:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8220:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8221:                     }
 8222:                 }
 8223:                 close($fh);
 8224:             }
 8225:         }
 8226:     }
 8227:     return $output;
 8228: }
 8229: 
 8230: sub check_for_existing {
 8231:     my ($path,$fname,$element) = @_;
 8232:     my ($state,$msg);
 8233:     if (-d $path.'/'.$fname) {
 8234:         $state = 'exists';
 8235:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8236:     } elsif (-e $path.'/'.$fname) {
 8237:         $state = 'exists';
 8238:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8239:     }
 8240:     if ($state eq 'exists') {
 8241:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8242:     }
 8243:     return ($state,$msg);
 8244: }
 8245: 
 8246: sub check_for_upload {
 8247:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8248:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8249:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8250:     my $getpropath = 1;
 8251:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8252:                                             $getpropath);
 8253:     my $found_file = 0;
 8254:     my $locked_file = 0;
 8255:     foreach my $line (@dir_list) {
 8256:         my ($file_name)=split(/\&/,$line,2);
 8257:         if ($file_name eq $fname){
 8258:             $file_name = $path.$file_name;
 8259:             if ($group ne '') {
 8260:                 $file_name = $group.$file_name;
 8261:             }
 8262:             $found_file = 1;
 8263:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8264:                 $locked_file = 1;
 8265:             }
 8266:         }
 8267:     }
 8268:     if (($current_disk_usage + $filesize) > $disk_quota){
 8269:         my $msg = '<span class="LC_error">'.
 8270:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8271:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8272:         return ('will_exceed_quota',$msg);
 8273:     } elsif ($found_file) {
 8274:         if ($locked_file) {
 8275:             my $msg = '<span class="LC_error">';
 8276:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
 8277:             $msg .= '</span><br />';
 8278:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8279:             return ('file_locked',$msg);
 8280:         } else {
 8281:             my $msg = '<span class="LC_error">';
 8282:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 8283:             $msg .= '</span>';
 8284:             $msg .= '<br />';
 8285:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8286:             return ('file_exists',$msg);
 8287:         }
 8288:     }
 8289: }
 8290: 
 8291: 
 8292: =pod
 8293: 
 8294: =back
 8295: 
 8296: =head1 CSV Upload/Handling functions
 8297: 
 8298: =over 4
 8299: 
 8300: =item * &upfile_store($r)
 8301: 
 8302: Store uploaded file, $r should be the HTTP Request object,
 8303: needs $env{'form.upfile'}
 8304: returns $datatoken to be put into hidden field
 8305: 
 8306: =cut
 8307: 
 8308: sub upfile_store {
 8309:     my $r=shift;
 8310:     $env{'form.upfile'}=~s/\r/\n/gs;
 8311:     $env{'form.upfile'}=~s/\f/\n/gs;
 8312:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8313:     $env{'form.upfile'}=~s/\n+$//gs;
 8314: 
 8315:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8316: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8317:     {
 8318:         my $datafile = $r->dir_config('lonDaemons').
 8319:                            '/tmp/'.$datatoken.'.tmp';
 8320:         if ( open(my $fh,">$datafile") ) {
 8321:             print $fh $env{'form.upfile'};
 8322:             close($fh);
 8323:         }
 8324:     }
 8325:     return $datatoken;
 8326: }
 8327: 
 8328: =pod
 8329: 
 8330: =item * &load_tmp_file($r)
 8331: 
 8332: Load uploaded file from tmp, $r should be the HTTP Request object,
 8333: needs $env{'form.datatoken'},
 8334: sets $env{'form.upfile'} to the contents of the file
 8335: 
 8336: =cut
 8337: 
 8338: sub load_tmp_file {
 8339:     my $r=shift;
 8340:     my @studentdata=();
 8341:     {
 8342:         my $studentfile = $r->dir_config('lonDaemons').
 8343:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8344:         if ( open(my $fh,"<$studentfile") ) {
 8345:             @studentdata=<$fh>;
 8346:             close($fh);
 8347:         }
 8348:     }
 8349:     $env{'form.upfile'}=join('',@studentdata);
 8350: }
 8351: 
 8352: =pod
 8353: 
 8354: =item * &upfile_record_sep()
 8355: 
 8356: Separate uploaded file into records
 8357: returns array of records,
 8358: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8359: 
 8360: =cut
 8361: 
 8362: sub upfile_record_sep {
 8363:     if ($env{'form.upfiletype'} eq 'xml') {
 8364:     } else {
 8365: 	my @records;
 8366: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8367: 	    if ($line=~/^\s*$/) { next; }
 8368: 	    push(@records,$line);
 8369: 	}
 8370: 	return @records;
 8371:     }
 8372: }
 8373: 
 8374: =pod
 8375: 
 8376: =item * &record_sep($record)
 8377: 
 8378: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8379: 
 8380: =cut
 8381: 
 8382: sub takeleft {
 8383:     my $index=shift;
 8384:     return substr('0000'.$index,-4,4);
 8385: }
 8386: 
 8387: sub record_sep {
 8388:     my $record=shift;
 8389:     my %components=();
 8390:     if ($env{'form.upfiletype'} eq 'xml') {
 8391:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8392:         my $i=0;
 8393:         foreach my $field (split(/\s+/,$record)) {
 8394:             $field=~s/^(\"|\')//;
 8395:             $field=~s/(\"|\')$//;
 8396:             $components{&takeleft($i)}=$field;
 8397:             $i++;
 8398:         }
 8399:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8400:         my $i=0;
 8401:         foreach my $field (split(/\t/,$record)) {
 8402:             $field=~s/^(\"|\')//;
 8403:             $field=~s/(\"|\')$//;
 8404:             $components{&takeleft($i)}=$field;
 8405:             $i++;
 8406:         }
 8407:     } else {
 8408:         my $separator=',';
 8409:         if ($env{'form.upfiletype'} eq 'semisv') {
 8410:             $separator=';';
 8411:         }
 8412:         my $i=0;
 8413: # the character we are looking for to indicate the end of a quote or a record 
 8414:         my $looking_for=$separator;
 8415: # do not add the characters to the fields
 8416:         my $ignore=0;
 8417: # we just encountered a separator (or the beginning of the record)
 8418:         my $just_found_separator=1;
 8419: # store the field we are working on here
 8420:         my $field='';
 8421: # work our way through all characters in record
 8422:         foreach my $character ($record=~/(.)/g) {
 8423:             if ($character eq $looking_for) {
 8424:                if ($character ne $separator) {
 8425: # Found the end of a quote, again looking for separator
 8426:                   $looking_for=$separator;
 8427:                   $ignore=1;
 8428:                } else {
 8429: # Found a separator, store away what we got
 8430:                   $components{&takeleft($i)}=$field;
 8431: 	          $i++;
 8432:                   $just_found_separator=1;
 8433:                   $ignore=0;
 8434:                   $field='';
 8435:                }
 8436:                next;
 8437:             }
 8438: # single or double quotation marks after a separator indicate beginning of a quote
 8439: # we are now looking for the end of the quote and need to ignore separators
 8440:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8441:                $looking_for=$character;
 8442:                next;
 8443:             }
 8444: # ignore would be true after we reached the end of a quote
 8445:             if ($ignore) { next; }
 8446:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8447:             $field.=$character;
 8448:             $just_found_separator=0; 
 8449:         }
 8450: # catch the very last entry, since we never encountered the separator
 8451:         $components{&takeleft($i)}=$field;
 8452:     }
 8453:     return %components;
 8454: }
 8455: 
 8456: ######################################################
 8457: ######################################################
 8458: 
 8459: =pod
 8460: 
 8461: =item * &upfile_select_html()
 8462: 
 8463: Return HTML code to select a file from the users machine and specify 
 8464: the file type.
 8465: 
 8466: =cut
 8467: 
 8468: ######################################################
 8469: ######################################################
 8470: sub upfile_select_html {
 8471:     my %Types = (
 8472:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8473:                  semisv => &mt('Semicolon separated values'),
 8474:                  space => &mt('Space separated'),
 8475:                  tab   => &mt('Tabulator separated'),
 8476: #                 xml   => &mt('HTML/XML'),
 8477:                  );
 8478:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8479:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8480:     foreach my $type (sort(keys(%Types))) {
 8481:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8482:     }
 8483:     $Str .= "</select>\n";
 8484:     return $Str;
 8485: }
 8486: 
 8487: sub get_samples {
 8488:     my ($records,$toget) = @_;
 8489:     my @samples=({});
 8490:     my $got=0;
 8491:     foreach my $rec (@$records) {
 8492: 	my %temp = &record_sep($rec);
 8493: 	if (! grep(/\S/, values(%temp))) { next; }
 8494: 	if (%temp) {
 8495: 	    $samples[$got]=\%temp;
 8496: 	    $got++;
 8497: 	    if ($got == $toget) { last; }
 8498: 	}
 8499:     }
 8500:     return \@samples;
 8501: }
 8502: 
 8503: ######################################################
 8504: ######################################################
 8505: 
 8506: =pod
 8507: 
 8508: =item * &csv_print_samples($r,$records)
 8509: 
 8510: Prints a table of sample values from each column uploaded $r is an
 8511: Apache Request ref, $records is an arrayref from
 8512: &Apache::loncommon::upfile_record_sep
 8513: 
 8514: =cut
 8515: 
 8516: ######################################################
 8517: ######################################################
 8518: sub csv_print_samples {
 8519:     my ($r,$records) = @_;
 8520:     my $samples = &get_samples($records,5);
 8521: 
 8522:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8523:               &start_data_table_header_row());
 8524:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8525:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8526:     $r->print(&end_data_table_header_row());
 8527:     foreach my $hash (@$samples) {
 8528: 	$r->print(&start_data_table_row());
 8529: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8530: 	    $r->print('<td>');
 8531: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8532: 	    $r->print('</td>');
 8533: 	}
 8534: 	$r->print(&end_data_table_row());
 8535:     }
 8536:     $r->print(&end_data_table().'<br />'."\n");
 8537: }
 8538: 
 8539: ######################################################
 8540: ######################################################
 8541: 
 8542: =pod
 8543: 
 8544: =item * &csv_print_select_table($r,$records,$d)
 8545: 
 8546: Prints a table to create associations between values and table columns.
 8547: 
 8548: $r is an Apache Request ref,
 8549: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8550: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8551: 
 8552: =cut
 8553: 
 8554: ######################################################
 8555: ######################################################
 8556: sub csv_print_select_table {
 8557:     my ($r,$records,$d) = @_;
 8558:     my $i=0;
 8559:     my $samples = &get_samples($records,1);
 8560:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8561: 	      &start_data_table().&start_data_table_header_row().
 8562:               '<th>'.&mt('Attribute').'</th>'.
 8563:               '<th>'.&mt('Column').'</th>'.
 8564:               &end_data_table_header_row()."\n");
 8565:     foreach my $array_ref (@$d) {
 8566: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8567: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8568: 
 8569: 	$r->print('<td><select name=f'.$i.
 8570: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8571: 	$r->print('<option value="none"></option>');
 8572: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8573: 	    $r->print('<option value="'.$sample.'"'.
 8574:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8575:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8576: 	}
 8577: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8578: 	$i++;
 8579:     }
 8580:     $r->print(&end_data_table());
 8581:     $i--;
 8582:     return $i;
 8583: }
 8584: 
 8585: ######################################################
 8586: ######################################################
 8587: 
 8588: =pod
 8589: 
 8590: =item * &csv_samples_select_table($r,$records,$d)
 8591: 
 8592: Prints a table of sample values from the upload and can make associate samples to internal names.
 8593: 
 8594: $r is an Apache Request ref,
 8595: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8596: $d is an array of 2 element arrays (internal name, displayed name)
 8597: 
 8598: =cut
 8599: 
 8600: ######################################################
 8601: ######################################################
 8602: sub csv_samples_select_table {
 8603:     my ($r,$records,$d) = @_;
 8604:     my $i=0;
 8605:     #
 8606:     my $max_samples = 5;
 8607:     my $samples = &get_samples($records,$max_samples);
 8608:     $r->print(&start_data_table().
 8609:               &start_data_table_header_row().'<th>'.
 8610:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8611:               &end_data_table_header_row());
 8612: 
 8613:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8614: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8615: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8616: 	foreach my $option (@$d) {
 8617: 	    my ($value,$display,$defaultcol)=@{ $option };
 8618: 	    $r->print('<option value="'.$value.'"'.
 8619:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8620:                       $display.'</option>');
 8621: 	}
 8622: 	$r->print('</select></td><td>');
 8623: 	foreach my $line (0..($max_samples-1)) {
 8624: 	    if (defined($samples->[$line]{$key})) { 
 8625: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8626: 	    }
 8627: 	}
 8628: 	$r->print('</td>'.&end_data_table_row());
 8629: 	$i++;
 8630:     }
 8631:     $r->print(&end_data_table());
 8632:     $i--;
 8633:     return($i);
 8634: }
 8635: 
 8636: ######################################################
 8637: ######################################################
 8638: 
 8639: =pod
 8640: 
 8641: =item * &clean_excel_name($name)
 8642: 
 8643: Returns a replacement for $name which does not contain any illegal characters.
 8644: 
 8645: =cut
 8646: 
 8647: ######################################################
 8648: ######################################################
 8649: sub clean_excel_name {
 8650:     my ($name) = @_;
 8651:     $name =~ s/[:\*\?\/\\]//g;
 8652:     if (length($name) > 31) {
 8653:         $name = substr($name,0,31);
 8654:     }
 8655:     return $name;
 8656: }
 8657: 
 8658: =pod
 8659: 
 8660: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8661: 
 8662: Returns either 1 or undef
 8663: 
 8664: 1 if the part is to be hidden, undef if it is to be shown
 8665: 
 8666: Arguments are:
 8667: 
 8668: $id the id of the part to be checked
 8669: $symb, optional the symb of the resource to check
 8670: $udom, optional the domain of the user to check for
 8671: $uname, optional the username of the user to check for
 8672: 
 8673: =cut
 8674: 
 8675: sub check_if_partid_hidden {
 8676:     my ($id,$symb,$udom,$uname) = @_;
 8677:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8678: 					 $symb,$udom,$uname);
 8679:     my $truth=1;
 8680:     #if the string starts with !, then the list is the list to show not hide
 8681:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8682:     my @hiddenlist=split(/,/,$hiddenparts);
 8683:     foreach my $checkid (@hiddenlist) {
 8684: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8685:     }
 8686:     return !$truth;
 8687: }
 8688: 
 8689: 
 8690: ############################################################
 8691: ############################################################
 8692: 
 8693: =pod
 8694: 
 8695: =back 
 8696: 
 8697: =head1 cgi-bin script and graphing routines
 8698: 
 8699: =over 4
 8700: 
 8701: =item * &get_cgi_id()
 8702: 
 8703: Inputs: none
 8704: 
 8705: Returns an id which can be used to pass environment variables
 8706: to various cgi-bin scripts.  These environment variables will
 8707: be removed from the users environment after a given time by
 8708: the routine &Apache::lonnet::transfer_profile_to_env.
 8709: 
 8710: =cut
 8711: 
 8712: ############################################################
 8713: ############################################################
 8714: my $uniq=0;
 8715: sub get_cgi_id {
 8716:     $uniq=($uniq+1)%100000;
 8717:     return (time.'_'.$$.'_'.$uniq);
 8718: }
 8719: 
 8720: ############################################################
 8721: ############################################################
 8722: 
 8723: =pod
 8724: 
 8725: =item * &DrawBarGraph()
 8726: 
 8727: Facilitates the plotting of data in a (stacked) bar graph.
 8728: Puts plot definition data into the users environment in order for 
 8729: graph.png to plot it.  Returns an <img> tag for the plot.
 8730: The bars on the plot are labeled '1','2',...,'n'.
 8731: 
 8732: Inputs:
 8733: 
 8734: =over 4
 8735: 
 8736: =item $Title: string, the title of the plot
 8737: 
 8738: =item $xlabel: string, text describing the X-axis of the plot
 8739: 
 8740: =item $ylabel: string, text describing the Y-axis of the plot
 8741: 
 8742: =item $Max: scalar, the maximum Y value to use in the plot
 8743: If $Max is < any data point, the graph will not be rendered.
 8744: 
 8745: =item $colors: array ref holding the colors to be used for the data sets when
 8746: they are plotted.  If undefined, default values will be used.
 8747: 
 8748: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8749: 
 8750: =item @Values: An array of array references.  Each array reference holds data
 8751: to be plotted in a stacked bar chart.
 8752: 
 8753: =item If the final element of @Values is a hash reference the key/value
 8754: pairs will be added to the graph definition.
 8755: 
 8756: =back
 8757: 
 8758: Returns:
 8759: 
 8760: An <img> tag which references graph.png and the appropriate identifying
 8761: information for the plot.
 8762: 
 8763: =cut
 8764: 
 8765: ############################################################
 8766: ############################################################
 8767: sub DrawBarGraph {
 8768:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8769:     #
 8770:     if (! defined($colors)) {
 8771:         $colors = ['#33ff00', 
 8772:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8773:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8774:                   ]; 
 8775:     }
 8776:     my $extra_settings = {};
 8777:     if (ref($Values[-1]) eq 'HASH') {
 8778:         $extra_settings = pop(@Values);
 8779:     }
 8780:     #
 8781:     my $identifier = &get_cgi_id();
 8782:     my $id = 'cgi.'.$identifier;        
 8783:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8784:         return '';
 8785:     }
 8786:     #
 8787:     my @Labels;
 8788:     if (defined($labels)) {
 8789:         @Labels = @$labels;
 8790:     } else {
 8791:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8792:             push (@Labels,$i+1);
 8793:         }
 8794:     }
 8795:     #
 8796:     my $NumBars = scalar(@{$Values[0]});
 8797:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8798:     my %ValuesHash;
 8799:     my $NumSets=1;
 8800:     foreach my $array (@Values) {
 8801:         next if (! ref($array));
 8802:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8803:             join(',',@$array);
 8804:     }
 8805:     #
 8806:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8807:     if ($NumBars < 3) {
 8808:         $width = 120+$NumBars*32;
 8809:         $xskip = 1;
 8810:         $bar_width = 30;
 8811:     } elsif ($NumBars < 5) {
 8812:         $width = 120+$NumBars*20;
 8813:         $xskip = 1;
 8814:         $bar_width = 20;
 8815:     } elsif ($NumBars < 10) {
 8816:         $width = 120+$NumBars*15;
 8817:         $xskip = 1;
 8818:         $bar_width = 15;
 8819:     } elsif ($NumBars <= 25) {
 8820:         $width = 120+$NumBars*11;
 8821:         $xskip = 5;
 8822:         $bar_width = 8;
 8823:     } elsif ($NumBars <= 50) {
 8824:         $width = 120+$NumBars*8;
 8825:         $xskip = 5;
 8826:         $bar_width = 4;
 8827:     } else {
 8828:         $width = 120+$NumBars*8;
 8829:         $xskip = 5;
 8830:         $bar_width = 4;
 8831:     }
 8832:     #
 8833:     $Max = 1 if ($Max < 1);
 8834:     if ( int($Max) < $Max ) {
 8835:         $Max++;
 8836:         $Max = int($Max);
 8837:     }
 8838:     $Title  = '' if (! defined($Title));
 8839:     $xlabel = '' if (! defined($xlabel));
 8840:     $ylabel = '' if (! defined($ylabel));
 8841:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8842:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8843:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8844:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8845:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8846:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8847:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8848:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8849:     $ValuesHash{$id.'.height'}   = $height;
 8850:     $ValuesHash{$id.'.width'}    = $width;
 8851:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8852:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8853:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8854:     #
 8855:     # Deal with other parameters
 8856:     while (my ($key,$value) = each(%$extra_settings)) {
 8857:         $ValuesHash{$id.'.'.$key} = $value;
 8858:     }
 8859:     #
 8860:     &Apache::lonnet::appenv(\%ValuesHash);
 8861:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8862: }
 8863: 
 8864: ############################################################
 8865: ############################################################
 8866: 
 8867: =pod
 8868: 
 8869: =item * &DrawXYGraph()
 8870: 
 8871: Facilitates the plotting of data in an XY graph.
 8872: Puts plot definition data into the users environment in order for 
 8873: graph.png to plot it.  Returns an <img> tag for the plot.
 8874: 
 8875: Inputs:
 8876: 
 8877: =over 4
 8878: 
 8879: =item $Title: string, the title of the plot
 8880: 
 8881: =item $xlabel: string, text describing the X-axis of the plot
 8882: 
 8883: =item $ylabel: string, text describing the Y-axis of the plot
 8884: 
 8885: =item $Max: scalar, the maximum Y value to use in the plot
 8886: If $Max is < any data point, the graph will not be rendered.
 8887: 
 8888: =item $colors: Array ref containing the hex color codes for the data to be 
 8889: plotted in.  If undefined, default values will be used.
 8890: 
 8891: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8892: 
 8893: =item $Ydata: Array ref containing Array refs.  
 8894: Each of the contained arrays will be plotted as a separate curve.
 8895: 
 8896: =item %Values: hash indicating or overriding any default values which are 
 8897: passed to graph.png.  
 8898: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8899: 
 8900: =back
 8901: 
 8902: Returns:
 8903: 
 8904: An <img> tag which references graph.png and the appropriate identifying
 8905: information for the plot.
 8906: 
 8907: =cut
 8908: 
 8909: ############################################################
 8910: ############################################################
 8911: sub DrawXYGraph {
 8912:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8913:     #
 8914:     # Create the identifier for the graph
 8915:     my $identifier = &get_cgi_id();
 8916:     my $id = 'cgi.'.$identifier;
 8917:     #
 8918:     $Title  = '' if (! defined($Title));
 8919:     $xlabel = '' if (! defined($xlabel));
 8920:     $ylabel = '' if (! defined($ylabel));
 8921:     my %ValuesHash = 
 8922:         (
 8923:          $id.'.title'  => &escape($Title),
 8924:          $id.'.xlabel' => &escape($xlabel),
 8925:          $id.'.ylabel' => &escape($ylabel),
 8926:          $id.'.y_max_value'=> $Max,
 8927:          $id.'.labels'     => join(',',@$Xlabels),
 8928:          $id.'.PlotType'   => 'XY',
 8929:          );
 8930:     #
 8931:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8932:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8933:     }
 8934:     #
 8935:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8936:         return '';
 8937:     }
 8938:     my $NumSets=1;
 8939:     foreach my $array (@{$Ydata}){
 8940:         next if (! ref($array));
 8941:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8942:     }
 8943:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8944:     #
 8945:     # Deal with other parameters
 8946:     while (my ($key,$value) = each(%Values)) {
 8947:         $ValuesHash{$id.'.'.$key} = $value;
 8948:     }
 8949:     #
 8950:     &Apache::lonnet::appenv(\%ValuesHash);
 8951:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8952: }
 8953: 
 8954: ############################################################
 8955: ############################################################
 8956: 
 8957: =pod
 8958: 
 8959: =item * &DrawXYYGraph()
 8960: 
 8961: Facilitates the plotting of data in an XY graph with two Y axes.
 8962: Puts plot definition data into the users environment in order for 
 8963: graph.png to plot it.  Returns an <img> tag for the plot.
 8964: 
 8965: Inputs:
 8966: 
 8967: =over 4
 8968: 
 8969: =item $Title: string, the title of the plot
 8970: 
 8971: =item $xlabel: string, text describing the X-axis of the plot
 8972: 
 8973: =item $ylabel: string, text describing the Y-axis of the plot
 8974: 
 8975: =item $colors: Array ref containing the hex color codes for the data to be 
 8976: plotted in.  If undefined, default values will be used.
 8977: 
 8978: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8979: 
 8980: =item $Ydata1: The first data set
 8981: 
 8982: =item $Min1: The minimum value of the left Y-axis
 8983: 
 8984: =item $Max1: The maximum value of the left Y-axis
 8985: 
 8986: =item $Ydata2: The second data set
 8987: 
 8988: =item $Min2: The minimum value of the right Y-axis
 8989: 
 8990: =item $Max2: The maximum value of the left Y-axis
 8991: 
 8992: =item %Values: hash indicating or overriding any default values which are 
 8993: passed to graph.png.  
 8994: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8995: 
 8996: =back
 8997: 
 8998: Returns:
 8999: 
 9000: An <img> tag which references graph.png and the appropriate identifying
 9001: information for the plot.
 9002: 
 9003: =cut
 9004: 
 9005: ############################################################
 9006: ############################################################
 9007: sub DrawXYYGraph {
 9008:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9009:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9010:     #
 9011:     # Create the identifier for the graph
 9012:     my $identifier = &get_cgi_id();
 9013:     my $id = 'cgi.'.$identifier;
 9014:     #
 9015:     $Title  = '' if (! defined($Title));
 9016:     $xlabel = '' if (! defined($xlabel));
 9017:     $ylabel = '' if (! defined($ylabel));
 9018:     my %ValuesHash = 
 9019:         (
 9020:          $id.'.title'  => &escape($Title),
 9021:          $id.'.xlabel' => &escape($xlabel),
 9022:          $id.'.ylabel' => &escape($ylabel),
 9023:          $id.'.labels' => join(',',@$Xlabels),
 9024:          $id.'.PlotType' => 'XY',
 9025:          $id.'.NumSets' => 2,
 9026:          $id.'.two_axes' => 1,
 9027:          $id.'.y1_max_value' => $Max1,
 9028:          $id.'.y1_min_value' => $Min1,
 9029:          $id.'.y2_max_value' => $Max2,
 9030:          $id.'.y2_min_value' => $Min2,
 9031:          );
 9032:     #
 9033:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9034:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9035:     }
 9036:     #
 9037:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9038:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9039:         return '';
 9040:     }
 9041:     my $NumSets=1;
 9042:     foreach my $array ($Ydata1,$Ydata2){
 9043:         next if (! ref($array));
 9044:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9045:     }
 9046:     #
 9047:     # Deal with other parameters
 9048:     while (my ($key,$value) = each(%Values)) {
 9049:         $ValuesHash{$id.'.'.$key} = $value;
 9050:     }
 9051:     #
 9052:     &Apache::lonnet::appenv(\%ValuesHash);
 9053:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9054: }
 9055: 
 9056: ############################################################
 9057: ############################################################
 9058: 
 9059: =pod
 9060: 
 9061: =back 
 9062: 
 9063: =head1 Statistics helper routines?  
 9064: 
 9065: Bad place for them but what the hell.
 9066: 
 9067: =over 4
 9068: 
 9069: =item * &chartlink()
 9070: 
 9071: Returns a link to the chart for a specific student.  
 9072: 
 9073: Inputs:
 9074: 
 9075: =over 4
 9076: 
 9077: =item $linktext: The text of the link
 9078: 
 9079: =item $sname: The students username
 9080: 
 9081: =item $sdomain: The students domain
 9082: 
 9083: =back
 9084: 
 9085: =back
 9086: 
 9087: =cut
 9088: 
 9089: ############################################################
 9090: ############################################################
 9091: sub chartlink {
 9092:     my ($linktext, $sname, $sdomain) = @_;
 9093:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9094:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9095:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9096:        '">'.$linktext.'</a>';
 9097: }
 9098: 
 9099: #######################################################
 9100: #######################################################
 9101: 
 9102: =pod
 9103: 
 9104: =head1 Course Environment Routines
 9105: 
 9106: =over 4
 9107: 
 9108: =item * &restore_course_settings()
 9109: 
 9110: =item * &store_course_settings()
 9111: 
 9112: Restores/Store indicated form parameters from the course environment.
 9113: Will not overwrite existing values of the form parameters.
 9114: 
 9115: Inputs: 
 9116: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9117: 
 9118: a hash ref describing the data to be stored.  For example:
 9119:    
 9120: %Save_Parameters = ('Status' => 'scalar',
 9121:     'chartoutputmode' => 'scalar',
 9122:     'chartoutputdata' => 'scalar',
 9123:     'Section' => 'array',
 9124:     'Group' => 'array',
 9125:     'StudentData' => 'array',
 9126:     'Maps' => 'array');
 9127: 
 9128: Returns: both routines return nothing
 9129: 
 9130: =back
 9131: 
 9132: =cut
 9133: 
 9134: #######################################################
 9135: #######################################################
 9136: sub store_course_settings {
 9137:     return &store_settings($env{'request.course.id'},@_);
 9138: }
 9139: 
 9140: sub store_settings {
 9141:     # save to the environment
 9142:     # appenv the same items, just to be safe
 9143:     my $udom  = $env{'user.domain'};
 9144:     my $uname = $env{'user.name'};
 9145:     my ($context,$prefix,$Settings) = @_;
 9146:     my %SaveHash;
 9147:     my %AppHash;
 9148:     while (my ($setting,$type) = each(%$Settings)) {
 9149:         my $basename = join('.','internal',$context,$prefix,$setting);
 9150:         my $envname = 'environment.'.$basename;
 9151:         if (exists($env{'form.'.$setting})) {
 9152:             # Save this value away
 9153:             if ($type eq 'scalar' &&
 9154:                 (! exists($env{$envname}) || 
 9155:                  $env{$envname} ne $env{'form.'.$setting})) {
 9156:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9157:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9158:             } elsif ($type eq 'array') {
 9159:                 my $stored_form;
 9160:                 if (ref($env{'form.'.$setting})) {
 9161:                     $stored_form = join(',',
 9162:                                         map {
 9163:                                             &escape($_);
 9164:                                         } sort(@{$env{'form.'.$setting}}));
 9165:                 } else {
 9166:                     $stored_form = 
 9167:                         &escape($env{'form.'.$setting});
 9168:                 }
 9169:                 # Determine if the array contents are the same.
 9170:                 if ($stored_form ne $env{$envname}) {
 9171:                     $SaveHash{$basename} = $stored_form;
 9172:                     $AppHash{$envname}   = $stored_form;
 9173:                 }
 9174:             }
 9175:         }
 9176:     }
 9177:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9178:                                           $udom,$uname);
 9179:     if ($put_result !~ /^(ok|delayed)/) {
 9180:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9181:                                  'got error:'.$put_result);
 9182:     }
 9183:     # Make sure these settings stick around in this session, too
 9184:     &Apache::lonnet::appenv(\%AppHash);
 9185:     return;
 9186: }
 9187: 
 9188: sub restore_course_settings {
 9189:     return &restore_settings($env{'request.course.id'},@_);
 9190: }
 9191: 
 9192: sub restore_settings {
 9193:     my ($context,$prefix,$Settings) = @_;
 9194:     while (my ($setting,$type) = each(%$Settings)) {
 9195:         next if (exists($env{'form.'.$setting}));
 9196:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9197:             '.'.$setting;
 9198:         if (exists($env{$envname})) {
 9199:             if ($type eq 'scalar') {
 9200:                 $env{'form.'.$setting} = $env{$envname};
 9201:             } elsif ($type eq 'array') {
 9202:                 $env{'form.'.$setting} = [ 
 9203:                                            map { 
 9204:                                                &unescape($_); 
 9205:                                            } split(',',$env{$envname})
 9206:                                            ];
 9207:             }
 9208:         }
 9209:     }
 9210: }
 9211: 
 9212: #######################################################
 9213: #######################################################
 9214: 
 9215: =pod
 9216: 
 9217: =head1 Domain E-mail Routines  
 9218: 
 9219: =over 4
 9220: 
 9221: =item * &build_recipient_list()
 9222: 
 9223: Build recipient lists for four types of e-mail:
 9224: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9225: (d) Help requests, generated by
 9226: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 9227: 
 9228: Inputs:
 9229: defmail (scalar - email address of default recipient), 
 9230: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9231: defdom (domain for which to retrieve configuration settings),
 9232: origmail (scalar - email address of recipient from loncapa.conf, 
 9233: i.e., predates configuration by DC via domainprefs.pm 
 9234: 
 9235: Returns: comma separated list of addresses to which to send e-mail.
 9236: 
 9237: =back
 9238: 
 9239: =cut
 9240: 
 9241: ############################################################
 9242: ############################################################
 9243: sub build_recipient_list {
 9244:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9245:     my @recipients;
 9246:     my $otheremails;
 9247:     my %domconfig =
 9248:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9249:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9250:         if (exists($domconfig{'contacts'}{$mailing})) {
 9251:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9252:                 my @contacts = ('adminemail','supportemail');
 9253:                 foreach my $item (@contacts) {
 9254:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9255:                         my $addr = $domconfig{'contacts'}{$item}; 
 9256:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9257:                             push(@recipients,$addr);
 9258:                         }
 9259:                     }
 9260:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9261:                 }
 9262:             }
 9263:         } elsif ($origmail ne '') {
 9264:             push(@recipients,$origmail);
 9265:         }
 9266:     } elsif ($origmail ne '') {
 9267:         push(@recipients,$origmail);
 9268:     }
 9269:     if (defined($defmail)) {
 9270:         if ($defmail ne '') {
 9271:             push(@recipients,$defmail);
 9272:         }
 9273:     }
 9274:     if ($otheremails) {
 9275:         my @others;
 9276:         if ($otheremails =~ /,/) {
 9277:             @others = split(/,/,$otheremails);
 9278:         } else {
 9279:             push(@others,$otheremails);
 9280:         }
 9281:         foreach my $addr (@others) {
 9282:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9283:                 push(@recipients,$addr);
 9284:             }
 9285:         }
 9286:     }
 9287:     my $recipientlist = join(',',@recipients); 
 9288:     return $recipientlist;
 9289: }
 9290: 
 9291: ############################################################
 9292: ############################################################
 9293: 
 9294: =pod
 9295: 
 9296: =head1 Course Catalog Routines
 9297: 
 9298: =over 4
 9299: 
 9300: =item * &gather_categories()
 9301: 
 9302: Converts category definitions - keys of categories hash stored in  
 9303: coursecategories in configuration.db on the primary library server in a 
 9304: domain - to an array.  Also generates javascript and idx hash used to 
 9305: generate Domain Coordinator interface for editing Course Categories.
 9306: 
 9307: Inputs:
 9308: 
 9309: categories (reference to hash of category definitions).
 9310: 
 9311: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9312:       categories and subcategories).
 9313: 
 9314: idx (reference to hash of counters used in Domain Coordinator interface for 
 9315:       editing Course Categories).
 9316: 
 9317: jsarray (reference to array of categories used to create Javascript arrays for
 9318:          Domain Coordinator interface for editing Course Categories).
 9319: 
 9320: Returns: nothing
 9321: 
 9322: Side effects: populates cats, idx and jsarray. 
 9323: 
 9324: =cut
 9325: 
 9326: sub gather_categories {
 9327:     my ($categories,$cats,$idx,$jsarray) = @_;
 9328:     my %counters;
 9329:     my $num = 0;
 9330:     foreach my $item (keys(%{$categories})) {
 9331:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9332:         if ($container eq '' && $depth == 0) {
 9333:             $cats->[$depth][$categories->{$item}] = $cat;
 9334:         } else {
 9335:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9336:         }
 9337:         my ($escitem,$tail) = split(/:/,$item,2);
 9338:         if ($counters{$tail} eq '') {
 9339:             $counters{$tail} = $num;
 9340:             $num ++;
 9341:         }
 9342:         if (ref($idx) eq 'HASH') {
 9343:             $idx->{$item} = $counters{$tail};
 9344:         }
 9345:         if (ref($jsarray) eq 'ARRAY') {
 9346:             push(@{$jsarray->[$counters{$tail}]},$item);
 9347:         }
 9348:     }
 9349:     return;
 9350: }
 9351: 
 9352: =pod
 9353: 
 9354: =item * &extract_categories()
 9355: 
 9356: Used to generate breadcrumb trails for course categories.
 9357: 
 9358: Inputs:
 9359: 
 9360: categories (reference to hash of category definitions).
 9361: 
 9362: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9363:       categories and subcategories).
 9364: 
 9365: trails (reference to array of breacrumb trails for each category).
 9366: 
 9367: allitems (reference to hash - key is category key 
 9368:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9369: 
 9370: idx (reference to hash of counters used in Domain Coordinator interface for
 9371:       editing Course Categories).
 9372: 
 9373: jsarray (reference to array of categories used to create Javascript arrays for
 9374:          Domain Coordinator interface for editing Course Categories).
 9375: 
 9376: subcats (reference to hash of arrays containing all subcategories within each 
 9377:          category, -recursive)
 9378: 
 9379: Returns: nothing
 9380: 
 9381: Side effects: populates trails and allitems hash references.
 9382: 
 9383: =cut
 9384: 
 9385: sub extract_categories {
 9386:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9387:     if (ref($categories) eq 'HASH') {
 9388:         &gather_categories($categories,$cats,$idx,$jsarray);
 9389:         if (ref($cats->[0]) eq 'ARRAY') {
 9390:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9391:                 my $name = $cats->[0][$i];
 9392:                 my $item = &escape($name).'::0';
 9393:                 my $trailstr;
 9394:                 if ($name eq 'instcode') {
 9395:                     $trailstr = &mt('Official courses (with institutional codes)');
 9396:                 } else {
 9397:                     $trailstr = $name;
 9398:                 }
 9399:                 if ($allitems->{$item} eq '') {
 9400:                     push(@{$trails},$trailstr);
 9401:                     $allitems->{$item} = scalar(@{$trails})-1;
 9402:                 }
 9403:                 my @parents = ($name);
 9404:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9405:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9406:                         my $category = $cats->[1]{$name}[$j];
 9407:                         if (ref($subcats) eq 'HASH') {
 9408:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9409:                         }
 9410:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9411:                     }
 9412:                 } else {
 9413:                     if (ref($subcats) eq 'HASH') {
 9414:                         $subcats->{$item} = [];
 9415:                     }
 9416:                 }
 9417:             }
 9418:         }
 9419:     }
 9420:     return;
 9421: }
 9422: 
 9423: =pod
 9424: 
 9425: =item *&recurse_categories()
 9426: 
 9427: Recursively used to generate breadcrumb trails for course categories.
 9428: 
 9429: Inputs:
 9430: 
 9431: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9432:       categories and subcategories).
 9433: 
 9434: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9435: 
 9436: category (current course category, for which breadcrumb trail is being generated).
 9437: 
 9438: trails (reference to array of breadcrumb trails for each category).
 9439: 
 9440: allitems (reference to hash - key is category key
 9441:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9442: 
 9443: parents (array containing containers directories for current category, 
 9444:          back to top level). 
 9445: 
 9446: Returns: nothing
 9447: 
 9448: Side effects: populates trails and allitems hash references
 9449: 
 9450: =cut
 9451: 
 9452: sub recurse_categories {
 9453:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9454:     my $shallower = $depth - 1;
 9455:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9456:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9457:             my $name = $cats->[$depth]{$category}[$k];
 9458:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9459:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9460:             if ($allitems->{$item} eq '') {
 9461:                 push(@{$trails},$trailstr);
 9462:                 $allitems->{$item} = scalar(@{$trails})-1;
 9463:             }
 9464:             my $deeper = $depth+1;
 9465:             push(@{$parents},$category);
 9466:             if (ref($subcats) eq 'HASH') {
 9467:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9468:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9469:                     my $higher;
 9470:                     if ($j > 0) {
 9471:                         $higher = &escape($parents->[$j]).':'.
 9472:                                   &escape($parents->[$j-1]).':'.$j;
 9473:                     } else {
 9474:                         $higher = &escape($parents->[$j]).'::'.$j;
 9475:                     }
 9476:                     push(@{$subcats->{$higher}},$subcat);
 9477:                 }
 9478:             }
 9479:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9480:                                 $subcats);
 9481:             pop(@{$parents});
 9482:         }
 9483:     } else {
 9484:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9485:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9486:         if ($allitems->{$item} eq '') {
 9487:             push(@{$trails},$trailstr);
 9488:             $allitems->{$item} = scalar(@{$trails})-1;
 9489:         }
 9490:     }
 9491:     return;
 9492: }
 9493: 
 9494: =pod
 9495: 
 9496: =item *&assign_categories_table()
 9497: 
 9498: Create a datatable for display of hierarchical categories in a domain,
 9499: with checkboxes to allow a course to be categorized. 
 9500: 
 9501: Inputs:
 9502: 
 9503: cathash - reference to hash of categories defined for the domain (from
 9504:           configuration.db)
 9505: 
 9506: currcat - scalar with an & separated list of categories assigned to a course. 
 9507: 
 9508: Returns: $output (markup to be displayed) 
 9509: 
 9510: =cut
 9511: 
 9512: sub assign_categories_table {
 9513:     my ($cathash,$currcat) = @_;
 9514:     my $output;
 9515:     if (ref($cathash) eq 'HASH') {
 9516:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9517:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9518:         $maxdepth = scalar(@cats);
 9519:         if (@cats > 0) {
 9520:             my $itemcount = 0;
 9521:             if (ref($cats[0]) eq 'ARRAY') {
 9522:                 $output = &Apache::loncommon::start_data_table();
 9523:                 my @currcategories;
 9524:                 if ($currcat ne '') {
 9525:                     @currcategories = split('&',$currcat);
 9526:                 }
 9527:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9528:                     my $parent = $cats[0][$i];
 9529:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9530:                     next if ($parent eq 'instcode');
 9531:                     my $item = &escape($parent).'::0';
 9532:                     my $checked = '';
 9533:                     if (@currcategories > 0) {
 9534:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9535:                             $checked = ' checked="checked"';
 9536:                         }
 9537:                     }
 9538:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9539:                                '<input type="checkbox" name="usecategory" value="'.
 9540:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9541:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9542:                     my $depth = 1;
 9543:                     push(@path,$parent);
 9544:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9545:                     pop(@path);
 9546:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9547:                     $itemcount ++;
 9548:                 }
 9549:                 $output .= &Apache::loncommon::end_data_table();
 9550:             }
 9551:         }
 9552:     }
 9553:     return $output;
 9554: }
 9555: 
 9556: =pod
 9557: 
 9558: =item *&assign_category_rows()
 9559: 
 9560: Create a datatable row for display of nested categories in a domain,
 9561: with checkboxes to allow a course to be categorized,called recursively.
 9562: 
 9563: Inputs:
 9564: 
 9565: itemcount - track row number for alternating colors
 9566: 
 9567: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9568:       categories and subcategories.
 9569: 
 9570: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9571: 
 9572: parent - parent of current category item
 9573: 
 9574: path - Array containing all categories back up through the hierarchy from the
 9575:        current category to the top level.
 9576: 
 9577: currcategories - reference to array of current categories assigned to the course
 9578: 
 9579: Returns: $output (markup to be displayed).
 9580: 
 9581: =cut
 9582: 
 9583: sub assign_category_rows {
 9584:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9585:     my ($text,$name,$item,$chgstr);
 9586:     if (ref($cats) eq 'ARRAY') {
 9587:         my $maxdepth = scalar(@{$cats});
 9588:         if (ref($cats->[$depth]) eq 'HASH') {
 9589:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9590:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9591:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9592:                 $text .= '<td><table class="LC_datatable">';
 9593:                 for (my $j=0; $j<$numchildren; $j++) {
 9594:                     $name = $cats->[$depth]{$parent}[$j];
 9595:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9596:                     my $deeper = $depth+1;
 9597:                     my $checked = '';
 9598:                     if (ref($currcategories) eq 'ARRAY') {
 9599:                         if (@{$currcategories} > 0) {
 9600:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9601:                                 $checked = ' checked="checked"';
 9602:                             }
 9603:                         }
 9604:                     }
 9605:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9606:                              '<input type="checkbox" name="usecategory" value="'.
 9607:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9608:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9609:                              '</td><td>';
 9610:                     if (ref($path) eq 'ARRAY') {
 9611:                         push(@{$path},$name);
 9612:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9613:                         pop(@{$path});
 9614:                     }
 9615:                     $text .= '</td></tr>';
 9616:                 }
 9617:                 $text .= '</table></td>';
 9618:             }
 9619:         }
 9620:     }
 9621:     return $text;
 9622: }
 9623: 
 9624: ############################################################
 9625: ############################################################
 9626: 
 9627: 
 9628: sub commit_customrole {
 9629:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9630:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9631:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9632:                          ($end?', ending '.localtime($end):'').': <b>'.
 9633:               &Apache::lonnet::assigncustomrole(
 9634:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9635:                  '</b><br />';
 9636:     return $output;
 9637: }
 9638: 
 9639: sub commit_standardrole {
 9640:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9641:     my ($output,$logmsg,$linefeed);
 9642:     if ($context eq 'auto') {
 9643:         $linefeed = "\n";
 9644:     } else {
 9645:         $linefeed = "<br />\n";
 9646:     }  
 9647:     if ($three eq 'st') {
 9648:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9649:                                          $one,$two,$sec,$context);
 9650:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9651:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9652:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9653:         } else {
 9654:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9655:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9656:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9657:             if ($context eq 'auto') {
 9658:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9659:             } else {
 9660:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9661:                &mt('Add to classlist').': <b>ok</b>';
 9662:             }
 9663:             $output .= $linefeed;
 9664:         }
 9665:     } else {
 9666:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9667:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9668:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9669:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9670:         if ($context eq 'auto') {
 9671:             $output .= $result.$linefeed;
 9672:         } else {
 9673:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9674:         }
 9675:     }
 9676:     return $output;
 9677: }
 9678: 
 9679: sub commit_studentrole {
 9680:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9681:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9682:     if ($context eq 'auto') {
 9683:         $linefeed = "\n";
 9684:     } else {
 9685:         $linefeed = '<br />'."\n";
 9686:     }
 9687:     if (defined($one) && defined($two)) {
 9688:         my $cid=$one.'_'.$two;
 9689:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9690:         my $secchange = 0;
 9691:         my $expire_role_result;
 9692:         my $modify_section_result;
 9693:         if ($oldsec ne '-1') { 
 9694:             if ($oldsec ne $sec) {
 9695:                 $secchange = 1;
 9696:                 my $now = time;
 9697:                 my $uurl='/'.$cid;
 9698:                 $uurl=~s/\_/\//g;
 9699:                 if ($oldsec) {
 9700:                     $uurl.='/'.$oldsec;
 9701:                 }
 9702:                 $oldsecurl = $uurl;
 9703:                 $expire_role_result = 
 9704:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9705:                 if ($env{'request.course.sec'} ne '') { 
 9706:                     if ($expire_role_result eq 'refused') {
 9707:                         my @roles = ('st');
 9708:                         my @statuses = ('previous');
 9709:                         my @roledoms = ($one);
 9710:                         my $withsec = 1;
 9711:                         my %roleshash = 
 9712:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9713:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9714:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9715:                             my ($oldstart,$oldend) = 
 9716:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9717:                             if ($oldend > 0 && $oldend <= $now) {
 9718:                                 $expire_role_result = 'ok';
 9719:                             }
 9720:                         }
 9721:                     }
 9722:                 }
 9723:                 $result = $expire_role_result;
 9724:             }
 9725:         }
 9726:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9727:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9728:             if ($modify_section_result =~ /^ok/) {
 9729:                 if ($secchange == 1) {
 9730:                     if ($sec eq '') {
 9731:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9732:                     } else {
 9733:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9734:                     }
 9735:                 } elsif ($oldsec eq '-1') {
 9736:                     if ($sec eq '') {
 9737:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9738:                     } else {
 9739:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9740:                     }
 9741:                 } else {
 9742:                     if ($sec eq '') {
 9743:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9744:                     } else {
 9745:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9746:                     }
 9747:                 }
 9748:             } else {
 9749:                 if ($secchange) {       
 9750:                     $$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;
 9751:                 } else {
 9752:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9753:                 }
 9754:             }
 9755:             $result = $modify_section_result;
 9756:         } elsif ($secchange == 1) {
 9757:             if ($oldsec eq '') {
 9758:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9759:             } else {
 9760:                 $$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;
 9761:             }
 9762:             if ($expire_role_result eq 'refused') {
 9763:                 my $newsecurl = '/'.$cid;
 9764:                 $newsecurl =~ s/\_/\//g;
 9765:                 if ($sec ne '') {
 9766:                     $newsecurl.='/'.$sec;
 9767:                 }
 9768:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9769:                     if ($sec eq '') {
 9770:                         $$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;
 9771:                     } else {
 9772:                         $$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;
 9773:                     }
 9774:                 }
 9775:             }
 9776:         }
 9777:     } else {
 9778:         $$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;
 9779:         $result = "error: incomplete course id\n";
 9780:     }
 9781:     return $result;
 9782: }
 9783: 
 9784: ############################################################
 9785: ############################################################
 9786: 
 9787: sub check_clone {
 9788:     my ($args,$linefeed) = @_;
 9789:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9790:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9791:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9792:     my $clonemsg;
 9793:     my $can_clone = 0;
 9794: 
 9795:     if ($clonehome eq 'no_host') {
 9796:         $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'});     
 9797:     } else {
 9798: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9799: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9800: 	    $can_clone = 1;
 9801: 	} else {
 9802: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9803: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9804: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9805:             if (grep(/^\*$/,@cloners)) {
 9806:                 $can_clone = 1;
 9807:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9808:                 $can_clone = 1;
 9809:             } else {
 9810: 	        my %roleshash =
 9811: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9812: 					 $args->{'ccdomain'},
 9813:                                          'userroles',['active'],['cc'],
 9814: 					 [$args->{'clonedomain'}]);
 9815: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9816: 		    $can_clone = 1;
 9817: 	        } else {
 9818:                     $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'});
 9819: 	        }
 9820: 	    }
 9821:         }
 9822:     }
 9823:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9824: }
 9825: 
 9826: sub construct_course {
 9827:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9828:     my $outcome;
 9829:     my $linefeed =  '<br />'."\n";
 9830:     if ($context eq 'auto') {
 9831:         $linefeed = "\n";
 9832:     }
 9833: 
 9834: #
 9835: # Are we cloning?
 9836: #
 9837:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9838:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9839: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9840: 	if ($context ne 'auto') {
 9841:             if ($clonemsg ne '') {
 9842: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9843:             }
 9844: 	}
 9845: 	$outcome .= $clonemsg.$linefeed;
 9846: 
 9847:         if (!$can_clone) {
 9848: 	    return (0,$outcome);
 9849: 	}
 9850:     }
 9851: 
 9852: #
 9853: # Open course
 9854: #
 9855:     my $crstype = lc($args->{'crstype'});
 9856:     my %cenv=();
 9857:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9858:                                              $args->{'cdescr'},
 9859:                                              $args->{'curl'},
 9860:                                              $args->{'course_home'},
 9861:                                              $args->{'nonstandard'},
 9862:                                              $args->{'crscode'},
 9863:                                              $args->{'ccuname'}.':'.
 9864:                                              $args->{'ccdomain'},
 9865:                                              $args->{'crstype'});
 9866: 
 9867:     # Note: The testing routines depend on this being output; see 
 9868:     # Utils::Course. This needs to at least be output as a comment
 9869:     # if anyone ever decides to not show this, and Utils::Course::new
 9870:     # will need to be suitably modified.
 9871:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9872: #
 9873: # Check if created correctly
 9874: #
 9875:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9876:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9877:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9878: 
 9879: #
 9880: # Do the cloning
 9881: #   
 9882:     if ($can_clone && $cloneid) {
 9883: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9884: 	if ($context ne 'auto') {
 9885: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9886: 	}
 9887: 	$outcome .= $clonemsg.$linefeed;
 9888: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9889: # Copy all files
 9890: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9891: # Restore URL
 9892: 	$cenv{'url'}=$oldcenv{'url'};
 9893: # Restore title
 9894: 	$cenv{'description'}=$oldcenv{'description'};
 9895: # Mark as cloned
 9896: 	$cenv{'clonedfrom'}=$cloneid;
 9897: # Need to clone grading mode
 9898:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9899:         $cenv{'grading'}=$newenv{'grading'};
 9900: # Do not clone these environment entries
 9901:         &Apache::lonnet::del('environment',
 9902:                   ['default_enrollment_start_date',
 9903:                    'default_enrollment_end_date',
 9904:                    'question.email',
 9905:                    'policy.email',
 9906:                    'comment.email',
 9907:                    'pch.users.denied',
 9908:                    'plc.users.denied',
 9909:                    'hidefromcat',
 9910:                    'categories'],
 9911:                    $$crsudom,$$crsunum);
 9912:     }
 9913: 
 9914: #
 9915: # Set environment (will override cloned, if existing)
 9916: #
 9917:     my @sections = ();
 9918:     my @xlists = ();
 9919:     if ($args->{'crstype'}) {
 9920:         $cenv{'type'}=$args->{'crstype'};
 9921:     }
 9922:     if ($args->{'crsid'}) {
 9923:         $cenv{'courseid'}=$args->{'crsid'};
 9924:     }
 9925:     if ($args->{'crscode'}) {
 9926:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9927:     }
 9928:     if ($args->{'crsquota'} ne '') {
 9929:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9930:     } else {
 9931:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9932:     }
 9933:     if ($args->{'ccuname'}) {
 9934:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9935:                                         ':'.$args->{'ccdomain'};
 9936:     } else {
 9937:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9938:     }
 9939:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9940:     if ($args->{'crssections'}) {
 9941:         $cenv{'internal.sectionnums'} = '';
 9942:         if ($args->{'crssections'} =~ m/,/) {
 9943:             @sections = split/,/,$args->{'crssections'};
 9944:         } else {
 9945:             $sections[0] = $args->{'crssections'};
 9946:         }
 9947:         if (@sections > 0) {
 9948:             foreach my $item (@sections) {
 9949:                 my ($sec,$gp) = split/:/,$item;
 9950:                 my $class = $args->{'crscode'}.$sec;
 9951:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9952:                 $cenv{'internal.sectionnums'} .= $item.',';
 9953:                 unless ($addcheck eq 'ok') {
 9954:                     push @badclasses, $class;
 9955:                 }
 9956:             }
 9957:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9958:         }
 9959:     }
 9960: # do not hide course coordinator from staff listing, 
 9961: # even if privileged
 9962:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9963: # add crosslistings
 9964:     if ($args->{'crsxlist'}) {
 9965:         $cenv{'internal.crosslistings'}='';
 9966:         if ($args->{'crsxlist'} =~ m/,/) {
 9967:             @xlists = split/,/,$args->{'crsxlist'};
 9968:         } else {
 9969:             $xlists[0] = $args->{'crsxlist'};
 9970:         }
 9971:         if (@xlists > 0) {
 9972:             foreach my $item (@xlists) {
 9973:                 my ($xl,$gp) = split/:/,$item;
 9974:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9975:                 $cenv{'internal.crosslistings'} .= $item.',';
 9976:                 unless ($addcheck eq 'ok') {
 9977:                     push @badclasses, $xl;
 9978:                 }
 9979:             }
 9980:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9981:         }
 9982:     }
 9983:     if ($args->{'autoadds'}) {
 9984:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9985:     }
 9986:     if ($args->{'autodrops'}) {
 9987:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9988:     }
 9989: # check for notification of enrollment changes
 9990:     my @notified = ();
 9991:     if ($args->{'notify_owner'}) {
 9992:         if ($args->{'ccuname'} ne '') {
 9993:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9994:         }
 9995:     }
 9996:     if ($args->{'notify_dc'}) {
 9997:         if ($uname ne '') { 
 9998:             push(@notified,$uname.':'.$udom);
 9999:         }
10000:     }
10001:     if (@notified > 0) {
10002:         my $notifylist;
10003:         if (@notified > 1) {
10004:             $notifylist = join(',',@notified);
10005:         } else {
10006:             $notifylist = $notified[0];
10007:         }
10008:         $cenv{'internal.notifylist'} = $notifylist;
10009:     }
10010:     if (@badclasses > 0) {
10011:         my %lt=&Apache::lonlocal::texthash(
10012:                 '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',
10013:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10014:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10015:         );
10016:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10017:                            ' ('.$lt{'adby'}.')';
10018:         if ($context eq 'auto') {
10019:             $outcome .= $badclass_msg.$linefeed;
10020:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10021:             foreach my $item (@badclasses) {
10022:                 if ($context eq 'auto') {
10023:                     $outcome .= " - $item\n";
10024:                 } else {
10025:                     $outcome .= "<li>$item</li>\n";
10026:                 }
10027:             }
10028:             if ($context eq 'auto') {
10029:                 $outcome .= $linefeed;
10030:             } else {
10031:                 $outcome .= "</ul><br /><br /></div>\n";
10032:             }
10033:         } 
10034:     }
10035:     if ($args->{'no_end_date'}) {
10036:         $args->{'endaccess'} = 0;
10037:     }
10038:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10039:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10040:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10041:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10042:     if ($args->{'showphotos'}) {
10043:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10044:     }
10045:     $cenv{'internal.authtype'} = $args->{'authtype'};
10046:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10047:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10048:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10049:             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'); 
10050:             if ($context eq 'auto') {
10051:                 $outcome .= $krb_msg;
10052:             } else {
10053:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10054:             }
10055:             $outcome .= $linefeed;
10056:         }
10057:     }
10058:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10059:        if ($args->{'setpolicy'}) {
10060:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10061:        }
10062:        if ($args->{'setcontent'}) {
10063:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10064:        }
10065:     }
10066:     if ($args->{'reshome'}) {
10067: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10068: 	$cenv{'reshome'}=~s/\/+$/\//;
10069:     }
10070: #
10071: # course has keyed access
10072: #
10073:     if ($args->{'setkeys'}) {
10074:        $cenv{'keyaccess'}='yes';
10075:     }
10076: # if specified, key authority is not course, but user
10077: # only active if keyaccess is yes
10078:     if ($args->{'keyauth'}) {
10079: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10080: 	$user = &LONCAPA::clean_username($user);
10081: 	$domain = &LONCAPA::clean_username($domain);
10082: 	if ($user ne '' && $domain ne '') {
10083: 	    $cenv{'keyauth'}=$user.':'.$domain;
10084: 	}
10085:     }
10086: 
10087:     if ($args->{'disresdis'}) {
10088:         $cenv{'pch.roles.denied'}='st';
10089:     }
10090:     if ($args->{'disablechat'}) {
10091:         $cenv{'plc.roles.denied'}='st';
10092:     }
10093: 
10094:     # Record we've not yet viewed the Course Initialization Helper for this 
10095:     # course
10096:     $cenv{'course.helper.not.run'} = 1;
10097:     #
10098:     # Use new Randomseed
10099:     #
10100:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10101:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10102:     #
10103:     # The encryption code and receipt prefix for this course
10104:     #
10105:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10106:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10107:     #
10108:     # By default, use standard grading
10109:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10110: 
10111:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10112:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10113: #
10114: # Open all assignments
10115: #
10116:     if ($args->{'openall'}) {
10117:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10118:        my %storecontent = ($storeunder         => time,
10119:                            $storeunder.'.type' => 'date_start');
10120:        
10121:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10122:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10123:    }
10124: #
10125: # Set first page
10126: #
10127:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10128: 	    || ($cloneid)) {
10129: 	use LONCAPA::map;
10130: 	$outcome .= &mt('Setting first resource').': ';
10131: 
10132: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10133:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10134: 
10135:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10136:         my $title; my $url;
10137:         if ($args->{'firstres'} eq 'syl') {
10138: 	    $title=&mt('Syllabus');
10139:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10140:         } else {
10141:             $title=&mt('Navigate Contents');
10142:             $url='/adm/navmaps';
10143:         }
10144: 
10145:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10146: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10147: 
10148: 	if ($errtext) { $fatal=2; }
10149:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10150:     }
10151: 
10152:     return (1,$outcome);
10153: }
10154: 
10155: ############################################################
10156: ############################################################
10157: 
10158: sub course_type {
10159:     my ($cid) = @_;
10160:     if (!defined($cid)) {
10161:         $cid = $env{'request.course.id'};
10162:     }
10163:     if (defined($env{'course.'.$cid.'.type'})) {
10164:         return $env{'course.'.$cid.'.type'};
10165:     } else {
10166:         return 'Course';
10167:     }
10168: }
10169: 
10170: sub group_term {
10171:     my $crstype = &course_type();
10172:     my %names = (
10173:                   'Course' => 'group',
10174:                   'Group' => 'team',
10175:                 );
10176:     return $names{$crstype};
10177: }
10178: 
10179: sub icon {
10180:     my ($file)=@_;
10181:     my $curfext = lc((split(/\./,$file))[-1]);
10182:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10183:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10184:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10185: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10186: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10187: 	            $curfext.".gif") {
10188: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10189: 		$curfext.".gif";
10190: 	}
10191:     }
10192:     return &lonhttpdurl($iconname);
10193: } 
10194: 
10195: sub lonhttpdurl {
10196: #
10197: # Had been used for "small fry" static images on separate port 8080.
10198: # Modify here if lightweight http functionality desired again.
10199: # Currently eliminated due to increasing firewall issues.
10200: #
10201:     my ($url)=@_;
10202:     return $url;
10203: }
10204: 
10205: sub connection_aborted {
10206:     my ($r)=@_;
10207:     $r->print(" ");$r->rflush();
10208:     my $c = $r->connection;
10209:     return $c->aborted();
10210: }
10211: 
10212: #    Escapes strings that may have embedded 's that will be put into
10213: #    strings as 'strings'.
10214: sub escape_single {
10215:     my ($input) = @_;
10216:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10217:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10218:     return $input;
10219: }
10220: 
10221: #  Same as escape_single, but escape's "'s  This 
10222: #  can be used for  "strings"
10223: sub escape_double {
10224:     my ($input) = @_;
10225:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10226:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10227:     return $input;
10228: }
10229:  
10230: #   Escapes the last element of a full URL.
10231: sub escape_url {
10232:     my ($url)   = @_;
10233:     my @urlslices = split(/\//, $url,-1);
10234:     my $lastitem = &escape(pop(@urlslices));
10235:     return join('/',@urlslices).'/'.$lastitem;
10236: }
10237: 
10238: # -------------------------------------------------------- Initliaze user login
10239: sub init_user_environment {
10240:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10241:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10242: 
10243:     my $public=($username eq 'public' && $domain eq 'public');
10244: 
10245: # See if old ID present, if so, remove
10246: 
10247:     my ($filename,$cookie,$userroles);
10248:     my $now=time;
10249: 
10250:     if ($public) {
10251: 	my $max_public=100;
10252: 	my $oldest;
10253: 	my $oldest_time=0;
10254: 	for(my $next=1;$next<=$max_public;$next++) {
10255: 	    if (-e $lonids."/publicuser_$next.id") {
10256: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10257: 		if ($mtime<$oldest_time || !$oldest_time) {
10258: 		    $oldest_time=$mtime;
10259: 		    $oldest=$next;
10260: 		}
10261: 	    } else {
10262: 		$cookie="publicuser_$next";
10263: 		last;
10264: 	    }
10265: 	}
10266: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10267:     } else {
10268: 	# if this isn't a robot, kill any existing non-robot sessions
10269: 	if (!$args->{'robot'}) {
10270: 	    opendir(DIR,$lonids);
10271: 	    while ($filename=readdir(DIR)) {
10272: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10273: 		    unlink($lonids.'/'.$filename);
10274: 		}
10275: 	    }
10276: 	    closedir(DIR);
10277: 	}
10278: # Give them a new cookie
10279: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10280: 		                   : $now.$$.int(rand(10000)));
10281: 	$cookie="$username\_$id\_$domain\_$authhost";
10282:     
10283: # Initialize roles
10284: 
10285: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10286:     }
10287: # ------------------------------------ Check browser type and MathML capability
10288: 
10289:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10290:         $clientunicode,$clientos) = &decode_user_agent($r);
10291: 
10292: # -------------------------------------- Any accessibility options to remember?
10293:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
10294: 	foreach my $option ('imagesuppress','appletsuppress',
10295: 			    'embedsuppress','fontenhance','blackwhite') {
10296: 	    if ($form->{$option} eq 'true') {
10297: 		&Apache::lonnet::put('environment',{$option => 'on'},
10298: 				     $domain,$username);
10299: 	    } else {
10300: 		&Apache::lonnet::del('environment',[$option],
10301: 				     $domain,$username);
10302: 	    }
10303: 	}
10304:     }
10305: # ------------------------------------------------------------- Get environment
10306: 
10307:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10308:     my ($tmp) = keys(%userenv);
10309:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10310: 	# default remote control to off
10311: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10312:     } else {
10313: 	undef(%userenv);
10314:     }
10315:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10316: 	$form->{'interface'}=$userenv{'interface'};
10317:     }
10318:     $env{'environment.remote'}=$userenv{'remote'};
10319:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10320: 
10321: # --------------- Do not trust query string to be put directly into environment
10322:     foreach my $option ('imagesuppress','appletsuppress',
10323: 			'embedsuppress','fontenhance','blackwhite',
10324: 			'interface','localpath','localres') {
10325: 	$form->{$option}=~s/[\n\r\=]//gs;
10326:     }
10327: # --------------------------------------------------------- Write first profile
10328: 
10329:     {
10330: 	my %initial_env = 
10331: 	    ("user.name"          => $username,
10332: 	     "user.domain"        => $domain,
10333: 	     "user.home"          => $authhost,
10334: 	     "browser.type"       => $clientbrowser,
10335: 	     "browser.version"    => $clientversion,
10336: 	     "browser.mathml"     => $clientmathml,
10337: 	     "browser.unicode"    => $clientunicode,
10338: 	     "browser.os"         => $clientos,
10339: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10340: 	     "request.course.fn"  => '',
10341: 	     "request.course.uri" => '',
10342: 	     "request.course.sec" => '',
10343: 	     "request.role"       => 'cm',
10344: 	     "request.role.adv"   => $env{'user.adv'},
10345: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10346: 
10347:         if ($form->{'localpath'}) {
10348: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10349: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10350:         }
10351: 	
10352: 	if ($public) {
10353: 	    $initial_env{"environment.remote"} = "off";
10354: 	}
10355: 	if ($form->{'interface'}) {
10356: 	    $form->{'interface'}=~s/\W//gs;
10357: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10358: 	    $env{'browser.interface'}=$form->{'interface'};
10359: 	    foreach my $option ('imagesuppress','appletsuppress',
10360: 				'embedsuppress','fontenhance','blackwhite') {
10361: 		if (($form->{$option} eq 'true') ||
10362: 		    ($userenv{$option} eq 'on')) {
10363: 		    $initial_env{"browser.$option"} = "on";
10364: 		}
10365: 	    }
10366: 	}
10367: 
10368:         foreach my $tool ('aboutme','blog','portfolio') {
10369:             $userenv{'availabletools.'.$tool} = 
10370:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10371:         }
10372: 
10373:         foreach my $crstype ('official','unofficial') {
10374:             $userenv{'canrequest.'.$crstype} =
10375:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10376:                                                   'reload','requestcourses');
10377:         }
10378: 
10379: 	$env{'user.environment'} = "$lonids/$cookie.id";
10380: 	
10381: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10382: 		 &GDBM_WRCREAT(),0640)) {
10383: 	    &_add_to_env(\%disk_env,\%initial_env);
10384: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10385: 	    &_add_to_env(\%disk_env,$userroles);
10386: 	    if (ref($args->{'extra_env'})) {
10387: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10388: 	    }
10389: 	    untie(%disk_env);
10390: 	} else {
10391: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10392: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10393: 	    return 'error: '.$!;
10394: 	}
10395:     }
10396:     $env{'request.role'}='cm';
10397:     $env{'request.role.adv'}=$env{'user.adv'};
10398:     $env{'browser.type'}=$clientbrowser;
10399: 
10400:     return $cookie;
10401: 
10402: }
10403: 
10404: sub _add_to_env {
10405:     my ($idf,$env_data,$prefix) = @_;
10406:     if (ref($env_data) eq 'HASH') {
10407:         while (my ($key,$value) = each(%$env_data)) {
10408: 	    $idf->{$prefix.$key} = $value;
10409: 	    $env{$prefix.$key}   = $value;
10410:         }
10411:     }
10412: }
10413: 
10414: # --- Get the symbolic name of a problem and the url
10415: sub get_symb {
10416:     my ($request,$silent) = @_;
10417:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10418:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10419:     if ($symb eq '') {
10420:         if (!$silent) {
10421:             $request->print("Unable to handle ambiguous references:$url:.");
10422:             return ();
10423:         }
10424:     }
10425:     &Apache::lonenc::check_decrypt(\$symb);
10426:     return ($symb);
10427: }
10428: 
10429: # --------------------------------------------------------------Get annotation
10430: 
10431: sub get_annotation {
10432:     my ($symb,$enc) = @_;
10433: 
10434:     my $key = $symb;
10435:     if (!$enc) {
10436:         $key =
10437:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10438:     }
10439:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10440:     return $annotation{$key};
10441: }
10442: 
10443: sub clean_symb {
10444:     my ($symb,$delete_enc) = @_;
10445: 
10446:     &Apache::lonenc::check_decrypt(\$symb);
10447:     my $enc = $env{'request.enc'};
10448:     if ($delete_enc) {
10449:         delete($env{'request.enc'});
10450:     }
10451: 
10452:     return ($symb,$enc);
10453: }
10454: 
10455: =pod
10456: 
10457: =back
10458: 
10459: =cut
10460: 
10461: 1;
10462: __END__;
10463: 

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