File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.788: download - view: text, annotated - select for diffs
Tue Apr 21 10:44:04 2009 UTC (15 years, 2 months ago) by amueller
Branches: MAIN
CVS tags: HEAD
removed a style that I wrongly added on revision 1.783

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.788 2009/04/21 10:44:04 amueller 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) {
  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:         var title = 'Student_Browser';
  426:         var options = 'scrollbars=1,resizable=1,menubar=0';
  427:         options += ',width=700,height=600';
  428:         stdeditbrowser = open(url,title,options,'1');
  429:         stdeditbrowser.focus();
  430:     }
  431: </script>
  432: ENDSTDBRW
  433: }
  434: 
  435: sub selectstudent_link {
  436:    my ($form,$unameele,$udomele)=@_;
  437:    if ($env{'request.course.id'}) {  
  438:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  439: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  440: 					'/'.$env{'request.course.sec'})) {
  441: 	   return '';
  442:        }
  443:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  444:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  445:    }
  446:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  447:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  448:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  449:    }
  450:    return '';
  451: }
  452: 
  453: sub authorbrowser_javascript {
  454:     return <<"ENDAUTHORBRW";
  455: <script type="text/javascript" language="JavaScript">
  456: var stdeditbrowser;
  457: 
  458: function openauthorbrowser(formname,udom) {
  459:     var url = '/adm/pickauthor?';
  460:     url += 'form='+formname+'&roledom='+udom;
  461:     var title = 'Author_Browser';
  462:     var options = 'scrollbars=1,resizable=1,menubar=0';
  463:     options += ',width=700,height=600';
  464:     stdeditbrowser = open(url,title,options,'1');
  465:     stdeditbrowser.focus();
  466: }
  467: 
  468: </script>
  469: ENDAUTHORBRW
  470: }
  471: 
  472: sub coursebrowser_javascript {
  473:     my ($domainfilter,$sec_element,$formname)=@_;
  474:     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');
  475:    my $output = '
  476: <script type="text/javascript" language="JavaScript">
  477:     var stdeditbrowser;'."\n";
  478:    $output .= <<"ENDSTDBRW";
  479:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  480:         var url = '/adm/pickcourse?';
  481:         var domainfilter = '';
  482:         var formid = getFormIdByName(formname);
  483:         if (formid > -1) {
  484:             var domid = getIndexByName(formid,udom);
  485:             if (domid > -1) {
  486:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  487:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  488:                 }
  489:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  490:                     domainfilter=document.forms[formid].elements[domid].value;
  491:                 }
  492:             }
  493:         }
  494:         if (domainfilter != null) {
  495:            if (domainfilter != '') {
  496:                url += 'domainfilter='+domainfilter+'&';
  497: 	   }
  498:         }
  499:         url += 'form=' + formname + '&cnumelement='+uname+
  500: 	                            '&cdomelement='+udom+
  501:                                     '&cnameelement='+desc;
  502:         if (extra_element !=null && extra_element != '') {
  503:             if (formname == 'rolechoice' || formname == 'studentform') {
  504:                 url += '&roleelement='+extra_element;
  505:                 if (domainfilter == null || domainfilter == '') {
  506:                     url += '&domainfilter='+extra_element;
  507:                 }
  508:             }
  509:             else {
  510:                 if (formname == 'portform') {
  511:                     url += '&setroles='+extra_element;
  512:                 }
  513:             }     
  514:         }
  515:         if (multflag !=null && multflag != '') {
  516:             url += '&multiple='+multflag;
  517:         }
  518:         if (crstype == 'Course/Group') {
  519:             if (formname == 'cu') {
  520:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  521:                 if (crstype == "") {
  522:                     alert("$crs_or_grp_alert");
  523:                     return;
  524:                 }
  525:             }
  526:         }
  527:         if (crstype !=null && crstype != '') {
  528:             url += '&type='+crstype;
  529:         }
  530:         var title = 'Course_Browser';
  531:         var options = 'scrollbars=1,resizable=1,menubar=0';
  532:         options += ',width=700,height=600';
  533:         stdeditbrowser = open(url,title,options,'1');
  534:         stdeditbrowser.focus();
  535:     }
  536: 
  537:     function getFormIdByName(formname) {
  538:         for (var i=0;i<document.forms.length;i++) {
  539:             if (document.forms[i].name == formname) {
  540:                 return i;
  541:             }
  542:         }
  543:         return -1; 
  544:     }
  545: 
  546:     function getIndexByName(formid,item) {
  547:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  548:             if (document.forms[formid].elements[i].name == item) {
  549:                 return i;
  550:             }
  551:         }
  552:         return -1;
  553:     }
  554: ENDSTDBRW
  555:     if ($sec_element ne '') {
  556:         $output .= &setsec_javascript($sec_element,$formname);
  557:     }
  558:     $output .= '
  559: </script>';
  560:     return $output;
  561: }
  562: 
  563: sub setsec_javascript {
  564:     my ($sec_element,$formname) = @_;
  565:     my $setsections = qq|
  566: function setSect(sectionlist) {
  567:     var sectionsArray = new Array();
  568:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  569:         sectionsArray = sectionlist.split(",");
  570:     }
  571:     var numSections = sectionsArray.length;
  572:     document.$formname.$sec_element.length = 0;
  573:     if (numSections == 0) {
  574:         document.$formname.$sec_element.multiple=false;
  575:         document.$formname.$sec_element.size=1;
  576:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  577:     } else {
  578:         if (numSections == 1) {
  579:             document.$formname.$sec_element.multiple=false;
  580:             document.$formname.$sec_element.size=1;
  581:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  582:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  583:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  584:         } else {
  585:             for (var i=0; i<numSections; i++) {
  586:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  587:             }
  588:             document.$formname.$sec_element.multiple=true
  589:             if (numSections < 3) {
  590:                 document.$formname.$sec_element.size=numSections;
  591:             } else {
  592:                 document.$formname.$sec_element.size=3;
  593:             }
  594:             document.$formname.$sec_element.options[0].selected = false
  595:         }
  596:     }
  597: }
  598: |;
  599:     return $setsections;
  600: }
  601: 
  602: 
  603: sub selectcourse_link {
  604:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  605:    return '<span class="LC_nobreak">'
  606:          ."<a href='"
  607:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  608:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  609:          .'","'.$multflag.'","'.$selecttype.'");'
  610:          ."'>".&mt('Select Course').'</a>'
  611:          .'</span>';
  612: }
  613: 
  614: sub selectauthor_link {
  615:    my ($form,$udom)=@_;
  616:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  617:           &mt('Select Author').'</a>';
  618: }
  619: 
  620: sub check_uncheck_jscript {
  621:     my $jscript = <<"ENDSCRT";
  622: function checkAll(field) {
  623:     if (field.length > 0) {
  624:         for (i = 0; i < field.length; i++) {
  625:             field[i].checked = true ;
  626:         }
  627:     } else {
  628:         field.checked = true
  629:     }
  630: }
  631:  
  632: function uncheckAll(field) {
  633:     if (field.length > 0) {
  634:         for (i = 0; i < field.length; i++) {
  635:             field[i].checked = false ;
  636:         }
  637:     } else {
  638:         field.checked = false ;
  639:     }
  640: }
  641: ENDSCRT
  642:     return $jscript;
  643: }
  644: 
  645: sub select_timezone {
  646:    my ($name,$selected,$onchange,$includeempty)=@_;
  647:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  648:    if ($includeempty) {
  649:        $output .= '<option value=""';
  650:        if (($selected eq '') || ($selected eq 'local')) {
  651:            $output .= ' selected="selected" ';
  652:        }
  653:        $output .= '> </option>';
  654:    }
  655:    my @timezones = DateTime::TimeZone->all_names;
  656:    foreach my $tzone (@timezones) {
  657:        $output.= '<option value="'.$tzone.'"';
  658:        if ($tzone eq $selected) {
  659:            $output.=' selected="selected"';
  660:        }
  661:        $output.=">$tzone</option>\n";
  662:    }
  663:    $output.="</select>";
  664:    return $output;
  665: }
  666: 
  667: sub select_datelocale {
  668:     my ($name,$selected,$onchange,$includeempty)=@_;
  669:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  670:     if ($includeempty) {
  671:         $output .= '<option value=""';
  672:         if ($selected eq '') {
  673:             $output .= ' selected="selected" ';
  674:         }
  675:         $output .= '> </option>';
  676:     }
  677:     my (@possibles,%locale_names);
  678:     my @locales = DateTime::Locale::Catalog::Locales;
  679:     foreach my $locale (@locales) {
  680:         if (ref($locale) eq 'HASH') {
  681:             my $id = $locale->{'id'};
  682:             if ($id ne '') {
  683:                 my $en_terr = $locale->{'en_territory'};
  684:                 my $native_terr = $locale->{'native_territory'};
  685:                 my @languages = &Apache::lonlocal::preferred_languages();
  686:                 if (grep(/^en$/,@languages) || !@languages) {
  687:                     if ($en_terr ne '') {
  688:                         $locale_names{$id} = '('.$en_terr.')';
  689:                     } elsif ($native_terr ne '') {
  690:                         $locale_names{$id} = $native_terr;
  691:                     }
  692:                 } else {
  693:                     if ($native_terr ne '') {
  694:                         $locale_names{$id} = $native_terr.' ';
  695:                     } elsif ($en_terr ne '') {
  696:                         $locale_names{$id} = '('.$en_terr.')';
  697:                     }
  698:                 }
  699:                 push (@possibles,$id);
  700:             }
  701:         }
  702:     }
  703:     foreach my $item (sort(@possibles)) {
  704:         $output.= '<option value="'.$item.'"';
  705:         if ($item eq $selected) {
  706:             $output.=' selected="selected"';
  707:         }
  708:         $output.=">$item";
  709:         if ($locale_names{$item} ne '') {
  710:             $output.="  $locale_names{$item}</option>\n";
  711:         }
  712:         $output.="</option>\n";
  713:     }
  714:     $output.="</select>";
  715:     return $output;
  716: }
  717: 
  718: =pod
  719: 
  720: =item * &linked_select_forms(...)
  721: 
  722: linked_select_forms returns a string containing a <script></script> block
  723: and html for two <select> menus.  The select menus will be linked in that
  724: changing the value of the first menu will result in new values being placed
  725: in the second menu.  The values in the select menu will appear in alphabetical
  726: order unless a defined order is provided.
  727: 
  728: linked_select_forms takes the following ordered inputs:
  729: 
  730: =over 4
  731: 
  732: =item * $formname, the name of the <form> tag
  733: 
  734: =item * $middletext, the text which appears between the <select> tags
  735: 
  736: =item * $firstdefault, the default value for the first menu
  737: 
  738: =item * $firstselectname, the name of the first <select> tag
  739: 
  740: =item * $secondselectname, the name of the second <select> tag
  741: 
  742: =item * $hashref, a reference to a hash containing the data for the menus.
  743: 
  744: =item * $menuorder, the order of values in the first menu
  745: 
  746: =back 
  747: 
  748: Below is an example of such a hash.  Only the 'text', 'default', and 
  749: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  750: values for the first select menu.  The text that coincides with the 
  751: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  752: and text for the second menu are given in the hash pointed to by 
  753: $menu{$choice1}->{'select2'}.  
  754: 
  755:  my %menu = ( A1 => { text =>"Choice A1" ,
  756:                        default => "B3",
  757:                        select2 => { 
  758:                            B1 => "Choice B1",
  759:                            B2 => "Choice B2",
  760:                            B3 => "Choice B3",
  761:                            B4 => "Choice B4"
  762:                            },
  763:                        order => ['B4','B3','B1','B2'],
  764:                    },
  765:                A2 => { text =>"Choice A2" ,
  766:                        default => "C2",
  767:                        select2 => { 
  768:                            C1 => "Choice C1",
  769:                            C2 => "Choice C2",
  770:                            C3 => "Choice C3"
  771:                            },
  772:                        order => ['C2','C1','C3'],
  773:                    },
  774:                A3 => { text =>"Choice A3" ,
  775:                        default => "D6",
  776:                        select2 => { 
  777:                            D1 => "Choice D1",
  778:                            D2 => "Choice D2",
  779:                            D3 => "Choice D3",
  780:                            D4 => "Choice D4",
  781:                            D5 => "Choice D5",
  782:                            D6 => "Choice D6",
  783:                            D7 => "Choice D7"
  784:                            },
  785:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  786:                    }
  787:                );
  788: 
  789: =cut
  790: 
  791: sub linked_select_forms {
  792:     my ($formname,
  793:         $middletext,
  794:         $firstdefault,
  795:         $firstselectname,
  796:         $secondselectname, 
  797:         $hashref,
  798:         $menuorder,
  799:         ) = @_;
  800:     my $second = "document.$formname.$secondselectname";
  801:     my $first = "document.$formname.$firstselectname";
  802:     # output the javascript to do the changing
  803:     my $result = '';
  804:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  805:     $result.="var select2data = new Object();\n";
  806:     $" = '","';
  807:     my $debug = '';
  808:     foreach my $s1 (sort(keys(%$hashref))) {
  809:         $result.="select2data.d_$s1 = new Object();\n";        
  810:         $result.="select2data.d_$s1.def = new String('".
  811:             $hashref->{$s1}->{'default'}."');\n";
  812:         $result.="select2data.d_$s1.values = new Array(";
  813:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  814:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  815:             @s2values = @{$hashref->{$s1}->{'order'}};
  816:         }
  817:         $result.="\"@s2values\");\n";
  818:         $result.="select2data.d_$s1.texts = new Array(";        
  819:         my @s2texts;
  820:         foreach my $value (@s2values) {
  821:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  822:         }
  823:         $result.="\"@s2texts\");\n";
  824:     }
  825:     $"=' ';
  826:     $result.= <<"END";
  827: 
  828: function select1_changed() {
  829:     // Determine new choice
  830:     var newvalue = "d_" + $first.value;
  831:     // update select2
  832:     var values     = select2data[newvalue].values;
  833:     var texts      = select2data[newvalue].texts;
  834:     var select2def = select2data[newvalue].def;
  835:     var i;
  836:     // out with the old
  837:     for (i = 0; i < $second.options.length; i++) {
  838:         $second.options[i] = null;
  839:     }
  840:     // in with the nuclear
  841:     for (i=0;i<values.length; i++) {
  842:         $second.options[i] = new Option(values[i]);
  843:         $second.options[i].value = values[i];
  844:         $second.options[i].text = texts[i];
  845:         if (values[i] == select2def) {
  846:             $second.options[i].selected = true;
  847:         }
  848:     }
  849: }
  850: </script>
  851: END
  852:     # output the initial values for the selection lists
  853:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  854:     my @order = sort(keys(%{$hashref}));
  855:     if (ref($menuorder) eq 'ARRAY') {
  856:         @order = @{$menuorder};
  857:     }
  858:     foreach my $value (@order) {
  859:         $result.="    <option value=\"$value\" ";
  860:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  861:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  862:     }
  863:     $result .= "</select>\n";
  864:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  865:     $result .= $middletext;
  866:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  867:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  868:     
  869:     my @secondorder = sort(keys(%select2));
  870:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  871:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  872:     }
  873:     foreach my $value (@secondorder) {
  874:         $result.="    <option value=\"$value\" ";        
  875:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  876:         $result.=">".&mt($select2{$value})."</option>\n";
  877:     }
  878:     $result .= "</select>\n";
  879:     #    return $debug;
  880:     return $result;
  881: }   #  end of sub linked_select_forms {
  882: 
  883: =pod
  884: 
  885: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  886: 
  887: Returns a string corresponding to an HTML link to the given help
  888: $topic, where $topic corresponds to the name of a .tex file in
  889: /home/httpd/html/adm/help/tex, with underscores replaced by
  890: spaces. 
  891: 
  892: $text will optionally be linked to the same topic, allowing you to
  893: link text in addition to the graphic. If you do not want to link
  894: text, but wish to specify one of the later parameters, pass an
  895: empty string. 
  896: 
  897: $stayOnPage is a value that will be interpreted as a boolean. If true,
  898: the link will not open a new window. If false, the link will open
  899: a new window using Javascript. (Default is false.) 
  900: 
  901: $width and $height are optional numerical parameters that will
  902: override the width and height of the popped up window, which may
  903: be useful for certain help topics with big pictures included. 
  904: 
  905: =cut
  906: 
  907: sub help_open_topic {
  908:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  909:     $text = "" if (not defined $text);
  910:     $stayOnPage = 0 if (not defined $stayOnPage);
  911:     if ($env{'browser.interface'} eq 'textual') {
  912: 	$stayOnPage=1;
  913:     }
  914:     $width = 350 if (not defined $width);
  915:     $height = 400 if (not defined $height);
  916:     my $filename = $topic;
  917:     $filename =~ s/ /_/g;
  918: 
  919:     my $template = "";
  920:     my $link;
  921:     
  922:     $topic=~s/\W/\_/g;
  923: 
  924:     if (!$stayOnPage) {
  925: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  926:     } else {
  927: 	$link = "/adm/help/${filename}.hlp";
  928:     }
  929: 
  930:     # Add the text
  931:     if ($text ne "") {	
  932: 	$template.='<span class="LC_help_open_topic">'
  933:                   .'<a target="_top" href="'.$link.'">'
  934:                   .$text.'</a>';
  935:     }
  936: 
  937:     # (Always) Add the graphic
  938:     my $title = &mt('Online Help');
  939:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  940:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  941:               .'<img src="'.$helpicon.'" border="0"'
  942:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  943:               .' title="'.$title.'"' 
  944:               .' /></a>';
  945:     if ($text ne "") {	
  946:         $template.='</span>';
  947:     }
  948:     return $template;
  949: 
  950: }
  951: 
  952: # This is a quicky function for Latex cheatsheet editing, since it 
  953: # appears in at least four places
  954: sub helpLatexCheatsheet {
  955:     my ($topic,$text,$not_author) = @_;
  956:     my $out;
  957:     my $addOther = '';
  958:     if ($topic) {
  959: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  960: 							       undef, undef, 600).
  961: 								   '</span> ';
  962:     }
  963:     $out = '<span>' # Start cheatsheet
  964: 	  .$addOther
  965:           .'<span>'
  966: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  967: 					       undef,undef,600)
  968: 	  .'</span> <span>'
  969: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  970: 					       undef,undef,600)
  971: 	  .'</span>';
  972:     unless ($not_author) {
  973:         $out .= ' <span>'
  974: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  975: 	                                            undef,undef,600)
  976: 	       .'</span>';
  977:     }
  978:     $out .= '</span>'; # End cheatsheet
  979:     return $out;
  980: }
  981: 
  982: sub general_help {
  983:     my $helptopic='Student_Intro';
  984:     if ($env{'request.role'}=~/^(ca|au)/) {
  985: 	$helptopic='Authoring_Intro';
  986:     } elsif ($env{'request.role'}=~/^cc/) {
  987: 	$helptopic='Course_Coordination_Intro';
  988:     } elsif ($env{'request.role'}=~/^dc/) {
  989:         $helptopic='Domain_Coordination_Intro';
  990:     }
  991:     return $helptopic;
  992: }
  993: 
  994: sub update_help_link {
  995:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  996:     my $origurl = $ENV{'REQUEST_URI'};
  997:     $origurl=~s|^/~|/priv/|;
  998:     my $timestamp = time;
  999:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1000:         $$datum = &escape($$datum);
 1001:     }
 1002: 
 1003:     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";
 1004:     my $output .= <<"ENDOUTPUT";
 1005: <script type="text/javascript">
 1006: banner_link = '$banner_link';
 1007: </script>
 1008: ENDOUTPUT
 1009:     return $output;
 1010: }
 1011: 
 1012: # now just updates the help link and generates a blue icon
 1013: sub help_open_menu {
 1014:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1015: 	= @_;    
 1016:     $stayOnPage = 0 if (not defined $stayOnPage);
 1017:     # only use pop-up help (stayOnPage == 0)
 1018:     # if environment.remote is on (using remote control UI)
 1019:     if ($env{'browser.interface'} eq 'textual' ||
 1020:     	$env{'environment.remote'} eq 'off' ) {
 1021:         $stayOnPage=1;
 1022:     }
 1023:     my $output;
 1024:     if ($component_help) {
 1025: 	if (!$text) {
 1026: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1027: 				       $width,$height);
 1028: 	} else {
 1029: 	    my $help_text;
 1030: 	    $help_text=&unescape($topic);
 1031: 	    $output='<table><tr><td>'.
 1032: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1033: 				 $width,$height).'</td></tr></table>';
 1034: 	}
 1035:     }
 1036:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1037:     return $output.$banner_link;
 1038: }
 1039: 
 1040: sub top_nav_help {
 1041:     my ($text) = @_;
 1042:     $text = &mt($text);
 1043:     my $stay_on_page = 
 1044: 	($env{'browser.interface'}  eq 'textual' ||
 1045: 	 $env{'environment.remote'} eq 'off' );
 1046:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1047: 	                     : "javascript:helpMenu('open')";
 1048:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1049: 
 1050:     my $title = &mt('Get help');
 1051: 
 1052:     return <<"END";
 1053: $banner_link
 1054:  <a href="$link" title="$title">$text</a>
 1055: END
 1056: }
 1057: 
 1058: sub help_menu_js {
 1059:     my ($text) = @_;
 1060: 
 1061:     my $stayOnPage = 
 1062: 	($env{'browser.interface'}  eq 'textual' ||
 1063: 	 $env{'environment.remote'} eq 'off' );
 1064: 
 1065:     my $width = 620;
 1066:     my $height = 600;
 1067:     my $helptopic=&general_help();
 1068:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1069:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1070:     my $start_page =
 1071:         &Apache::loncommon::start_page('Help Menu', undef,
 1072: 				       {'frameset'    => 1,
 1073: 					'js_ready'    => 1,
 1074: 					'add_entries' => {
 1075: 					    'border' => '0',
 1076: 					    'rows'   => "110,*",},});
 1077:     my $end_page =
 1078:         &Apache::loncommon::end_page({'frameset' => 1,
 1079: 				      'js_ready' => 1,});
 1080: 
 1081:     my $template .= <<"ENDTEMPLATE";
 1082: <script type="text/javascript">
 1083: // <!-- BEGIN LON-CAPA Internal
 1084: // <![CDATA[
 1085: var banner_link = '';
 1086: function helpMenu(target) {
 1087:     var caller = this;
 1088:     if (target == 'open') {
 1089:         var newWindow = null;
 1090:         try {
 1091:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1092:         }
 1093:         catch(error) {
 1094:             writeHelp(caller);
 1095:             return;
 1096:         }
 1097:         if (newWindow) {
 1098:             caller = newWindow;
 1099:         }
 1100:     }
 1101:     writeHelp(caller);
 1102:     return;
 1103: }
 1104: function writeHelp(caller) {
 1105:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1106:     caller.document.close()
 1107:     caller.focus()
 1108: }
 1109: // ]]>
 1110: // END LON-CAPA Internal -->
 1111: </script>
 1112: ENDTEMPLATE
 1113:     return $template;
 1114: }
 1115: 
 1116: sub help_open_bug {
 1117:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1118:     unless ($env{'user.adv'}) { return ''; }
 1119:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1120:     $text = "" if (not defined $text);
 1121:     $stayOnPage = 0 if (not defined $stayOnPage);
 1122:     if ($env{'browser.interface'} eq 'textual' ||
 1123: 	$env{'environment.remote'} eq 'off' ) {
 1124: 	$stayOnPage=1;
 1125:     }
 1126:     $width = 600 if (not defined $width);
 1127:     $height = 600 if (not defined $height);
 1128: 
 1129:     $topic=~s/\W+/\+/g;
 1130:     my $link='';
 1131:     my $template='';
 1132:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1133: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1134:     if (!$stayOnPage)
 1135:     {
 1136: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1137:     }
 1138:     else
 1139:     {
 1140: 	$link = $url;
 1141:     }
 1142:     # Add the text
 1143:     if ($text ne "")
 1144:     {
 1145: 	$template .= 
 1146:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1147:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1148:     }
 1149: 
 1150:     # Add the graphic
 1151:     my $title = &mt('Report a Bug');
 1152:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1153:     $template .= <<"ENDTEMPLATE";
 1154:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1155: ENDTEMPLATE
 1156:     if ($text ne '') { $template.='</td></tr></table>' };
 1157:     return $template;
 1158: 
 1159: }
 1160: 
 1161: sub help_open_faq {
 1162:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1163:     unless ($env{'user.adv'}) { return ''; }
 1164:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1165:     $text = "" if (not defined $text);
 1166:     $stayOnPage = 0 if (not defined $stayOnPage);
 1167:     if ($env{'browser.interface'} eq 'textual' ||
 1168: 	$env{'environment.remote'} eq 'off' ) {
 1169: 	$stayOnPage=1;
 1170:     }
 1171:     $width = 350 if (not defined $width);
 1172:     $height = 400 if (not defined $height);
 1173: 
 1174:     $topic=~s/\W+/\+/g;
 1175:     my $link='';
 1176:     my $template='';
 1177:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1178:     if (!$stayOnPage)
 1179:     {
 1180: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1181:     }
 1182:     else
 1183:     {
 1184: 	$link = $url;
 1185:     }
 1186: 
 1187:     # Add the text
 1188:     if ($text ne "")
 1189:     {
 1190: 	$template .= 
 1191:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1192:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1193:     }
 1194: 
 1195:     # Add the graphic
 1196:     my $title = &mt('View the FAQ');
 1197:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1198:     $template .= <<"ENDTEMPLATE";
 1199:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1200: ENDTEMPLATE
 1201:     if ($text ne '') { $template.='</td></tr></table>' };
 1202:     return $template;
 1203: 
 1204: }
 1205: 
 1206: ###############################################################
 1207: ###############################################################
 1208: 
 1209: =pod
 1210: 
 1211: =item * &change_content_javascript():
 1212: 
 1213: This and the next function allow you to create small sections of an
 1214: otherwise static HTML page that you can update on the fly with
 1215: Javascript, even in Netscape 4.
 1216: 
 1217: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1218: must be written to the HTML page once. It will prove the Javascript
 1219: function "change(name, content)". Calling the change function with the
 1220: name of the section 
 1221: you want to update, matching the name passed to C<changable_area>, and
 1222: the new content you want to put in there, will put the content into
 1223: that area.
 1224: 
 1225: B<Note>: Netscape 4 only reserves enough space for the changable area
 1226: to contain room for the original contents. You need to "make space"
 1227: for whatever changes you wish to make, and be B<sure> to check your
 1228: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1229: it's adequate for updating a one-line status display, but little more.
 1230: This script will set the space to 100% width, so you only need to
 1231: worry about height in Netscape 4.
 1232: 
 1233: Modern browsers are much less limiting, and if you can commit to the
 1234: user not using Netscape 4, this feature may be used freely with
 1235: pretty much any HTML.
 1236: 
 1237: =cut
 1238: 
 1239: sub change_content_javascript {
 1240:     # If we're on Netscape 4, we need to use Layer-based code
 1241:     if ($env{'browser.type'} eq 'netscape' &&
 1242: 	$env{'browser.version'} =~ /^4\./) {
 1243: 	return (<<NETSCAPE4);
 1244: 	function change(name, content) {
 1245: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1246: 	    doc.open();
 1247: 	    doc.write(content);
 1248: 	    doc.close();
 1249: 	}
 1250: NETSCAPE4
 1251:     } else {
 1252: 	# Otherwise, we need to use semi-standards-compliant code
 1253: 	# (technically, "innerHTML" isn't standard but the equivalent
 1254: 	# is really scary, and every useful browser supports it
 1255: 	return (<<DOMBASED);
 1256: 	function change(name, content) {
 1257: 	    element = document.getElementById(name);
 1258: 	    element.innerHTML = content;
 1259: 	}
 1260: DOMBASED
 1261:     }
 1262: }
 1263: 
 1264: =pod
 1265: 
 1266: =item * &changable_area($name,$origContent):
 1267: 
 1268: This provides a "changable area" that can be modified on the fly via
 1269: the Javascript code provided in C<change_content_javascript>. $name is
 1270: the name you will use to reference the area later; do not repeat the
 1271: same name on a given HTML page more then once. $origContent is what
 1272: the area will originally contain, which can be left blank.
 1273: 
 1274: =cut
 1275: 
 1276: sub changable_area {
 1277:     my ($name, $origContent) = @_;
 1278: 
 1279:     if ($env{'browser.type'} eq 'netscape' &&
 1280: 	$env{'browser.version'} =~ /^4\./) {
 1281: 	# If this is netscape 4, we need to use the Layer tag
 1282: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1283:     } else {
 1284: 	return "<span id='$name'>$origContent</span>";
 1285:     }
 1286: }
 1287: 
 1288: =pod
 1289: 
 1290: =item * &viewport_geometry_js 
 1291: 
 1292: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1293: 
 1294: =cut
 1295: 
 1296: 
 1297: sub viewport_geometry_js { 
 1298:     return <<"GEOMETRY";
 1299: var Geometry = {};
 1300: function init_geometry() {
 1301:     if (Geometry.init) { return };
 1302:     Geometry.init=1;
 1303:     if (window.innerHeight) {
 1304:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1305:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1306:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1307:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1308:     }
 1309:     else if (document.documentElement && document.documentElement.clientHeight) {
 1310:         Geometry.getViewportHeight =
 1311:             function() { return document.documentElement.clientHeight; };
 1312:         Geometry.getViewportWidth =
 1313:             function() { return document.documentElement.clientWidth; };
 1314: 
 1315:         Geometry.getHorizontalScroll =
 1316:             function() { return document.documentElement.scrollLeft; };
 1317:         Geometry.getVerticalScroll =
 1318:             function() { return document.documentElement.scrollTop; };
 1319:     }
 1320:     else if (document.body.clientHeight) {
 1321:         Geometry.getViewportHeight =
 1322:             function() { return document.body.clientHeight; };
 1323:         Geometry.getViewportWidth =
 1324:             function() { return document.body.clientWidth; };
 1325:         Geometry.getHorizontalScroll =
 1326:             function() { return document.body.scrollLeft; };
 1327:         Geometry.getVerticalScroll =
 1328:             function() { return document.body.scrollTop; };
 1329:     }
 1330: }
 1331: 
 1332: GEOMETRY
 1333: }
 1334: 
 1335: =pod
 1336: 
 1337: =item * &viewport_size_js()
 1338: 
 1339: 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. 
 1340: 
 1341: =cut
 1342: 
 1343: sub viewport_size_js {
 1344:     my $geometry = &viewport_geometry_js();
 1345:     return <<"DIMS";
 1346: 
 1347: $geometry
 1348: 
 1349: function getViewportDims(width,height) {
 1350:     init_geometry();
 1351:     width.value = Geometry.getViewportWidth();
 1352:     height.value = Geometry.getViewportHeight();
 1353:     return;
 1354: }
 1355: 
 1356: DIMS
 1357: }
 1358: 
 1359: =pod
 1360: 
 1361: =item * &resize_textarea_js()
 1362: 
 1363: emits the needed javascript to resize a textarea to be as big as possible
 1364: 
 1365: creates a function resize_textrea that takes two IDs first should be
 1366: the id of the element to resize, second should be the id of a div that
 1367: surrounds everything that comes after the textarea, this routine needs
 1368: to be attached to the <body> for the onload and onresize events.
 1369: 
 1370: =back
 1371: 
 1372: =cut
 1373: 
 1374: sub resize_textarea_js {
 1375:     my $geometry = &viewport_geometry_js();
 1376:     return <<"RESIZE";
 1377:     <script type="text/javascript">
 1378: $geometry
 1379: 
 1380: function getX(element) {
 1381:     var x = 0;
 1382:     while (element) {
 1383: 	x += element.offsetLeft;
 1384: 	element = element.offsetParent;
 1385:     }
 1386:     return x;
 1387: }
 1388: function getY(element) {
 1389:     var y = 0;
 1390:     while (element) {
 1391: 	y += element.offsetTop;
 1392: 	element = element.offsetParent;
 1393:     }
 1394:     return y;
 1395: }
 1396: 
 1397: 
 1398: function resize_textarea(textarea_id,bottom_id) {
 1399:     init_geometry();
 1400:     var textarea        = document.getElementById(textarea_id);
 1401:     //alert(textarea);
 1402: 
 1403:     var textarea_top    = getY(textarea);
 1404:     var textarea_height = textarea.offsetHeight;
 1405:     var bottom          = document.getElementById(bottom_id);
 1406:     var bottom_top      = getY(bottom);
 1407:     var bottom_height   = bottom.offsetHeight;
 1408:     var window_height   = Geometry.getViewportHeight();
 1409:     var fudge           = 23;
 1410:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1411:     if (new_height < 300) {
 1412: 	new_height = 300;
 1413:     }
 1414:     textarea.style.height=new_height+'px';
 1415: }
 1416: </script>
 1417: RESIZE
 1418: 
 1419: }
 1420: 
 1421: =pod
 1422: 
 1423: =head1 Excel and CSV file utility routines
 1424: 
 1425: =over 4
 1426: 
 1427: =cut
 1428: 
 1429: ###############################################################
 1430: ###############################################################
 1431: 
 1432: =pod
 1433: 
 1434: =item * &csv_translate($text) 
 1435: 
 1436: Translate $text to allow it to be output as a 'comma separated values' 
 1437: format.
 1438: 
 1439: =cut
 1440: 
 1441: ###############################################################
 1442: ###############################################################
 1443: sub csv_translate {
 1444:     my $text = shift;
 1445:     $text =~ s/\"/\"\"/g;
 1446:     $text =~ s/\n/ /g;
 1447:     return $text;
 1448: }
 1449: 
 1450: ###############################################################
 1451: ###############################################################
 1452: 
 1453: =pod
 1454: 
 1455: =item * &define_excel_formats()
 1456: 
 1457: Define some commonly used Excel cell formats.
 1458: 
 1459: Currently supported formats:
 1460: 
 1461: =over 4
 1462: 
 1463: =item header
 1464: 
 1465: =item bold
 1466: 
 1467: =item h1
 1468: 
 1469: =item h2
 1470: 
 1471: =item h3
 1472: 
 1473: =item h4
 1474: 
 1475: =item i
 1476: 
 1477: =item date
 1478: 
 1479: =back
 1480: 
 1481: Inputs: $workbook
 1482: 
 1483: Returns: $format, a hash reference.
 1484: 
 1485: =cut
 1486: 
 1487: ###############################################################
 1488: ###############################################################
 1489: sub define_excel_formats {
 1490:     my ($workbook) = @_;
 1491:     my $format;
 1492:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1493:                                                 bottom    => 1,
 1494:                                                 align     => 'center');
 1495:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1496:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1497:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1498:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1499:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1500:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1501:     $format->{'date'} = $workbook->add_format(num_format=>
 1502:                                             'mm/dd/yyyy hh:mm:ss');
 1503:     return $format;
 1504: }
 1505: 
 1506: ###############################################################
 1507: ###############################################################
 1508: 
 1509: =pod
 1510: 
 1511: =item * &create_workbook()
 1512: 
 1513: Create an Excel worksheet.  If it fails, output message on the
 1514: request object and return undefs.
 1515: 
 1516: Inputs: Apache request object
 1517: 
 1518: Returns (undef) on failure, 
 1519:     Excel worksheet object, scalar with filename, and formats 
 1520:     from &Apache::loncommon::define_excel_formats on success
 1521: 
 1522: =cut
 1523: 
 1524: ###############################################################
 1525: ###############################################################
 1526: sub create_workbook {
 1527:     my ($r) = @_;
 1528:         #
 1529:     # Create the excel spreadsheet
 1530:     my $filename = '/prtspool/'.
 1531:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1532:         time.'_'.rand(1000000000).'.xls';
 1533:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1534:     if (! defined($workbook)) {
 1535:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1536:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1537:                             "This error has been logged.  ".
 1538:                             "Please alert your LON-CAPA administrator").
 1539:                   '</p>');
 1540:         return (undef);
 1541:     }
 1542:     #
 1543:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1544:     #
 1545:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1546:     return ($workbook,$filename,$format);
 1547: }
 1548: 
 1549: ###############################################################
 1550: ###############################################################
 1551: 
 1552: =pod
 1553: 
 1554: =item * &create_text_file()
 1555: 
 1556: Create a file to write to and eventually make available to the user.
 1557: If file creation fails, outputs an error message on the request object and 
 1558: return undefs.
 1559: 
 1560: Inputs: Apache request object, and file suffix
 1561: 
 1562: Returns (undef) on failure, 
 1563:     Filehandle and filename on success.
 1564: 
 1565: =cut
 1566: 
 1567: ###############################################################
 1568: ###############################################################
 1569: sub create_text_file {
 1570:     my ($r,$suffix) = @_;
 1571:     if (! defined($suffix)) { $suffix = 'txt'; };
 1572:     my $fh;
 1573:     my $filename = '/prtspool/'.
 1574:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1575:         time.'_'.rand(1000000000).'.'.$suffix;
 1576:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1577:     if (! defined($fh)) {
 1578:         $r->log_error("Couldn't open $filename for output $!");
 1579:         $r->print(&mt('Problems occurred in creating the output file. '
 1580:                      .'This error has been logged. '
 1581:                      .'Please alert your LON-CAPA administrator.'));
 1582:     }
 1583:     return ($fh,$filename)
 1584: }
 1585: 
 1586: 
 1587: =pod 
 1588: 
 1589: =back
 1590: 
 1591: =cut
 1592: 
 1593: ###############################################################
 1594: ##        Home server <option> list generating code          ##
 1595: ###############################################################
 1596: 
 1597: # ------------------------------------------
 1598: 
 1599: sub domain_select {
 1600:     my ($name,$value,$multiple)=@_;
 1601:     my %domains=map { 
 1602: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1603:     } &Apache::lonnet::all_domains();
 1604:     if ($multiple) {
 1605: 	$domains{''}=&mt('Any domain');
 1606: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1607: 	return &multiple_select_form($name,$value,4,\%domains);
 1608:     } else {
 1609: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1610: 	return &select_form($name,$value,%domains);
 1611:     }
 1612: }
 1613: 
 1614: #-------------------------------------------
 1615: 
 1616: =pod
 1617: 
 1618: =head1 Routines for form select boxes
 1619: 
 1620: =over 4
 1621: 
 1622: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1623: 
 1624: Returns a string containing a <select> element int multiple mode
 1625: 
 1626: 
 1627: Args:
 1628:   $name - name of the <select> element
 1629:   $value - scalar or array ref of values that should already be selected
 1630:   $size - number of rows long the select element is
 1631:   $hash - the elements should be 'option' => 'shown text'
 1632:           (shown text should already have been &mt())
 1633:   $order - (optional) array ref of the order to show the elements in
 1634: 
 1635: =cut
 1636: 
 1637: #-------------------------------------------
 1638: sub multiple_select_form {
 1639:     my ($name,$value,$size,$hash,$order)=@_;
 1640:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1641:     my $output='';
 1642:     if (! defined($size)) {
 1643:         $size = 4;
 1644:         if (scalar(keys(%$hash))<4) {
 1645:             $size = scalar(keys(%$hash));
 1646:         }
 1647:     }
 1648:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1649:     my @order;
 1650:     if (ref($order) eq 'ARRAY')  {
 1651:         @order = @{$order};
 1652:     } else {
 1653:         @order = sort(keys(%$hash));
 1654:     }
 1655:     if (exists($$hash{'select_form_order'})) {
 1656:         @order = @{$$hash{'select_form_order'}};
 1657:     }
 1658:         
 1659:     foreach my $key (@order) {
 1660:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1661:         $output.='selected="selected" ' if ($selected{$key});
 1662:         $output.='>'.$hash->{$key}."</option>\n";
 1663:     }
 1664:     $output.="</select>\n";
 1665:     return $output;
 1666: }
 1667: 
 1668: #-------------------------------------------
 1669: 
 1670: =pod
 1671: 
 1672: =item * &select_form($defdom,$name,%hash)
 1673: 
 1674: Returns a string containing a <select name='$name' size='1'> form to 
 1675: allow a user to select options from a hash option_name => displayed text.  
 1676: See lonrights.pm for an example invocation and use.
 1677: 
 1678: =cut
 1679: 
 1680: #-------------------------------------------
 1681: sub select_form {
 1682:     my ($def,$name,%hash) = @_;
 1683:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1684:     my @keys;
 1685:     if (exists($hash{'select_form_order'})) {
 1686: 	@keys=@{$hash{'select_form_order'}};
 1687:     } else {
 1688: 	@keys=sort(keys(%hash));
 1689:     }
 1690:     foreach my $key (@keys) {
 1691:         $selectform.=
 1692: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1693:             ($key eq $def ? 'selected="selected" ' : '').
 1694:                 ">".&mt($hash{$key})."</option>\n";
 1695:     }
 1696:     $selectform.="</select>";
 1697:     return $selectform;
 1698: }
 1699: 
 1700: # For display filters
 1701: 
 1702: sub display_filter {
 1703:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1704:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1705:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1706: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1707: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1708: 	   '</label></span> <span class="LC_nobreak">'.
 1709:            &mt('Filter [_1]',
 1710: 	   &select_form($env{'form.displayfilter'},
 1711: 			'displayfilter',
 1712: 			('currentfolder' => 'Current folder/page',
 1713: 			 'containing' => 'Containing phrase',
 1714: 			 'none' => 'None'))).
 1715: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1716: }
 1717: 
 1718: sub gradeleveldescription {
 1719:     my $gradelevel=shift;
 1720:     my %gradelevels=(0 => 'Not specified',
 1721: 		     1 => 'Grade 1',
 1722: 		     2 => 'Grade 2',
 1723: 		     3 => 'Grade 3',
 1724: 		     4 => 'Grade 4',
 1725: 		     5 => 'Grade 5',
 1726: 		     6 => 'Grade 6',
 1727: 		     7 => 'Grade 7',
 1728: 		     8 => 'Grade 8',
 1729: 		     9 => 'Grade 9',
 1730: 		     10 => 'Grade 10',
 1731: 		     11 => 'Grade 11',
 1732: 		     12 => 'Grade 12',
 1733: 		     13 => 'Grade 13',
 1734: 		     14 => '100 Level',
 1735: 		     15 => '200 Level',
 1736: 		     16 => '300 Level',
 1737: 		     17 => '400 Level',
 1738: 		     18 => 'Graduate Level');
 1739:     return &mt($gradelevels{$gradelevel});
 1740: }
 1741: 
 1742: sub select_level_form {
 1743:     my ($deflevel,$name)=@_;
 1744:     unless ($deflevel) { $deflevel=0; }
 1745:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1746:     for (my $i=0; $i<=18; $i++) {
 1747:         $selectform.="<option value=\"$i\" ".
 1748:             ($i==$deflevel ? 'selected="selected" ' : '').
 1749:                 ">".&gradeleveldescription($i)."</option>\n";
 1750:     }
 1751:     $selectform.="</select>";
 1752:     return $selectform;
 1753: }
 1754: 
 1755: #-------------------------------------------
 1756: 
 1757: =pod
 1758: 
 1759: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1760: 
 1761: Returns a string containing a <select name='$name' size='1'> form to 
 1762: allow a user to select the domain to preform an operation in.  
 1763: See loncreateuser.pm for an example invocation and use.
 1764: 
 1765: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1766: selected");
 1767: 
 1768: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1769: 
 1770: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1771: 
 1772: =cut
 1773: 
 1774: #-------------------------------------------
 1775: sub select_dom_form {
 1776:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1777:     my $onchange;
 1778:     if ($autosubmit) {
 1779:         $onchange = ' onchange="this.form.submit()"';
 1780:     }
 1781:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1782:     if ($includeempty) { @domains=('',@domains); }
 1783:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1784:     foreach my $dom (@domains) {
 1785:         $selectdomain.="<option value=\"$dom\" ".
 1786:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1787:         if ($showdomdesc) {
 1788:             if ($dom ne '') {
 1789:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1790:                 if ($domdesc ne '') {
 1791:                     $selectdomain .= ' ('.$domdesc.')';
 1792:                 }
 1793:             } 
 1794:         }
 1795:         $selectdomain .= "</option>\n";
 1796:     }
 1797:     $selectdomain.="</select>";
 1798:     return $selectdomain;
 1799: }
 1800: 
 1801: #-------------------------------------------
 1802: 
 1803: =pod
 1804: 
 1805: =item * &home_server_form_item($domain,$name,$defaultflag)
 1806: 
 1807: input: 4 arguments (two required, two optional) - 
 1808:     $domain - domain of new user
 1809:     $name - name of form element
 1810:     $default - Value of 'default' causes a default item to be first 
 1811:                             option, and selected by default. 
 1812:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1813:                             if 1 server found, or default, if 0 found.
 1814: output: returns 2 items: 
 1815: (a) form element which contains either:
 1816:    (i) <select name="$name">
 1817:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1818:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1819:        </select>
 1820:        form item if there are multiple library servers in $domain, or
 1821:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1822:        if there is only one library server in $domain.
 1823: 
 1824: (b) number of library servers found.
 1825: 
 1826: See loncreateuser.pm for example of use.
 1827: 
 1828: =cut
 1829: 
 1830: #-------------------------------------------
 1831: sub home_server_form_item {
 1832:     my ($domain,$name,$default,$hide) = @_;
 1833:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1834:     my $result;
 1835:     my $numlib = keys(%servers);
 1836:     if ($numlib > 1) {
 1837:         $result .= '<select name="'.$name.'" />'."\n";
 1838:         if ($default) {
 1839:             $result .= '<option value="default" selected>'.&mt('default').
 1840:                        '</option>'."\n";
 1841:         }
 1842:         foreach my $hostid (sort(keys(%servers))) {
 1843:             $result.= '<option value="'.$hostid.'">'.
 1844: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1845:         }
 1846:         $result .= '</select>'."\n";
 1847:     } elsif ($numlib == 1) {
 1848:         my $hostid;
 1849:         foreach my $item (keys(%servers)) {
 1850:             $hostid = $item;
 1851:         }
 1852:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1853:                    $hostid.'" />';
 1854:                    if (!$hide) {
 1855:                        $result .= $hostid.' '.$servers{$hostid};
 1856:                    }
 1857:                    $result .= "\n";
 1858:     } elsif ($default) {
 1859:         $result .= '<input type="hidden" name="'.$name.
 1860:                    '" value="default" />';
 1861:                    if (!$hide) {
 1862:                        $result .= &mt('default');
 1863:                    }
 1864:                    $result .= "\n";
 1865:     }
 1866:     return ($result,$numlib);
 1867: }
 1868: 
 1869: =pod
 1870: 
 1871: =back 
 1872: 
 1873: =cut
 1874: 
 1875: ###############################################################
 1876: ##                  Decoding User Agent                      ##
 1877: ###############################################################
 1878: 
 1879: =pod
 1880: 
 1881: =head1 Decoding the User Agent
 1882: 
 1883: =over 4
 1884: 
 1885: =item * &decode_user_agent()
 1886: 
 1887: Inputs: $r
 1888: 
 1889: Outputs:
 1890: 
 1891: =over 4
 1892: 
 1893: =item * $httpbrowser
 1894: 
 1895: =item * $clientbrowser
 1896: 
 1897: =item * $clientversion
 1898: 
 1899: =item * $clientmathml
 1900: 
 1901: =item * $clientunicode
 1902: 
 1903: =item * $clientos
 1904: 
 1905: =back
 1906: 
 1907: =back 
 1908: 
 1909: =cut
 1910: 
 1911: ###############################################################
 1912: ###############################################################
 1913: sub decode_user_agent {
 1914:     my ($r)=@_;
 1915:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1916:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1917:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1918:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1919:     my $clientbrowser='unknown';
 1920:     my $clientversion='0';
 1921:     my $clientmathml='';
 1922:     my $clientunicode='0';
 1923:     for (my $i=0;$i<=$#browsertype;$i++) {
 1924:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1925: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1926: 	    $clientbrowser=$bname;
 1927:             $httpbrowser=~/$vreg/i;
 1928: 	    $clientversion=$1;
 1929:             $clientmathml=($clientversion>=$minv);
 1930:             $clientunicode=($clientversion>=$univ);
 1931: 	}
 1932:     }
 1933:     my $clientos='unknown';
 1934:     if (($httpbrowser=~/linux/i) ||
 1935:         ($httpbrowser=~/unix/i) ||
 1936:         ($httpbrowser=~/ux/i) ||
 1937:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1938:     if (($httpbrowser=~/vax/i) ||
 1939:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1940:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1941:     if (($httpbrowser=~/mac/i) ||
 1942:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1943:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1944:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1945:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1946:             $clientunicode,$clientos,);
 1947: }
 1948: 
 1949: ###############################################################
 1950: ##    Authentication changing form generation subroutines    ##
 1951: ###############################################################
 1952: ##
 1953: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1954: ## hash, and have reasonable default values.
 1955: ##
 1956: ##    formname = the name given in the <form> tag.
 1957: #-------------------------------------------
 1958: 
 1959: =pod
 1960: 
 1961: =head1 Authentication Routines
 1962: 
 1963: =over 4
 1964: 
 1965: =item * &authform_xxxxxx()
 1966: 
 1967: The authform_xxxxxx subroutines provide javascript and html forms which 
 1968: handle some of the conveniences required for authentication forms.  
 1969: This is not an optimal method, but it works.  
 1970: 
 1971: =over 4
 1972: 
 1973: =item * authform_header
 1974: 
 1975: =item * authform_authorwarning
 1976: 
 1977: =item * authform_nochange
 1978: 
 1979: =item * authform_kerberos
 1980: 
 1981: =item * authform_internal
 1982: 
 1983: =item * authform_filesystem
 1984: 
 1985: =back
 1986: 
 1987: See loncreateuser.pm for invocation and use examples.
 1988: 
 1989: =cut
 1990: 
 1991: #-------------------------------------------
 1992: sub authform_header{  
 1993:     my %in = (
 1994:         formname => 'cu',
 1995:         kerb_def_dom => '',
 1996:         @_,
 1997:     );
 1998:     $in{'formname'} = 'document.' . $in{'formname'};
 1999:     my $result='';
 2000: 
 2001: #---------------------------------------------- Code for upper case translation
 2002:     my $Javascript_toUpperCase;
 2003:     unless ($in{kerb_def_dom}) {
 2004:         $Javascript_toUpperCase =<<"END";
 2005:         switch (choice) {
 2006:            case 'krb': currentform.elements[choicearg].value =
 2007:                currentform.elements[choicearg].value.toUpperCase();
 2008:                break;
 2009:            default:
 2010:         }
 2011: END
 2012:     } else {
 2013:         $Javascript_toUpperCase = "";
 2014:     }
 2015: 
 2016:     my $radioval = "'nochange'";
 2017:     if (defined($in{'curr_authtype'})) {
 2018:         if ($in{'curr_authtype'} ne '') {
 2019:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2020:         }
 2021:     }
 2022:     my $argfield = 'null';
 2023:     if (defined($in{'mode'})) {
 2024:         if ($in{'mode'} eq 'modifycourse')  {
 2025:             if (defined($in{'curr_autharg'})) {
 2026:                 if ($in{'curr_autharg'} ne '') {
 2027:                     $argfield = "'$in{'curr_autharg'}'";
 2028:                 }
 2029:             }
 2030:         }
 2031:     }
 2032: 
 2033:     $result.=<<"END";
 2034: var current = new Object();
 2035: current.radiovalue = $radioval;
 2036: current.argfield = $argfield;
 2037: 
 2038: function changed_radio(choice,currentform) {
 2039:     var choicearg = choice + 'arg';
 2040:     // If a radio button in changed, we need to change the argfield
 2041:     if (current.radiovalue != choice) {
 2042:         current.radiovalue = choice;
 2043:         if (current.argfield != null) {
 2044:             currentform.elements[current.argfield].value = '';
 2045:         }
 2046:         if (choice == 'nochange') {
 2047:             current.argfield = null;
 2048:         } else {
 2049:             current.argfield = choicearg;
 2050:             switch(choice) {
 2051:                 case 'krb': 
 2052:                     currentform.elements[current.argfield].value = 
 2053:                         "$in{'kerb_def_dom'}";
 2054:                 break;
 2055:               default:
 2056:                 break;
 2057:             }
 2058:         }
 2059:     }
 2060:     return;
 2061: }
 2062: 
 2063: function changed_text(choice,currentform) {
 2064:     var choicearg = choice + 'arg';
 2065:     if (currentform.elements[choicearg].value !='') {
 2066:         $Javascript_toUpperCase
 2067:         // clear old field
 2068:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2069:             currentform.elements[current.argfield].value = '';
 2070:         }
 2071:         current.argfield = choicearg;
 2072:     }
 2073:     set_auth_radio_buttons(choice,currentform);
 2074:     return;
 2075: }
 2076: 
 2077: function set_auth_radio_buttons(newvalue,currentform) {
 2078:     var i=0;
 2079:     while (i < currentform.login.length) {
 2080:         if (currentform.login[i].value == newvalue) { break; }
 2081:         i++;
 2082:     }
 2083:     if (i == currentform.login.length) {
 2084:         return;
 2085:     }
 2086:     current.radiovalue = newvalue;
 2087:     currentform.login[i].checked = true;
 2088:     return;
 2089: }
 2090: END
 2091:     return $result;
 2092: }
 2093: 
 2094: sub authform_authorwarning{
 2095:     my $result='';
 2096:     $result='<i>'.
 2097:         &mt('As a general rule, only authors or co-authors should be '.
 2098:             'filesystem authenticated '.
 2099:             '(which allows access to the server filesystem).')."</i>\n";
 2100:     return $result;
 2101: }
 2102: 
 2103: sub authform_nochange{  
 2104:     my %in = (
 2105:               formname => 'document.cu',
 2106:               kerb_def_dom => 'MSU.EDU',
 2107:               @_,
 2108:           );
 2109:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2110:     my $result;
 2111:     if (keys(%can_assign) == 0) {
 2112:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2113:     } else {
 2114:         $result = '<label>'.&mt('[_1] Do not change login data',
 2115:                   '<input type="radio" name="login" value="nochange" '.
 2116:                   'checked="checked" onclick="'.
 2117:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2118: 	    '</label>';
 2119:     }
 2120:     return $result;
 2121: }
 2122: 
 2123: sub authform_kerberos {
 2124:     my %in = (
 2125:               formname => 'document.cu',
 2126:               kerb_def_dom => 'MSU.EDU',
 2127:               kerb_def_auth => 'krb4',
 2128:               @_,
 2129:               );
 2130:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2131:         $autharg,$jscall);
 2132:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2133:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2134:        $check5 = ' checked="checked"';
 2135:     } else {
 2136:        $check4 = ' checked="checked"';
 2137:     }
 2138:     $krbarg = $in{'kerb_def_dom'};
 2139:     if (defined($in{'curr_authtype'})) {
 2140:         if ($in{'curr_authtype'} eq 'krb') {
 2141:             $krbcheck = ' checked="checked"';
 2142:             if (defined($in{'mode'})) {
 2143:                 if ($in{'mode'} eq 'modifyuser') {
 2144:                     $krbcheck = '';
 2145:                 }
 2146:             }
 2147:             if (defined($in{'curr_kerb_ver'})) {
 2148:                 if ($in{'curr_krb_ver'} eq '5') {
 2149:                     $check5 = ' checked="checked"';
 2150:                     $check4 = '';
 2151:                 } else {
 2152:                     $check4 = ' checked="checked"';
 2153:                     $check5 = '';
 2154:                 }
 2155:             }
 2156:             if (defined($in{'curr_autharg'})) {
 2157:                 $krbarg = $in{'curr_autharg'};
 2158:             }
 2159:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2160:                 if (defined($in{'curr_autharg'})) {
 2161:                     $result = 
 2162:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2163:         $in{'curr_autharg'},$krbver);
 2164:                 } else {
 2165:                     $result =
 2166:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2167:                 }
 2168:                 return $result; 
 2169:             }
 2170:         }
 2171:     } else {
 2172:         if ($authnum == 1) {
 2173:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2174:         }
 2175:     }
 2176:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2177:         return;
 2178:     } elsif ($authtype eq '') {
 2179:         if (defined($in{'mode'})) {
 2180:             if ($in{'mode'} eq 'modifycourse') {
 2181:                 if ($authnum == 1) {
 2182:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2183:                 }
 2184:             }
 2185:         }
 2186:     }
 2187:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2188:     if ($authtype eq '') {
 2189:         $authtype = '<input type="radio" name="login" value="krb" '.
 2190:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2191:                     $krbcheck.' />';
 2192:     }
 2193:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2194:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2195:          $in{'curr_authtype'} eq 'krb5') ||
 2196:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2197:          $in{'curr_authtype'} eq 'krb4')) {
 2198:         $result .= &mt
 2199:         ('[_1] Kerberos authenticated with domain [_2] '.
 2200:          '[_3] Version 4 [_4] Version 5 [_5]',
 2201:          '<label>'.$authtype,
 2202:          '</label><input type="text" size="10" name="krbarg" '.
 2203:              'value="'.$krbarg.'" '.
 2204:              'onchange="'.$jscall.'" />',
 2205:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2206:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2207: 	 '</label>');
 2208:     } elsif ($can_assign{'krb4'}) {
 2209:         $result .= &mt
 2210:         ('[_1] Kerberos authenticated with domain [_2] '.
 2211:          '[_3] Version 4 [_4]',
 2212:          '<label>'.$authtype,
 2213:          '</label><input type="text" size="10" name="krbarg" '.
 2214:              'value="'.$krbarg.'" '.
 2215:              'onchange="'.$jscall.'" />',
 2216:          '<label><input type="hidden" name="krbver" value="4" />',
 2217:          '</label>');
 2218:     } elsif ($can_assign{'krb5'}) {
 2219:         $result .= &mt
 2220:         ('[_1] Kerberos authenticated with domain [_2] '.
 2221:          '[_3] Version 5 [_4]',
 2222:          '<label>'.$authtype,
 2223:          '</label><input type="text" size="10" name="krbarg" '.
 2224:              'value="'.$krbarg.'" '.
 2225:              'onchange="'.$jscall.'" />',
 2226:          '<label><input type="hidden" name="krbver" value="5" />',
 2227:          '</label>');
 2228:     }
 2229:     return $result;
 2230: }
 2231: 
 2232: sub authform_internal{  
 2233:     my %in = (
 2234:                 formname => 'document.cu',
 2235:                 kerb_def_dom => 'MSU.EDU',
 2236:                 @_,
 2237:                 );
 2238:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2239:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2240:     if (defined($in{'curr_authtype'})) {
 2241:         if ($in{'curr_authtype'} eq 'int') {
 2242:             if ($can_assign{'int'}) {
 2243:                 $intcheck = 'checked="checked" ';
 2244:                 if (defined($in{'mode'})) {
 2245:                     if ($in{'mode'} eq 'modifyuser') {
 2246:                         $intcheck = '';
 2247:                     }
 2248:                 }
 2249:                 if (defined($in{'curr_autharg'})) {
 2250:                     $intarg = $in{'curr_autharg'};
 2251:                 }
 2252:             } else {
 2253:                 $result = &mt('Currently internally authenticated.');
 2254:                 return $result;
 2255:             }
 2256:         }
 2257:     } else {
 2258:         if ($authnum == 1) {
 2259:             $authtype = '<input type="hidden" name="login" value="int" />';
 2260:         }
 2261:     }
 2262:     if (!$can_assign{'int'}) {
 2263:         return;
 2264:     } elsif ($authtype eq '') {
 2265:         if (defined($in{'mode'})) {
 2266:             if ($in{'mode'} eq 'modifycourse') {
 2267:                 if ($authnum == 1) {
 2268:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2269:                 }
 2270:             }
 2271:         }
 2272:     }
 2273:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2274:     if ($authtype eq '') {
 2275:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2276:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2277:     }
 2278:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2279:                $intarg.'" onchange="'.$jscall.'" />';
 2280:     $result = &mt
 2281:         ('[_1] Internally authenticated (with initial password [_2])',
 2282:          '<label>'.$authtype,'</label>'.$autharg);
 2283:     $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>';
 2284:     return $result;
 2285: }
 2286: 
 2287: sub authform_local{  
 2288:     my %in = (
 2289:               formname => 'document.cu',
 2290:               kerb_def_dom => 'MSU.EDU',
 2291:               @_,
 2292:               );
 2293:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2294:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2295:     if (defined($in{'curr_authtype'})) {
 2296:         if ($in{'curr_authtype'} eq 'loc') {
 2297:             if ($can_assign{'loc'}) {
 2298:                 $loccheck = 'checked="checked" ';
 2299:                 if (defined($in{'mode'})) {
 2300:                     if ($in{'mode'} eq 'modifyuser') {
 2301:                         $loccheck = '';
 2302:                     }
 2303:                 }
 2304:                 if (defined($in{'curr_autharg'})) {
 2305:                     $locarg = $in{'curr_autharg'};
 2306:                 }
 2307:             } else {
 2308:                 $result = &mt('Currently using local (institutional) authentication.');
 2309:                 return $result;
 2310:             }
 2311:         }
 2312:     } else {
 2313:         if ($authnum == 1) {
 2314:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2315:         }
 2316:     }
 2317:     if (!$can_assign{'loc'}) {
 2318:         return;
 2319:     } elsif ($authtype eq '') {
 2320:         if (defined($in{'mode'})) {
 2321:             if ($in{'mode'} eq 'modifycourse') {
 2322:                 if ($authnum == 1) {
 2323:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2324:                 }
 2325:             }
 2326:         }
 2327:     }
 2328:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2329:     if ($authtype eq '') {
 2330:         $authtype = '<input type="radio" name="login" value="loc" '.
 2331:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2332:                     $jscall.'" />';
 2333:     }
 2334:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2335:                $locarg.'" onchange="'.$jscall.'" />';
 2336:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2337:                   '<label>'.$authtype,'</label>'.$autharg);
 2338:     return $result;
 2339: }
 2340: 
 2341: sub authform_filesystem{  
 2342:     my %in = (
 2343:               formname => 'document.cu',
 2344:               kerb_def_dom => 'MSU.EDU',
 2345:               @_,
 2346:               );
 2347:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2348:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2349:     if (defined($in{'curr_authtype'})) {
 2350:         if ($in{'curr_authtype'} eq 'fsys') {
 2351:             if ($can_assign{'fsys'}) {
 2352:                 $fsyscheck = 'checked="checked" ';
 2353:                 if (defined($in{'mode'})) {
 2354:                     if ($in{'mode'} eq 'modifyuser') {
 2355:                         $fsyscheck = '';
 2356:                     }
 2357:                 }
 2358:             } else {
 2359:                 $result = &mt('Currently Filesystem Authenticated.');
 2360:                 return $result;
 2361:             }           
 2362:         }
 2363:     } else {
 2364:         if ($authnum == 1) {
 2365:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2366:         }
 2367:     }
 2368:     if (!$can_assign{'fsys'}) {
 2369:         return;
 2370:     } elsif ($authtype eq '') {
 2371:         if (defined($in{'mode'})) {
 2372:             if ($in{'mode'} eq 'modifycourse') {
 2373:                 if ($authnum == 1) {
 2374:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2375:                 }
 2376:             }
 2377:         }
 2378:     }
 2379:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2380:     if ($authtype eq '') {
 2381:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2382:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2383:                     $jscall.'" />';
 2384:     }
 2385:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2386:                ' onchange="'.$jscall.'" />';
 2387:     $result = &mt
 2388:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2389:          '<label><input type="radio" name="login" value="fsys" '.
 2390:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2391:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2392:                   'onchange="'.$jscall.'" />');
 2393:     return $result;
 2394: }
 2395: 
 2396: sub get_assignable_auth {
 2397:     my ($dom) = @_;
 2398:     if ($dom eq '') {
 2399:         $dom = $env{'request.role.domain'};
 2400:     }
 2401:     my %can_assign = (
 2402:                           krb4 => 1,
 2403:                           krb5 => 1,
 2404:                           int  => 1,
 2405:                           loc  => 1,
 2406:                      );
 2407:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2408:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2409:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2410:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2411:             my $context;
 2412:             if ($env{'request.role'} =~ /^au/) {
 2413:                 $context = 'author';
 2414:             } elsif ($env{'request.role'} =~ /^dc/) {
 2415:                 $context = 'domain';
 2416:             } elsif ($env{'request.course.id'}) {
 2417:                 $context = 'course';
 2418:             }
 2419:             if ($context) {
 2420:                 if (ref($authhash->{$context}) eq 'HASH') {
 2421:                    %can_assign = %{$authhash->{$context}}; 
 2422:                 }
 2423:             }
 2424:         }
 2425:     }
 2426:     my $authnum = 0;
 2427:     foreach my $key (keys(%can_assign)) {
 2428:         if ($can_assign{$key}) {
 2429:             $authnum ++;
 2430:         }
 2431:     }
 2432:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2433:         $authnum --;
 2434:     }
 2435:     return ($authnum,%can_assign);
 2436: }
 2437: 
 2438: ###############################################################
 2439: ##    Get Kerberos Defaults for Domain                 ##
 2440: ###############################################################
 2441: ##
 2442: ## Returns default kerberos version and an associated argument
 2443: ## as listed in file domain.tab. If not listed, provides
 2444: ## appropriate default domain and kerberos version.
 2445: ##
 2446: #-------------------------------------------
 2447: 
 2448: =pod
 2449: 
 2450: =item * &get_kerberos_defaults()
 2451: 
 2452: get_kerberos_defaults($target_domain) returns the default kerberos
 2453: version and domain. If not found, it defaults to version 4 and the 
 2454: domain of the server.
 2455: 
 2456: =over 4
 2457: 
 2458: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2459: 
 2460: =back
 2461: 
 2462: =back
 2463: 
 2464: =cut
 2465: 
 2466: #-------------------------------------------
 2467: sub get_kerberos_defaults {
 2468:     my $domain=shift;
 2469:     my ($krbdef,$krbdefdom);
 2470:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2471:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2472:         $krbdef = $domdefaults{'auth_def'};
 2473:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2474:     } else {
 2475:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2476:         my $krbdefdom=$1;
 2477:         $krbdefdom=~tr/a-z/A-Z/;
 2478:         $krbdef = "krb4";
 2479:     }
 2480:     return ($krbdef,$krbdefdom);
 2481: }
 2482: 
 2483: 
 2484: ###############################################################
 2485: ##                Thesaurus Functions                        ##
 2486: ###############################################################
 2487: 
 2488: =pod
 2489: 
 2490: =head1 Thesaurus Functions
 2491: 
 2492: =over 4
 2493: 
 2494: =item * &initialize_keywords()
 2495: 
 2496: Initializes the package variable %Keywords if it is empty.  Uses the
 2497: package variable $thesaurus_db_file.
 2498: 
 2499: =cut
 2500: 
 2501: ###################################################
 2502: 
 2503: sub initialize_keywords {
 2504:     return 1 if (scalar keys(%Keywords));
 2505:     # If we are here, %Keywords is empty, so fill it up
 2506:     #   Make sure the file we need exists...
 2507:     if (! -e $thesaurus_db_file) {
 2508:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2509:                                  " failed because it does not exist");
 2510:         return 0;
 2511:     }
 2512:     #   Set up the hash as a database
 2513:     my %thesaurus_db;
 2514:     if (! tie(%thesaurus_db,'GDBM_File',
 2515:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2516:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2517:                                  $thesaurus_db_file);
 2518:         return 0;
 2519:     } 
 2520:     #  Get the average number of appearances of a word.
 2521:     my $avecount = $thesaurus_db{'average.count'};
 2522:     #  Put keywords (those that appear > average) into %Keywords
 2523:     while (my ($word,$data)=each (%thesaurus_db)) {
 2524:         my ($count,undef) = split /:/,$data;
 2525:         $Keywords{$word}++ if ($count > $avecount);
 2526:     }
 2527:     untie %thesaurus_db;
 2528:     # Remove special values from %Keywords.
 2529:     foreach my $value ('total.count','average.count') {
 2530:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2531:   }
 2532:     return 1;
 2533: }
 2534: 
 2535: ###################################################
 2536: 
 2537: =pod
 2538: 
 2539: =item * &keyword($word)
 2540: 
 2541: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2542: than the average number of times in the thesaurus database.  Calls 
 2543: &initialize_keywords
 2544: 
 2545: =cut
 2546: 
 2547: ###################################################
 2548: 
 2549: sub keyword {
 2550:     return if (!&initialize_keywords());
 2551:     my $word=lc(shift());
 2552:     $word=~s/\W//g;
 2553:     return exists($Keywords{$word});
 2554: }
 2555: 
 2556: ###############################################################
 2557: 
 2558: =pod 
 2559: 
 2560: =item * &get_related_words()
 2561: 
 2562: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2563: an array of words.  If the keyword is not in the thesaurus, an empty array
 2564: will be returned.  The order of the words returned is determined by the
 2565: database which holds them.
 2566: 
 2567: Uses global $thesaurus_db_file.
 2568: 
 2569: =cut
 2570: 
 2571: ###############################################################
 2572: sub get_related_words {
 2573:     my $keyword = shift;
 2574:     my %thesaurus_db;
 2575:     if (! -e $thesaurus_db_file) {
 2576:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2577:                                  "failed because the file does not exist");
 2578:         return ();
 2579:     }
 2580:     if (! tie(%thesaurus_db,'GDBM_File',
 2581:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2582:         return ();
 2583:     } 
 2584:     my @Words=();
 2585:     my $count=0;
 2586:     if (exists($thesaurus_db{$keyword})) {
 2587: 	# The first element is the number of times
 2588: 	# the word appears.  We do not need it now.
 2589: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2590: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2591: 	my $threshold=$mostfrequentcount/10;
 2592:         foreach my $possibleword (@RelatedWords) {
 2593:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2594:             if ($wordcount>$threshold) {
 2595: 		push(@Words,$word);
 2596:                 $count++;
 2597:                 if ($count>10) { last; }
 2598: 	    }
 2599:         }
 2600:     }
 2601:     untie %thesaurus_db;
 2602:     return @Words;
 2603: }
 2604: 
 2605: =pod
 2606: 
 2607: =back
 2608: 
 2609: =cut
 2610: 
 2611: # -------------------------------------------------------------- Plaintext name
 2612: =pod
 2613: 
 2614: =head1 User Name Functions
 2615: 
 2616: =over 4
 2617: 
 2618: =item * &plainname($uname,$udom,$first)
 2619: 
 2620: Takes a users logon name and returns it as a string in
 2621: "first middle last generation" form 
 2622: if $first is set to 'lastname' then it returns it as
 2623: 'lastname generation, firstname middlename' if their is a lastname
 2624: 
 2625: =cut
 2626: 
 2627: 
 2628: ###############################################################
 2629: sub plainname {
 2630:     my ($uname,$udom,$first)=@_;
 2631:     return if (!defined($uname) || !defined($udom));
 2632:     my %names=&getnames($uname,$udom);
 2633:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2634: 					  $names{'middlename'},
 2635: 					  $names{'lastname'},
 2636: 					  $names{'generation'},$first);
 2637:     $name=~s/^\s+//;
 2638:     $name=~s/\s+$//;
 2639:     $name=~s/\s+/ /g;
 2640:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2641:     return $name;
 2642: }
 2643: 
 2644: # -------------------------------------------------------------------- Nickname
 2645: =pod
 2646: 
 2647: =item * &nickname($uname,$udom)
 2648: 
 2649: Gets a users name and returns it as a string as
 2650: 
 2651: "&quot;nickname&quot;"
 2652: 
 2653: if the user has a nickname or
 2654: 
 2655: "first middle last generation"
 2656: 
 2657: if the user does not
 2658: 
 2659: =cut
 2660: 
 2661: sub nickname {
 2662:     my ($uname,$udom)=@_;
 2663:     return if (!defined($uname) || !defined($udom));
 2664:     my %names=&getnames($uname,$udom);
 2665:     my $name=$names{'nickname'};
 2666:     if ($name) {
 2667:        $name='&quot;'.$name.'&quot;'; 
 2668:     } else {
 2669:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2670: 	     $names{'lastname'}.' '.$names{'generation'};
 2671:        $name=~s/\s+$//;
 2672:        $name=~s/\s+/ /g;
 2673:     }
 2674:     return $name;
 2675: }
 2676: 
 2677: sub getnames {
 2678:     my ($uname,$udom)=@_;
 2679:     return if (!defined($uname) || !defined($udom));
 2680:     if ($udom eq 'public' && $uname eq 'public') {
 2681: 	return ('lastname' => &mt('Public'));
 2682:     }
 2683:     my $id=$uname.':'.$udom;
 2684:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2685:     if ($cached) {
 2686: 	return %{$names};
 2687:     } else {
 2688: 	my %loadnames=&Apache::lonnet::get('environment',
 2689:                     ['firstname','middlename','lastname','generation','nickname'],
 2690: 					 $udom,$uname);
 2691: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2692: 	return %loadnames;
 2693:     }
 2694: }
 2695: 
 2696: # -------------------------------------------------------------------- getemails
 2697: 
 2698: =pod
 2699: 
 2700: =item * &getemails($uname,$udom)
 2701: 
 2702: Gets a user's email information and returns it as a hash with keys:
 2703: notification, critnotification, permanentemail
 2704: 
 2705: For notification and critnotification, values are comma-separated lists 
 2706: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2707:  
 2708: 
 2709: =cut
 2710: 
 2711: 
 2712: sub getemails {
 2713:     my ($uname,$udom)=@_;
 2714:     if ($udom eq 'public' && $uname eq 'public') {
 2715: 	return;
 2716:     }
 2717:     if (!$udom) { $udom=$env{'user.domain'}; }
 2718:     if (!$uname) { $uname=$env{'user.name'}; }
 2719:     my $id=$uname.':'.$udom;
 2720:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2721:     if ($cached) {
 2722: 	return %{$names};
 2723:     } else {
 2724: 	my %loadnames=&Apache::lonnet::get('environment',
 2725:                     			   ['notification','critnotification',
 2726: 					    'permanentemail'],
 2727: 					   $udom,$uname);
 2728: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2729: 	return %loadnames;
 2730:     }
 2731: }
 2732: 
 2733: sub flush_email_cache {
 2734:     my ($uname,$udom)=@_;
 2735:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2736:     if (!$uname) { $uname=$env{'user.name'};   }
 2737:     return if ($udom eq 'public' && $uname eq 'public');
 2738:     my $id=$uname.':'.$udom;
 2739:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2740: }
 2741: 
 2742: # -------------------------------------------------------------------- getlangs
 2743: 
 2744: =pod
 2745: 
 2746: =item * &getlangs($uname,$udom)
 2747: 
 2748: Gets a user's language preference and returns it as a hash with key:
 2749: language.
 2750: 
 2751: =cut
 2752: 
 2753: 
 2754: sub getlangs {
 2755:     my ($uname,$udom) = @_;
 2756:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2757:     if (!$uname) { $uname=$env{'user.name'};   }
 2758:     my $id=$uname.':'.$udom;
 2759:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2760:     if ($cached) {
 2761:         return %{$langs};
 2762:     } else {
 2763:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2764:                                            $udom,$uname);
 2765:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2766:         return %loadlangs;
 2767:     }
 2768: }
 2769: 
 2770: sub flush_langs_cache {
 2771:     my ($uname,$udom)=@_;
 2772:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2773:     if (!$uname) { $uname=$env{'user.name'};   }
 2774:     return if ($udom eq 'public' && $uname eq 'public');
 2775:     my $id=$uname.':'.$udom;
 2776:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2777: }
 2778: 
 2779: # ------------------------------------------------------------------ Screenname
 2780: 
 2781: =pod
 2782: 
 2783: =item * &screenname($uname,$udom)
 2784: 
 2785: Gets a users screenname and returns it as a string
 2786: 
 2787: =cut
 2788: 
 2789: sub screenname {
 2790:     my ($uname,$udom)=@_;
 2791:     if ($uname eq $env{'user.name'} &&
 2792: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2793:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2794:     return $names{'screenname'};
 2795: }
 2796: 
 2797: 
 2798: # ------------------------------------------------------------- Message Wrapper
 2799: 
 2800: sub messagewrapper {
 2801:     my ($link,$username,$domain,$subject,$text)=@_;
 2802:     return 
 2803:         '<a href="/adm/email?compose=individual&amp;'.
 2804:         'recname='.$username.'&amp;recdom='.$domain.
 2805: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2806:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2807: }
 2808: # --------------------------------------------------------------- Notes Wrapper
 2809: 
 2810: sub noteswrapper {
 2811:     my ($link,$un,$do)=@_;
 2812:     return 
 2813: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2814: }
 2815: # ------------------------------------------------------------- Aboutme Wrapper
 2816: 
 2817: sub aboutmewrapper {
 2818:     my ($link,$username,$domain,$target)=@_;
 2819:     if (!defined($username)  && !defined($domain)) {
 2820:         return;
 2821:     }
 2822:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2823: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2824: }
 2825: 
 2826: # ------------------------------------------------------------ Syllabus Wrapper
 2827: 
 2828: 
 2829: sub syllabuswrapper {
 2830:     my ($linktext,$coursedir,$domain)=@_;
 2831:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2832: }
 2833: 
 2834: sub track_student_link {
 2835:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2836:     my $link ="/adm/trackstudent?";
 2837:     my $title = 'View recent activity';
 2838:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2839:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2840:         $link .= "selected_student=$sname:$sdom";
 2841:         $title .= ' of this student';
 2842:     } 
 2843:     if (defined($target) && $target !~ /^\s*$/) {
 2844:         $target = qq{target="$target"};
 2845:     } else {
 2846:         $target = '';
 2847:     }
 2848:     if ($start) { $link.='&amp;start='.$start; }
 2849:     $title = &mt($title);
 2850:     $linktext = &mt($linktext);
 2851:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2852: 	&help_open_topic('View_recent_activity');
 2853: }
 2854: 
 2855: sub slot_reservations_link {
 2856:     my ($linktext,$sname,$sdom,$target) = @_;
 2857:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2858:     my $title = 'View slot reservation history';
 2859:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2860:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2861:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2862:         $title .= ' of this student';
 2863:     }
 2864:     if (defined($target) && $target !~ /^\s*$/) {
 2865:         $target = qq{target="$target"};
 2866:     } else {
 2867:         $target = '';
 2868:     }
 2869:     $title = &mt($title);
 2870:     $linktext = &mt($linktext);
 2871:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2872: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2873: 
 2874: }
 2875: 
 2876: # ===================================================== Display a student photo
 2877: 
 2878: 
 2879: sub student_image_tag {
 2880:     my ($domain,$user)=@_;
 2881:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2882:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2883: 	return '<img src="'.$imgsrc.'" align="right" />';
 2884:     } else {
 2885: 	return '';
 2886:     }
 2887: }
 2888: 
 2889: =pod
 2890: 
 2891: =back
 2892: 
 2893: =head1 Access .tab File Data
 2894: 
 2895: =over 4
 2896: 
 2897: =item * &languageids() 
 2898: 
 2899: returns list of all language ids
 2900: 
 2901: =cut
 2902: 
 2903: sub languageids {
 2904:     return sort(keys(%language));
 2905: }
 2906: 
 2907: =pod
 2908: 
 2909: =item * &languagedescription() 
 2910: 
 2911: returns description of a specified language id
 2912: 
 2913: =cut
 2914: 
 2915: sub languagedescription {
 2916:     my $code=shift;
 2917:     return  ($supported_language{$code}?'* ':'').
 2918:             $language{$code}.
 2919: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2920: }
 2921: 
 2922: sub plainlanguagedescription {
 2923:     my $code=shift;
 2924:     return $language{$code};
 2925: }
 2926: 
 2927: sub supportedlanguagecode {
 2928:     my $code=shift;
 2929:     return $supported_language{$code};
 2930: }
 2931: 
 2932: =pod
 2933: 
 2934: =item * &copyrightids() 
 2935: 
 2936: returns list of all copyrights
 2937: 
 2938: =cut
 2939: 
 2940: sub copyrightids {
 2941:     return sort(keys(%cprtag));
 2942: }
 2943: 
 2944: =pod
 2945: 
 2946: =item * &copyrightdescription() 
 2947: 
 2948: returns description of a specified copyright id
 2949: 
 2950: =cut
 2951: 
 2952: sub copyrightdescription {
 2953:     return &mt($cprtag{shift(@_)});
 2954: }
 2955: 
 2956: =pod
 2957: 
 2958: =item * &source_copyrightids() 
 2959: 
 2960: returns list of all source copyrights
 2961: 
 2962: =cut
 2963: 
 2964: sub source_copyrightids {
 2965:     return sort(keys(%scprtag));
 2966: }
 2967: 
 2968: =pod
 2969: 
 2970: =item * &source_copyrightdescription() 
 2971: 
 2972: returns description of a specified source copyright id
 2973: 
 2974: =cut
 2975: 
 2976: sub source_copyrightdescription {
 2977:     return &mt($scprtag{shift(@_)});
 2978: }
 2979: 
 2980: =pod
 2981: 
 2982: =item * &filecategories() 
 2983: 
 2984: returns list of all file categories
 2985: 
 2986: =cut
 2987: 
 2988: sub filecategories {
 2989:     return sort(keys(%category_extensions));
 2990: }
 2991: 
 2992: =pod
 2993: 
 2994: =item * &filecategorytypes() 
 2995: 
 2996: returns list of file types belonging to a given file
 2997: category
 2998: 
 2999: =cut
 3000: 
 3001: sub filecategorytypes {
 3002:     my ($cat) = @_;
 3003:     return @{$category_extensions{lc($cat)}};
 3004: }
 3005: 
 3006: =pod
 3007: 
 3008: =item * &fileembstyle() 
 3009: 
 3010: returns embedding style for a specified file type
 3011: 
 3012: =cut
 3013: 
 3014: sub fileembstyle {
 3015:     return $fe{lc(shift(@_))};
 3016: }
 3017: 
 3018: sub filemimetype {
 3019:     return $fm{lc(shift(@_))};
 3020: }
 3021: 
 3022: 
 3023: sub filecategoryselect {
 3024:     my ($name,$value)=@_;
 3025:     return &select_form($value,$name,
 3026: 			'' => &mt('Any category'),
 3027: 			map { $_,$_ } sort(keys(%category_extensions)));
 3028: }
 3029: 
 3030: =pod
 3031: 
 3032: =item * &filedescription() 
 3033: 
 3034: returns description for a specified file type
 3035: 
 3036: =cut
 3037: 
 3038: sub filedescription {
 3039:     my $file_description = $fd{lc(shift())};
 3040:     $file_description =~ s:([\[\]]):~$1:g;
 3041:     return &mt($file_description);
 3042: }
 3043: 
 3044: =pod
 3045: 
 3046: =item * &filedescriptionex() 
 3047: 
 3048: returns description for a specified file type with
 3049: extra formatting
 3050: 
 3051: =cut
 3052: 
 3053: sub filedescriptionex {
 3054:     my $ex=shift;
 3055:     my $file_description = $fd{lc($ex)};
 3056:     $file_description =~ s:([\[\]]):~$1:g;
 3057:     return '.'.$ex.' '.&mt($file_description);
 3058: }
 3059: 
 3060: # End of .tab access
 3061: =pod
 3062: 
 3063: =back
 3064: 
 3065: =cut
 3066: 
 3067: # ------------------------------------------------------------------ File Types
 3068: sub fileextensions {
 3069:     return sort(keys(%fe));
 3070: }
 3071: 
 3072: # ----------------------------------------------------------- Display Languages
 3073: # returns a hash with all desired display languages
 3074: #
 3075: 
 3076: sub display_languages {
 3077:     my %languages=();
 3078:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3079: 	$languages{$lang}=1;
 3080:     }
 3081:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3082:     if ($env{'form.displaylanguage'}) {
 3083: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3084: 	    $languages{$lang}=1;
 3085:         }
 3086:     }
 3087:     return %languages;
 3088: }
 3089: 
 3090: sub languages {
 3091:     my ($possible_langs) = @_;
 3092:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3093:     if (!ref($possible_langs)) {
 3094: 	if( wantarray ) {
 3095: 	    return @preferred_langs;
 3096: 	} else {
 3097: 	    return $preferred_langs[0];
 3098: 	}
 3099:     }
 3100:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3101:     my @preferred_possibilities;
 3102:     foreach my $preferred_lang (@preferred_langs) {
 3103: 	if (exists($possibilities{$preferred_lang})) {
 3104: 	    push(@preferred_possibilities, $preferred_lang);
 3105: 	}
 3106:     }
 3107:     if( wantarray ) {
 3108: 	return @preferred_possibilities;
 3109:     }
 3110:     return $preferred_possibilities[0];
 3111: }
 3112: 
 3113: sub user_lang {
 3114:     my ($touname,$toudom,$fromcid) = @_;
 3115:     my @userlangs;
 3116:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3117:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3118:                     $env{'course.'.$fromcid.'.languages'}));
 3119:     } else {
 3120:         my %langhash = &getlangs($touname,$toudom);
 3121:         if ($langhash{'languages'} ne '') {
 3122:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3123:         } else {
 3124:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3125:             if ($domdefs{'lang_def'} ne '') {
 3126:                 @userlangs = ($domdefs{'lang_def'});
 3127:             }
 3128:         }
 3129:     }
 3130:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3131:     my $user_lh = Apache::localize->get_handle(@languages);
 3132:     return $user_lh;
 3133: }
 3134: 
 3135: 
 3136: ###############################################################
 3137: ##               Student Answer Attempts                     ##
 3138: ###############################################################
 3139: 
 3140: =pod
 3141: 
 3142: =head1 Alternate Problem Views
 3143: 
 3144: =over 4
 3145: 
 3146: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3147:     $getattempt, $regexp, $gradesub)
 3148: 
 3149: Return string with previous attempt on problem. Arguments:
 3150: 
 3151: =over 4
 3152: 
 3153: =item * $symb: Problem, including path
 3154: 
 3155: =item * $username: username of the desired student
 3156: 
 3157: =item * $domain: domain of the desired student
 3158: 
 3159: =item * $course: Course ID
 3160: 
 3161: =item * $getattempt: Leave blank for all attempts, otherwise put
 3162:     something
 3163: 
 3164: =item * $regexp: if string matches this regexp, the string will be
 3165:     sent to $gradesub
 3166: 
 3167: =item * $gradesub: routine that processes the string if it matches $regexp
 3168: 
 3169: =back
 3170: 
 3171: The output string is a table containing all desired attempts, if any.
 3172: 
 3173: =cut
 3174: 
 3175: sub get_previous_attempt {
 3176:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3177:   my $prevattempts='';
 3178:   no strict 'refs';
 3179:   if ($symb) {
 3180:     my (%returnhash)=
 3181:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3182:     if ($returnhash{'version'}) {
 3183:       my %lasthash=();
 3184:       my $version;
 3185:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3186:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3187: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3188:         }
 3189:       }
 3190:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3191:       $prevattempts.='<th>'.&mt('History').'</th>';
 3192:       foreach my $key (sort(keys(%lasthash))) {
 3193: 	my ($ign,@parts) = split(/\./,$key);
 3194: 	if ($#parts > 0) {
 3195: 	  my $data=$parts[-1];
 3196: 	  pop(@parts);
 3197: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3198: 	} else {
 3199: 	  if ($#parts == 0) {
 3200: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3201: 	  } else {
 3202: 	    $prevattempts.='<th>'.$ign.'</th>';
 3203: 	  }
 3204: 	}
 3205:       }
 3206:       $prevattempts.=&end_data_table_header_row();
 3207:       if ($getattempt eq '') {
 3208: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3209: 	  $prevattempts.=&start_data_table_row().
 3210: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3211: 	    foreach my $key (sort(keys(%lasthash))) {
 3212: 		my $value = &format_previous_attempt_value($key,
 3213: 							   $returnhash{$version.':'.$key});
 3214: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3215: 	    }
 3216: 	  $prevattempts.=&end_data_table_row();
 3217: 	 }
 3218:       }
 3219:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3220:       foreach my $key (sort(keys(%lasthash))) {
 3221: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3222: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3223: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3224:       }
 3225:       $prevattempts.= &end_data_table_row().&end_data_table();
 3226:     } else {
 3227:       $prevattempts=
 3228: 	  &start_data_table().&start_data_table_row().
 3229: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3230: 	  &end_data_table_row().&end_data_table();
 3231:     }
 3232:   } else {
 3233:     $prevattempts=
 3234: 	  &start_data_table().&start_data_table_row().
 3235: 	  '<td>'.&mt('No data.').'</td>'.
 3236: 	  &end_data_table_row().&end_data_table();
 3237:   }
 3238: }
 3239: 
 3240: sub format_previous_attempt_value {
 3241:     my ($key,$value) = @_;
 3242:     if ($key =~ /timestamp/) {
 3243: 	$value = &Apache::lonlocal::locallocaltime($value);
 3244:     } elsif (ref($value) eq 'ARRAY') {
 3245: 	$value = '('.join(', ', @{ $value }).')';
 3246:     } else {
 3247: 	$value = &unescape($value);
 3248:     }
 3249:     return $value;
 3250: }
 3251: 
 3252: 
 3253: sub relative_to_absolute {
 3254:     my ($url,$output)=@_;
 3255:     my $parser=HTML::TokeParser->new(\$output);
 3256:     my $token;
 3257:     my $thisdir=$url;
 3258:     my @rlinks=();
 3259:     while ($token=$parser->get_token) {
 3260: 	if ($token->[0] eq 'S') {
 3261: 	    if ($token->[1] eq 'a') {
 3262: 		if ($token->[2]->{'href'}) {
 3263: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3264: 		}
 3265: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3266: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3267: 	    } elsif ($token->[1] eq 'base') {
 3268: 		$thisdir=$token->[2]->{'href'};
 3269: 	    }
 3270: 	}
 3271:     }
 3272:     $thisdir=~s-/[^/]*$--;
 3273:     foreach my $link (@rlinks) {
 3274: 	unless (($link=~/^https?\:\/\//i) ||
 3275: 		($link=~/^\//) ||
 3276: 		($link=~/^javascript:/i) ||
 3277: 		($link=~/^mailto:/i) ||
 3278: 		($link=~/^\#/)) {
 3279: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3280: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3281: 	}
 3282:     }
 3283: # -------------------------------------------------- Deal with Applet codebases
 3284:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3285:     return $output;
 3286: }
 3287: 
 3288: =pod
 3289: 
 3290: =item * &get_student_view()
 3291: 
 3292: show a snapshot of what student was looking at
 3293: 
 3294: =cut
 3295: 
 3296: sub get_student_view {
 3297:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3298:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3299:   my (%form);
 3300:   my @elements=('symb','courseid','domain','username');
 3301:   foreach my $element (@elements) {
 3302:       $form{'grade_'.$element}=eval '$'.$element #'
 3303:   }
 3304:   if (defined($moreenv)) {
 3305:       %form=(%form,%{$moreenv});
 3306:   }
 3307:   if (defined($target)) { $form{'grade_target'} = $target; }
 3308:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3309:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3310:   $userview=~s/\<body[^\>]*\>//gi;
 3311:   $userview=~s/\<\/body\>//gi;
 3312:   $userview=~s/\<html\>//gi;
 3313:   $userview=~s/\<\/html\>//gi;
 3314:   $userview=~s/\<head\>//gi;
 3315:   $userview=~s/\<\/head\>//gi;
 3316:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3317:   $userview=&relative_to_absolute($feedurl,$userview);
 3318:   if (wantarray) {
 3319:      return ($userview,$response);
 3320:   } else {
 3321:      return $userview;
 3322:   }
 3323: }
 3324: 
 3325: sub get_student_view_with_retries {
 3326:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3327: 
 3328:     my $ok = 0;                 # True if we got a good response.
 3329:     my $content;
 3330:     my $response;
 3331: 
 3332:     # Try to get the student_view done. within the retries count:
 3333:     
 3334:     do {
 3335:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3336:          $ok      = $response->is_success;
 3337:          if (!$ok) {
 3338:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3339:          }
 3340:          $retries--;
 3341:     } while (!$ok && ($retries > 0));
 3342:     
 3343:     if (!$ok) {
 3344:        $content = '';          # On error return an empty content.
 3345:     }
 3346:     if (wantarray) {
 3347:        return ($content, $response);
 3348:     } else {
 3349:        return $content;
 3350:     }
 3351: }
 3352: 
 3353: =pod
 3354: 
 3355: =item * &get_student_answers() 
 3356: 
 3357: show a snapshot of how student was answering problem
 3358: 
 3359: =cut
 3360: 
 3361: sub get_student_answers {
 3362:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3363:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3364:   my (%moreenv);
 3365:   my @elements=('symb','courseid','domain','username');
 3366:   foreach my $element (@elements) {
 3367:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3368:   }
 3369:   $moreenv{'grade_target'}='answer';
 3370:   %moreenv=(%form,%moreenv);
 3371:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3372:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3373:   return $userview;
 3374: }
 3375: 
 3376: =pod
 3377: 
 3378: =item * &submlink()
 3379: 
 3380: Inputs: $text $uname $udom $symb $target
 3381: 
 3382: Returns: A link to grades.pm such as to see the SUBM view of a student
 3383: 
 3384: =cut
 3385: 
 3386: ###############################################
 3387: sub submlink {
 3388:     my ($text,$uname,$udom,$symb,$target)=@_;
 3389:     if (!($uname && $udom)) {
 3390: 	(my $cursymb, my $courseid,$udom,$uname)=
 3391: 	    &Apache::lonnet::whichuser($symb);
 3392: 	if (!$symb) { $symb=$cursymb; }
 3393:     }
 3394:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3395:     $symb=&escape($symb);
 3396:     if ($target) { $target="target=\"$target\""; }
 3397:     return '<a href="/adm/grades?&command=submission&'.
 3398: 	'symb='.$symb.'&student='.$uname.
 3399: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3400: }
 3401: ##############################################
 3402: 
 3403: =pod
 3404: 
 3405: =item * &pgrdlink()
 3406: 
 3407: Inputs: $text $uname $udom $symb $target
 3408: 
 3409: Returns: A link to grades.pm such as to see the PGRD view of a student
 3410: 
 3411: =cut
 3412: 
 3413: ###############################################
 3414: sub pgrdlink {
 3415:     my $link=&submlink(@_);
 3416:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3417:     return $link;
 3418: }
 3419: ##############################################
 3420: 
 3421: =pod
 3422: 
 3423: =item * &pprmlink()
 3424: 
 3425: Inputs: $text $uname $udom $symb $target
 3426: 
 3427: Returns: A link to parmset.pm such as to see the PPRM view of a
 3428: student and a specific resource
 3429: 
 3430: =cut
 3431: 
 3432: ###############################################
 3433: sub pprmlink {
 3434:     my ($text,$uname,$udom,$symb,$target)=@_;
 3435:     if (!($uname && $udom)) {
 3436: 	(my $cursymb, my $courseid,$udom,$uname)=
 3437: 	    &Apache::lonnet::whichuser($symb);
 3438: 	if (!$symb) { $symb=$cursymb; }
 3439:     }
 3440:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3441:     $symb=&escape($symb);
 3442:     if ($target) { $target="target=\"$target\""; }
 3443:     return '<a href="/adm/parmset?command=set&amp;'.
 3444: 	'symb='.$symb.'&amp;uname='.$uname.
 3445: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3446: }
 3447: ##############################################
 3448: 
 3449: =pod
 3450: 
 3451: =back
 3452: 
 3453: =cut
 3454: 
 3455: ###############################################
 3456: 
 3457: 
 3458: sub timehash {
 3459:     my ($thistime) = @_;
 3460:     my $timezone = &Apache::lonlocal::gettimezone();
 3461:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3462:                      ->set_time_zone($timezone);
 3463:     my $wday = $dt->day_of_week();
 3464:     if ($wday == 7) { $wday = 0; }
 3465:     return ( 'second' => $dt->second(),
 3466:              'minute' => $dt->minute(),
 3467:              'hour'   => $dt->hour(),
 3468:              'day'     => $dt->day_of_month(),
 3469:              'month'   => $dt->month(),
 3470:              'year'    => $dt->year(),
 3471:              'weekday' => $wday,
 3472:              'dayyear' => $dt->day_of_year(),
 3473:              'dlsav'   => $dt->is_dst() );
 3474: }
 3475: 
 3476: sub utc_string {
 3477:     my ($date)=@_;
 3478:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3479: }
 3480: 
 3481: sub maketime {
 3482:     my %th=@_;
 3483:     my ($epoch_time,$timezone,$dt);
 3484:     $timezone = &Apache::lonlocal::gettimezone();
 3485:     eval {
 3486:         $dt = DateTime->new( year   => $th{'year'},
 3487:                              month  => $th{'month'},
 3488:                              day    => $th{'day'},
 3489:                              hour   => $th{'hour'},
 3490:                              minute => $th{'minute'},
 3491:                              second => $th{'second'},
 3492:                              time_zone => $timezone,
 3493:                          );
 3494:     };
 3495:     if (!$@) {
 3496:         $epoch_time = $dt->epoch;
 3497:         if ($epoch_time) {
 3498:             return $epoch_time;
 3499:         }
 3500:     }
 3501:     return POSIX::mktime(
 3502:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3503:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3504: }
 3505: 
 3506: #########################################
 3507: 
 3508: sub findallcourses {
 3509:     my ($roles,$uname,$udom) = @_;
 3510:     my %roles;
 3511:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3512:     my %courses;
 3513:     my $now=time;
 3514:     if (!defined($uname)) {
 3515:         $uname = $env{'user.name'};
 3516:     }
 3517:     if (!defined($udom)) {
 3518:         $udom = $env{'user.domain'};
 3519:     }
 3520:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3521:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3522:         if (!%roles) {
 3523:             %roles = (
 3524:                        cc => 1,
 3525:                        in => 1,
 3526:                        ep => 1,
 3527:                        ta => 1,
 3528:                        cr => 1,
 3529:                        st => 1,
 3530:              );
 3531:         }
 3532:         foreach my $entry (keys(%roleshash)) {
 3533:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3534:             if ($trole =~ /^cr/) { 
 3535:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3536:             } else {
 3537:                 next if (!exists($roles{$trole}));
 3538:             }
 3539:             if ($tend) {
 3540:                 next if ($tend < $now);
 3541:             }
 3542:             if ($tstart) {
 3543:                 next if ($tstart > $now);
 3544:             }
 3545:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3546:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3547:             if ($secpart eq '') {
 3548:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3549:                 $sec = 'none';
 3550:                 $realsec = '';
 3551:             } else {
 3552:                 $cnum = $cnumpart;
 3553:                 ($sec,$role) = split(/_/,$secpart);
 3554:                 $realsec = $sec;
 3555:             }
 3556:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3557:         }
 3558:     } else {
 3559:         foreach my $key (keys(%env)) {
 3560: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3561:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3562: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3563: 	        next if ($role eq 'ca' || $role eq 'aa');
 3564: 	        next if (%roles && !exists($roles{$role}));
 3565: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3566:                 my $active=1;
 3567:                 if ($starttime) {
 3568: 		    if ($now<$starttime) { $active=0; }
 3569:                 }
 3570:                 if ($endtime) {
 3571:                     if ($now>$endtime) { $active=0; }
 3572:                 }
 3573:                 if ($active) {
 3574:                     if ($sec eq '') {
 3575:                         $sec = 'none';
 3576:                     }
 3577:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3578:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3579:                 }
 3580:             }
 3581:         }
 3582:     }
 3583:     return %courses;
 3584: }
 3585: 
 3586: ###############################################
 3587: 
 3588: sub blockcheck {
 3589:     my ($setters,$activity,$uname,$udom) = @_;
 3590: 
 3591:     if (!defined($udom)) {
 3592:         $udom = $env{'user.domain'};
 3593:     }
 3594:     if (!defined($uname)) {
 3595:         $uname = $env{'user.name'};
 3596:     }
 3597: 
 3598:     # If uname and udom are for a course, check for blocks in the course.
 3599: 
 3600:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3601:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3602:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3603:         return ($startblock,$endblock);
 3604:     }
 3605: 
 3606:     my $startblock = 0;
 3607:     my $endblock = 0;
 3608:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3609: 
 3610:     # If uname is for a user, and activity is course-specific, i.e.,
 3611:     # boards, chat or groups, check for blocking in current course only.
 3612: 
 3613:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3614:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3615:         foreach my $key (keys(%live_courses)) {
 3616:             if ($key ne $env{'request.course.id'}) {
 3617:                 delete($live_courses{$key});
 3618:             }
 3619:         }
 3620:     }
 3621: 
 3622:     my $otheruser = 0;
 3623:     my %own_courses;
 3624:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3625:         # Resource belongs to user other than current user.
 3626:         $otheruser = 1;
 3627:         # Gather courses for current user
 3628:         %own_courses = 
 3629:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3630:     }
 3631: 
 3632:     # Gather active course roles - course coordinator, instructor, 
 3633:     # exam proctor, ta, student, or custom role.
 3634: 
 3635:     foreach my $course (keys(%live_courses)) {
 3636:         my ($cdom,$cnum);
 3637:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3638:             $cdom = $env{'course.'.$course.'.domain'};
 3639:             $cnum = $env{'course.'.$course.'.num'};
 3640:         } else {
 3641:             ($cdom,$cnum) = split(/_/,$course); 
 3642:         }
 3643:         my $no_ownblock = 0;
 3644:         my $no_userblock = 0;
 3645:         if ($otheruser && $activity ne 'com') {
 3646:             # Check if current user has 'evb' priv for this
 3647:             if (defined($own_courses{$course})) {
 3648:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3649:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3650:                     if ($sec ne 'none') {
 3651:                         $checkrole .= '/'.$sec;
 3652:                     }
 3653:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3654:                         $no_ownblock = 1;
 3655:                         last;
 3656:                     }
 3657:                 }
 3658:             }
 3659:             # if they have 'evb' priv and are currently not playing student
 3660:             next if (($no_ownblock) &&
 3661:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3662:         }
 3663:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3664:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3665:             if ($sec ne 'none') {
 3666:                 $checkrole .= '/'.$sec;
 3667:             }
 3668:             if ($otheruser) {
 3669:                 # Resource belongs to user other than current user.
 3670:                 # Assemble privs for that user, and check for 'evb' priv.
 3671:                 my ($trole,$tdom,$tnum,$tsec);
 3672:                 my $entry = $live_courses{$course}{$sec};
 3673:                 if ($entry =~ /^cr/) {
 3674:                     ($trole,$tdom,$tnum,$tsec) = 
 3675:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3676:                 } else {
 3677:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3678:                 }
 3679:                 my ($spec,$area,$trest,%allroles,%userroles);
 3680:                 $area = '/'.$tdom.'/'.$tnum;
 3681:                 $trest = $tnum;
 3682:                 if ($tsec ne '') {
 3683:                     $area .= '/'.$tsec;
 3684:                     $trest .= '/'.$tsec;
 3685:                 }
 3686:                 $spec = $trole.'.'.$area;
 3687:                 if ($trole =~ /^cr/) {
 3688:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3689:                                                       $tdom,$spec,$trest,$area);
 3690:                 } else {
 3691:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3692:                                                        $tdom,$spec,$trest,$area);
 3693:                 }
 3694:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3695:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3696:                     if ($1) {
 3697:                         $no_userblock = 1;
 3698:                         last;
 3699:                     }
 3700:                 }
 3701:             } else {
 3702:                 # Resource belongs to current user
 3703:                 # Check for 'evb' priv via lonnet::allowed().
 3704:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3705:                     $no_ownblock = 1;
 3706:                     last;
 3707:                 }
 3708:             }
 3709:         }
 3710:         # if they have the evb priv and are currently not playing student
 3711:         next if (($no_ownblock) &&
 3712:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3713:         next if ($no_userblock);
 3714: 
 3715:         # Retrieve blocking times and identity of blocker for course
 3716:         # of specified user, unless user has 'evb' privilege.
 3717:         
 3718:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3719:         if (($start != 0) && 
 3720:             (($startblock == 0) || ($startblock > $start))) {
 3721:             $startblock = $start;
 3722:         }
 3723:         if (($end != 0)  &&
 3724:             (($endblock == 0) || ($endblock < $end))) {
 3725:             $endblock = $end;
 3726:         }
 3727:     }
 3728:     return ($startblock,$endblock);
 3729: }
 3730: 
 3731: sub get_blocks {
 3732:     my ($setters,$activity,$cdom,$cnum) = @_;
 3733:     my $startblock = 0;
 3734:     my $endblock = 0;
 3735:     my $course = $cdom.'_'.$cnum;
 3736:     $setters->{$course} = {};
 3737:     $setters->{$course}{'staff'} = [];
 3738:     $setters->{$course}{'times'} = [];
 3739:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3740:     foreach my $record (keys(%records)) {
 3741:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3742:         if ($start <= time && $end >= time) {
 3743:             my ($staff_name,$staff_dom,$title,$blocks) =
 3744:                 &parse_block_record($records{$record});
 3745:             if ($blocks->{$activity} eq 'on') {
 3746:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3747:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3748:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3749:                     $startblock = $start;
 3750:                 }
 3751:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3752:                     $endblock = $end;
 3753:                 }
 3754:             }
 3755:         }
 3756:     }
 3757:     return ($startblock,$endblock);
 3758: }
 3759: 
 3760: sub parse_block_record {
 3761:     my ($record) = @_;
 3762:     my ($setuname,$setudom,$title,$blocks);
 3763:     if (ref($record) eq 'HASH') {
 3764:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3765:         $title = &unescape($record->{'event'});
 3766:         $blocks = $record->{'blocks'};
 3767:     } else {
 3768:         my @data = split(/:/,$record,3);
 3769:         if (scalar(@data) eq 2) {
 3770:             $title = $data[1];
 3771:             ($setuname,$setudom) = split(/@/,$data[0]);
 3772:         } else {
 3773:             ($setuname,$setudom,$title) = @data;
 3774:         }
 3775:         $blocks = { 'com' => 'on' };
 3776:     }
 3777:     return ($setuname,$setudom,$title,$blocks);
 3778: }
 3779: 
 3780: sub build_block_table {
 3781:     my ($startblock,$endblock,$setters) = @_;
 3782:     my %lt = &Apache::lonlocal::texthash(
 3783:         'cacb' => 'Currently active communication blocks',
 3784:         'cour' => 'Course',
 3785:         'dura' => 'Duration',
 3786:         'blse' => 'Block set by'
 3787:     );
 3788:     my $output;
 3789:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3790:     $output .= &start_data_table();
 3791:     $output .= '
 3792: <tr>
 3793:  <th>'.$lt{'cour'}.'</th>
 3794:  <th>'.$lt{'dura'}.'</th>
 3795:  <th>'.$lt{'blse'}.'</th>
 3796: </tr>
 3797: ';
 3798:     foreach my $course (keys(%{$setters})) {
 3799:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3800:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3801:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3802:             my $fullname = &plainname($uname,$udom);
 3803:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3804:                 && $env{'user.name'} ne 'public' 
 3805:                 && $env{'user.domain'} ne 'public') {
 3806:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3807:             }
 3808:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3809:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3810:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3811:             $output .= &Apache::loncommon::start_data_table_row().
 3812:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3813:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3814:                        '<td>'.$fullname.'</td>'.
 3815:                         &Apache::loncommon::end_data_table_row();
 3816:         }
 3817:     }
 3818:     $output .= &end_data_table();
 3819: }
 3820: 
 3821: sub blocking_status {
 3822:     my ($activity,$uname,$udom) = @_;
 3823:     my %setters;
 3824:     my ($blocked,$output,$ownitem,$is_course);
 3825:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3826:     if ($startblock && $endblock) {
 3827:         $blocked = 1;
 3828:         if (wantarray) {
 3829:             my $category;
 3830:             if ($activity eq 'boards') {
 3831:                 $category = 'Discussion posts in this course';
 3832:             } elsif ($activity eq 'blogs') {
 3833:                 $category = 'Blogs';
 3834:             } elsif ($activity eq 'port') {
 3835:                 if (defined($uname) && defined($udom)) {
 3836:                     if ($uname eq $env{'user.name'} &&
 3837:                         $udom eq $env{'user.domain'}) {
 3838:                         $ownitem = 1;
 3839:                     }
 3840:                 }
 3841:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3842:                 if ($ownitem) { 
 3843:                     $category = 'Your portfolio files';  
 3844:                 } elsif ($is_course) {
 3845:                     my $coursedesc;
 3846:                     foreach my $course (keys(%setters)) {
 3847:                         my %courseinfo =
 3848:                              &Apache::lonnet::coursedescription($course);
 3849:                         $coursedesc = $courseinfo{'description'};
 3850:                     }
 3851:                     $category = "Group portfolio in the course '$coursedesc'";
 3852:                 } else {
 3853:                     $category = 'Portfolio files belonging to ';
 3854:                     if ($env{'user.name'} eq 'public' && 
 3855:                         $env{'user.domain'} eq 'public') {
 3856:                         $category .= &plainname($uname,$udom);
 3857:                     } else {
 3858:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3859:                     }
 3860:                 }
 3861:             } elsif ($activity eq 'groups') {
 3862:                 $category = 'Groups in this course';
 3863:             }
 3864:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3865:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3866:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3867:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3868:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3869:             }
 3870:         }
 3871:     }
 3872:     if (wantarray) {
 3873:         return ($blocked,$output);
 3874:     } else {
 3875:         return $blocked;
 3876:     }
 3877: }
 3878: 
 3879: ###############################################
 3880: 
 3881: sub check_ip_acc {
 3882:     my ($acc)=@_;
 3883:     &Apache::lonxml::debug("acc is $acc");
 3884:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3885:         return 1;
 3886:     }
 3887:     my $allowed=0;
 3888:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3889: 
 3890:     my $name;
 3891:     foreach my $pattern (split(',',$acc)) {
 3892:         $pattern =~ s/^\s*//;
 3893:         $pattern =~ s/\s*$//;
 3894:         if ($pattern =~ /\*$/) {
 3895:             #35.8.*
 3896:             $pattern=~s/\*//;
 3897:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3898:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3899:             #35.8.3.[34-56]
 3900:             my $low=$2;
 3901:             my $high=$3;
 3902:             $pattern=$1;
 3903:             if ($ip =~ /^\Q$pattern\E/) {
 3904:                 my $last=(split(/\./,$ip))[3];
 3905:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3906:             }
 3907:         } elsif ($pattern =~ /^\*/) {
 3908:             #*.msu.edu
 3909:             $pattern=~s/\*//;
 3910:             if (!defined($name)) {
 3911:                 use Socket;
 3912:                 my $netaddr=inet_aton($ip);
 3913:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3914:             }
 3915:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3916:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3917:             #127.0.0.1
 3918:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3919:         } else {
 3920:             #some.name.com
 3921:             if (!defined($name)) {
 3922:                 use Socket;
 3923:                 my $netaddr=inet_aton($ip);
 3924:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3925:             }
 3926:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3927:         }
 3928:         if ($allowed) { last; }
 3929:     }
 3930:     return $allowed;
 3931: }
 3932: 
 3933: ###############################################
 3934: 
 3935: =pod
 3936: 
 3937: =head1 Domain Template Functions
 3938: 
 3939: =over 4
 3940: 
 3941: =item * &determinedomain()
 3942: 
 3943: Inputs: $domain (usually will be undef)
 3944: 
 3945: Returns: Determines which domain should be used for designs
 3946: 
 3947: =cut
 3948: 
 3949: ###############################################
 3950: sub determinedomain {
 3951:     my $domain=shift;
 3952:     if (! $domain) {
 3953:         # Determine domain if we have not been given one
 3954:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3955:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3956:         if ($env{'request.role.domain'}) { 
 3957:             $domain=$env{'request.role.domain'}; 
 3958:         }
 3959:     }
 3960:     return $domain;
 3961: }
 3962: ###############################################
 3963: 
 3964: sub devalidate_domconfig_cache {
 3965:     my ($udom)=@_;
 3966:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3967: }
 3968: 
 3969: # ---------------------- Get domain configuration for a domain
 3970: sub get_domainconf {
 3971:     my ($udom) = @_;
 3972:     my $cachetime=1800;
 3973:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3974:     if (defined($cached)) { return %{$result}; }
 3975: 
 3976:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3977: 					     ['login','rolecolors'],$udom);
 3978:     my (%designhash,%legacy);
 3979:     if (keys(%domconfig) > 0) {
 3980:         if (ref($domconfig{'login'}) eq 'HASH') {
 3981:             if (keys(%{$domconfig{'login'}})) {
 3982:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3983:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3984:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3985:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3986:                                 $domconfig{'login'}{$key}{$img};
 3987:                         }
 3988:                     } else {
 3989:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3990:                     }
 3991:                 }
 3992:             } else {
 3993:                 $legacy{'login'} = 1;
 3994:             }
 3995:         } else {
 3996:             $legacy{'login'} = 1;
 3997:         }
 3998:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3999:             if (keys(%{$domconfig{'rolecolors'}})) {
 4000:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4001:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4002:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4003:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4004:                         }
 4005:                     }
 4006:                 }
 4007:             } else {
 4008:                 $legacy{'rolecolors'} = 1;
 4009:             }
 4010:         } else {
 4011:             $legacy{'rolecolors'} = 1;
 4012:         }
 4013:         if (keys(%legacy) > 0) {
 4014:             my %legacyhash = &get_legacy_domconf($udom);
 4015:             foreach my $item (keys(%legacyhash)) {
 4016:                 if ($item =~ /^\Q$udom\E\.login/) {
 4017:                     if ($legacy{'login'}) { 
 4018:                         $designhash{$item} = $legacyhash{$item};
 4019:                     }
 4020:                 } else {
 4021:                     if ($legacy{'rolecolors'}) {
 4022:                         $designhash{$item} = $legacyhash{$item};
 4023:                     }
 4024:                 }
 4025:             }
 4026:         }
 4027:     } else {
 4028:         %designhash = &get_legacy_domconf($udom); 
 4029:     }
 4030:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4031: 				  $cachetime);
 4032:     return %designhash;
 4033: }
 4034: 
 4035: sub get_legacy_domconf {
 4036:     my ($udom) = @_;
 4037:     my %legacyhash;
 4038:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4039:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4040:     if (-e $designfile) {
 4041:         if ( open (my $fh,"<$designfile") ) {
 4042:             while (my $line = <$fh>) {
 4043:                 next if ($line =~ /^\#/);
 4044:                 chomp($line);
 4045:                 my ($key,$val)=(split(/\=/,$line));
 4046:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4047:             }
 4048:             close($fh);
 4049:         }
 4050:     }
 4051:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4052:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4053:     }
 4054:     return %legacyhash;
 4055: }
 4056: 
 4057: =pod
 4058: 
 4059: =item * &domainlogo()
 4060: 
 4061: Inputs: $domain (usually will be undef)
 4062: 
 4063: Returns: A link to a domain logo, if the domain logo exists.
 4064: If the domain logo does not exist, a description of the domain.
 4065: 
 4066: =cut
 4067: 
 4068: ###############################################
 4069: sub domainlogo {
 4070:     my $domain = &determinedomain(shift);
 4071:     my %designhash = &get_domainconf($domain);    
 4072:     # See if there is a logo
 4073:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4074:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4075:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4076: 	    if ($imgsrc =~ m{^/res/}) {
 4077: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4078: 		&Apache::lonnet::repcopy($local_name);
 4079: 	    }
 4080: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4081:         } 
 4082:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4083:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4084:         return &Apache::lonnet::domain($domain,'description');
 4085:     } else {
 4086:         return '';
 4087:     }
 4088: }
 4089: ##############################################
 4090: 
 4091: =pod
 4092: 
 4093: =item * &designparm()
 4094: 
 4095: Inputs: $which parameter; $domain (usually will be undef)
 4096: 
 4097: Returns: value of designparamter $which
 4098: 
 4099: =cut
 4100: 
 4101: 
 4102: ##############################################
 4103: sub designparm {
 4104:     my ($which,$domain)=@_;
 4105:     if ($env{'browser.blackwhite'} eq 'on') {
 4106: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4107: 	    return '#000000';
 4108: 	}
 4109: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4110: 	    return '#FFFFFF';
 4111: 	}
 4112: 	if ($which=~/\.tabbg$/) {
 4113: 	    return '#CCCCCC';
 4114: 	}
 4115:     }
 4116:     if (exists($env{'environment.color.'.$which})) {
 4117: 	return $env{'environment.color.'.$which};
 4118:     }
 4119:     $domain=&determinedomain($domain);
 4120:     my %domdesign = &get_domainconf($domain);
 4121:     my $output;
 4122:     if ($domdesign{$domain.'.'.$which} ne '') {
 4123: 	$output = $domdesign{$domain.'.'.$which};
 4124:     } else {
 4125:         $output = $defaultdesign{$which};
 4126:     }
 4127:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4128:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4129:         if ($output =~ m{^/(adm|res)/}) {
 4130: 	    if ($output =~ m{^/res/}) {
 4131: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4132: 		&Apache::lonnet::repcopy($local_name);
 4133: 	    }
 4134:             $output = &lonhttpdurl($output);
 4135:         }
 4136:     }
 4137:     return $output;
 4138: }
 4139: 
 4140: ###############################################
 4141: ###############################################
 4142: 
 4143: =pod
 4144: 
 4145: =back
 4146: 
 4147: =head1 HTML Helpers
 4148: 
 4149: =over 4
 4150: 
 4151: =item * &bodytag()
 4152: 
 4153: Returns a uniform header for LON-CAPA web pages.
 4154: 
 4155: Inputs: 
 4156: 
 4157: =over 4
 4158: 
 4159: =item * $title, A title to be displayed on the page.
 4160: 
 4161: =item * $function, the current role (can be undef).
 4162: 
 4163: =item * $addentries, extra parameters for the <body> tag.
 4164: 
 4165: =item * $bodyonly, if defined, only return the <body> tag.
 4166: 
 4167: =item * $domain, if defined, force a given domain.
 4168: 
 4169: =item * $forcereg, if page should register as content page (relevant for 
 4170:             text interface only)
 4171: 
 4172: =item * $customtitle, alternate text to use instead of $title
 4173:                       in the title box that appears, this text
 4174:                       is not auto translated like the $title is
 4175: 
 4176: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4177:                    navigational links
 4178: 
 4179: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4180: 
 4181: =item * $notitle, if true keep the nav controls, but remove the title bar
 4182: 
 4183: =item * $no_inline_link, if true and in remote mode, don't show the 
 4184:          'Switch To Inline Menu' link
 4185: 
 4186: =item * $args, optional argument valid values are
 4187:             no_auto_mt_title -> prevents &mt()ing the title arg
 4188:             inherit_jsmath -> when creating popup window in a page,
 4189:                               should it have jsmath forced on by the
 4190:                               current page
 4191: 
 4192: =back
 4193: 
 4194: Returns: A uniform header for LON-CAPA web pages.  
 4195: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4196: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4197: other decorations will be returned.
 4198: 
 4199: =cut
 4200: 
 4201: sub bodytag {
 4202:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4203: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4204: 
 4205:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4206: 
 4207:     $function = &get_users_function() if (!$function);
 4208:     my $img =    &designparm($function.'.img',$domain);
 4209:     my $font =   &designparm($function.'.font',$domain);
 4210:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4211: 
 4212:     my %design = ( 'style'   => 'margin-top: 0px',
 4213: 		   'bgcolor' => $pgbg,
 4214: 		   'text'    => $font,
 4215:                    'alink'   => &designparm($function.'.alink',$domain),
 4216: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4217: 		   'link'    => &designparm($function.'.link',$domain),);
 4218:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4219: 
 4220:  # role and realm
 4221:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4222:     if ($role  eq 'ca') {
 4223:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4224:         $realm = &plainname($rname,$rdom);
 4225:     } 
 4226: # realm
 4227:     if ($env{'request.course.id'}) {
 4228:         if ($env{'request.role'} !~ /^cr/) {
 4229:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4230:         }
 4231: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4232:     } else {
 4233:         $role = &Apache::lonnet::plaintext($role);
 4234:     }
 4235: 
 4236:     if (!$realm) { $realm='&nbsp;'; }
 4237: # Set messages
 4238:     my $messages=&domainlogo($domain);
 4239: 
 4240:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4241: 
 4242: # construct main body tag
 4243:     my $bodytag = "<body $extra_body_attr>".
 4244: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4245: 
 4246:     if ($bodyonly) {
 4247:         return $bodytag;
 4248:     } elsif ($env{'browser.interface'} eq 'textual') {
 4249: # Accessibility
 4250:           
 4251: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4252: 	if (!$notitle) {
 4253: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4254: 	}
 4255: 	return $bodytag;
 4256:     }
 4257: 
 4258:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4259:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4260: 	undef($role);
 4261:     } else {
 4262: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4263:     }
 4264:     
 4265:     my $roleinfo=(<<ENDROLE);
 4266: <td class="LC_title_bar_who">
 4267: <div class="LC_title_bar_name">
 4268:     $name
 4269:     &nbsp;
 4270: </div>
 4271: <div class="LC_title_bar_role">
 4272: $role&nbsp;
 4273: </div>
 4274: <div class="LC_title_bar_realm">
 4275: $realm&nbsp;
 4276: </div>
 4277: </td>
 4278: ENDROLE
 4279: 
 4280:     my $titleinfo = '<h1>'.$title.'</h1>';
 4281:     if ($customtitle) {
 4282:         $titleinfo = $customtitle;
 4283:     }
 4284:     #
 4285:     # Extra info if you are the DC
 4286:     my $dc_info = '';
 4287:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4288:                         $env{'course.'.$env{'request.course.id'}.
 4289:                                  '.domain'}.'/'})) {
 4290:         my $cid = $env{'request.course.id'};
 4291:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4292:         $dc_info =~ s/\s+$//;
 4293:         $dc_info = '('.$dc_info.')';
 4294:     }
 4295: 
 4296:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4297:         # No Remote
 4298: 	if ($env{'request.state'} eq 'construct') {
 4299: 	    $forcereg=1;
 4300: 	}
 4301: 
 4302: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4303: 	    # this is for resources; directories have customtitle, and crumbs
 4304:             # and select recent are created in lonpubdir.pm  
 4305: 	    my ($uname,$thisdisfn)=
 4306: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4307: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4308: 	    $formaction=~s/\/+/\//g;
 4309: 
 4310: 	    my $parentpath = '';
 4311: 	    my $lastitem = '';
 4312: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4313: 		$parentpath = $1;
 4314: 		$lastitem = $2;
 4315: 	    } else {
 4316: 		$lastitem = $thisdisfn;
 4317: 	    }
 4318: 	    $titleinfo = 
 4319: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4320: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4321: 		.'<form name="dirs" method="post" action="'.$formaction
 4322: 		.'" target="_top"><tt><b>'
 4323: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4324: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4325: 		.'</form>'
 4326: 		.&Apache::lonmenu::constspaceform();
 4327:         }
 4328: 
 4329:         my $titletable;
 4330: 	if (!$notitle) {
 4331: 	    $titletable =
 4332: 		'<table id="LC_title_bar">'.
 4333:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4334: 			 '</tr></table>';
 4335: 	}
 4336: 	if ($notopbar) {
 4337: 	    $bodytag .= $titletable;
 4338: 	} else {
 4339: 	    if ($env{'request.state'} eq 'construct') {
 4340:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4341: 							  $titletable);
 4342:             } else {
 4343:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4344: 		    $titletable;
 4345:             }
 4346:         }
 4347:         return $bodytag;
 4348:     }
 4349: 
 4350: #
 4351: # Top frame rendering, Remote is up
 4352: #
 4353: 
 4354:     my $imgsrc = $img;
 4355:     if ($img =~ /^\/adm/) {
 4356:         $imgsrc = &lonhttpdurl($img);
 4357:     }
 4358:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4359: 
 4360:     # Explicit link to get inline menu
 4361:     my $menu= ($no_inline_link?''
 4362: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4363:     #
 4364:     if ($notitle) {
 4365: 	return $bodytag;
 4366:     }
 4367:     return(<<ENDBODY);
 4368: $bodytag
 4369: <table id="LC_title_bar" class="LC_with_remote">
 4370: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4371:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4372: </tr>
 4373: <tr><td>$titleinfo $dc_info $menu</td>
 4374: $roleinfo
 4375: </tr>
 4376: </table>
 4377: ENDBODY
 4378: }
 4379: 
 4380: sub make_attr_string {
 4381:     my ($register,$attr_ref) = @_;
 4382: 
 4383:     if ($attr_ref && !ref($attr_ref)) {
 4384: 	die("addentries Must be a hash ref ".
 4385: 	    join(':',caller(1))." ".
 4386: 	    join(':',caller(0))." ");
 4387:     }
 4388: 
 4389:     if ($register) {
 4390: 	my ($on_load,$on_unload);
 4391: 	foreach my $key (keys(%{$attr_ref})) {
 4392: 	    if      (lc($key) eq 'onload') {
 4393: 		$on_load.=$attr_ref->{$key}.';';
 4394: 		delete($attr_ref->{$key});
 4395: 
 4396: 	    } elsif (lc($key) eq 'onunload') {
 4397: 		$on_unload.=$attr_ref->{$key}.';';
 4398: 		delete($attr_ref->{$key});
 4399: 	    }
 4400: 	}
 4401: 	$attr_ref->{'onload'}  =
 4402: 	    &Apache::lonmenu::loadevents().  $on_load;
 4403: 	$attr_ref->{'onunload'}=
 4404: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4405:     }
 4406: 
 4407: # Accessibility font enhance
 4408:     if ($env{'browser.fontenhance'} eq 'on') {
 4409: 	my $style;
 4410: 	foreach my $key (keys(%{$attr_ref})) {
 4411: 	    if (lc($key) eq 'style') {
 4412: 		$style.=$attr_ref->{$key}.';';
 4413: 		delete($attr_ref->{$key});
 4414: 	    }
 4415: 	}
 4416: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4417:     }
 4418: 
 4419:     if ($env{'browser.blackwhite'} eq 'on') {
 4420: 	delete($attr_ref->{'font'});
 4421: 	delete($attr_ref->{'link'});
 4422: 	delete($attr_ref->{'alink'});
 4423: 	delete($attr_ref->{'vlink'});
 4424: 	delete($attr_ref->{'bgcolor'});
 4425: 	delete($attr_ref->{'background'});
 4426:     }
 4427: 
 4428:     my $attr_string;
 4429:     foreach my $attr (keys(%$attr_ref)) {
 4430: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4431:     }
 4432:     return $attr_string;
 4433: }
 4434: 
 4435: 
 4436: ###############################################
 4437: ###############################################
 4438: 
 4439: =pod
 4440: 
 4441: =item * &endbodytag()
 4442: 
 4443: Returns a uniform footer for LON-CAPA web pages.
 4444: 
 4445: Inputs: 1 - optional reference to an args hash
 4446: If in the hash, key for noredirectlink has a value which evaluates to true,
 4447: a 'Continue' link is not displayed if the page contains an
 4448: internal redirect in the <head></head> section,
 4449: i.e., $env{'internal.head.redirect'} exists   
 4450: 
 4451: =cut
 4452: 
 4453: sub endbodytag {
 4454:     my ($args) = @_;
 4455:     my $endbodytag='</body>';
 4456:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4457:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4458:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4459: 	    $endbodytag=
 4460: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4461: 	        &mt('Continue').'</a>'.
 4462: 	        $endbodytag;
 4463:         }
 4464:     }
 4465:     return $endbodytag;
 4466: }
 4467: 
 4468: =pod
 4469: 
 4470: =item * &standard_css()
 4471: 
 4472: Returns a style sheet
 4473: 
 4474: Inputs: (all optional)
 4475:             domain         -> force to color decorate a page for a specific
 4476:                                domain
 4477:             function       -> force usage of a specific rolish color scheme
 4478:             bgcolor        -> override the default page bgcolor
 4479: 
 4480: =cut
 4481: 
 4482: sub standard_css {
 4483:     my ($function,$domain,$bgcolor) = @_;
 4484:     $function  = &get_users_function() if (!$function);
 4485:     my $img    = &designparm($function.'.img',   $domain);
 4486:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4487:     my $font   = &designparm($function.'.font',  $domain);
 4488:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4489:     my $pgbg_or_bgcolor =
 4490: 	         $bgcolor ||
 4491: 	         &designparm($function.'.pgbg',  $domain);
 4492:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4493:     my $alink  = &designparm($function.'.alink', $domain);
 4494:     my $vlink  = &designparm($function.'.vlink', $domain);
 4495:     my $link   = &designparm($function.'.link',  $domain);
 4496: 
 4497:     my $loginbg = &designparm('login.sidebg',$domain);
 4498:     my $bgcol = &designparm('login.bgcol',$domain);
 4499:     my $textcol = &designparm('login.textcol',$domain);
 4500: 
 4501:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4502:     my $mono                 = 'monospace';
 4503:     my $data_table_head      = $tabbg;
 4504:     my $data_table_light     = '#EEEEEE';
 4505:     my $data_table_dark      = '#DDDDDD';
 4506:     my $data_table_darker    = '#CCCCCC';
 4507:     my $data_table_highlight = '#FFFF00';
 4508:     my $mail_new             = '#FFBB77';
 4509:     my $mail_new_hover       = '#DD9955';
 4510:     my $mail_read            = '#BBBB77';
 4511:     my $mail_read_hover      = '#999944';
 4512:     my $mail_replied         = '#AAAA88';
 4513:     my $mail_replied_hover   = '#888855';
 4514:     my $mail_other           = '#99BBBB';
 4515:     my $mail_other_hover     = '#669999';
 4516:     my $table_header         = '#DDDDDD';
 4517:     my $feedback_link_bg     = '#BBBBBB';
 4518:     my $lg_border_color	     = '#C8C8C8';
 4519: 
 4520:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4521: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4522: 	                                                 : '0px 3px 0px 4px';
 4523: 
 4524: 
 4525:     return <<END;
 4526: body{
 4527:      font-family: $sans;
 4528:      line-height:130%;
 4529:      font-size:0.83em;
 4530:      color:$font;
 4531:   }
 4532: a:link, a:visited { font-size:100%; }
 4533: 
 4534: a:focus { color: red; background: yellow }
 4535: table.thinborder,
 4536: table.thinborder tr th {
 4537:   border-style: solid;
 4538:   border-width: 1px;
 4539:   border-color: $lg_border_color;
 4540:   background: $tabbg;
 4541: }
 4542: table.thinborder tr td {
 4543:   border-style: solid;
 4544:   border-width: 1px;
 4545:   border-color: $lg_border_color;
 4546: }
 4547: 
 4548: form, .inline { display: inline; }
 4549: 
 4550: .LC_right {text-align:right;}
 4551: .LC_middle {vertical-align:middle;}
 4552: 
 4553: /* just for tests */
 4554: .LC_400Box {width:400px; }
 4555: /* end */
 4556: 
 4557: .LC_filename {
 4558:   font-family: $mono;
 4559:   white-space:pre;
 4560: }
 4561: 
 4562: .LC_fileicon {
 4563:   border: none;
 4564:   height: 1.3em;
 4565:   vertical-align: text-bottom;
 4566:   margin-right: 0.3em;
 4567:   text-decoration:none;
 4568: }
 4569: 
 4570: .LC_error {
 4571:   color: red;
 4572:   font-size: larger;
 4573: }
 4574: .LC_warning,
 4575: .LC_diff_removed {
 4576:   color: red;
 4577: }
 4578: 
 4579: .LC_info,
 4580: .LC_success,
 4581: .LC_diff_added {
 4582:   color: green;
 4583: }
 4584: .LC_unknown {
 4585:   color: yellow;
 4586: }
 4587: 
 4588: .LC_icon {
 4589:   border: none;
 4590: }
 4591: 
 4592: .LC_indexer_icon {
 4593:   border: 0px;
 4594:   height: 22px;
 4595: }
 4596: .LC_docs_spacer {
 4597:   width: 25px;
 4598:   height: 1px;
 4599:   border: none;
 4600: }
 4601: 
 4602: .LC_internal_info {
 4603:   color: #999999;
 4604: }
 4605: 
 4606: table.LC_pastsubmission {
 4607:   border: 1px solid black;
 4608:   margin: 2px;
 4609: }
 4610: 
 4611: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4612:   width: 100%;
 4613:   background: $pgbg;
 4614:   border: 2px;
 4615:   border-collapse: separate;
 4616:   padding: 0px;
 4617: }
 4618: 
 4619: table#LC_title_bar, table.LC_breadcrumbs,
 4620: table#LC_title_bar.LC_with_remote {
 4621:   width: 100%;
 4622:   border-color: $pgbg;
 4623:   border-style: solid;
 4624:   border-width: $border;
 4625: 
 4626:   background: $pgbg;
 4627:   font-family: $sans;
 4628:   border-collapse: collapse;
 4629:   padding: 0px;
 4630: }
 4631: table.LC_docs_path {
 4632:   width: 100%;
 4633:   border: 0;
 4634:   background: $pgbg;
 4635:   font-family: $sans;
 4636:   border-collapse: collapse;
 4637:   padding: 0px;
 4638: }
 4639: 
 4640: table#LC_title_bar td {
 4641:   background: $tabbg;
 4642: }
 4643: table#LC_title_bar .LC_title_bar_who {
 4644:   background: $tabbg;
 4645:   color: $font;
 4646:   font: small $sans;
 4647:   text-align: right;
 4648:   margin: 0px;
 4649: }
 4650: table#LC_title_bar .LC_title_bar_name {
 4651:   margin: 0px;
 4652: }
 4653: table#LC_title_bar .LC_title_bar_role {
 4654:   margin: 0px;
 4655: }
 4656: table#LC_title_bar .LC_title_bar_realm {
 4657:   margin: 0px;
 4658: }
 4659: span.LC_metadata {
 4660:     font-family: $sans;
 4661: }
 4662: table#LC_title_bar td.LC_title_bar_domain_logo {
 4663:   background: $sidebg;
 4664:   text-align: right;
 4665:   padding: 0px;
 4666: }
 4667: table#LC_title_bar td.LC_title_bar_role_logo {
 4668:   background: $sidebg;
 4669:   padding: 0px;
 4670: }
 4671: 
 4672: table#LC_menubuttons img{
 4673:   border: 0px;
 4674: }
 4675: table#LC_top_nav td {
 4676:   background: $tabbg;
 4677:   border: 0px;
 4678:   font-size: small;
 4679:   vertical-align:top;
 4680:   padding:2px 5px 2px 5px;
 4681: }
 4682: table#LC_top_nav td a, div#LC_top_nav a {
 4683:   color: $font;
 4684:   font-family: $sans;
 4685: }
 4686: table#LC_top_nav td.LC_top_nav_logo {
 4687:   background: $tabbg;
 4688:   text-align: left;
 4689:   white-space: nowrap;
 4690:   width: 31px;
 4691: }
 4692: table#LC_top_nav td.LC_top_nav_logo img {
 4693:   border: 0px;
 4694:   vertical-align: bottom;
 4695: }
 4696: table#LC_top_nav td.LC_top_nav_exit,
 4697: table#LC_top_nav td.LC_top_nav_help {
 4698:   width: 2.0em;
 4699: }
 4700: table#LC_top_nav td.LC_top_nav_login {
 4701:   width: 4.0em;
 4702:   text-align: center;
 4703: }
 4704: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4705:   background: $tabbg;
 4706:   color: $font;
 4707:   font-family: $sans;
 4708:   font-size: smaller;
 4709: }
 4710: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4711: table.LC_docs_path td.LC_docs_path_component {
 4712:   background: $tabbg;
 4713:   color: $font;
 4714:   font-family: $sans;
 4715:   font-size: larger;
 4716:   text-align: right;
 4717: }
 4718: td.LC_table_cell_checkbox {
 4719:   text-align: center;
 4720: }
 4721: table#LC_mainmenu td.LC_mainmenu_column {
 4722:     vertical-align: top;
 4723: }
 4724: 
 4725: .LC_fontsize_small
 4726: {
 4727:  font-size: 70%;
 4728: }
 4729: 
 4730: .LC_fontsize_medium
 4731: {
 4732:  font-size: 85%;
 4733: }
 4734: 
 4735: .LC_fontsize_large
 4736: {
 4737:  font-size: 120%;
 4738: }
 4739: 
 4740: .LC_menubuttons_inline_text {
 4741:   color: $font;
 4742:   font-family: $sans;
 4743:   font-size: 90%;
 4744:   padding-left:3px;
 4745: }
 4746: 
 4747: .LC_menubuttons_link {
 4748:   text-decoration: none;
 4749: }
 4750: /*2008--9-5: new menu style sheet.Changed category*/
 4751: .LC_menubuttons_category {
 4752:   color: $font;
 4753:   background: $pgbg;
 4754:   font-family: $sans;
 4755:   font-size: larger;
 4756:   font-weight: bold;
 4757: }
 4758: 
 4759: td.LC_menubuttons_text {
 4760:  	color: $font;
 4761: }
 4762: 
 4763: 
 4764: 
 4765: .LC_current_location {
 4766:   font-family: $sans;
 4767:   background: $tabbg;
 4768: }
 4769: .LC_new_mail {
 4770:   font-family: $sans;
 4771:   background: $tabbg;
 4772:   font-weight: bold;
 4773: }
 4774: 
 4775: 
 4776: .LC_dropadd_labeltext {
 4777:   font-family: $sans;
 4778:   text-align: right;
 4779: }
 4780: 
 4781: .LC_preferences_labeltext {
 4782:   font-family: $sans;
 4783:   text-align: right;
 4784: }
 4785: 
 4786: .LC_roleslog_note {
 4787:   font-size: small;
 4788: }
 4789: 
 4790: .LC_mail_functions {
 4791:     font-weight: bold;
 4792: }
 4793: 
 4794: table.LC_aboutme_port {
 4795:   border: 0px;
 4796:   border-collapse: collapse;
 4797:   border-spacing: 0px;
 4798: }
 4799: table.LC_data_table, table.LC_mail_list {
 4800:   border: 1px solid #000000;
 4801:   border-collapse: separate;
 4802:   border-spacing: 1px;
 4803:   background: $pgbg;
 4804: }
 4805: .LC_data_table_dense {
 4806:   font-size: small;
 4807: }
 4808: table.LC_nested_outer {
 4809:   border: 1px solid #000000;
 4810:   border-collapse: collapse;
 4811:   border-spacing: 0px;
 4812:   width: 100%;
 4813: }
 4814: table.LC_nested {
 4815:   border: 0px;
 4816:   border-collapse: collapse;
 4817:   border-spacing: 0px;
 4818:   width: 100%;
 4819: }
 4820: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4821: table.LC_prior_tries tr th {
 4822:   font-weight: bold;
 4823:   background-color: $data_table_head;
 4824:   font-size:90%;
 4825: }
 4826: table.LC_data_table tr.LC_info_row > td {
 4827:   background-color: #CCCCCC;
 4828:   font-weight: bold;
 4829:   text-align: left;
 4830: }
 4831: table.LC_data_table tr.LC_odd_row > td,
 4832: table.LC_pick_box tr > td.LC_odd_row,
 4833: table.LC_aboutme_port tr td {
 4834:   background-color: $data_table_light;
 4835:   padding: 2px;
 4836: }
 4837: table.LC_data_table tr.LC_even_row > td,
 4838: table.LC_pick_box tr > td.LC_even_row,
 4839: table.LC_aboutme_port tr.LC_even_row td {
 4840:   background-color: $data_table_dark;
 4841:   padding: 2px;
 4842: }
 4843: table.LC_data_table tr.LC_data_table_highlight td {
 4844:   background-color: $data_table_darker;
 4845: }
 4846: table.LC_data_table tr td.LC_leftcol_header {
 4847:   background-color: $data_table_head;
 4848:   font-weight: bold;
 4849: }
 4850: table.LC_data_table tr.LC_empty_row td,
 4851: table.LC_nested tr.LC_empty_row td {
 4852:   background-color: #FFFFFF;
 4853:   font-weight: bold;
 4854:   font-style: italic;
 4855:   text-align: center;
 4856:   padding: 8px;
 4857: }
 4858: table.LC_nested tr.LC_empty_row td {
 4859:   padding: 4ex
 4860: }
 4861: table.LC_nested_outer tr th {
 4862:   font-weight: bold;
 4863:   background-color: $data_table_head;
 4864:   font-size: small;
 4865:   border-bottom: 1px solid #000000;
 4866: }
 4867: table.LC_nested_outer tr td.LC_subheader {
 4868:   background-color: $data_table_head;
 4869:   font-weight: bold;
 4870:   font-size: small;
 4871:   border-bottom: 1px solid #000000;
 4872:   text-align: right;
 4873: }
 4874: table.LC_nested tr.LC_info_row td {
 4875:   background-color: #CCCCCC;
 4876:   font-weight: bold;
 4877:   font-size: small;
 4878:   text-align: center;
 4879: }
 4880: table.LC_nested tr.LC_info_row td.LC_left_item,
 4881: table.LC_nested_outer tr th.LC_left_item {
 4882:   text-align: left;
 4883: }
 4884: table.LC_nested td {
 4885:   background-color: #FFFFFF;
 4886:   font-size: small;
 4887: }
 4888: table.LC_nested_outer tr th.LC_right_item,
 4889: table.LC_nested tr.LC_info_row td.LC_right_item,
 4890: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4891: table.LC_nested tr td.LC_right_item {
 4892:   text-align: right;
 4893: }
 4894: 
 4895: table.LC_nested tr.LC_odd_row td {
 4896:   background-color: #EEEEEE;
 4897: }
 4898: 
 4899: table.LC_createuser {
 4900: }
 4901: 
 4902: table.LC_createuser tr.LC_section_row td {
 4903:   font-size: small;
 4904: }
 4905: 
 4906: table.LC_createuser tr.LC_info_row td  {
 4907:   background-color: #CCCCCC;
 4908:   font-weight: bold;
 4909:   text-align: center;
 4910: }
 4911: 
 4912: table.LC_calendar {
 4913:   border: 1px solid #000000;
 4914:   border-collapse: collapse;
 4915: }
 4916: table.LC_calendar_pickdate {
 4917:   font-size: xx-small;
 4918: }
 4919: table.LC_calendar tr td {
 4920:   border: 1px solid #000000;
 4921:   vertical-align: top;
 4922: }
 4923: table.LC_calendar tr td.LC_calendar_day_empty {
 4924:   background-color: $data_table_dark;
 4925: }
 4926: table.LC_calendar tr td.LC_calendar_day_current {
 4927:   background-color: $data_table_highlight;
 4928: }
 4929: table.LC_mail_list tr.LC_mail_new {
 4930:   background-color: $mail_new;
 4931: }
 4932: table.LC_mail_list tr.LC_mail_new:hover {
 4933:   background-color: $mail_new_hover;
 4934: }
 4935: table.LC_mail_list tr.LC_mail_even{
 4936: }
 4937: table.LC_mail_list tr.LC_mail_odd{
 4938: }
 4939: table.LC_mail_list tr.LC_mail_read {
 4940:   background-color: $mail_read;
 4941: }
 4942: table.LC_mail_list tr.LC_mail_read:hover {
 4943:   background-color: $mail_read_hover;
 4944: }
 4945: table.LC_mail_list tr.LC_mail_replied {
 4946:   background-color: $mail_replied;
 4947: }
 4948: table.LC_mail_list tr.LC_mail_replied:hover {
 4949:   background-color: $mail_replied_hover;
 4950: }
 4951: table.LC_mail_list tr.LC_mail_other {
 4952:   background-color: $mail_other;
 4953: }
 4954: table.LC_mail_list tr.LC_mail_other:hover {
 4955:   background-color: $mail_other_hover;
 4956: }
 4957: 
 4958: table.LC_data_table tr > td.LC_browser_file,
 4959: table.LC_data_table tr > td.LC_browser_file_published {
 4960:   background: #CCFF88;
 4961: }
 4962: table.LC_data_table tr > td.LC_browser_file_locked,
 4963: table.LC_data_table tr > td.LC_browser_file_unpublished {
 4964:   background: #FFAA99;
 4965: }
 4966: table.LC_data_table tr > td.LC_browser_file_obsolete {
 4967:   background: #AAAAAA;
 4968: }
 4969: table.LC_data_table tr > td.LC_browser_file_modified,
 4970: table.LC_data_table tr > td.LC_browser_file_metamodified {
 4971:   background: #FFFF77;
 4972: }
 4973: table.LC_data_table tr.LC_browser_folder > td {
 4974:   background: #CCCCFF;
 4975: }
 4976: 
 4977: table.LC_data_table tr > td.LC_roles_is {
 4978: /*  background: #77FF77; */
 4979: }
 4980: table.LC_data_table tr > td.LC_roles_future {
 4981:   background: #FFFF77;
 4982: }
 4983: table.LC_data_table tr > td.LC_roles_will {
 4984:   background: #FFAA77;
 4985: }
 4986: table.LC_data_table tr > td.LC_roles_expired {
 4987:   background: #FF7777;
 4988: }
 4989: table.LC_data_table tr > td.LC_roles_will_not {
 4990:   background: #AAFF77;
 4991: }
 4992: table.LC_data_table tr > td.LC_roles_selected {
 4993:   background: #11CC55;
 4994: }
 4995: 
 4996: span.LC_current_location {
 4997:   font-size:larger;
 4998:   background: $pgbg;
 4999: }
 5000: 
 5001: span.LC_parm_menu_item {
 5002:   font-size: larger;
 5003:   font-family: $sans;
 5004: }
 5005: span.LC_parm_scope_all {
 5006:   color: red;
 5007: }
 5008: span.LC_parm_scope_folder {
 5009:   color: green;
 5010: }
 5011: span.LC_parm_scope_resource {
 5012:   color: orange;
 5013: }
 5014: span.LC_parm_part {
 5015:   color: blue;
 5016: }
 5017: span.LC_parm_folder, span.LC_parm_symb {
 5018:   font-size: x-small;
 5019:   font-family: $mono;
 5020:   color: #AAAAAA;
 5021: }
 5022: 
 5023: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 5024: td.LC_parm_overview_parm_selectors,td.LC_parm_overview_restrictions  {
 5025:   border: 1px solid black;
 5026:   border-collapse: collapse;
 5027: }
 5028: table.LC_parm_overview_restrictions td {
 5029:   border-width: 1px 4px 1px 4px;
 5030:   border-style: solid;
 5031:   border-color: $pgbg;
 5032:   text-align: center;
 5033: }
 5034: table.LC_parm_overview_restrictions th {
 5035:   background: $tabbg;
 5036:   border-width: 1px 4px 1px 4px;
 5037:   border-style: solid;
 5038:   border-color: $pgbg;
 5039: }
 5040: table#LC_helpmenu {
 5041:   border: 0px;
 5042:   height: 55px;
 5043:   border-spacing: 0px;
 5044: }
 5045: 
 5046: table#LC_helpmenu fieldset legend {
 5047:   font-size: larger;
 5048:   font-weight: bold;
 5049: }
 5050: table#LC_helpmenu_links {
 5051:   width: 100%;
 5052:   border: 1px solid black;
 5053:   background: $pgbg;
 5054:   padding: 0px;
 5055:   border-spacing: 1px;
 5056: }
 5057: table#LC_helpmenu_links tr td {
 5058:   padding: 1px;
 5059:   background: $tabbg;
 5060:   text-align: center;
 5061:   font-weight: bold;
 5062: }
 5063: 
 5064: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5065: table#LC_helpmenu_links a:active {
 5066:   text-decoration: none;
 5067:   color: $font;
 5068: }
 5069: table#LC_helpmenu_links a:hover {
 5070:   text-decoration: underline;
 5071:   color: $vlink;
 5072: }
 5073: 
 5074: .LC_chrt_popup_exists {
 5075:   border: 1px solid #339933;
 5076:   margin: -1px;
 5077: }
 5078: .LC_chrt_popup_up {
 5079:   border: 1px solid yellow;
 5080:   margin: -1px;
 5081: }
 5082: .LC_chrt_popup {
 5083:   border: 1px solid #8888FF;
 5084:   background: #CCCCFF;
 5085: }
 5086: table.LC_pick_box {
 5087:   border-collapse: separate;
 5088:   background: white;
 5089:   border: 1px solid black;
 5090:   border-spacing: 1px;
 5091: }
 5092: table.LC_pick_box td.LC_pick_box_title {
 5093:   background: $tabbg;
 5094:   font-weight: bold;
 5095:   text-align: right;
 5096:   vertical-align: top;
 5097:   width: 184px;
 5098:   padding: 8px;
 5099: }
 5100: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5101:   background: $tabbg;
 5102:   font-weight: bold;
 5103:   text-align: right;
 5104:   width: 350px;
 5105:   padding: 8px;
 5106: }
 5107: 
 5108: table.LC_pick_box td.LC_pick_box_value {
 5109:   text-align: left;
 5110:   padding: 8px;
 5111: }
 5112: table.LC_pick_box td.LC_pick_box_select {
 5113:   text-align: left;
 5114:   padding: 8px;
 5115: }
 5116: table.LC_pick_box td.LC_pick_box_separator {
 5117:   padding: 0px;
 5118:   height: 1px;
 5119:   background: black;
 5120: }
 5121: table.LC_pick_box td.LC_pick_box_submit {
 5122:   text-align: right;
 5123: }
 5124: table.LC_pick_box td.LC_evenrow_value {
 5125:   text-align: left;
 5126:   padding: 8px;
 5127:   background-color: $data_table_light;
 5128: }
 5129: table.LC_pick_box td.LC_oddrow_value {
 5130:   text-align: left;
 5131:   padding: 8px;
 5132:   background-color: $data_table_light;
 5133: }
 5134: table.LC_helpform_receipt {
 5135:   width: 620px;
 5136:   border-collapse: separate;
 5137:   background: white;
 5138:   border: 1px solid black;
 5139:   border-spacing: 1px;
 5140: }
 5141: table.LC_helpform_receipt td.LC_pick_box_title {
 5142:   background: $tabbg;
 5143:   font-weight: bold;
 5144:   text-align: right;
 5145:   width: 184px;
 5146:   padding: 8px;
 5147: }
 5148: table.LC_helpform_receipt td.LC_evenrow_value {
 5149:   text-align: left;
 5150:   padding: 8px;
 5151:   background-color: $data_table_light;
 5152: }
 5153: table.LC_helpform_receipt td.LC_oddrow_value {
 5154:   text-align: left;
 5155:   padding: 8px;
 5156:   background-color: $data_table_light;
 5157: }
 5158: table.LC_helpform_receipt td.LC_pick_box_separator {
 5159:   padding: 0px;
 5160:   height: 1px;
 5161:   background: black;
 5162: }
 5163: span.LC_helpform_receipt_cat {
 5164:   font-weight: bold;
 5165: }
 5166: table.LC_group_priv_box {
 5167:   background: white;
 5168:   border: 1px solid black;
 5169:   border-spacing: 1px;
 5170: }
 5171: table.LC_group_priv_box td.LC_pick_box_title {
 5172:   background: $tabbg;
 5173:   font-weight: bold;
 5174:   text-align: right;
 5175:   width: 184px;
 5176: }
 5177: table.LC_group_priv_box td.LC_groups_fixed {
 5178:   background: $data_table_light;
 5179:   text-align: center;
 5180: }
 5181: table.LC_group_priv_box td.LC_groups_optional {
 5182:   background: $data_table_dark;
 5183:   text-align: center;
 5184: }
 5185: table.LC_group_priv_box td.LC_groups_functionality {
 5186:   background: $data_table_darker;
 5187:   text-align: center;
 5188:   font-weight: bold;
 5189: }
 5190: table.LC_group_priv td {
 5191:   text-align: left;
 5192:   padding: 0px;
 5193: }
 5194: 
 5195: table.LC_notify_front_page {
 5196:   background: white;
 5197:   border: 1px solid black;
 5198:   padding: 8px;
 5199: }
 5200: table.LC_notify_front_page td {
 5201:   padding: 8px;
 5202: }
 5203: .LC_navbuttons {
 5204:   margin: 2ex 0ex 2ex 0ex;
 5205: }
 5206: .LC_topic_bar {
 5207:   font-family: $sans;
 5208:   font-weight: bold;
 5209:   width: 100%;
 5210:   background: $tabbg;
 5211:   vertical-align: middle;
 5212:   margin: 2ex 0ex 2ex 0ex;
 5213: }
 5214: .LC_topic_bar span {
 5215:   vertical-align: middle;
 5216: }
 5217: .LC_topic_bar img {
 5218:   vertical-align: bottom;
 5219: }
 5220: table.LC_course_group_status {
 5221:   margin: 20px;
 5222: }
 5223: table.LC_status_selector td {
 5224:   vertical-align: top;
 5225:   text-align: center;
 5226:   padding: 4px;
 5227: }
 5228: table.LC_descriptive_input td.LC_description {
 5229:   vertical-align: top;
 5230:   text-align: right;
 5231:   font-weight: bold;
 5232: }
 5233: div.LC_feedback_link {
 5234:   clear: both;
 5235:   background: white;
 5236:   width: 100%;
 5237: }
 5238: span.LC_feedback_link {
 5239:   background: $feedback_link_bg;
 5240:   font-size: larger;
 5241: }
 5242: span.LC_message_link {
 5243:   background: $feedback_link_bg;
 5244:   font-size: larger;
 5245:   position: absolute;
 5246:   right: 1em;
 5247: }
 5248: 
 5249: table.LC_prior_tries {
 5250:   border: 1px solid #000000;
 5251:   border-collapse: separate;
 5252:   border-spacing: 1px;
 5253: }
 5254: 
 5255: table.LC_prior_tries td {
 5256:   padding: 2px;
 5257: }
 5258: 
 5259: .LC_answer_correct {
 5260:   background: #AAFFAA;
 5261:   color: black;
 5262: }
 5263: .LC_answer_charged_try {
 5264:   background: #FFAAAA ! important;
 5265:   color: black;
 5266: }
 5267: .LC_answer_not_charged_try,
 5268: .LC_answer_no_grade,
 5269: .LC_answer_late {
 5270:   background: #FFFFAA;
 5271:   color: black;
 5272: }
 5273: .LC_answer_previous {
 5274:   background: #AAAAFF;
 5275:   color: black;
 5276: }
 5277: .LC_answer_no_message {
 5278:   background: #FFFFFF;
 5279:   color: black;
 5280: }
 5281: .LC_answer_unknown {
 5282:   background: orange;
 5283:   color: black;
 5284: }
 5285: span.LC_prior_numerical,
 5286: span.LC_prior_string,
 5287: span.LC_prior_custom,
 5288: span.LC_prior_reaction,
 5289: span.LC_prior_math {
 5290:   font-family: monospace;
 5291:   white-space: pre;
 5292: }
 5293: 
 5294: span.LC_prior_string {
 5295:   font-family: monospace;
 5296:   white-space: pre;
 5297: }
 5298: 
 5299: table.LC_prior_option {
 5300:   width: 100%;
 5301:   border-collapse: collapse;
 5302: }
 5303: table.LC_prior_rank, table.LC_prior_match {
 5304:   border-collapse: collapse;
 5305: }
 5306: table.LC_prior_option tr td,
 5307: table.LC_prior_rank tr td,
 5308: table.LC_prior_match tr td {
 5309:   border: 1px solid #000000;
 5310: }
 5311: 
 5312: td.LC_nobreak,
 5313: span.LC_nobreak {
 5314:   white-space: nowrap;
 5315: }
 5316: 
 5317: span.LC_cusr_emph {
 5318:   font-style: italic;
 5319: }
 5320: 
 5321: span.LC_cusr_subheading {
 5322:   font-weight: normal;
 5323:   font-size: 85%;
 5324: }
 5325: 
 5326: table.LC_docs_documents {
 5327:   background: #BBBBBB;
 5328:   border-width: 0px;
 5329:   border-collapse: collapse;
 5330: }
 5331: table.LC_docs_documents td.LC_docs_document {
 5332:   border: 2px solid black;
 5333:   padding: 4px;
 5334: }
 5335: .LC_docs_entry_move {
 5336:   border: 0px;
 5337:   border-collapse: collapse;
 5338: }
 5339: 
 5340: .LC_docs_entry_move td {
 5341:   border: 2px solid #BBBBBB;
 5342:   background: #DDDDDD;
 5343: }
 5344: 
 5345: .LC_docs_editor td.LC_docs_entry_commands {
 5346:   background: #DDDDDD;
 5347:   font-size: x-small;
 5348: }
 5349: .LC_docs_copy {
 5350:   color: #000099;
 5351: }
 5352: .LC_docs_cut {
 5353:   color: #550044;
 5354: }
 5355: .LC_docs_rename {
 5356:   color: #009900;
 5357: }
 5358: .LC_docs_remove {
 5359:   color: #990000;
 5360: }
 5361: 
 5362: .LC_docs_reinit_warn,
 5363: .LC_docs_ext_edit {
 5364:   font-size: x-small;
 5365: }
 5366: 
 5367: .LC_docs_editor td.LC_docs_entry_title,
 5368: .LC_docs_editor td.LC_docs_entry_icon {
 5369:   background: #FFFFBB;
 5370: }
 5371: .LC_docs_editor td.LC_docs_entry_parameter {
 5372:   background: #BBBBFF;
 5373:   font-size: x-small;
 5374:   white-space: nowrap;
 5375: }
 5376: 
 5377: table.LC_docs_adddocs td,
 5378: table.LC_docs_adddocs th {
 5379:   border: 1px solid #BBBBBB;
 5380:   padding: 4px;
 5381:   background: #DDDDDD;
 5382: }
 5383: 
 5384: table.LC_sty_begin {
 5385:   background: #BBFFBB;
 5386: }
 5387: table.LC_sty_end {
 5388:   background: #FFBBBB;
 5389: }
 5390: 
 5391: table.LC_double_column {
 5392:   border-width: 0px;
 5393:   border-collapse: collapse;
 5394:   width: 100%;
 5395:   padding: 2px;
 5396: }
 5397: 
 5398: table.LC_double_column tr td.LC_left_col {
 5399:   top: 2px;
 5400:   left: 2px;
 5401:   width: 47%;
 5402:   vertical-align: top;
 5403: }
 5404: 
 5405: table.LC_double_column tr td.LC_right_col {
 5406:   top: 2px;
 5407:   right: 2px;
 5408:   width: 47%;
 5409:   vertical-align: top;
 5410: }
 5411: 
 5412: span.LC_role_level {
 5413:   font-weight: bold;
 5414: }
 5415: 
 5416: div.LC_left_float {
 5417:   float: left;
 5418:   padding-right: 5%;
 5419:   padding-bottom: 4px;
 5420: }
 5421: 
 5422: div.LC_clear_float_header {
 5423:   padding-bottom: 2px;
 5424: }
 5425: 
 5426: div.LC_clear_float_footer {
 5427:   padding-top: 10px;
 5428:   clear: both;
 5429: }
 5430: 
 5431: 
 5432: div.LC_grade_show_user {
 5433:   margin-top: 20px;
 5434:   border: 1px solid black;
 5435: }
 5436: div.LC_grade_user_name {
 5437:   background: #DDDDEE;
 5438:   border-bottom: 1px solid black;
 5439:   font-weight: bold;
 5440:   font-size: large;
 5441: }
 5442: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5443:   background: #DDEEDD;
 5444: }
 5445: 
 5446: div.LC_grade_show_problem,
 5447: div.LC_grade_submissions,
 5448: div.LC_grade_message_center,
 5449: div.LC_grade_info_links,
 5450: div.LC_grade_assign {
 5451:   margin: 5px;
 5452:   width: 99%;
 5453:   background: #FFFFFF;
 5454: }
 5455: div.LC_grade_show_problem_header,
 5456: div.LC_grade_submissions_header,
 5457: div.LC_grade_message_center_header,
 5458: div.LC_grade_assign_header {
 5459:   font-weight: bold;
 5460:   font-size: large;
 5461: }
 5462: div.LC_grade_show_problem_problem,
 5463: div.LC_grade_submissions_body,
 5464: div.LC_grade_message_center_body,
 5465: div.LC_grade_assign_body {
 5466:   border: 1px solid black;
 5467:   width: 99%;
 5468:   background: #FFFFFF;
 5469: }
 5470: span.LC_grade_check_note {
 5471:   font-weight: normal;
 5472:   font-size: medium;
 5473:   display: inline;
 5474:   position: absolute;
 5475:   right: 1em;
 5476: }
 5477: 
 5478: table.LC_scantron_action {
 5479:   width: 100%;
 5480: }
 5481: table.LC_scantron_action tr th {
 5482:   font-weight:bold;
 5483:   font-style:normal;
 5484: }
 5485: .LC_edit_problem_header,
 5486: div.LC_edit_problem_footer {
 5487:   font-weight: normal;
 5488:   font-size:  medium;
 5489:   margin: 2px;
 5490: }
 5491: div.LC_edit_problem_header,
 5492: div.LC_edit_problem_header div,
 5493: div.LC_edit_problem_footer,
 5494: div.LC_edit_problem_footer div,
 5495: div.LC_edit_problem_editxml_header,
 5496: div.LC_edit_problem_editxml_header div {
 5497:   margin-top: 5px;
 5498: }
 5499: div.LC_edit_problem_header_edit_row {
 5500:   background: $tabbg;
 5501:   padding: 3px;
 5502:   margin-bottom: 5px;
 5503: }
 5504: div.LC_edit_problem_header_title {
 5505:   font-weight: bold;
 5506:   font-size: larger;
 5507:   background: $tabbg;
 5508:   padding: 3px;
 5509: }
 5510: table.LC_edit_problem_header_title {
 5511:   font-size: larger;
 5512:   font-weight:  bold;
 5513:   width: 100%;
 5514:   border-color: $pgbg;
 5515:   border-style: solid;
 5516:   border-width: $border;
 5517: 
 5518:   background: $tabbg;
 5519:   border-collapse: collapse;
 5520:   padding: 0px
 5521: }
 5522: 
 5523: div.LC_edit_problem_discards {
 5524:   float: left;
 5525:   padding-bottom: 5px;
 5526: }
 5527: div.LC_edit_problem_saves {
 5528:   float: right;
 5529:   padding-bottom: 5px;
 5530: }
 5531: hr.LC_edit_problem_divide {
 5532:   clear: both;
 5533:   color: $tabbg;
 5534:   background-color: $tabbg;
 5535:   height: 3px;
 5536:   border: 0px;
 5537: }
 5538: img.stift{
 5539:   border-width:0;
 5540:   vertical-align:middle;
 5541: }
 5542: 
 5543: table#LC_mainmenu{
 5544:  margin-top:10px;
 5545:  width:80%;
 5546: 
 5547: }
 5548: 
 5549: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5550:   vertical-align: top;
 5551:   width: 45%;
 5552: }
 5553: .LC_mainmenu_fieldset_category {
 5554:   color: $font;
 5555:   background: $pgbg;
 5556:   font-family: $sans;
 5557:   font-size: small;
 5558:   font-weight: bold;
 5559: }
 5560: div.LC_createcourse {
 5561:     margin: 10px 10px 10px 10px;
 5562: }
 5563: 
 5564: /* ---- Remove when done ----
 5565: # The following styles is part of the redesign of LON-CAPA and are
 5566: # subject to change during this project.
 5567: # Don't rely on their current functionality as they might be 
 5568: # changed or removed.
 5569: # --------------------------*/
 5570: 
 5571: a:hover,
 5572: ol.LC_smallMenu a:hover,
 5573: ol#LC_MenuBreadcrumbs a:hover,
 5574: ol#LC_PathBreadcrumbs a:hover,
 5575: ul#LC_TabMainMenuContent a:hover,
 5576: .LC_FormSectionClearButton input:hover
 5577: ul.LC_TabContent   li:hover a{
 5578: 	color:#BF2317;
 5579:         text-decoration:none;
 5580: }
 5581: 
 5582: h1 {
 5583: 	padding:5px 10px 5px 20px;
 5584: 	line-height:130%;
 5585: }
 5586: 
 5587: h2,h3,h4,h5,h6
 5588: {
 5589: 	margin:5px 0px 5px 0px;
 5590: 	padding:0px;
 5591: 	line-height:130%;
 5592: }
 5593: .LC_hcell{
 5594:         padding:3px 15px 3px 15px;
 5595:         margin:0px;
 5596: 	background-color:$tabbg;
 5597: 	border-bottom:solid 1px $lg_border_color;
 5598: }
 5599: .LC_noBorder {
 5600:         border:0px;
 5601: }
 5602: 
 5603: 
 5604: /* Main Header with discription of Person, Course, etc. */
 5605: 
 5606: .LC_Right {
 5607:         float: right;
 5608:         margin: 0px;
 5609:         padding: 0px;
 5610: }
 5611: 
 5612: p, .LC_ContentBox {
 5613: 	padding: 10px;
 5614: 
 5615: }
 5616: .LC_FormSectionClearButton input {
 5617:         background-color:transparent;
 5618:         border:0px;
 5619:         cursor:pointer;
 5620:         text-decoration:underline;
 5621: }
 5622: 
 5623: .LC_help_open_topic {
 5624:         color: #FFFFFF;
 5625:         background-color: #EEEEFF;
 5626:         margin: 1px;
 5627:         padding: 4px;
 5628:         border: 1px solid #000033;
 5629:         white-space: nowrap;
 5630: /*		vertical-align: middle; */
 5631: }
 5632: 
 5633: dl,ul,div,fieldset {
 5634: 	margin: 10px 10px 10px 0px;
 5635: 	overflow:hidden;
 5636: }
 5637: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5638: 	margin: 0px;
 5639: }
 5640: 
 5641: ol.LC_smallMenu li {
 5642: 	display: inline;
 5643: 	padding: 5px 5px 0px 10px;
 5644: 	vertical-align: top;
 5645: }
 5646: 
 5647: ol.LC_smallMenu li img {
 5648: 	vertical-align: bottom;
 5649: }
 5650: 
 5651: ol.LC_smallMenu a {
 5652: 	font-size: 90%;
 5653: 	color: RGB(80, 80, 80);
 5654: 	text-decoration: none;
 5655: }
 5656: ol#LC_TabMainMenuContent, ul.LC_TabContent ,
 5657: ul.LC_TabContentBigger {
 5658: 	display:block;
 5659: 	list-style:none;
 5660: 	margin: 0px;
 5661: 	padding: 0px;
 5662: }
 5663: 
 5664: ol#LC_TabMainMenuContent li, ul.LC_TabContent li,
 5665: ul.LC_TabContentBigger li{
 5666: 	display: inline;
 5667: 	border-right: solid 1px $lg_border_color;
 5668: 	float:left;
 5669: 	line-height:140%;
 5670: 	white-space:nowrap;
 5671: }
 5672: ol#LC_TabMainMenuContent li{
 5673: 	vertical-align: bottom;
 5674: 	border-bottom: solid 1px RGB(175, 175, 175);
 5675: 	padding: 5px 10px 5px 10px;
 5676: 	margin-right:5px;
 5677: 	margin-bottom:3px;
 5678: 	font-weight: bold;
 5679: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5680: }
 5681: 
 5682: ol#LC_TabMainMenuContent li a{
 5683: 	color: RGB(47, 47, 47);
 5684: 	text-decoration: none;
 5685: }
 5686: ul.LC_TabContent {
 5687: 	min-height:1.6em;
 5688: }
 5689: ul.LC_TabContent li{
 5690: 	vertical-align:middle;
 5691: 	padding:0px 10px 0px 10px;
 5692: 	background-color:$tabbg;
 5693: 	border-bottom:solid 1px $lg_border_color;
 5694: }
 5695: ul.LC_TabContent li a, ul.LC_TabContent li{
 5696: 	color:rgb(47,47,47);
 5697: 	text-decoration:none;
 5698: 	font-size:95%;
 5699: 	font-weight:bold;
 5700: 	padding-right: 16px;
 5701: }
 5702: ul.LC_TabContent li:hover, ul.LC_TabContent li.active{
 5703:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5704: 	border-bottom:solid 1px #FFFFFF;
 5705: 	padding-right: 16px;
 5706: }
 5707: ul.LC_TabContentBigger li{
 5708: 	vertical-align:bottom;
 5709: 	border-top:solid 1px $lg_border_color;
 5710: 	border-left:solid 1px $lg_border_color;
 5711: 	padding:5px 10px 5px 10px;
 5712: 	margin-left:2px;
 5713: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5714: }
 5715: ul.LC_TabContentBigger li:hover, ul.LC_TabContentBigger li.active{
 5716: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5717: }
 5718: ul.LC_TabContentBigger li, ul.LC_TabContentBigger li a{
 5719: 	font-size:110%;
 5720: 	font-weight:bold;
 5721: }
 5722: 
 5723: ol#LC_MenuBreadcrumbs, ol#LC_PathBreadcrumbs, ul.LC_CourseBreadcrumbs{
 5724: 	border-top: solid 1px RGB(255, 255, 255);
 5725: 	height: 20px;
 5726: 	line-height: 20px;
 5727: 	vertical-align: bottom;
 5728: 	margin: 0px 0px 30px 0px;
 5729: 	padding-left: 10px;
 5730: 	list-style-position: inside;
 5731: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5732: }
 5733: 
 5734: ol#LC_MenuBreadcrumbs li, ol#LC_PathBreadcrumbs li, ul.LC_CourseBreadcrumbs li {
 5735: /*
 5736: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5737: */
 5738: 	display: inline;
 5739: 	padding: 0px 0px 0px 10px;
 5740: /*	vertical-align: bottom; */
 5741: 	overflow:hidden;
 5742: }
 5743: 
 5744: ol#LC_MenuBreadcrumbs li a, ul.LC_CourseBreadcrumbs li a {
 5745: 	text-decoration: none;
 5746: 	font-size:90%;
 5747: }
 5748: ol#LC_PathBreadcrumbs li a{
 5749: 	text-decoration:none;
 5750: 	font-size:100%;
 5751: 	font-weight:bold;
 5752: }
 5753: .LC_BoxPadding
 5754: {
 5755: 	padding: 10px;
 5756: }
 5757: .LC_ContentBoxSpecial
 5758: {
 5759: 	border: solid 1px $lg_border_color;
 5760: }
 5761: .LC_ContentBoxSpecialContactInfo
 5762: {
 5763: 	border: solid 1px $lg_border_color;
 5764: 	max-width:25%;
 5765: 	min-width:25%;
 5766: }
 5767: .LC_AboutMe_Image
 5768: {
 5769: 	float:left;
 5770: 	margin-right:10px;
 5771: }
 5772: .LC_Clear_AboutMe_Image
 5773: {
 5774: 	clear:left;
 5775: }
 5776: dl.LC_ListStyleClean dt {
 5777: 	padding-right: 5px;
 5778: 	display: table-header-group;
 5779: }
 5780: 
 5781: dl.LC_ListStyleClean dd {
 5782: 	display: table-row;
 5783: }
 5784: 
 5785: .LC_ListStyleClean,
 5786: .LC_ListStyleSimple,
 5787: .LC_ListStyleNormal,
 5788: .LC_ListStyle_Border,
 5789: .LC_ListStyleSpecial
 5790: 	{
 5791: 	/*display:block;	*/
 5792: 	list-style-position: inside;
 5793: 	list-style-type: none;
 5794: 	overflow: hidden;
 5795: 	padding: 0px;
 5796: }
 5797: 
 5798: .LC_ListStyleSimple li,
 5799: .LC_ListStyleSimple dd,
 5800: .LC_ListStyleNormal li,
 5801: .LC_ListStyleNormal dd,
 5802: .LC_ListStyleSpecial li,
 5803: .LC_ListStyleSpecial dd
 5804: 	{
 5805: 	margin: 0px;
 5806: 	padding: 5px 5px 5px 10px;
 5807: 	clear: both;
 5808: }
 5809: 
 5810: .LC_ListStyleClean li,
 5811: .LC_ListStyleClean dd {
 5812: 	padding-top: 0px;
 5813: 	padding-bottom: 0px;
 5814: }
 5815: 
 5816: .LC_ListStyleSimple dd,
 5817: .LC_ListStyleSimple li{
 5818: 	border-bottom: solid 1px $lg_border_color;
 5819: }
 5820: 
 5821: .LC_ListStyleSpecial li,
 5822: .LC_ListStyleSpecial dd {
 5823: 	list-style-type: none;
 5824: 	background-color: RGB(220, 220, 220);
 5825: 	margin-bottom: 4px;
 5826: }
 5827: 
 5828: table.LC_SimpleTable {
 5829: 	margin:5px;
 5830: 	border:solid 1px $lg_border_color;
 5831: 	}
 5832: 
 5833: table.LC_SimpleTable tr {
 5834: 	padding:0px;
 5835: 	border:solid 1px $lg_border_color;
 5836: }
 5837: table.LC_SimpleTable thead{
 5838: 	 background:rgb(220,220,220);
 5839: }
 5840: 
 5841: div.LC_columnSection {
 5842: 	display: block;
 5843: 	clear: both;
 5844: 	overflow: hidden;
 5845: 	margin:0px;
 5846: }
 5847: 
 5848: div.LC_columnSection>* {
 5849: 	float: left;
 5850: 	margin: 10px 20px 10px 0px;
 5851: 	overflow:hidden;
 5852: }
 5853: 
 5854: .ContentBoxSpecialTemplate
 5855: {
 5856:         border: solid 1px $lg_border_color;
 5857: }
 5858: .ContentBoxTemplate {
 5859:         padding:10px;
 5860: }
 5861: 
 5862: div.LC_columnSection > .ContentBoxTemplate,
 5863: div.LC_columnSection > .ContentBoxSpecialTemplate
 5864:         {
 5865:         width: 600px;
 5866: }
 5867: 
 5868: .clear{
 5869: 	clear: both;
 5870: 	line-height: 0px;
 5871: 	font-size: 0px;
 5872: 	height: 0px;
 5873: }
 5874: 
 5875: .LC_loginpage_container {
 5876: 	text-align:left;
 5877: 	margin : 0 auto;
 5878: 	width:90%;
 5879: 	padding: 10px;
 5880: 	height: auto;
 5881: 	background-color:#FFFFFF;
 5882: 	border:1px solid #CCCCCC;
 5883: }
 5884: 
 5885: 
 5886: .LC_loginpage_loginContainer {
 5887: 	float:left;
 5888: 	width: 182px;
 5889: 	padding: 2px;
 5890: 	border:1px solid #CCCCCC;
 5891: 	background-color:$loginbg;
 5892: }
 5893: 
 5894: .LC_loginpage_loginContainer h2{
 5895: 	margin-top:0;
 5896: 	display:block;
 5897: 	background:$bgcol;
 5898: 	color:$textcol;
 5899: 	padding-left:5px;
 5900: }
 5901: 
 5902: .LC_loginpage_loginInfo {
 5903: 	float:left;
 5904: 	width:182px;
 5905: 	border:1px solid #CCCCCC;
 5906: 	padding:2px;
 5907: }
 5908: 
 5909: .LC_loginpage_space {
 5910: 	clear: both;
 5911: 	margin-bottom: 20px;
 5912: 	border-bottom: 1px solid #CCCCCC;
 5913: }
 5914: 
 5915: .LC_loginpage_floatLeft {
 5916: 	float: left;
 5917: 	width: 200px;
 5918: 	margin: 0;
 5919: }
 5920: 
 5921: table em{
 5922: 	font-weight: bold;
 5923: 	font-style: normal;
 5924: }
 5925: table.LC_tableBrowseRes,
 5926: table.LC_tableOfContent{
 5927:         border:none;
 5928: 	border-spacing: 1;
 5929: 	padding: 3px;
 5930: 	background-color: #FFFFFF;
 5931: 	font-size: 90%;
 5932: }
 5933: table.LC_tableBrowseRes a,
 5934: table.LC_tableOfContent a {
 5935:         background-color: transparent;
 5936: 	text-decoration: none;
 5937: }
 5938: 
 5939: table.LC_tableBrowseRes tr.LC_trOdd,
 5940: table.LC_tableOfContent tr.LC_trOdd{
 5941: 	background-color: #EEEEEE;
 5942: }
 5943: 
 5944: table.LC_tableOfContent img{
 5945: 	border: none;
 5946: 	height: 1.3em;
 5947: 	vertical-align: text-bottom;
 5948: 	margin-right: 0.3em;
 5949: }
 5950: 
 5951: a#LC_content_toolbar_firsthomework{
 5952: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 5953: }
 5954: 
 5955: a#LC_content_toolbar_launchnav{
 5956: 	background-image:url(/res/adm/pages/start-navigation.gif);
 5957: }
 5958: 
 5959: a#LC_content_toolbar_closenav{
 5960: 	background-image:url(/res/adm/pages/close-navigation.gif);
 5961: }
 5962: 
 5963: a#LC_content_toolbar_everything{
 5964: 	background-image:url(/res/adm/pages/show-all.gif);
 5965: }
 5966: 
 5967: a#LC_content_toolbar_uncompleted{
 5968: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 5969: }
 5970: 
 5971: #LC_content_toolbar_clearbubbles{
 5972: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 5973: }
 5974: 
 5975: a#LC_content_toolbar_changefolder{
 5976: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 5977: }
 5978: 
 5979: a#LC_content_toolbar_changefolder_toggled{
 5980: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 5981: }
 5982: 
 5983: ul#LC_toolbar li a:hover{
 5984: 	background-position: bottom center;
 5985: }
 5986: 
 5987: ul#LC_toolbar{
 5988: 	padding:0;
 5989: 	margin: 2px;
 5990: 	list-style:none;
 5991: 	position:relative;
 5992: 	background-color:white;
 5993: }
 5994: 
 5995: ul#LC_toolbar li{
 5996: 	border:1px solid white;
 5997: 	padding:0;
 5998: 	margin: 0;
 5999:     float: left;
 6000: 	display:inline;
 6001: 	vertical-align:middle;
 6002: }
 6003: 
 6004: 
 6005: a.LC_toolbarItem{
 6006: 	display:block;
 6007: 	padding:0;
 6008: 	margin:0;
 6009: 	height: 32px;
 6010: 	width: 32px;
 6011: 	color:white;
 6012: 	border:0 none;
 6013: 	background-repeat:no-repeat;
 6014: 	background-color:transparent;
 6015: }
 6016: 
 6017: ul.LC_functionslist li {
 6018:   float: left;
 6019:   white-space: nowrap;
 6020:   height: 35px; /* at least as high as heighest list item */
 6021:   margin: 0px 15px 15px 10px;
 6022: }
 6023: 
 6024: 
 6025: END
 6026: }
 6027: 
 6028: =pod
 6029: 
 6030: =item * &headtag()
 6031: 
 6032: Returns a uniform footer for LON-CAPA web pages.
 6033: 
 6034: Inputs: $title - optional title for the head
 6035:         $head_extra - optional extra HTML to put inside the <head>
 6036:         $args - optional arguments
 6037:             force_register - if is true call registerurl so the remote is 
 6038:                              informed
 6039:             redirect       -> array ref of
 6040:                                    1- seconds before redirect occurs
 6041:                                    2- url to redirect to
 6042:                                    3- whether the side effect should occur
 6043:                            (side effect of setting 
 6044:                                $env{'internal.head.redirect'} to the url 
 6045:                                redirected too)
 6046:             domain         -> force to color decorate a page for a specific
 6047:                                domain
 6048:             function       -> force usage of a specific rolish color scheme
 6049:             bgcolor        -> override the default page bgcolor
 6050:             no_auto_mt_title
 6051:                            -> prevent &mt()ing the title arg
 6052: 
 6053: =cut
 6054: 
 6055: sub headtag {
 6056:     my ($title,$head_extra,$args) = @_;
 6057:     
 6058:     my $function = $args->{'function'} || &get_users_function();
 6059:     my $domain   = $args->{'domain'}   || &determinedomain();
 6060:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6061:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6062: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6063: 		   #time(),
 6064: 		   $env{'environment.color.timestamp'},
 6065: 		   $function,$domain,$bgcolor);
 6066: 
 6067:     $url = '/adm/css/'.&escape($url).'.css';
 6068: 
 6069:     my $result =
 6070: 	'<head>'.
 6071: 	&font_settings();
 6072: 
 6073:     if (!$args->{'frameset'}) {
 6074: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6075:     }
 6076:     if ($args->{'force_register'}) {
 6077: 	$result .= &Apache::lonmenu::registerurl(1);
 6078:     }
 6079:     if (!$args->{'no_nav_bar'} 
 6080: 	&& !$args->{'only_body'}
 6081: 	&& !$args->{'frameset'}) {
 6082: 	$result .= &help_menu_js();
 6083:     }
 6084: 
 6085:     if (ref($args->{'redirect'})) {
 6086: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6087: 	$url = &Apache::lonenc::check_encrypt($url);
 6088: 	if (!$inhibit_continue) {
 6089: 	    $env{'internal.head.redirect'} = $url;
 6090: 	}
 6091: 	$result.=<<ADDMETA
 6092: <meta http-equiv="pragma" content="no-cache" />
 6093: <meta http-equiv="Refresh" content="$time; url=$url" />
 6094: ADDMETA
 6095:     }
 6096:     if (!defined($title)) {
 6097: 	$title = 'The LearningOnline Network with CAPA';
 6098:     }
 6099:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6100:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6101: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6102: 	.$head_extra;
 6103:     return $result;
 6104: }
 6105: 
 6106: =pod
 6107: 
 6108: =item * &font_settings()
 6109: 
 6110: Returns neccessary <meta> to set the proper encoding
 6111: 
 6112: Inputs: none
 6113: 
 6114: =cut
 6115: 
 6116: sub font_settings {
 6117:     my $headerstring='';
 6118:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6119: 	$headerstring.=
 6120: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6121:     }
 6122:     return $headerstring;
 6123: }
 6124: 
 6125: =pod
 6126: 
 6127: =item * &xml_begin()
 6128: 
 6129: Returns the needed doctype and <html>
 6130: 
 6131: Inputs: none
 6132: 
 6133: =cut
 6134: 
 6135: sub xml_begin {
 6136:     my $output='';
 6137: 
 6138:     if ($env{'internal.start_page'}==1) {
 6139: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6140:     }
 6141: 
 6142:     if ($env{'browser.mathml'}) {
 6143: 	$output='<?xml version="1.0"?>'
 6144:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6145: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6146:             
 6147: #	    .'<!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">] >'
 6148: 	    .'<!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">'
 6149:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6150: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6151:     } else {
 6152: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6153:     }
 6154:     return $output;
 6155: }
 6156: 
 6157: =pod
 6158: 
 6159: =item * &endheadtag()
 6160: 
 6161: Returns a uniform </head> for LON-CAPA web pages.
 6162: 
 6163: Inputs: none
 6164: 
 6165: =cut
 6166: 
 6167: sub endheadtag {
 6168:     return '</head>';
 6169: }
 6170: 
 6171: =pod
 6172: 
 6173: =item * &head()
 6174: 
 6175: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6176: 
 6177: Inputs:
 6178: 
 6179: =over 4
 6180: 
 6181: $title - optional title for the page
 6182: 
 6183: $head_extra - optional extra HTML to put inside the <head>
 6184: 
 6185: =back
 6186: 
 6187: =cut
 6188: 
 6189: sub head {
 6190:     my ($title,$head_extra,$args) = @_;
 6191:     return &headtag($title,$head_extra,$args).&endheadtag();
 6192: }
 6193: 
 6194: =pod
 6195: 
 6196: =item * &start_page()
 6197: 
 6198: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6199: 
 6200: Inputs:
 6201: 
 6202: =over 4
 6203: 
 6204: $title - optional title for the page
 6205: 
 6206: $head_extra - optional extra HTML to incude inside the <head>
 6207: 
 6208: $args - additional optional args supported are:
 6209: 
 6210: =over 8
 6211: 
 6212:              only_body      -> is true will set &bodytag() onlybodytag
 6213:                                     arg on
 6214:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6215:              add_entries    -> additional attributes to add to the  <body>
 6216:              domain         -> force to color decorate a page for a 
 6217:                                     specific domain
 6218:              function       -> force usage of a specific rolish color
 6219:                                     scheme
 6220:              redirect       -> see &headtag()
 6221:              bgcolor        -> override the default page bg color
 6222:              js_ready       -> return a string ready for being used in 
 6223:                                     a javascript writeln
 6224:              html_encode    -> return a string ready for being used in 
 6225:                                     a html attribute
 6226:              force_register -> if is true will turn on the &bodytag()
 6227:                                     $forcereg arg
 6228:              body_title     -> alternate text to use instead of $title
 6229:                                     in the title box that appears, this text
 6230:                                     is not auto translated like the $title is
 6231:              frameset       -> if true will start with a <frameset>
 6232:                                     rather than <body>
 6233:              no_title       -> if true the title bar won't be shown
 6234:              skip_phases    -> hash ref of 
 6235:                                     head -> skip the <html><head> generation
 6236:                                     body -> skip all <body> generation
 6237:              no_inline_link -> if true and in remote mode, don't show the 
 6238:                                     'Switch To Inline Menu' link
 6239:              no_auto_mt_title -> prevent &mt()ing the title arg
 6240:              inherit_jsmath -> when creating popup window in a page,
 6241:                                     should it have jsmath forced on by the
 6242:                                     current page
 6243: 
 6244: =back
 6245: 
 6246: =back
 6247: 
 6248: =cut
 6249: 
 6250: sub start_page {
 6251:     my ($title,$head_extra,$args) = @_;
 6252:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6253:     my %head_args;
 6254:     foreach my $arg ('redirect','force_register','domain','function',
 6255: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6256: 		     'no_auto_mt_title') {
 6257: 	if (defined($args->{$arg})) {
 6258: 	    $head_args{$arg} = $args->{$arg};
 6259: 	}
 6260:     }
 6261: 
 6262:     $env{'internal.start_page'}++;
 6263:     my $result;
 6264:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6265: 	$result.=
 6266: 	    &xml_begin().
 6267: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6268:     }
 6269:     
 6270:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6271: 	if ($args->{'frameset'}) {
 6272: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6273: 						$args->{'add_entries'});
 6274: 	    $result .= "\n<frameset $attr_string>\n";
 6275: 	} else {
 6276: 	    $result .=
 6277: 		&bodytag($title, 
 6278: 			 $args->{'function'},       $args->{'add_entries'},
 6279: 			 $args->{'only_body'},      $args->{'domain'},
 6280: 			 $args->{'force_register'}, $args->{'body_title'},
 6281: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6282: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6283: 			 $args);
 6284: 	}
 6285:     }
 6286: 
 6287:     if ($args->{'js_ready'}) {
 6288: 		$result = &js_ready($result);
 6289:     }
 6290:     if ($args->{'html_encode'}) {
 6291: 		$result = &html_encode($result);
 6292:     }
 6293: 
 6294: 	#Breadcrumbs
 6295:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6296: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6297: 		#if any br links exists, add them to the breadcrumbs
 6298: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6299: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6300: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6301: 			}
 6302: 		}
 6303: 
 6304: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6305: 		if(exists($args->{'bread_crumbs_component'})){
 6306: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6307: 		}else{
 6308: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6309: 		}
 6310:     }
 6311:     return $result;
 6312: }
 6313: 
 6314: 
 6315: =pod
 6316: 
 6317: =item * &head()
 6318: 
 6319: Returns a complete </body></html> section for LON-CAPA web pages.
 6320: 
 6321: Inputs:         $args - additional optional args supported are:
 6322:                  js_ready     -> return a string ready for being used in 
 6323:                                  a javascript writeln
 6324:                  html_encode  -> return a string ready for being used in 
 6325:                                  a html attribute
 6326:                  frameset     -> if true will start with a <frameset>
 6327:                                  rather than <body>
 6328:                  dicsussion   -> if true will get discussion from
 6329:                                   lonxml::xmlend
 6330:                                  (you can pass the target and parser arguments
 6331:                                   through optional 'target' and 'parser' args
 6332:                                   to this routine)
 6333: 
 6334: =cut
 6335: 
 6336: sub end_page {
 6337:     my ($args) = @_;
 6338:     $env{'internal.end_page'}++;
 6339:     my $result;
 6340:     if ($args->{'discussion'}) {
 6341: 	my ($target,$parser);
 6342: 	if (ref($args->{'discussion'})) {
 6343: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6344: 				$args->{'discussion'}{'parser'});
 6345: 	}
 6346: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6347:     }
 6348: 
 6349:     if ($args->{'frameset'}) {
 6350: 	$result .= '</frameset>';
 6351:     } else {
 6352: 	$result .= &endbodytag($args);
 6353:     }
 6354:     $result .= "\n</html>";
 6355: 
 6356:     if ($args->{'js_ready'}) {
 6357: 	$result = &js_ready($result);
 6358:     }
 6359: 
 6360:     if ($args->{'html_encode'}) {
 6361: 	$result = &html_encode($result);
 6362:     }
 6363: 
 6364:     return $result;
 6365: }
 6366: 
 6367: sub html_encode {
 6368:     my ($result) = @_;
 6369: 
 6370:     $result = &HTML::Entities::encode($result,'<>&"');
 6371:     
 6372:     return $result;
 6373: }
 6374: sub js_ready {
 6375:     my ($result) = @_;
 6376: 
 6377:     $result =~ s/[\n\r]/ /xmsg;
 6378:     $result =~ s/\\/\\\\/xmsg;
 6379:     $result =~ s/'/\\'/xmsg;
 6380:     $result =~ s{</}{<\\/}xmsg;
 6381:     
 6382:     return $result;
 6383: }
 6384: 
 6385: sub validate_page {
 6386:     if (  exists($env{'internal.start_page'})
 6387: 	  &&     $env{'internal.start_page'} > 1) {
 6388: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6389: 				 $env{'internal.start_page'}.' '.
 6390: 				 $ENV{'request.filename'});
 6391:     }
 6392:     if (  exists($env{'internal.end_page'})
 6393: 	  &&     $env{'internal.end_page'} > 1) {
 6394: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6395: 				 $env{'internal.end_page'}.' '.
 6396: 				 $env{'request.filename'});
 6397:     }
 6398:     if (     exists($env{'internal.start_page'})
 6399: 	&& ! exists($env{'internal.end_page'})) {
 6400: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6401: 				 $env{'request.filename'});
 6402:     }
 6403:     if (   ! exists($env{'internal.start_page'})
 6404: 	&&   exists($env{'internal.end_page'})) {
 6405: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6406: 				 $env{'request.filename'});
 6407:     }
 6408: }
 6409: 
 6410: sub simple_error_page {
 6411:     my ($r,$title,$msg) = @_;
 6412:     my $page =
 6413: 	&Apache::loncommon::start_page($title).
 6414: 	&mt($msg).
 6415: 	&Apache::loncommon::end_page();
 6416:     if (ref($r)) {
 6417: 	$r->print($page);
 6418: 	return;
 6419:     }
 6420:     return $page;
 6421: }
 6422: 
 6423: {
 6424:     my @row_count;
 6425:     sub start_data_table {
 6426: 	my ($add_class) = @_;
 6427: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6428: 	unshift(@row_count,0);
 6429: 	return '<table class="'.$css_class.'">'."\n";
 6430:     }
 6431: 
 6432:     sub end_data_table {
 6433: 	shift(@row_count);
 6434: 	return '</table>'."\n";;
 6435:     }
 6436: 
 6437:     sub start_data_table_row {
 6438: 	my ($add_class) = @_;
 6439: 	$row_count[0]++;
 6440: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6441: 	$css_class = (join(' ',$css_class,$add_class));
 6442: 	return  '<tr class="'.$css_class.'">'."\n";;
 6443:     }
 6444:     
 6445:     sub continue_data_table_row {
 6446: 	my ($add_class) = @_;
 6447: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6448: 	$css_class = (join(' ',$css_class,$add_class));
 6449: 	return  '<tr class="'.$css_class.'">'."\n";;
 6450:     }
 6451: 
 6452:     sub end_data_table_row {
 6453: 	return '</tr>'."\n";;
 6454:     }
 6455: 
 6456:     sub start_data_table_empty_row {
 6457: #	$row_count[0]++;
 6458: 	return  '<tr class="LC_empty_row" >'."\n";;
 6459:     }
 6460: 
 6461:     sub end_data_table_empty_row {
 6462: 	return '</tr>'."\n";;
 6463:     }
 6464: 
 6465:     sub start_data_table_header_row {
 6466: 	return  '<tr class="LC_header_row">'."\n";;
 6467:     }
 6468: 
 6469:     sub end_data_table_header_row {
 6470: 	return '</tr>'."\n";;
 6471:     }
 6472: }
 6473: 
 6474: =pod
 6475: 
 6476: =item * &inhibit_menu_check($arg)
 6477: 
 6478: Checks for a inhibitmenu state and generates output to preserve it
 6479: 
 6480: Inputs:         $arg - can be any of
 6481:                      - undef - in which case the return value is a string 
 6482:                                to add  into arguments list of a uri
 6483:                      - 'input' - in which case the return value is a HTML
 6484:                                  <form> <input> field of type hidden to
 6485:                                  preserve the value
 6486:                      - a url - in which case the return value is the url with
 6487:                                the neccesary cgi args added to preserve the
 6488:                                inhibitmenu state
 6489:                      - a ref to a url - no return value, but the string is
 6490:                                         updated to include the neccessary cgi
 6491:                                         args to preserve the inhibitmenu state
 6492: 
 6493: =cut
 6494: 
 6495: sub inhibit_menu_check {
 6496:     my ($arg) = @_;
 6497:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6498:     if ($arg eq 'input') {
 6499: 	if ($env{'form.inhibitmenu'}) {
 6500: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6501: 	} else {
 6502: 	    return
 6503: 	}
 6504:     }
 6505:     if ($env{'form.inhibitmenu'}) {
 6506: 	if (ref($arg)) {
 6507: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6508: 	} elsif ($arg eq '') {
 6509: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6510: 	} else {
 6511: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6512: 	}
 6513:     }
 6514:     if (!ref($arg)) {
 6515: 	return $arg;
 6516:     }
 6517: }
 6518: 
 6519: ###############################################
 6520: 
 6521: =pod
 6522: 
 6523: =back
 6524: 
 6525: =head1 User Information Routines
 6526: 
 6527: =over 4
 6528: 
 6529: =item * &get_users_function()
 6530: 
 6531: Used by &bodytag to determine the current users primary role.
 6532: Returns either 'student','coordinator','admin', or 'author'.
 6533: 
 6534: =cut
 6535: 
 6536: ###############################################
 6537: sub get_users_function {
 6538:     my $function = 'student';
 6539:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6540:         $function='coordinator';
 6541:     }
 6542:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6543:         $function='admin';
 6544:     }
 6545:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6546:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6547:         $function='author';
 6548:     }
 6549:     return $function;
 6550: }
 6551: 
 6552: ###############################################
 6553: 
 6554: =pod
 6555: 
 6556: =item * &check_user_status()
 6557: 
 6558: Determines current status of supplied role for a
 6559: specific user. Roles can be active, previous or future.
 6560: 
 6561: Inputs: 
 6562: user's domain, user's username, course's domain,
 6563: course's number, optional section ID.
 6564: 
 6565: Outputs:
 6566: role status: active, previous or future. 
 6567: 
 6568: =cut
 6569: 
 6570: sub check_user_status {
 6571:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6572:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6573:     my @uroles = keys %userinfo;
 6574:     my $srchstr;
 6575:     my $active_chk = 'none';
 6576:     my $now = time;
 6577:     if (@uroles > 0) {
 6578:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6579:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6580:         } else {
 6581:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6582:         }
 6583:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6584:             my $role_end = 0;
 6585:             my $role_start = 0;
 6586:             $active_chk = 'active';
 6587:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6588:                 $role_end = $1;
 6589:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6590:                     $role_start = $1;
 6591:                 }
 6592:             }
 6593:             if ($role_start > 0) {
 6594:                 if ($now < $role_start) {
 6595:                     $active_chk = 'future';
 6596:                 }
 6597:             }
 6598:             if ($role_end > 0) {
 6599:                 if ($now > $role_end) {
 6600:                     $active_chk = 'previous';
 6601:                 }
 6602:             }
 6603:         }
 6604:     }
 6605:     return $active_chk;
 6606: }
 6607: 
 6608: ###############################################
 6609: 
 6610: =pod
 6611: 
 6612: =item * &get_sections()
 6613: 
 6614: Determines all the sections for a course including
 6615: sections with students and sections containing other roles.
 6616: Incoming parameters: 
 6617: 
 6618: 1. domain
 6619: 2. course number 
 6620: 3. reference to array containing roles for which sections should 
 6621: be gathered (optional).
 6622: 4. reference to array containing status types for which sections 
 6623: should be gathered (optional).
 6624: 
 6625: If the third argument is undefined, sections are gathered for any role. 
 6626: If the fourth argument is undefined, sections are gathered for any status.
 6627: Permissible values are 'active' or 'future' or 'previous'.
 6628:  
 6629: Returns section hash (keys are section IDs, values are
 6630: number of users in each section), subject to the
 6631: optional roles filter, optional status filter 
 6632: 
 6633: =cut
 6634: 
 6635: ###############################################
 6636: sub get_sections {
 6637:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6638:     if (!defined($cdom) || !defined($cnum)) {
 6639:         my $cid =  $env{'request.course.id'};
 6640: 
 6641: 	return if (!defined($cid));
 6642: 
 6643:         $cdom = $env{'course.'.$cid.'.domain'};
 6644:         $cnum = $env{'course.'.$cid.'.num'};
 6645:     }
 6646: 
 6647:     my %sectioncount;
 6648:     my $now = time;
 6649: 
 6650:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6651: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6652: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6653: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6654:         my $start_index = &Apache::loncoursedata::CL_START();
 6655:         my $end_index = &Apache::loncoursedata::CL_END();
 6656:         my $status;
 6657: 	while (my ($student,$data) = each(%$classlist)) {
 6658: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6659: 				                     $data->[$status_index],
 6660:                                                      $data->[$start_index],
 6661:                                                      $data->[$end_index]);
 6662:             if ($stu_status eq 'Active') {
 6663:                 $status = 'active';
 6664:             } elsif ($end < $now) {
 6665:                 $status = 'previous';
 6666:             } elsif ($start > $now) {
 6667:                 $status = 'future';
 6668:             } 
 6669: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6670:                 if ((!defined($possible_status)) || (($status ne '') && 
 6671:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6672: 		    $sectioncount{$section}++;
 6673:                 }
 6674: 	    }
 6675: 	}
 6676:     }
 6677:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6678:     foreach my $user (sort(keys(%courseroles))) {
 6679: 	if ($user !~ /^(\w{2})/) { next; }
 6680: 	my ($role) = ($user =~ /^(\w{2})/);
 6681: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6682: 	my ($section,$status);
 6683: 	if ($role eq 'cr' &&
 6684: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6685: 	    $section=$1;
 6686: 	}
 6687: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6688: 	if (!defined($section) || $section eq '-1') { next; }
 6689:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6690:         if ($end == -1 && $start == -1) {
 6691:             next; #deleted role
 6692:         }
 6693:         if (!defined($possible_status)) { 
 6694:             $sectioncount{$section}++;
 6695:         } else {
 6696:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6697:                 $status = 'active';
 6698:             } elsif ($end < $now) {
 6699:                 $status = 'future';
 6700:             } elsif ($start > $now) {
 6701:                 $status = 'previous';
 6702:             }
 6703:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6704:                 $sectioncount{$section}++;
 6705:             }
 6706:         }
 6707:     }
 6708:     return %sectioncount;
 6709: }
 6710: 
 6711: ###############################################
 6712: 
 6713: =pod
 6714: 
 6715: =item * &get_course_users()
 6716: 
 6717: Retrieves usernames:domains for users in the specified course
 6718: with specific role(s), and access status. 
 6719: 
 6720: Incoming parameters:
 6721: 1. course domain
 6722: 2. course number
 6723: 3. access status: users must have - either active, 
 6724: previous, future, or all.
 6725: 4. reference to array of permissible roles
 6726: 5. reference to array of section restrictions (optional)
 6727: 6. reference to results object (hash of hashes).
 6728: 7. reference to optional userdata hash
 6729: 8. reference to optional statushash
 6730: 9. flag if privileged users (except those set to unhide in
 6731:    course settings) should be excluded    
 6732: Keys of top level results hash are roles.
 6733: Keys of inner hashes are username:domain, with 
 6734: values set to access type.
 6735: Optional userdata hash returns an array with arguments in the 
 6736: same order as loncoursedata::get_classlist() for student data.
 6737: 
 6738: Optional statushash returns
 6739: 
 6740: Entries for end, start, section and status are blank because
 6741: of the possibility of multiple values for non-student roles.
 6742: 
 6743: =cut
 6744: 
 6745: ###############################################
 6746: 
 6747: sub get_course_users {
 6748:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6749:     my %idx = ();
 6750:     my %seclists;
 6751: 
 6752:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6753:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6754:     $idx{end} = &Apache::loncoursedata::CL_END();
 6755:     $idx{start} = &Apache::loncoursedata::CL_START();
 6756:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6757:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6758:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6759:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6760: 
 6761:     if (grep(/^st$/,@{$roles})) {
 6762:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6763:         my $now = time;
 6764:         foreach my $student (keys(%{$classlist})) {
 6765:             my $match = 0;
 6766:             my $secmatch = 0;
 6767:             my $section = $$classlist{$student}[$idx{section}];
 6768:             my $status = $$classlist{$student}[$idx{status}];
 6769:             if ($section eq '') {
 6770:                 $section = 'none';
 6771:             }
 6772:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6773:                 if (grep(/^all$/,@{$sections})) {
 6774:                     $secmatch = 1;
 6775:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6776:                     if (grep(/^none$/,@{$sections})) {
 6777:                         $secmatch = 1;
 6778:                     }
 6779:                 } else {  
 6780: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6781: 		        $secmatch = 1;
 6782:                     }
 6783: 		}
 6784:                 if (!$secmatch) {
 6785:                     next;
 6786:                 }
 6787:             }
 6788:             if (defined($$types{'active'})) {
 6789:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6790:                     push(@{$$users{st}{$student}},'active');
 6791:                     $match = 1;
 6792:                 }
 6793:             }
 6794:             if (defined($$types{'previous'})) {
 6795:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6796:                     push(@{$$users{st}{$student}},'previous');
 6797:                     $match = 1;
 6798:                 }
 6799:             }
 6800:             if (defined($$types{'future'})) {
 6801:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6802:                     push(@{$$users{st}{$student}},'future');
 6803:                     $match = 1;
 6804:                 }
 6805:             }
 6806:             if ($match) {
 6807:                 push(@{$seclists{$student}},$section);
 6808:                 if (ref($userdata) eq 'HASH') {
 6809:                     $$userdata{$student} = $$classlist{$student};
 6810:                 }
 6811:                 if (ref($statushash) eq 'HASH') {
 6812:                     $statushash->{$student}{'st'}{$section} = $status;
 6813:                 }
 6814:             }
 6815:         }
 6816:     }
 6817:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6818:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6819:         my $now = time;
 6820:         my %displaystatus = ( previous => 'Expired',
 6821:                               active   => 'Active',
 6822:                               future   => 'Future',
 6823:                             );
 6824:         my %nothide;
 6825:         if ($hidepriv) {
 6826:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6827:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6828:                 if ($user !~ /:/) {
 6829:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6830:                 } else {
 6831:                     $nothide{$user} = 1;
 6832:                 }
 6833:             }
 6834:         }
 6835:         foreach my $person (sort(keys(%coursepersonnel))) {
 6836:             my $match = 0;
 6837:             my $secmatch = 0;
 6838:             my $status;
 6839:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6840:             $user =~ s/:$//;
 6841:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6842:             if ($end == -1 || $start == -1) {
 6843:                 next;
 6844:             }
 6845:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6846:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6847:                 my ($uname,$udom) = split(/:/,$user);
 6848:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6849:                     if (grep(/^all$/,@{$sections})) {
 6850:                         $secmatch = 1;
 6851:                     } elsif ($usec eq '') {
 6852:                         if (grep(/^none$/,@{$sections})) {
 6853:                             $secmatch = 1;
 6854:                         }
 6855:                     } else {
 6856:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6857:                             $secmatch = 1;
 6858:                         }
 6859:                     }
 6860:                     if (!$secmatch) {
 6861:                         next;
 6862:                     }
 6863:                 }
 6864:                 if ($usec eq '') {
 6865:                     $usec = 'none';
 6866:                 }
 6867:                 if ($uname ne '' && $udom ne '') {
 6868:                     if ($hidepriv) {
 6869:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6870:                             (!$nothide{$uname.':'.$udom})) {
 6871:                             next;
 6872:                         }
 6873:                     }
 6874:                     if ($end > 0 && $end < $now) {
 6875:                         $status = 'previous';
 6876:                     } elsif ($start > $now) {
 6877:                         $status = 'future';
 6878:                     } else {
 6879:                         $status = 'active';
 6880:                     }
 6881:                     foreach my $type (keys(%{$types})) { 
 6882:                         if ($status eq $type) {
 6883:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6884:                                 push(@{$$users{$role}{$user}},$type);
 6885:                             }
 6886:                             $match = 1;
 6887:                         }
 6888:                     }
 6889:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6890:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6891: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6892:                         }
 6893:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6894:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6895:                         }
 6896:                         if (ref($statushash) eq 'HASH') {
 6897:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6898:                         }
 6899:                     }
 6900:                 }
 6901:             }
 6902:         }
 6903:         if (grep(/^ow$/,@{$roles})) {
 6904:             if ((defined($cdom)) && (defined($cnum))) {
 6905:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6906:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6907:                     my $owner = $csettings{'internal.courseowner'};
 6908:                     next if ($owner eq '');
 6909:                     my ($ownername,$ownerdom);
 6910:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6911:                         $ownername = $1;
 6912:                         $ownerdom = $2;
 6913:                     } else {
 6914:                         $ownername = $owner;
 6915:                         $ownerdom = $cdom;
 6916:                         $owner = $ownername.':'.$ownerdom;
 6917:                     }
 6918:                     @{$$users{'ow'}{$owner}} = 'any';
 6919:                     if (defined($userdata) && 
 6920: 			!exists($$userdata{$owner})) {
 6921: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6922:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6923:                             push(@{$seclists{$owner}},'none');
 6924:                         }
 6925:                         if (ref($statushash) eq 'HASH') {
 6926:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6927:                         }
 6928: 		    }
 6929:                 }
 6930:             }
 6931:         }
 6932:         foreach my $user (keys(%seclists)) {
 6933:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6934:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6935:         }
 6936:     }
 6937:     return;
 6938: }
 6939: 
 6940: sub get_user_info {
 6941:     my ($udom,$uname,$idx,$userdata) = @_;
 6942:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6943: 	&plainname($uname,$udom,'lastname');
 6944:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6945:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6946:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6947:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6948:     return;
 6949: }
 6950: 
 6951: ###############################################
 6952: 
 6953: =pod
 6954: 
 6955: =item * &get_user_quota()
 6956: 
 6957: Retrieves quota assigned for storage of portfolio files for a user  
 6958: 
 6959: Incoming parameters:
 6960: 1. user's username
 6961: 2. user's domain
 6962: 
 6963: Returns:
 6964: 1. Disk quota (in Mb) assigned to student.
 6965: 2. (Optional) Type of setting: custom or default
 6966:    (individually assigned or default for user's 
 6967:    institutional status).
 6968: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6969:    or student - types as defined in localenroll::inst_usertypes 
 6970:    for user's domain, which determines default quota for user.
 6971: 4. (Optional) - Default quota which would apply to the user.
 6972: 
 6973: If a value has been stored in the user's environment, 
 6974: it will return that, otherwise it returns the maximal default
 6975: defined for the user's instituional status(es) in the domain.
 6976: 
 6977: =cut
 6978: 
 6979: ###############################################
 6980: 
 6981: 
 6982: sub get_user_quota {
 6983:     my ($uname,$udom) = @_;
 6984:     my ($quota,$quotatype,$settingstatus,$defquota);
 6985:     if (!defined($udom)) {
 6986:         $udom = $env{'user.domain'};
 6987:     }
 6988:     if (!defined($uname)) {
 6989:         $uname = $env{'user.name'};
 6990:     }
 6991:     if (($udom eq '' || $uname eq '') ||
 6992:         ($udom eq 'public') && ($uname eq 'public')) {
 6993:         $quota = 0;
 6994:         $quotatype = 'default';
 6995:         $defquota = 0; 
 6996:     } else {
 6997:         my $inststatus;
 6998:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6999:             $quota = $env{'environment.portfolioquota'};
 7000:             $inststatus = $env{'environment.inststatus'};
 7001:         } else {
 7002:             my %userenv = 
 7003:                 &Apache::lonnet::get('environment',['portfolioquota',
 7004:                                      'inststatus'],$udom,$uname);
 7005:             my ($tmp) = keys(%userenv);
 7006:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7007:                 $quota = $userenv{'portfolioquota'};
 7008:                 $inststatus = $userenv{'inststatus'};
 7009:             } else {
 7010:                 undef(%userenv);
 7011:             }
 7012:         }
 7013:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7014:         if ($quota eq '') {
 7015:             $quota = $defquota;
 7016:             $quotatype = 'default';
 7017:         } else {
 7018:             $quotatype = 'custom';
 7019:         }
 7020:     }
 7021:     if (wantarray) {
 7022:         return ($quota,$quotatype,$settingstatus,$defquota);
 7023:     } else {
 7024:         return $quota;
 7025:     }
 7026: }
 7027: 
 7028: ###############################################
 7029: 
 7030: =pod
 7031: 
 7032: =item * &default_quota()
 7033: 
 7034: Retrieves default quota assigned for storage of user portfolio files,
 7035: given an (optional) user's institutional status.
 7036: 
 7037: Incoming parameters:
 7038: 1. domain
 7039: 2. (Optional) institutional status(es).  This is a : separated list of 
 7040:    status types (e.g., faculty, staff, student etc.)
 7041:    which apply to the user for whom the default is being retrieved.
 7042:    If the institutional status string in undefined, the domain
 7043:    default quota will be returned. 
 7044: 
 7045: Returns:
 7046: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7047: 2. (Optional) institutional type which determined the value of the
 7048:    default quota.
 7049: 
 7050: If a value has been stored in the domain's configuration db,
 7051: it will return that, otherwise it returns 20 (for backwards 
 7052: compatibility with domains which have not set up a configuration
 7053: db file; the original statically defined portfolio quota was 20 Mb). 
 7054: 
 7055: If the user's status includes multiple types (e.g., staff and student),
 7056: the largest default quota which applies to the user determines the
 7057: default quota returned.
 7058: 
 7059: =back
 7060: 
 7061: =cut
 7062: 
 7063: ###############################################
 7064: 
 7065: 
 7066: sub default_quota {
 7067:     my ($udom,$inststatus) = @_;
 7068:     my ($defquota,$settingstatus);
 7069:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7070:                                             ['quotas'],$udom);
 7071:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7072:         if ($inststatus ne '') {
 7073:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7074:             foreach my $item (@statuses) {
 7075:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7076:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7077:                         if ($defquota eq '') {
 7078:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7079:                             $settingstatus = $item;
 7080:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7081:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7082:                             $settingstatus = $item;
 7083:                         }
 7084:                     }
 7085:                 } else {
 7086:                     if ($quotahash{'quotas'}{$item} ne '') {
 7087:                         if ($defquota eq '') {
 7088:                             $defquota = $quotahash{'quotas'}{$item};
 7089:                             $settingstatus = $item;
 7090:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7091:                             $defquota = $quotahash{'quotas'}{$item};
 7092:                             $settingstatus = $item;
 7093:                         }
 7094:                     }
 7095:                 }
 7096:             }
 7097:         }
 7098:         if ($defquota eq '') {
 7099:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7100:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7101:             } else {
 7102:                 $defquota = $quotahash{'quotas'}{'default'};
 7103:             }
 7104:             $settingstatus = 'default';
 7105:         }
 7106:     } else {
 7107:         $settingstatus = 'default';
 7108:         $defquota = 20;
 7109:     }
 7110:     if (wantarray) {
 7111:         return ($defquota,$settingstatus);
 7112:     } else {
 7113:         return $defquota;
 7114:     }
 7115: }
 7116: 
 7117: sub get_secgrprole_info {
 7118:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7119:     my %sections_count = &get_sections($cdom,$cnum);
 7120:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7121:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7122:     my @groups = sort(keys(%curr_groups));
 7123:     my $allroles = [];
 7124:     my $rolehash;
 7125:     my $accesshash = {
 7126:                      active => 'Currently has access',
 7127:                      future => 'Will have future access',
 7128:                      previous => 'Previously had access',
 7129:                   };
 7130:     if ($needroles) {
 7131:         $rolehash = {'all' => 'all'};
 7132:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7133: 	if (&Apache::lonnet::error(%user_roles)) {
 7134: 	    undef(%user_roles);
 7135: 	}
 7136:         foreach my $item (keys(%user_roles)) {
 7137:             my ($role)=split(/\:/,$item,2);
 7138:             if ($role eq 'cr') { next; }
 7139:             if ($role =~ /^cr/) {
 7140:                 $$rolehash{$role} = (split('/',$role))[3];
 7141:             } else {
 7142:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7143:             }
 7144:         }
 7145:         foreach my $key (sort(keys(%{$rolehash}))) {
 7146:             push(@{$allroles},$key);
 7147:         }
 7148:         push (@{$allroles},'st');
 7149:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7150:     }
 7151:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7152: }
 7153: 
 7154: sub user_picker {
 7155:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7156:     my $currdom = $dom;
 7157:     my %curr_selected = (
 7158:                         srchin => 'dom',
 7159:                         srchby => 'lastname',
 7160:                       );
 7161:     my $srchterm;
 7162:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7163:         if ($srch->{'srchby'} ne '') {
 7164:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7165:         }
 7166:         if ($srch->{'srchin'} ne '') {
 7167:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7168:         }
 7169:         if ($srch->{'srchtype'} ne '') {
 7170:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7171:         }
 7172:         if ($srch->{'srchdomain'} ne '') {
 7173:             $currdom = $srch->{'srchdomain'};
 7174:         }
 7175:         $srchterm = $srch->{'srchterm'};
 7176:     }
 7177:     my %lt=&Apache::lonlocal::texthash(
 7178:                     'usr'       => 'Search criteria',
 7179:                     'doma'      => 'Domain/institution to search',
 7180:                     'uname'     => 'username',
 7181:                     'lastname'  => 'last name',
 7182:                     'lastfirst' => 'last name, first name',
 7183:                     'crs'       => 'in this course',
 7184:                     'dom'       => 'in selected LON-CAPA domain', 
 7185:                     'alc'       => 'all LON-CAPA',
 7186:                     'instd'     => 'in institutional directory for selected domain',
 7187:                     'exact'     => 'is',
 7188:                     'contains'  => 'contains',
 7189:                     'begins'    => 'begins with',
 7190:                     'youm'      => "You must include some text to search for.",
 7191:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7192:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7193:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7194:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7195:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7196:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7197:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7198:                                        );
 7199:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7200:     my $srchinsel = ' <select name="srchin">';
 7201: 
 7202:     my @srchins = ('crs','dom','alc','instd');
 7203: 
 7204:     foreach my $option (@srchins) {
 7205:         # FIXME 'alc' option unavailable until 
 7206:         #       loncreateuser::print_user_query_page()
 7207:         #       has been completed.
 7208:         next if ($option eq 'alc');
 7209:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7210:         if ($curr_selected{'srchin'} eq $option) {
 7211:             $srchinsel .= ' 
 7212:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7213:         } else {
 7214:             $srchinsel .= '
 7215:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7216:         }
 7217:     }
 7218:     $srchinsel .= "\n  </select>\n";
 7219: 
 7220:     my $srchbysel =  ' <select name="srchby">';
 7221:     foreach my $option ('lastname','lastfirst','uname') {
 7222:         if ($curr_selected{'srchby'} eq $option) {
 7223:             $srchbysel .= '
 7224:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7225:         } else {
 7226:             $srchbysel .= '
 7227:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7228:          }
 7229:     }
 7230:     $srchbysel .= "\n  </select>\n";
 7231: 
 7232:     my $srchtypesel = ' <select name="srchtype">';
 7233:     foreach my $option ('begins','contains','exact') {
 7234:         if ($curr_selected{'srchtype'} eq $option) {
 7235:             $srchtypesel .= '
 7236:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7237:         } else {
 7238:             $srchtypesel .= '
 7239:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7240:         }
 7241:     }
 7242:     $srchtypesel .= "\n  </select>\n";
 7243: 
 7244:     my ($newuserscript,$new_user_create);
 7245: 
 7246:     if ($forcenewuser) {
 7247:         if (ref($srch) eq 'HASH') {
 7248:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7249:                 if ($cancreate) {
 7250:                     $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>';
 7251:                 } else {
 7252:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7253:                     my %usertypetext = (
 7254:                         official   => 'institutional',
 7255:                         unofficial => 'non-institutional',
 7256:                     );
 7257:                     $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
 7258:                 }
 7259:             }
 7260:         }
 7261: 
 7262:         $newuserscript = <<"ENDSCRIPT";
 7263: 
 7264: function setSearch(createnew,callingForm) {
 7265:     if (createnew == 1) {
 7266:         for (var i=0; i<callingForm.srchby.length; i++) {
 7267:             if (callingForm.srchby.options[i].value == 'uname') {
 7268:                 callingForm.srchby.selectedIndex = i;
 7269:             }
 7270:         }
 7271:         for (var i=0; i<callingForm.srchin.length; i++) {
 7272:             if ( callingForm.srchin.options[i].value == 'dom') {
 7273: 		callingForm.srchin.selectedIndex = i;
 7274:             }
 7275:         }
 7276:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7277:             if (callingForm.srchtype.options[i].value == 'exact') {
 7278:                 callingForm.srchtype.selectedIndex = i;
 7279:             }
 7280:         }
 7281:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7282:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7283:                 callingForm.srchdomain.selectedIndex = i;
 7284:             }
 7285:         }
 7286:     }
 7287: }
 7288: ENDSCRIPT
 7289: 
 7290:     }
 7291: 
 7292:     my $output = <<"END_BLOCK";
 7293: <script type="text/javascript">
 7294: function validateEntry(callingForm) {
 7295: 
 7296:     var checkok = 1;
 7297:     var srchin;
 7298:     for (var i=0; i<callingForm.srchin.length; i++) {
 7299: 	if ( callingForm.srchin[i].checked ) {
 7300: 	    srchin = callingForm.srchin[i].value;
 7301: 	}
 7302:     }
 7303: 
 7304:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7305:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7306:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7307:     var srchterm =  callingForm.srchterm.value;
 7308:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7309:     var msg = "";
 7310: 
 7311:     if (srchterm == "") {
 7312:         checkok = 0;
 7313:         msg += "$lt{'youm'}\\n";
 7314:     }
 7315: 
 7316:     if (srchtype== 'begins') {
 7317:         if (srchterm.length < 2) {
 7318:             checkok = 0;
 7319:             msg += "$lt{'thte'}\\n";
 7320:         }
 7321:     }
 7322: 
 7323:     if (srchtype== 'contains') {
 7324:         if (srchterm.length < 3) {
 7325:             checkok = 0;
 7326:             msg += "$lt{'thet'}\\n";
 7327:         }
 7328:     }
 7329:     if (srchin == 'instd') {
 7330:         if (srchdomain == '') {
 7331:             checkok = 0;
 7332:             msg += "$lt{'yomc'}\\n";
 7333:         }
 7334:     }
 7335:     if (srchin == 'dom') {
 7336:         if (srchdomain == '') {
 7337:             checkok = 0;
 7338:             msg += "$lt{'ymcd'}\\n";
 7339:         }
 7340:     }
 7341:     if (srchby == 'lastfirst') {
 7342:         if (srchterm.indexOf(",") == -1) {
 7343:             checkok = 0;
 7344:             msg += "$lt{'whus'}\\n";
 7345:         }
 7346:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7347:             checkok = 0;
 7348:             msg += "$lt{'whse'}\\n";
 7349:         }
 7350:     }
 7351:     if (checkok == 0) {
 7352:         alert("$lt{'thfo'}\\n"+msg);
 7353:         return;
 7354:     }
 7355:     if (checkok == 1) {
 7356:         callingForm.submit();
 7357:     }
 7358: }
 7359: 
 7360: $newuserscript
 7361: 
 7362: </script>
 7363: 
 7364: $new_user_create
 7365: 
 7366: <table>
 7367:  <tr>
 7368:   <td>$lt{'doma'}:</td>
 7369:   <td>$domform</td>
 7370:   </td>
 7371:  </tr>
 7372:  <tr>
 7373:   <td>$lt{'usr'}:</td>
 7374:   <td>$srchbysel
 7375:       $srchtypesel 
 7376:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7377:       $srchinsel 
 7378:   </td>
 7379:  </tr>
 7380: </table>
 7381: <br />
 7382: END_BLOCK
 7383: 
 7384:     return $output;
 7385: }
 7386: 
 7387: sub user_rule_check {
 7388:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7389:     my $response;
 7390:     if (ref($usershash) eq 'HASH') {
 7391:         foreach my $user (keys(%{$usershash})) {
 7392:             my ($uname,$udom) = split(/:/,$user);
 7393:             next if ($udom eq '' || $uname eq '');
 7394:             my ($id,$newuser);
 7395:             if (ref($usershash->{$user}) eq 'HASH') {
 7396:                 $newuser = $usershash->{$user}->{'newuser'};
 7397:                 $id = $usershash->{$user}->{'id'};
 7398:             }
 7399:             my $inst_response;
 7400:             if (ref($checks) eq 'HASH') {
 7401:                 if (defined($checks->{'username'})) {
 7402:                     ($inst_response,%{$inst_results->{$user}}) = 
 7403:                         &Apache::lonnet::get_instuser($udom,$uname);
 7404:                 } elsif (defined($checks->{'id'})) {
 7405:                     ($inst_response,%{$inst_results->{$user}}) =
 7406:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7407:                 }
 7408:             } else {
 7409:                 ($inst_response,%{$inst_results->{$user}}) =
 7410:                     &Apache::lonnet::get_instuser($udom,$uname);
 7411:                 return;
 7412:             }
 7413:             if (!$got_rules->{$udom}) {
 7414:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7415:                                                   ['usercreation'],$udom);
 7416:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7417:                     foreach my $item ('username','id') {
 7418:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7419:                             $$curr_rules{$udom}{$item} = 
 7420:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7421:                         }
 7422:                     }
 7423:                 }
 7424:                 $got_rules->{$udom} = 1;  
 7425:             }
 7426:             foreach my $item (keys(%{$checks})) {
 7427:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7428:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7429:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7430:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7431:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7432:                                 if ($rule_check{$rule}) {
 7433:                                     $$rulematch{$user}{$item} = $rule;
 7434:                                     if ($inst_response eq 'ok') {
 7435:                                         if (ref($inst_results) eq 'HASH') {
 7436:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7437:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7438:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7439:                                                 }
 7440:                                             }
 7441:                                         }
 7442:                                     }
 7443:                                     last;
 7444:                                 }
 7445:                             }
 7446:                         }
 7447:                     }
 7448:                 }
 7449:             }
 7450:         }
 7451:     }
 7452:     return;
 7453: }
 7454: 
 7455: sub user_rule_formats {
 7456:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7457:     my %text = ( 
 7458:                  'username' => 'Usernames',
 7459:                  'id'       => 'IDs',
 7460:                );
 7461:     my $output;
 7462:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7463:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7464:         if (@{$ruleorder} > 0) {
 7465:             $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>';
 7466:             foreach my $rule (@{$ruleorder}) {
 7467:                 if (ref($curr_rules) eq 'ARRAY') {
 7468:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7469:                         if (ref($rules->{$rule}) eq 'HASH') {
 7470:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7471:                                         $rules->{$rule}{'desc'}.'</li>';
 7472:                         }
 7473:                     }
 7474:                 }
 7475:             }
 7476:             $output .= '</ul>';
 7477:         }
 7478:     }
 7479:     return $output;
 7480: }
 7481: 
 7482: sub instrule_disallow_msg {
 7483:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7484:     my $response;
 7485:     my %text = (
 7486:                   item   => 'username',
 7487:                   items  => 'usernames',
 7488:                   match  => 'matches',
 7489:                   do     => 'does',
 7490:                   action => 'a username',
 7491:                   one    => 'one',
 7492:                );
 7493:     if ($count > 1) {
 7494:         $text{'item'} = 'usernames';
 7495:         $text{'match'} ='match';
 7496:         $text{'do'} = 'do';
 7497:         $text{'action'} = 'usernames',
 7498:         $text{'one'} = 'ones';
 7499:     }
 7500:     if ($checkitem eq 'id') {
 7501:         $text{'items'} = 'IDs';
 7502:         $text{'item'} = 'ID';
 7503:         $text{'action'} = 'an ID';
 7504:         if ($count > 1) {
 7505:             $text{'item'} = 'IDs';
 7506:             $text{'action'} = 'IDs';
 7507:         }
 7508:     }
 7509:     $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 />';
 7510:     if ($mode eq 'upload') {
 7511:         if ($checkitem eq 'username') {
 7512:             $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'}.");
 7513:         } elsif ($checkitem eq 'id') {
 7514:             $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.");
 7515:         }
 7516:     } elsif ($mode eq 'selfcreate') {
 7517:         if ($checkitem eq 'id') {
 7518:             $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.");
 7519:         }
 7520:     } else {
 7521:         if ($checkitem eq 'username') {
 7522:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7523:         } elsif ($checkitem eq 'id') {
 7524:             $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.");
 7525:         }
 7526:     }
 7527:     return $response;
 7528: }
 7529: 
 7530: sub personal_data_fieldtitles {
 7531:     my %fieldtitles = &Apache::lonlocal::texthash (
 7532:                         id => 'Student/Employee ID',
 7533:                         permanentemail => 'E-mail address',
 7534:                         lastname => 'Last Name',
 7535:                         firstname => 'First Name',
 7536:                         middlename => 'Middle Name',
 7537:                         generation => 'Generation',
 7538:                         gen => 'Generation',
 7539:                         inststatus => 'Affiliation',
 7540:                    );
 7541:     return %fieldtitles;
 7542: }
 7543: 
 7544: sub sorted_inst_types {
 7545:     my ($dom) = @_;
 7546:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7547:     my $othertitle = &mt('All users');
 7548:     if ($env{'request.course.id'}) {
 7549:         $othertitle  = &mt('Any users');
 7550:     }
 7551:     my @types;
 7552:     if (ref($order) eq 'ARRAY') {
 7553:         @types = @{$order};
 7554:     }
 7555:     if (@types == 0) {
 7556:         if (ref($usertypes) eq 'HASH') {
 7557:             @types = sort(keys(%{$usertypes}));
 7558:         }
 7559:     }
 7560:     if (keys(%{$usertypes}) > 0) {
 7561:         $othertitle = &mt('Other users');
 7562:     }
 7563:     return ($othertitle,$usertypes,\@types);
 7564: }
 7565: 
 7566: sub get_institutional_codes {
 7567:     my ($settings,$allcourses,$LC_code) = @_;
 7568: # Get complete list of course sections to update
 7569:     my @currsections = ();
 7570:     my @currxlists = ();
 7571:     my $coursecode = $$settings{'internal.coursecode'};
 7572: 
 7573:     if ($$settings{'internal.sectionnums'} ne '') {
 7574:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7575:     }
 7576: 
 7577:     if ($$settings{'internal.crosslistings'} ne '') {
 7578:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7579:     }
 7580: 
 7581:     if (@currxlists > 0) {
 7582:         foreach (@currxlists) {
 7583:             if (m/^([^:]+):(\w*)$/) {
 7584:                 unless (grep/^$1$/,@{$allcourses}) {
 7585:                     push @{$allcourses},$1;
 7586:                     $$LC_code{$1} = $2;
 7587:                 }
 7588:             }
 7589:         }
 7590:     }
 7591:  
 7592:     if (@currsections > 0) {
 7593:         foreach (@currsections) {
 7594:             if (m/^(\w+):(\w*)$/) {
 7595:                 my $sec = $coursecode.$1;
 7596:                 my $lc_sec = $2;
 7597:                 unless (grep/^$sec$/,@{$allcourses}) {
 7598:                     push @{$allcourses},$sec;
 7599:                     $$LC_code{$sec} = $lc_sec;
 7600:                 }
 7601:             }
 7602:         }
 7603:     }
 7604:     return;
 7605: }
 7606: 
 7607: =pod
 7608: 
 7609: =head1 Slot Helpers
 7610: 
 7611: =over 4
 7612: 
 7613: =item * sorted_slots()
 7614: 
 7615: Sorts an array of slot names in order of slot start time (earliest first). 
 7616: 
 7617: Inputs:
 7618: 
 7619: =over 4
 7620: 
 7621: slotsarr  - Reference to array of unsorted slot names.
 7622: 
 7623: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7624: 
 7625: =back
 7626: 
 7627: Returns:
 7628: 
 7629: =over 4
 7630: 
 7631: sorted   - An array of slot names sorted by the start time of the slot.
 7632: 
 7633: =back
 7634: 
 7635: =back
 7636: 
 7637: =cut
 7638: 
 7639: 
 7640: sub sorted_slots {
 7641:     my ($slotsarr,$slots) = @_;
 7642:     my @sorted;
 7643:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7644:         @sorted =
 7645:             sort {
 7646:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7647:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7648:                      }
 7649:                      if (ref($slots->{$a})) { return -1;}
 7650:                      if (ref($slots->{$b})) { return 1;}
 7651:                      return 0;
 7652:                  } @{$slotsarr};
 7653:     }
 7654:     return @sorted;
 7655: }
 7656: 
 7657: 
 7658: =pod
 7659: 
 7660: =head1 HTTP Helpers
 7661: 
 7662: =over 4
 7663: 
 7664: =item * &get_unprocessed_cgi($query,$possible_names)
 7665: 
 7666: Modify the %env hash to contain unprocessed CGI form parameters held in
 7667: $query.  The parameters listed in $possible_names (an array reference),
 7668: will be set in $env{'form.name'} if they do not already exist.
 7669: 
 7670: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7671: $possible_names is an ref to an array of form element names.  As an example:
 7672: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7673: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7674: 
 7675: =cut
 7676: 
 7677: sub get_unprocessed_cgi {
 7678:   my ($query,$possible_names)= @_;
 7679:   # $Apache::lonxml::debug=1;
 7680:   foreach my $pair (split(/&/,$query)) {
 7681:     my ($name, $value) = split(/=/,$pair);
 7682:     $name = &unescape($name);
 7683:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7684:       $value =~ tr/+/ /;
 7685:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7686:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7687:     }
 7688:   }
 7689: }
 7690: 
 7691: =pod
 7692: 
 7693: =item * &cacheheader() 
 7694: 
 7695: returns cache-controlling header code
 7696: 
 7697: =cut
 7698: 
 7699: sub cacheheader {
 7700:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7701:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7702:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7703:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7704:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7705:     return $output;
 7706: }
 7707: 
 7708: =pod
 7709: 
 7710: =item * &no_cache($r) 
 7711: 
 7712: specifies header code to not have cache
 7713: 
 7714: =cut
 7715: 
 7716: sub no_cache {
 7717:     my ($r) = @_;
 7718:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7719: 	$env{'request.method'} ne 'GET') { return ''; }
 7720:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7721:     $r->no_cache(1);
 7722:     $r->header_out("Expires" => $date);
 7723:     $r->header_out("Pragma" => "no-cache");
 7724: }
 7725: 
 7726: sub content_type {
 7727:     my ($r,$type,$charset) = @_;
 7728:     if ($r) {
 7729: 	#  Note that printout.pl calls this with undef for $r.
 7730: 	&no_cache($r);
 7731:     }
 7732:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7733:     unless ($charset) {
 7734: 	$charset=&Apache::lonlocal::current_encoding;
 7735:     }
 7736:     if ($charset) { $type.='; charset='.$charset; }
 7737:     if ($r) {
 7738: 	$r->content_type($type);
 7739:     } else {
 7740: 	print("Content-type: $type\n\n");
 7741:     }
 7742: }
 7743: 
 7744: =pod
 7745: 
 7746: =item * &add_to_env($name,$value) 
 7747: 
 7748: adds $name to the %env hash with value
 7749: $value, if $name already exists, the entry is converted to an array
 7750: reference and $value is added to the array.
 7751: 
 7752: =cut
 7753: 
 7754: sub add_to_env {
 7755:   my ($name,$value)=@_;
 7756:   if (defined($env{$name})) {
 7757:     if (ref($env{$name})) {
 7758:       #already have multiple values
 7759:       push(@{ $env{$name} },$value);
 7760:     } else {
 7761:       #first time seeing multiple values, convert hash entry to an arrayref
 7762:       my $first=$env{$name};
 7763:       undef($env{$name});
 7764:       push(@{ $env{$name} },$first,$value);
 7765:     }
 7766:   } else {
 7767:     $env{$name}=$value;
 7768:   }
 7769: }
 7770: 
 7771: =pod
 7772: 
 7773: =item * &get_env_multiple($name) 
 7774: 
 7775: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7776: values may be defined and end up as an array ref.
 7777: 
 7778: returns an array of values
 7779: 
 7780: =cut
 7781: 
 7782: sub get_env_multiple {
 7783:     my ($name) = @_;
 7784:     my @values;
 7785:     if (defined($env{$name})) {
 7786:         # exists is it an array
 7787:         if (ref($env{$name})) {
 7788:             @values=@{ $env{$name} };
 7789:         } else {
 7790:             $values[0]=$env{$name};
 7791:         }
 7792:     }
 7793:     return(@values);
 7794: }
 7795: 
 7796: sub ask_for_embedded_content {
 7797:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7798:     my $upload_output = '
 7799:    <form name="upload_embedded" action="'.$actionurl.'"
 7800:                   method="post" enctype="multipart/form-data">';
 7801:     $upload_output .= $state;
 7802:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7803: 
 7804:     my $num = 0;
 7805:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7806:         $upload_output .= &start_data_table_row().
 7807:             '<td>'.$embed_file.'</td><td>';
 7808:         if ($args->{'ignore_remote_references'}
 7809:             && $embed_file =~ m{^\w+://}) {
 7810:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7811:         } elsif ($args->{'error_on_invalid_names'}
 7812:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7813: 
 7814:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7815: 
 7816:         } else {
 7817:             $upload_output .='
 7818:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7819:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7820:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7821:             $upload_output .=
 7822:                 "\n\t\t".
 7823:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7824:                 $attrib.'" />';
 7825:             if (exists($$codebase{$embed_file})) {
 7826:                 $upload_output .=
 7827:                     "\n\t\t".
 7828:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7829:                     &escape($$codebase{$embed_file}).'" />';
 7830:             }
 7831:         }
 7832:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7833:         $num++;
 7834:     }
 7835:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7836:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7837:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7838:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7839:    </form>';
 7840:     return $upload_output;
 7841: }
 7842: 
 7843: sub upload_embedded {
 7844:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7845:         $current_disk_usage) = @_;
 7846:     my $output;
 7847:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7848:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7849:         my $orig_uploaded_filename =
 7850:             $env{'form.embedded_item_'.$i.'.filename'};
 7851: 
 7852:         $env{'form.embedded_orig_'.$i} =
 7853:             &unescape($env{'form.embedded_orig_'.$i});
 7854:         my ($path,$fname) =
 7855:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7856:         # no path, whole string is fname
 7857:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7858: 
 7859:         $path = $env{'form.currentpath'}.$path;
 7860:         $fname = &Apache::lonnet::clean_filename($fname);
 7861:         # See if there is anything left
 7862:         next if ($fname eq '');
 7863: 
 7864:         # Check if file already exists as a file or directory.
 7865:         my ($state,$msg);
 7866:         if ($context eq 'portfolio') {
 7867:             my $port_path = $dirpath;
 7868:             if ($group ne '') {
 7869:                 $port_path = "groups/$group/$port_path";
 7870:             }
 7871:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7872:                                               $dir_root,$port_path,$disk_quota,
 7873:                                               $current_disk_usage,$uname,$udom);
 7874:             if ($state eq 'will_exceed_quota'
 7875:                 || $state eq 'file_locked'
 7876:                 || $state eq 'file_exists' ) {
 7877:                 $output .= $msg;
 7878:                 next;
 7879:             }
 7880:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7881:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7882:             if ($state eq 'exists') {
 7883:                 $output .= $msg;
 7884:                 next;
 7885:             }
 7886:         }
 7887:         # Check if extension is valid
 7888:         if (($fname =~ /\.(\w+)$/) &&
 7889:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7890:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7891:             next;
 7892:         } elsif (($fname =~ /\.(\w+)$/) &&
 7893:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7894:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7895:             next;
 7896:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7897:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7898:             next;
 7899:         }
 7900: 
 7901:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7902:         if ($context eq 'portfolio') {
 7903:             my $result=
 7904:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7905:                                                 $dirpath.$path);
 7906:             if ($result !~ m|^/uploaded/|) {
 7907:                 $output .= '<span class="LC_error">'
 7908:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7909:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7910:                       .'</span><br />';
 7911:                 next;
 7912:             } else {
 7913:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7914:                            $path.$fname.'</span>').'</p>';     
 7915:             }
 7916:         } else {
 7917: # Save the file
 7918:             my $target = $env{'form.embedded_item_'.$i};
 7919:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7920:             my $dest = $fullpath.$fname;
 7921:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7922:             my @parts=split(/\//,$fullpath);
 7923:             my $count;
 7924:             my $filepath = $dir_root;
 7925:             for ($count=4;$count<=$#parts;$count++) {
 7926:                 $filepath .= "/$parts[$count]";
 7927:                 if ((-e $filepath)!=1) {
 7928:                     mkdir($filepath,0770);
 7929:                 }
 7930:             }
 7931:             my $fh;
 7932:             if (!open($fh,'>'.$dest)) {
 7933:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7934:                 $output .= '<span class="LC_error">'.
 7935:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7936:                            '</span><br />';
 7937:             } else {
 7938:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7939:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7940:                     $output .= '<span class="LC_error">'.
 7941:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7942:                               '</span><br />';
 7943:                 } else {
 7944:                     if ($context eq 'testbank') {
 7945:                         $output .= &mt('Embedded file uploaded successfully:').
 7946:                                    '&nbsp;<a href="'.$url.'">'.
 7947:                                    $orig_uploaded_filename.'</a><br />';
 7948:                     } else {
 7949:                         $output .= '<span class=\"LC_fontsize_large\">'.
 7950:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7951:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 7952:                     }
 7953:                 }
 7954:                 close($fh);
 7955:             }
 7956:         }
 7957:     }
 7958:     return $output;
 7959: }
 7960: 
 7961: sub check_for_existing {
 7962:     my ($path,$fname,$element) = @_;
 7963:     my ($state,$msg);
 7964:     if (-d $path.'/'.$fname) {
 7965:         $state = 'exists';
 7966:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7967:     } elsif (-e $path.'/'.$fname) {
 7968:         $state = 'exists';
 7969:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7970:     }
 7971:     if ($state eq 'exists') {
 7972:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7973:     }
 7974:     return ($state,$msg);
 7975: }
 7976: 
 7977: sub check_for_upload {
 7978:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7979:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7980:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7981:     my $getpropath = 1;
 7982:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7983:                                             $getpropath);
 7984:     my $found_file = 0;
 7985:     my $locked_file = 0;
 7986:     foreach my $line (@dir_list) {
 7987:         my ($file_name)=split(/\&/,$line,2);
 7988:         if ($file_name eq $fname){
 7989:             $file_name = $path.$file_name;
 7990:             if ($group ne '') {
 7991:                 $file_name = $group.$file_name;
 7992:             }
 7993:             $found_file = 1;
 7994:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7995:                 $locked_file = 1;
 7996:             }
 7997:         }
 7998:     }
 7999:     if (($current_disk_usage + $filesize) > $disk_quota){
 8000:         my $msg = '<span class="LC_error">'.
 8001:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8002:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8003:         return ('will_exceed_quota',$msg);
 8004:     } elsif ($found_file) {
 8005:         if ($locked_file) {
 8006:             my $msg = '<span class="LC_error">';
 8007:             $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>');
 8008:             $msg .= '</span><br />';
 8009:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8010:             return ('file_locked',$msg);
 8011:         } else {
 8012:             my $msg = '<span class="LC_error">';
 8013:             $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'});
 8014:             $msg .= '</span>';
 8015:             $msg .= '<br />';
 8016:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8017:             return ('file_exists',$msg);
 8018:         }
 8019:     }
 8020: }
 8021: 
 8022: 
 8023: =pod
 8024: 
 8025: =back
 8026: 
 8027: =head1 CSV Upload/Handling functions
 8028: 
 8029: =over 4
 8030: 
 8031: =item * &upfile_store($r)
 8032: 
 8033: Store uploaded file, $r should be the HTTP Request object,
 8034: needs $env{'form.upfile'}
 8035: returns $datatoken to be put into hidden field
 8036: 
 8037: =cut
 8038: 
 8039: sub upfile_store {
 8040:     my $r=shift;
 8041:     $env{'form.upfile'}=~s/\r/\n/gs;
 8042:     $env{'form.upfile'}=~s/\f/\n/gs;
 8043:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8044:     $env{'form.upfile'}=~s/\n+$//gs;
 8045: 
 8046:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8047: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8048:     {
 8049:         my $datafile = $r->dir_config('lonDaemons').
 8050:                            '/tmp/'.$datatoken.'.tmp';
 8051:         if ( open(my $fh,">$datafile") ) {
 8052:             print $fh $env{'form.upfile'};
 8053:             close($fh);
 8054:         }
 8055:     }
 8056:     return $datatoken;
 8057: }
 8058: 
 8059: =pod
 8060: 
 8061: =item * &load_tmp_file($r)
 8062: 
 8063: Load uploaded file from tmp, $r should be the HTTP Request object,
 8064: needs $env{'form.datatoken'},
 8065: sets $env{'form.upfile'} to the contents of the file
 8066: 
 8067: =cut
 8068: 
 8069: sub load_tmp_file {
 8070:     my $r=shift;
 8071:     my @studentdata=();
 8072:     {
 8073:         my $studentfile = $r->dir_config('lonDaemons').
 8074:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8075:         if ( open(my $fh,"<$studentfile") ) {
 8076:             @studentdata=<$fh>;
 8077:             close($fh);
 8078:         }
 8079:     }
 8080:     $env{'form.upfile'}=join('',@studentdata);
 8081: }
 8082: 
 8083: =pod
 8084: 
 8085: =item * &upfile_record_sep()
 8086: 
 8087: Separate uploaded file into records
 8088: returns array of records,
 8089: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8090: 
 8091: =cut
 8092: 
 8093: sub upfile_record_sep {
 8094:     if ($env{'form.upfiletype'} eq 'xml') {
 8095:     } else {
 8096: 	my @records;
 8097: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8098: 	    if ($line=~/^\s*$/) { next; }
 8099: 	    push(@records,$line);
 8100: 	}
 8101: 	return @records;
 8102:     }
 8103: }
 8104: 
 8105: =pod
 8106: 
 8107: =item * &record_sep($record)
 8108: 
 8109: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8110: 
 8111: =cut
 8112: 
 8113: sub takeleft {
 8114:     my $index=shift;
 8115:     return substr('0000'.$index,-4,4);
 8116: }
 8117: 
 8118: sub record_sep {
 8119:     my $record=shift;
 8120:     my %components=();
 8121:     if ($env{'form.upfiletype'} eq 'xml') {
 8122:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8123:         my $i=0;
 8124:         foreach my $field (split(/\s+/,$record)) {
 8125:             $field=~s/^(\"|\')//;
 8126:             $field=~s/(\"|\')$//;
 8127:             $components{&takeleft($i)}=$field;
 8128:             $i++;
 8129:         }
 8130:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8131:         my $i=0;
 8132:         foreach my $field (split(/\t/,$record)) {
 8133:             $field=~s/^(\"|\')//;
 8134:             $field=~s/(\"|\')$//;
 8135:             $components{&takeleft($i)}=$field;
 8136:             $i++;
 8137:         }
 8138:     } else {
 8139:         my $separator=',';
 8140:         if ($env{'form.upfiletype'} eq 'semisv') {
 8141:             $separator=';';
 8142:         }
 8143:         my $i=0;
 8144: # the character we are looking for to indicate the end of a quote or a record 
 8145:         my $looking_for=$separator;
 8146: # do not add the characters to the fields
 8147:         my $ignore=0;
 8148: # we just encountered a separator (or the beginning of the record)
 8149:         my $just_found_separator=1;
 8150: # store the field we are working on here
 8151:         my $field='';
 8152: # work our way through all characters in record
 8153:         foreach my $character ($record=~/(.)/g) {
 8154:             if ($character eq $looking_for) {
 8155:                if ($character ne $separator) {
 8156: # Found the end of a quote, again looking for separator
 8157:                   $looking_for=$separator;
 8158:                   $ignore=1;
 8159:                } else {
 8160: # Found a separator, store away what we got
 8161:                   $components{&takeleft($i)}=$field;
 8162: 	          $i++;
 8163:                   $just_found_separator=1;
 8164:                   $ignore=0;
 8165:                   $field='';
 8166:                }
 8167:                next;
 8168:             }
 8169: # single or double quotation marks after a separator indicate beginning of a quote
 8170: # we are now looking for the end of the quote and need to ignore separators
 8171:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8172:                $looking_for=$character;
 8173:                next;
 8174:             }
 8175: # ignore would be true after we reached the end of a quote
 8176:             if ($ignore) { next; }
 8177:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8178:             $field.=$character;
 8179:             $just_found_separator=0; 
 8180:         }
 8181: # catch the very last entry, since we never encountered the separator
 8182:         $components{&takeleft($i)}=$field;
 8183:     }
 8184:     return %components;
 8185: }
 8186: 
 8187: ######################################################
 8188: ######################################################
 8189: 
 8190: =pod
 8191: 
 8192: =item * &upfile_select_html()
 8193: 
 8194: Return HTML code to select a file from the users machine and specify 
 8195: the file type.
 8196: 
 8197: =cut
 8198: 
 8199: ######################################################
 8200: ######################################################
 8201: sub upfile_select_html {
 8202:     my %Types = (
 8203:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8204:                  semisv => &mt('Semicolon separated values'),
 8205:                  space => &mt('Space separated'),
 8206:                  tab   => &mt('Tabulator separated'),
 8207: #                 xml   => &mt('HTML/XML'),
 8208:                  );
 8209:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8210:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8211:     foreach my $type (sort(keys(%Types))) {
 8212:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8213:     }
 8214:     $Str .= "</select>\n";
 8215:     return $Str;
 8216: }
 8217: 
 8218: sub get_samples {
 8219:     my ($records,$toget) = @_;
 8220:     my @samples=({});
 8221:     my $got=0;
 8222:     foreach my $rec (@$records) {
 8223: 	my %temp = &record_sep($rec);
 8224: 	if (! grep(/\S/, values(%temp))) { next; }
 8225: 	if (%temp) {
 8226: 	    $samples[$got]=\%temp;
 8227: 	    $got++;
 8228: 	    if ($got == $toget) { last; }
 8229: 	}
 8230:     }
 8231:     return \@samples;
 8232: }
 8233: 
 8234: ######################################################
 8235: ######################################################
 8236: 
 8237: =pod
 8238: 
 8239: =item * &csv_print_samples($r,$records)
 8240: 
 8241: Prints a table of sample values from each column uploaded $r is an
 8242: Apache Request ref, $records is an arrayref from
 8243: &Apache::loncommon::upfile_record_sep
 8244: 
 8245: =cut
 8246: 
 8247: ######################################################
 8248: ######################################################
 8249: sub csv_print_samples {
 8250:     my ($r,$records) = @_;
 8251:     my $samples = &get_samples($records,5);
 8252: 
 8253:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8254:               &start_data_table_header_row());
 8255:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8256:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8257:     $r->print(&end_data_table_header_row());
 8258:     foreach my $hash (@$samples) {
 8259: 	$r->print(&start_data_table_row());
 8260: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8261: 	    $r->print('<td>');
 8262: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8263: 	    $r->print('</td>');
 8264: 	}
 8265: 	$r->print(&end_data_table_row());
 8266:     }
 8267:     $r->print(&end_data_table().'<br />'."\n");
 8268: }
 8269: 
 8270: ######################################################
 8271: ######################################################
 8272: 
 8273: =pod
 8274: 
 8275: =item * &csv_print_select_table($r,$records,$d)
 8276: 
 8277: Prints a table to create associations between values and table columns.
 8278: 
 8279: $r is an Apache Request ref,
 8280: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8281: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8282: 
 8283: =cut
 8284: 
 8285: ######################################################
 8286: ######################################################
 8287: sub csv_print_select_table {
 8288:     my ($r,$records,$d) = @_;
 8289:     my $i=0;
 8290:     my $samples = &get_samples($records,1);
 8291:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8292: 	      &start_data_table().&start_data_table_header_row().
 8293:               '<th>'.&mt('Attribute').'</th>'.
 8294:               '<th>'.&mt('Column').'</th>'.
 8295:               &end_data_table_header_row()."\n");
 8296:     foreach my $array_ref (@$d) {
 8297: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8298: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8299: 
 8300: 	$r->print('<td><select name=f'.$i.
 8301: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8302: 	$r->print('<option value="none"></option>');
 8303: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8304: 	    $r->print('<option value="'.$sample.'"'.
 8305:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8306:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8307: 	}
 8308: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8309: 	$i++;
 8310:     }
 8311:     $r->print(&end_data_table());
 8312:     $i--;
 8313:     return $i;
 8314: }
 8315: 
 8316: ######################################################
 8317: ######################################################
 8318: 
 8319: =pod
 8320: 
 8321: =item * &csv_samples_select_table($r,$records,$d)
 8322: 
 8323: Prints a table of sample values from the upload and can make associate samples to internal names.
 8324: 
 8325: $r is an Apache Request ref,
 8326: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8327: $d is an array of 2 element arrays (internal name, displayed name)
 8328: 
 8329: =cut
 8330: 
 8331: ######################################################
 8332: ######################################################
 8333: sub csv_samples_select_table {
 8334:     my ($r,$records,$d) = @_;
 8335:     my $i=0;
 8336:     #
 8337:     my $max_samples = 5;
 8338:     my $samples = &get_samples($records,$max_samples);
 8339:     $r->print(&start_data_table().
 8340:               &start_data_table_header_row().'<th>'.
 8341:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8342:               &end_data_table_header_row());
 8343: 
 8344:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8345: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8346: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8347: 	foreach my $option (@$d) {
 8348: 	    my ($value,$display,$defaultcol)=@{ $option };
 8349: 	    $r->print('<option value="'.$value.'"'.
 8350:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8351:                       $display.'</option>');
 8352: 	}
 8353: 	$r->print('</select></td><td>');
 8354: 	foreach my $line (0..($max_samples-1)) {
 8355: 	    if (defined($samples->[$line]{$key})) { 
 8356: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8357: 	    }
 8358: 	}
 8359: 	$r->print('</td>'.&end_data_table_row());
 8360: 	$i++;
 8361:     }
 8362:     $r->print(&end_data_table());
 8363:     $i--;
 8364:     return($i);
 8365: }
 8366: 
 8367: ######################################################
 8368: ######################################################
 8369: 
 8370: =pod
 8371: 
 8372: =item * &clean_excel_name($name)
 8373: 
 8374: Returns a replacement for $name which does not contain any illegal characters.
 8375: 
 8376: =cut
 8377: 
 8378: ######################################################
 8379: ######################################################
 8380: sub clean_excel_name {
 8381:     my ($name) = @_;
 8382:     $name =~ s/[:\*\?\/\\]//g;
 8383:     if (length($name) > 31) {
 8384:         $name = substr($name,0,31);
 8385:     }
 8386:     return $name;
 8387: }
 8388: 
 8389: =pod
 8390: 
 8391: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8392: 
 8393: Returns either 1 or undef
 8394: 
 8395: 1 if the part is to be hidden, undef if it is to be shown
 8396: 
 8397: Arguments are:
 8398: 
 8399: $id the id of the part to be checked
 8400: $symb, optional the symb of the resource to check
 8401: $udom, optional the domain of the user to check for
 8402: $uname, optional the username of the user to check for
 8403: 
 8404: =cut
 8405: 
 8406: sub check_if_partid_hidden {
 8407:     my ($id,$symb,$udom,$uname) = @_;
 8408:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8409: 					 $symb,$udom,$uname);
 8410:     my $truth=1;
 8411:     #if the string starts with !, then the list is the list to show not hide
 8412:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8413:     my @hiddenlist=split(/,/,$hiddenparts);
 8414:     foreach my $checkid (@hiddenlist) {
 8415: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8416:     }
 8417:     return !$truth;
 8418: }
 8419: 
 8420: 
 8421: ############################################################
 8422: ############################################################
 8423: 
 8424: =pod
 8425: 
 8426: =back 
 8427: 
 8428: =head1 cgi-bin script and graphing routines
 8429: 
 8430: =over 4
 8431: 
 8432: =item * &get_cgi_id()
 8433: 
 8434: Inputs: none
 8435: 
 8436: Returns an id which can be used to pass environment variables
 8437: to various cgi-bin scripts.  These environment variables will
 8438: be removed from the users environment after a given time by
 8439: the routine &Apache::lonnet::transfer_profile_to_env.
 8440: 
 8441: =cut
 8442: 
 8443: ############################################################
 8444: ############################################################
 8445: my $uniq=0;
 8446: sub get_cgi_id {
 8447:     $uniq=($uniq+1)%100000;
 8448:     return (time.'_'.$$.'_'.$uniq);
 8449: }
 8450: 
 8451: ############################################################
 8452: ############################################################
 8453: 
 8454: =pod
 8455: 
 8456: =item * &DrawBarGraph()
 8457: 
 8458: Facilitates the plotting of data in a (stacked) bar graph.
 8459: Puts plot definition data into the users environment in order for 
 8460: graph.png to plot it.  Returns an <img> tag for the plot.
 8461: The bars on the plot are labeled '1','2',...,'n'.
 8462: 
 8463: Inputs:
 8464: 
 8465: =over 4
 8466: 
 8467: =item $Title: string, the title of the plot
 8468: 
 8469: =item $xlabel: string, text describing the X-axis of the plot
 8470: 
 8471: =item $ylabel: string, text describing the Y-axis of the plot
 8472: 
 8473: =item $Max: scalar, the maximum Y value to use in the plot
 8474: If $Max is < any data point, the graph will not be rendered.
 8475: 
 8476: =item $colors: array ref holding the colors to be used for the data sets when
 8477: they are plotted.  If undefined, default values will be used.
 8478: 
 8479: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8480: 
 8481: =item @Values: An array of array references.  Each array reference holds data
 8482: to be plotted in a stacked bar chart.
 8483: 
 8484: =item If the final element of @Values is a hash reference the key/value
 8485: pairs will be added to the graph definition.
 8486: 
 8487: =back
 8488: 
 8489: Returns:
 8490: 
 8491: An <img> tag which references graph.png and the appropriate identifying
 8492: information for the plot.
 8493: 
 8494: =cut
 8495: 
 8496: ############################################################
 8497: ############################################################
 8498: sub DrawBarGraph {
 8499:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8500:     #
 8501:     if (! defined($colors)) {
 8502:         $colors = ['#33ff00', 
 8503:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8504:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8505:                   ]; 
 8506:     }
 8507:     my $extra_settings = {};
 8508:     if (ref($Values[-1]) eq 'HASH') {
 8509:         $extra_settings = pop(@Values);
 8510:     }
 8511:     #
 8512:     my $identifier = &get_cgi_id();
 8513:     my $id = 'cgi.'.$identifier;        
 8514:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8515:         return '';
 8516:     }
 8517:     #
 8518:     my @Labels;
 8519:     if (defined($labels)) {
 8520:         @Labels = @$labels;
 8521:     } else {
 8522:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8523:             push (@Labels,$i+1);
 8524:         }
 8525:     }
 8526:     #
 8527:     my $NumBars = scalar(@{$Values[0]});
 8528:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8529:     my %ValuesHash;
 8530:     my $NumSets=1;
 8531:     foreach my $array (@Values) {
 8532:         next if (! ref($array));
 8533:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8534:             join(',',@$array);
 8535:     }
 8536:     #
 8537:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8538:     if ($NumBars < 3) {
 8539:         $width = 120+$NumBars*32;
 8540:         $xskip = 1;
 8541:         $bar_width = 30;
 8542:     } elsif ($NumBars < 5) {
 8543:         $width = 120+$NumBars*20;
 8544:         $xskip = 1;
 8545:         $bar_width = 20;
 8546:     } elsif ($NumBars < 10) {
 8547:         $width = 120+$NumBars*15;
 8548:         $xskip = 1;
 8549:         $bar_width = 15;
 8550:     } elsif ($NumBars <= 25) {
 8551:         $width = 120+$NumBars*11;
 8552:         $xskip = 5;
 8553:         $bar_width = 8;
 8554:     } elsif ($NumBars <= 50) {
 8555:         $width = 120+$NumBars*8;
 8556:         $xskip = 5;
 8557:         $bar_width = 4;
 8558:     } else {
 8559:         $width = 120+$NumBars*8;
 8560:         $xskip = 5;
 8561:         $bar_width = 4;
 8562:     }
 8563:     #
 8564:     $Max = 1 if ($Max < 1);
 8565:     if ( int($Max) < $Max ) {
 8566:         $Max++;
 8567:         $Max = int($Max);
 8568:     }
 8569:     $Title  = '' if (! defined($Title));
 8570:     $xlabel = '' if (! defined($xlabel));
 8571:     $ylabel = '' if (! defined($ylabel));
 8572:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8573:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8574:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8575:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8576:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8577:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8578:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8579:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8580:     $ValuesHash{$id.'.height'}   = $height;
 8581:     $ValuesHash{$id.'.width'}    = $width;
 8582:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8583:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8584:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8585:     #
 8586:     # Deal with other parameters
 8587:     while (my ($key,$value) = each(%$extra_settings)) {
 8588:         $ValuesHash{$id.'.'.$key} = $value;
 8589:     }
 8590:     #
 8591:     &Apache::lonnet::appenv(\%ValuesHash);
 8592:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8593: }
 8594: 
 8595: ############################################################
 8596: ############################################################
 8597: 
 8598: =pod
 8599: 
 8600: =item * &DrawXYGraph()
 8601: 
 8602: Facilitates the plotting of data in an XY graph.
 8603: Puts plot definition data into the users environment in order for 
 8604: graph.png to plot it.  Returns an <img> tag for the plot.
 8605: 
 8606: Inputs:
 8607: 
 8608: =over 4
 8609: 
 8610: =item $Title: string, the title of the plot
 8611: 
 8612: =item $xlabel: string, text describing the X-axis of the plot
 8613: 
 8614: =item $ylabel: string, text describing the Y-axis of the plot
 8615: 
 8616: =item $Max: scalar, the maximum Y value to use in the plot
 8617: If $Max is < any data point, the graph will not be rendered.
 8618: 
 8619: =item $colors: Array ref containing the hex color codes for the data to be 
 8620: plotted in.  If undefined, default values will be used.
 8621: 
 8622: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8623: 
 8624: =item $Ydata: Array ref containing Array refs.  
 8625: Each of the contained arrays will be plotted as a separate curve.
 8626: 
 8627: =item %Values: hash indicating or overriding any default values which are 
 8628: passed to graph.png.  
 8629: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8630: 
 8631: =back
 8632: 
 8633: Returns:
 8634: 
 8635: An <img> tag which references graph.png and the appropriate identifying
 8636: information for the plot.
 8637: 
 8638: =cut
 8639: 
 8640: ############################################################
 8641: ############################################################
 8642: sub DrawXYGraph {
 8643:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8644:     #
 8645:     # Create the identifier for the graph
 8646:     my $identifier = &get_cgi_id();
 8647:     my $id = 'cgi.'.$identifier;
 8648:     #
 8649:     $Title  = '' if (! defined($Title));
 8650:     $xlabel = '' if (! defined($xlabel));
 8651:     $ylabel = '' if (! defined($ylabel));
 8652:     my %ValuesHash = 
 8653:         (
 8654:          $id.'.title'  => &escape($Title),
 8655:          $id.'.xlabel' => &escape($xlabel),
 8656:          $id.'.ylabel' => &escape($ylabel),
 8657:          $id.'.y_max_value'=> $Max,
 8658:          $id.'.labels'     => join(',',@$Xlabels),
 8659:          $id.'.PlotType'   => 'XY',
 8660:          );
 8661:     #
 8662:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8663:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8664:     }
 8665:     #
 8666:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8667:         return '';
 8668:     }
 8669:     my $NumSets=1;
 8670:     foreach my $array (@{$Ydata}){
 8671:         next if (! ref($array));
 8672:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8673:     }
 8674:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8675:     #
 8676:     # Deal with other parameters
 8677:     while (my ($key,$value) = each(%Values)) {
 8678:         $ValuesHash{$id.'.'.$key} = $value;
 8679:     }
 8680:     #
 8681:     &Apache::lonnet::appenv(\%ValuesHash);
 8682:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8683: }
 8684: 
 8685: ############################################################
 8686: ############################################################
 8687: 
 8688: =pod
 8689: 
 8690: =item * &DrawXYYGraph()
 8691: 
 8692: Facilitates the plotting of data in an XY graph with two Y axes.
 8693: Puts plot definition data into the users environment in order for 
 8694: graph.png to plot it.  Returns an <img> tag for the plot.
 8695: 
 8696: Inputs:
 8697: 
 8698: =over 4
 8699: 
 8700: =item $Title: string, the title of the plot
 8701: 
 8702: =item $xlabel: string, text describing the X-axis of the plot
 8703: 
 8704: =item $ylabel: string, text describing the Y-axis of the plot
 8705: 
 8706: =item $colors: Array ref containing the hex color codes for the data to be 
 8707: plotted in.  If undefined, default values will be used.
 8708: 
 8709: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8710: 
 8711: =item $Ydata1: The first data set
 8712: 
 8713: =item $Min1: The minimum value of the left Y-axis
 8714: 
 8715: =item $Max1: The maximum value of the left Y-axis
 8716: 
 8717: =item $Ydata2: The second data set
 8718: 
 8719: =item $Min2: The minimum value of the right Y-axis
 8720: 
 8721: =item $Max2: The maximum value of the left Y-axis
 8722: 
 8723: =item %Values: hash indicating or overriding any default values which are 
 8724: passed to graph.png.  
 8725: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8726: 
 8727: =back
 8728: 
 8729: Returns:
 8730: 
 8731: An <img> tag which references graph.png and the appropriate identifying
 8732: information for the plot.
 8733: 
 8734: =cut
 8735: 
 8736: ############################################################
 8737: ############################################################
 8738: sub DrawXYYGraph {
 8739:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8740:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8741:     #
 8742:     # Create the identifier for the graph
 8743:     my $identifier = &get_cgi_id();
 8744:     my $id = 'cgi.'.$identifier;
 8745:     #
 8746:     $Title  = '' if (! defined($Title));
 8747:     $xlabel = '' if (! defined($xlabel));
 8748:     $ylabel = '' if (! defined($ylabel));
 8749:     my %ValuesHash = 
 8750:         (
 8751:          $id.'.title'  => &escape($Title),
 8752:          $id.'.xlabel' => &escape($xlabel),
 8753:          $id.'.ylabel' => &escape($ylabel),
 8754:          $id.'.labels' => join(',',@$Xlabels),
 8755:          $id.'.PlotType' => 'XY',
 8756:          $id.'.NumSets' => 2,
 8757:          $id.'.two_axes' => 1,
 8758:          $id.'.y1_max_value' => $Max1,
 8759:          $id.'.y1_min_value' => $Min1,
 8760:          $id.'.y2_max_value' => $Max2,
 8761:          $id.'.y2_min_value' => $Min2,
 8762:          );
 8763:     #
 8764:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8765:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8766:     }
 8767:     #
 8768:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8769:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8770:         return '';
 8771:     }
 8772:     my $NumSets=1;
 8773:     foreach my $array ($Ydata1,$Ydata2){
 8774:         next if (! ref($array));
 8775:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8776:     }
 8777:     #
 8778:     # Deal with other parameters
 8779:     while (my ($key,$value) = each(%Values)) {
 8780:         $ValuesHash{$id.'.'.$key} = $value;
 8781:     }
 8782:     #
 8783:     &Apache::lonnet::appenv(\%ValuesHash);
 8784:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8785: }
 8786: 
 8787: ############################################################
 8788: ############################################################
 8789: 
 8790: =pod
 8791: 
 8792: =back 
 8793: 
 8794: =head1 Statistics helper routines?  
 8795: 
 8796: Bad place for them but what the hell.
 8797: 
 8798: =over 4
 8799: 
 8800: =item * &chartlink()
 8801: 
 8802: Returns a link to the chart for a specific student.  
 8803: 
 8804: Inputs:
 8805: 
 8806: =over 4
 8807: 
 8808: =item $linktext: The text of the link
 8809: 
 8810: =item $sname: The students username
 8811: 
 8812: =item $sdomain: The students domain
 8813: 
 8814: =back
 8815: 
 8816: =back
 8817: 
 8818: =cut
 8819: 
 8820: ############################################################
 8821: ############################################################
 8822: sub chartlink {
 8823:     my ($linktext, $sname, $sdomain) = @_;
 8824:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8825:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8826:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8827:        '">'.$linktext.'</a>';
 8828: }
 8829: 
 8830: #######################################################
 8831: #######################################################
 8832: 
 8833: =pod
 8834: 
 8835: =head1 Course Environment Routines
 8836: 
 8837: =over 4
 8838: 
 8839: =item * &restore_course_settings()
 8840: 
 8841: =item * &store_course_settings()
 8842: 
 8843: Restores/Store indicated form parameters from the course environment.
 8844: Will not overwrite existing values of the form parameters.
 8845: 
 8846: Inputs: 
 8847: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8848: 
 8849: a hash ref describing the data to be stored.  For example:
 8850:    
 8851: %Save_Parameters = ('Status' => 'scalar',
 8852:     'chartoutputmode' => 'scalar',
 8853:     'chartoutputdata' => 'scalar',
 8854:     'Section' => 'array',
 8855:     'Group' => 'array',
 8856:     'StudentData' => 'array',
 8857:     'Maps' => 'array');
 8858: 
 8859: Returns: both routines return nothing
 8860: 
 8861: =back
 8862: 
 8863: =cut
 8864: 
 8865: #######################################################
 8866: #######################################################
 8867: sub store_course_settings {
 8868:     return &store_settings($env{'request.course.id'},@_);
 8869: }
 8870: 
 8871: sub store_settings {
 8872:     # save to the environment
 8873:     # appenv the same items, just to be safe
 8874:     my $udom  = $env{'user.domain'};
 8875:     my $uname = $env{'user.name'};
 8876:     my ($context,$prefix,$Settings) = @_;
 8877:     my %SaveHash;
 8878:     my %AppHash;
 8879:     while (my ($setting,$type) = each(%$Settings)) {
 8880:         my $basename = join('.','internal',$context,$prefix,$setting);
 8881:         my $envname = 'environment.'.$basename;
 8882:         if (exists($env{'form.'.$setting})) {
 8883:             # Save this value away
 8884:             if ($type eq 'scalar' &&
 8885:                 (! exists($env{$envname}) || 
 8886:                  $env{$envname} ne $env{'form.'.$setting})) {
 8887:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8888:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8889:             } elsif ($type eq 'array') {
 8890:                 my $stored_form;
 8891:                 if (ref($env{'form.'.$setting})) {
 8892:                     $stored_form = join(',',
 8893:                                         map {
 8894:                                             &escape($_);
 8895:                                         } sort(@{$env{'form.'.$setting}}));
 8896:                 } else {
 8897:                     $stored_form = 
 8898:                         &escape($env{'form.'.$setting});
 8899:                 }
 8900:                 # Determine if the array contents are the same.
 8901:                 if ($stored_form ne $env{$envname}) {
 8902:                     $SaveHash{$basename} = $stored_form;
 8903:                     $AppHash{$envname}   = $stored_form;
 8904:                 }
 8905:             }
 8906:         }
 8907:     }
 8908:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8909:                                           $udom,$uname);
 8910:     if ($put_result !~ /^(ok|delayed)/) {
 8911:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8912:                                  'got error:'.$put_result);
 8913:     }
 8914:     # Make sure these settings stick around in this session, too
 8915:     &Apache::lonnet::appenv(\%AppHash);
 8916:     return;
 8917: }
 8918: 
 8919: sub restore_course_settings {
 8920:     return &restore_settings($env{'request.course.id'},@_);
 8921: }
 8922: 
 8923: sub restore_settings {
 8924:     my ($context,$prefix,$Settings) = @_;
 8925:     while (my ($setting,$type) = each(%$Settings)) {
 8926:         next if (exists($env{'form.'.$setting}));
 8927:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8928:             '.'.$setting;
 8929:         if (exists($env{$envname})) {
 8930:             if ($type eq 'scalar') {
 8931:                 $env{'form.'.$setting} = $env{$envname};
 8932:             } elsif ($type eq 'array') {
 8933:                 $env{'form.'.$setting} = [ 
 8934:                                            map { 
 8935:                                                &unescape($_); 
 8936:                                            } split(',',$env{$envname})
 8937:                                            ];
 8938:             }
 8939:         }
 8940:     }
 8941: }
 8942: 
 8943: #######################################################
 8944: #######################################################
 8945: 
 8946: =pod
 8947: 
 8948: =head1 Domain E-mail Routines  
 8949: 
 8950: =over 4
 8951: 
 8952: =item * &build_recipient_list()
 8953: 
 8954: Build recipient lists for four types of e-mail:
 8955: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8956: (d) Help requests, generated by
 8957: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 8958: 
 8959: Inputs:
 8960: defmail (scalar - email address of default recipient), 
 8961: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8962: defdom (domain for which to retrieve configuration settings),
 8963: origmail (scalar - email address of recipient from loncapa.conf, 
 8964: i.e., predates configuration by DC via domainprefs.pm 
 8965: 
 8966: Returns: comma separated list of addresses to which to send e-mail.
 8967: 
 8968: =back
 8969: 
 8970: =cut
 8971: 
 8972: ############################################################
 8973: ############################################################
 8974: sub build_recipient_list {
 8975:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8976:     my @recipients;
 8977:     my $otheremails;
 8978:     my %domconfig =
 8979:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8980:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8981:         if (exists($domconfig{'contacts'}{$mailing})) {
 8982:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8983:                 my @contacts = ('adminemail','supportemail');
 8984:                 foreach my $item (@contacts) {
 8985:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8986:                         my $addr = $domconfig{'contacts'}{$item}; 
 8987:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8988:                             push(@recipients,$addr);
 8989:                         }
 8990:                     }
 8991:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8992:                 }
 8993:             }
 8994:         } elsif ($origmail ne '') {
 8995:             push(@recipients,$origmail);
 8996:         }
 8997:     } elsif ($origmail ne '') {
 8998:         push(@recipients,$origmail);
 8999:     }
 9000:     if (defined($defmail)) {
 9001:         if ($defmail ne '') {
 9002:             push(@recipients,$defmail);
 9003:         }
 9004:     }
 9005:     if ($otheremails) {
 9006:         my @others;
 9007:         if ($otheremails =~ /,/) {
 9008:             @others = split(/,/,$otheremails);
 9009:         } else {
 9010:             push(@others,$otheremails);
 9011:         }
 9012:         foreach my $addr (@others) {
 9013:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9014:                 push(@recipients,$addr);
 9015:             }
 9016:         }
 9017:     }
 9018:     my $recipientlist = join(',',@recipients); 
 9019:     return $recipientlist;
 9020: }
 9021: 
 9022: ############################################################
 9023: ############################################################
 9024: 
 9025: =pod
 9026: 
 9027: =head1 Course Catalog Routines
 9028: 
 9029: =over 4
 9030: 
 9031: =item * &gather_categories()
 9032: 
 9033: Converts category definitions - keys of categories hash stored in  
 9034: coursecategories in configuration.db on the primary library server in a 
 9035: domain - to an array.  Also generates javascript and idx hash used to 
 9036: generate Domain Coordinator interface for editing Course Categories.
 9037: 
 9038: Inputs:
 9039: 
 9040: categories (reference to hash of category definitions).
 9041: 
 9042: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9043:       categories and subcategories).
 9044: 
 9045: idx (reference to hash of counters used in Domain Coordinator interface for 
 9046:       editing Course Categories).
 9047: 
 9048: jsarray (reference to array of categories used to create Javascript arrays for
 9049:          Domain Coordinator interface for editing Course Categories).
 9050: 
 9051: Returns: nothing
 9052: 
 9053: Side effects: populates cats, idx and jsarray. 
 9054: 
 9055: =cut
 9056: 
 9057: sub gather_categories {
 9058:     my ($categories,$cats,$idx,$jsarray) = @_;
 9059:     my %counters;
 9060:     my $num = 0;
 9061:     foreach my $item (keys(%{$categories})) {
 9062:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9063:         if ($container eq '' && $depth == 0) {
 9064:             $cats->[$depth][$categories->{$item}] = $cat;
 9065:         } else {
 9066:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9067:         }
 9068:         my ($escitem,$tail) = split(/:/,$item,2);
 9069:         if ($counters{$tail} eq '') {
 9070:             $counters{$tail} = $num;
 9071:             $num ++;
 9072:         }
 9073:         if (ref($idx) eq 'HASH') {
 9074:             $idx->{$item} = $counters{$tail};
 9075:         }
 9076:         if (ref($jsarray) eq 'ARRAY') {
 9077:             push(@{$jsarray->[$counters{$tail}]},$item);
 9078:         }
 9079:     }
 9080:     return;
 9081: }
 9082: 
 9083: =pod
 9084: 
 9085: =item * &extract_categories()
 9086: 
 9087: Used to generate breadcrumb trails for course categories.
 9088: 
 9089: Inputs:
 9090: 
 9091: categories (reference to hash of category definitions).
 9092: 
 9093: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9094:       categories and subcategories).
 9095: 
 9096: trails (reference to array of breacrumb trails for each category).
 9097: 
 9098: allitems (reference to hash - key is category key 
 9099:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9100: 
 9101: idx (reference to hash of counters used in Domain Coordinator interface for
 9102:       editing Course Categories).
 9103: 
 9104: jsarray (reference to array of categories used to create Javascript arrays for
 9105:          Domain Coordinator interface for editing Course Categories).
 9106: 
 9107: subcats (reference to hash of arrays containing all subcategories within each 
 9108:          category, -recursive)
 9109: 
 9110: Returns: nothing
 9111: 
 9112: Side effects: populates trails and allitems hash references.
 9113: 
 9114: =cut
 9115: 
 9116: sub extract_categories {
 9117:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9118:     if (ref($categories) eq 'HASH') {
 9119:         &gather_categories($categories,$cats,$idx,$jsarray);
 9120:         if (ref($cats->[0]) eq 'ARRAY') {
 9121:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9122:                 my $name = $cats->[0][$i];
 9123:                 my $item = &escape($name).'::0';
 9124:                 my $trailstr;
 9125:                 if ($name eq 'instcode') {
 9126:                     $trailstr = &mt('Official courses (with institutional codes)');
 9127:                 } else {
 9128:                     $trailstr = $name;
 9129:                 }
 9130:                 if ($allitems->{$item} eq '') {
 9131:                     push(@{$trails},$trailstr);
 9132:                     $allitems->{$item} = scalar(@{$trails})-1;
 9133:                 }
 9134:                 my @parents = ($name);
 9135:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9136:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9137:                         my $category = $cats->[1]{$name}[$j];
 9138:                         if (ref($subcats) eq 'HASH') {
 9139:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9140:                         }
 9141:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9142:                     }
 9143:                 } else {
 9144:                     if (ref($subcats) eq 'HASH') {
 9145:                         $subcats->{$item} = [];
 9146:                     }
 9147:                 }
 9148:             }
 9149:         }
 9150:     }
 9151:     return;
 9152: }
 9153: 
 9154: =pod
 9155: 
 9156: =item *&recurse_categories()
 9157: 
 9158: Recursively used to generate breadcrumb trails for course categories.
 9159: 
 9160: Inputs:
 9161: 
 9162: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9163:       categories and subcategories).
 9164: 
 9165: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9166: 
 9167: category (current course category, for which breadcrumb trail is being generated).
 9168: 
 9169: trails (reference to array of breadcrumb trails for each category).
 9170: 
 9171: allitems (reference to hash - key is category key
 9172:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9173: 
 9174: parents (array containing containers directories for current category, 
 9175:          back to top level). 
 9176: 
 9177: Returns: nothing
 9178: 
 9179: Side effects: populates trails and allitems hash references
 9180: 
 9181: =cut
 9182: 
 9183: sub recurse_categories {
 9184:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9185:     my $shallower = $depth - 1;
 9186:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9187:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9188:             my $name = $cats->[$depth]{$category}[$k];
 9189:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9190:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9191:             if ($allitems->{$item} eq '') {
 9192:                 push(@{$trails},$trailstr);
 9193:                 $allitems->{$item} = scalar(@{$trails})-1;
 9194:             }
 9195:             my $deeper = $depth+1;
 9196:             push(@{$parents},$category);
 9197:             if (ref($subcats) eq 'HASH') {
 9198:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9199:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9200:                     my $higher;
 9201:                     if ($j > 0) {
 9202:                         $higher = &escape($parents->[$j]).':'.
 9203:                                   &escape($parents->[$j-1]).':'.$j;
 9204:                     } else {
 9205:                         $higher = &escape($parents->[$j]).'::'.$j;
 9206:                     }
 9207:                     push(@{$subcats->{$higher}},$subcat);
 9208:                 }
 9209:             }
 9210:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9211:                                 $subcats);
 9212:             pop(@{$parents});
 9213:         }
 9214:     } else {
 9215:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9216:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9217:         if ($allitems->{$item} eq '') {
 9218:             push(@{$trails},$trailstr);
 9219:             $allitems->{$item} = scalar(@{$trails})-1;
 9220:         }
 9221:     }
 9222:     return;
 9223: }
 9224: 
 9225: =pod
 9226: 
 9227: =item *&assign_categories_table()
 9228: 
 9229: Create a datatable for display of hierarchical categories in a domain,
 9230: with checkboxes to allow a course to be categorized. 
 9231: 
 9232: Inputs:
 9233: 
 9234: cathash - reference to hash of categories defined for the domain (from
 9235:           configuration.db)
 9236: 
 9237: currcat - scalar with an & separated list of categories assigned to a course. 
 9238: 
 9239: Returns: $output (markup to be displayed) 
 9240: 
 9241: =cut
 9242: 
 9243: sub assign_categories_table {
 9244:     my ($cathash,$currcat) = @_;
 9245:     my $output;
 9246:     if (ref($cathash) eq 'HASH') {
 9247:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9248:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9249:         $maxdepth = scalar(@cats);
 9250:         if (@cats > 0) {
 9251:             my $itemcount = 0;
 9252:             if (ref($cats[0]) eq 'ARRAY') {
 9253:                 $output = &Apache::loncommon::start_data_table();
 9254:                 my @currcategories;
 9255:                 if ($currcat ne '') {
 9256:                     @currcategories = split('&',$currcat);
 9257:                 }
 9258:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9259:                     my $parent = $cats[0][$i];
 9260:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9261:                     next if ($parent eq 'instcode');
 9262:                     my $item = &escape($parent).'::0';
 9263:                     my $checked = '';
 9264:                     if (@currcategories > 0) {
 9265:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9266:                             $checked = ' checked="checked"';
 9267:                         }
 9268:                     }
 9269:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9270:                                '<input type="checkbox" name="usecategory" value="'.
 9271:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9272:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9273:                     my $depth = 1;
 9274:                     push(@path,$parent);
 9275:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9276:                     pop(@path);
 9277:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9278:                     $itemcount ++;
 9279:                 }
 9280:                 $output .= &Apache::loncommon::end_data_table();
 9281:             }
 9282:         }
 9283:     }
 9284:     return $output;
 9285: }
 9286: 
 9287: =pod
 9288: 
 9289: =item *&assign_category_rows()
 9290: 
 9291: Create a datatable row for display of nested categories in a domain,
 9292: with checkboxes to allow a course to be categorized,called recursively.
 9293: 
 9294: Inputs:
 9295: 
 9296: itemcount - track row number for alternating colors
 9297: 
 9298: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9299:       categories and subcategories.
 9300: 
 9301: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9302: 
 9303: parent - parent of current category item
 9304: 
 9305: path - Array containing all categories back up through the hierarchy from the
 9306:        current category to the top level.
 9307: 
 9308: currcategories - reference to array of current categories assigned to the course
 9309: 
 9310: Returns: $output (markup to be displayed).
 9311: 
 9312: =cut
 9313: 
 9314: sub assign_category_rows {
 9315:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9316:     my ($text,$name,$item,$chgstr);
 9317:     if (ref($cats) eq 'ARRAY') {
 9318:         my $maxdepth = scalar(@{$cats});
 9319:         if (ref($cats->[$depth]) eq 'HASH') {
 9320:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9321:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9322:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9323:                 $text .= '<td><table class="LC_datatable">';
 9324:                 for (my $j=0; $j<$numchildren; $j++) {
 9325:                     $name = $cats->[$depth]{$parent}[$j];
 9326:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9327:                     my $deeper = $depth+1;
 9328:                     my $checked = '';
 9329:                     if (ref($currcategories) eq 'ARRAY') {
 9330:                         if (@{$currcategories} > 0) {
 9331:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9332:                                 $checked = ' checked="checked"';
 9333:                             }
 9334:                         }
 9335:                     }
 9336:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9337:                              '<input type="checkbox" name="usecategory" value="'.
 9338:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9339:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9340:                              '</td><td>';
 9341:                     if (ref($path) eq 'ARRAY') {
 9342:                         push(@{$path},$name);
 9343:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9344:                         pop(@{$path});
 9345:                     }
 9346:                     $text .= '</td></tr>';
 9347:                 }
 9348:                 $text .= '</table></td>';
 9349:             }
 9350:         }
 9351:     }
 9352:     return $text;
 9353: }
 9354: 
 9355: ############################################################
 9356: ############################################################
 9357: 
 9358: 
 9359: sub commit_customrole {
 9360:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9361:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9362:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9363:                          ($end?', ending '.localtime($end):'').': <b>'.
 9364:               &Apache::lonnet::assigncustomrole(
 9365:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9366:                  '</b><br />';
 9367:     return $output;
 9368: }
 9369: 
 9370: sub commit_standardrole {
 9371:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9372:     my ($output,$logmsg,$linefeed);
 9373:     if ($context eq 'auto') {
 9374:         $linefeed = "\n";
 9375:     } else {
 9376:         $linefeed = "<br />\n";
 9377:     }  
 9378:     if ($three eq 'st') {
 9379:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9380:                                          $one,$two,$sec,$context);
 9381:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9382:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9383:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9384:         } else {
 9385:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9386:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9387:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9388:             if ($context eq 'auto') {
 9389:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9390:             } else {
 9391:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9392:                &mt('Add to classlist').': <b>ok</b>';
 9393:             }
 9394:             $output .= $linefeed;
 9395:         }
 9396:     } else {
 9397:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9398:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9399:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9400:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9401:         if ($context eq 'auto') {
 9402:             $output .= $result.$linefeed;
 9403:         } else {
 9404:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9405:         }
 9406:     }
 9407:     return $output;
 9408: }
 9409: 
 9410: sub commit_studentrole {
 9411:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9412:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9413:     if ($context eq 'auto') {
 9414:         $linefeed = "\n";
 9415:     } else {
 9416:         $linefeed = '<br />'."\n";
 9417:     }
 9418:     if (defined($one) && defined($two)) {
 9419:         my $cid=$one.'_'.$two;
 9420:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9421:         my $secchange = 0;
 9422:         my $expire_role_result;
 9423:         my $modify_section_result;
 9424:         if ($oldsec ne '-1') { 
 9425:             if ($oldsec ne $sec) {
 9426:                 $secchange = 1;
 9427:                 my $now = time;
 9428:                 my $uurl='/'.$cid;
 9429:                 $uurl=~s/\_/\//g;
 9430:                 if ($oldsec) {
 9431:                     $uurl.='/'.$oldsec;
 9432:                 }
 9433:                 $oldsecurl = $uurl;
 9434:                 $expire_role_result = 
 9435:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9436:                 if ($env{'request.course.sec'} ne '') { 
 9437:                     if ($expire_role_result eq 'refused') {
 9438:                         my @roles = ('st');
 9439:                         my @statuses = ('previous');
 9440:                         my @roledoms = ($one);
 9441:                         my $withsec = 1;
 9442:                         my %roleshash = 
 9443:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9444:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9445:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9446:                             my ($oldstart,$oldend) = 
 9447:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9448:                             if ($oldend > 0 && $oldend <= $now) {
 9449:                                 $expire_role_result = 'ok';
 9450:                             }
 9451:                         }
 9452:                     }
 9453:                 }
 9454:                 $result = $expire_role_result;
 9455:             }
 9456:         }
 9457:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9458:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9459:             if ($modify_section_result =~ /^ok/) {
 9460:                 if ($secchange == 1) {
 9461:                     if ($sec eq '') {
 9462:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9463:                     } else {
 9464:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9465:                     }
 9466:                 } elsif ($oldsec eq '-1') {
 9467:                     if ($sec eq '') {
 9468:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9469:                     } else {
 9470:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9471:                     }
 9472:                 } else {
 9473:                     if ($sec eq '') {
 9474:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9475:                     } else {
 9476:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9477:                     }
 9478:                 }
 9479:             } else {
 9480:                 if ($secchange) {       
 9481:                     $$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;
 9482:                 } else {
 9483:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9484:                 }
 9485:             }
 9486:             $result = $modify_section_result;
 9487:         } elsif ($secchange == 1) {
 9488:             if ($oldsec eq '') {
 9489:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9490:             } else {
 9491:                 $$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;
 9492:             }
 9493:             if ($expire_role_result eq 'refused') {
 9494:                 my $newsecurl = '/'.$cid;
 9495:                 $newsecurl =~ s/\_/\//g;
 9496:                 if ($sec ne '') {
 9497:                     $newsecurl.='/'.$sec;
 9498:                 }
 9499:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9500:                     if ($sec eq '') {
 9501:                         $$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;
 9502:                     } else {
 9503:                         $$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;
 9504:                     }
 9505:                 }
 9506:             }
 9507:         }
 9508:     } else {
 9509:         $$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;
 9510:         $result = "error: incomplete course id\n";
 9511:     }
 9512:     return $result;
 9513: }
 9514: 
 9515: ############################################################
 9516: ############################################################
 9517: 
 9518: sub check_clone {
 9519:     my ($args,$linefeed) = @_;
 9520:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9521:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9522:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9523:     my $clonemsg;
 9524:     my $can_clone = 0;
 9525: 
 9526:     if ($clonehome eq 'no_host') {
 9527:         $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'});     
 9528:     } else {
 9529: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9530: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9531: 	    $can_clone = 1;
 9532: 	} else {
 9533: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9534: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9535: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9536:             if (grep(/^\*$/,@cloners)) {
 9537:                 $can_clone = 1;
 9538:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9539:                 $can_clone = 1;
 9540:             } else {
 9541: 	        my %roleshash =
 9542: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9543: 					 $args->{'ccdomain'},
 9544:                                          'userroles',['active'],['cc'],
 9545: 					 [$args->{'clonedomain'}]);
 9546: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9547: 		    $can_clone = 1;
 9548: 	        } else {
 9549:                     $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'});
 9550: 	        }
 9551: 	    }
 9552:         }
 9553:     }
 9554:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9555: }
 9556: 
 9557: sub construct_course {
 9558:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9559:     my $outcome;
 9560:     my $linefeed =  '<br />'."\n";
 9561:     if ($context eq 'auto') {
 9562:         $linefeed = "\n";
 9563:     }
 9564: 
 9565: #
 9566: # Are we cloning?
 9567: #
 9568:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9569:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9570: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9571: 	if ($context ne 'auto') {
 9572:             if ($clonemsg ne '') {
 9573: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9574:             }
 9575: 	}
 9576: 	$outcome .= $clonemsg.$linefeed;
 9577: 
 9578:         if (!$can_clone) {
 9579: 	    return (0,$outcome);
 9580: 	}
 9581:     }
 9582: 
 9583: #
 9584: # Open course
 9585: #
 9586:     my $crstype = lc($args->{'crstype'});
 9587:     my %cenv=();
 9588:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9589:                                              $args->{'cdescr'},
 9590:                                              $args->{'curl'},
 9591:                                              $args->{'course_home'},
 9592:                                              $args->{'nonstandard'},
 9593:                                              $args->{'crscode'},
 9594:                                              $args->{'ccuname'}.':'.
 9595:                                              $args->{'ccdomain'},
 9596:                                              $args->{'crstype'});
 9597: 
 9598:     # Note: The testing routines depend on this being output; see 
 9599:     # Utils::Course. This needs to at least be output as a comment
 9600:     # if anyone ever decides to not show this, and Utils::Course::new
 9601:     # will need to be suitably modified.
 9602:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9603: #
 9604: # Check if created correctly
 9605: #
 9606:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9607:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9608:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9609: 
 9610: #
 9611: # Do the cloning
 9612: #   
 9613:     if ($can_clone && $cloneid) {
 9614: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9615: 	if ($context ne 'auto') {
 9616: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9617: 	}
 9618: 	$outcome .= $clonemsg.$linefeed;
 9619: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9620: # Copy all files
 9621: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9622: # Restore URL
 9623: 	$cenv{'url'}=$oldcenv{'url'};
 9624: # Restore title
 9625: 	$cenv{'description'}=$oldcenv{'description'};
 9626: # Mark as cloned
 9627: 	$cenv{'clonedfrom'}=$cloneid;
 9628: # Need to clone grading mode
 9629:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9630:         $cenv{'grading'}=$newenv{'grading'};
 9631: # Do not clone these environment entries
 9632:         &Apache::lonnet::del('environment',
 9633:                   ['default_enrollment_start_date',
 9634:                    'default_enrollment_end_date',
 9635:                    'question.email',
 9636:                    'policy.email',
 9637:                    'comment.email',
 9638:                    'pch.users.denied',
 9639:                    'plc.users.denied',
 9640:                    'hidefromcat',
 9641:                    'categories'],
 9642:                    $$crsudom,$$crsunum);
 9643:     }
 9644: 
 9645: #
 9646: # Set environment (will override cloned, if existing)
 9647: #
 9648:     my @sections = ();
 9649:     my @xlists = ();
 9650:     if ($args->{'crstype'}) {
 9651:         $cenv{'type'}=$args->{'crstype'};
 9652:     }
 9653:     if ($args->{'crsid'}) {
 9654:         $cenv{'courseid'}=$args->{'crsid'};
 9655:     }
 9656:     if ($args->{'crscode'}) {
 9657:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9658:     }
 9659:     if ($args->{'crsquota'} ne '') {
 9660:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9661:     } else {
 9662:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9663:     }
 9664:     if ($args->{'ccuname'}) {
 9665:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9666:                                         ':'.$args->{'ccdomain'};
 9667:     } else {
 9668:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9669:     }
 9670:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9671:     if ($args->{'crssections'}) {
 9672:         $cenv{'internal.sectionnums'} = '';
 9673:         if ($args->{'crssections'} =~ m/,/) {
 9674:             @sections = split/,/,$args->{'crssections'};
 9675:         } else {
 9676:             $sections[0] = $args->{'crssections'};
 9677:         }
 9678:         if (@sections > 0) {
 9679:             foreach my $item (@sections) {
 9680:                 my ($sec,$gp) = split/:/,$item;
 9681:                 my $class = $args->{'crscode'}.$sec;
 9682:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9683:                 $cenv{'internal.sectionnums'} .= $item.',';
 9684:                 unless ($addcheck eq 'ok') {
 9685:                     push @badclasses, $class;
 9686:                 }
 9687:             }
 9688:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9689:         }
 9690:     }
 9691: # do not hide course coordinator from staff listing, 
 9692: # even if privileged
 9693:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9694: # add crosslistings
 9695:     if ($args->{'crsxlist'}) {
 9696:         $cenv{'internal.crosslistings'}='';
 9697:         if ($args->{'crsxlist'} =~ m/,/) {
 9698:             @xlists = split/,/,$args->{'crsxlist'};
 9699:         } else {
 9700:             $xlists[0] = $args->{'crsxlist'};
 9701:         }
 9702:         if (@xlists > 0) {
 9703:             foreach my $item (@xlists) {
 9704:                 my ($xl,$gp) = split/:/,$item;
 9705:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9706:                 $cenv{'internal.crosslistings'} .= $item.',';
 9707:                 unless ($addcheck eq 'ok') {
 9708:                     push @badclasses, $xl;
 9709:                 }
 9710:             }
 9711:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9712:         }
 9713:     }
 9714:     if ($args->{'autoadds'}) {
 9715:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9716:     }
 9717:     if ($args->{'autodrops'}) {
 9718:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9719:     }
 9720: # check for notification of enrollment changes
 9721:     my @notified = ();
 9722:     if ($args->{'notify_owner'}) {
 9723:         if ($args->{'ccuname'} ne '') {
 9724:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9725:         }
 9726:     }
 9727:     if ($args->{'notify_dc'}) {
 9728:         if ($uname ne '') { 
 9729:             push(@notified,$uname.':'.$udom);
 9730:         }
 9731:     }
 9732:     if (@notified > 0) {
 9733:         my $notifylist;
 9734:         if (@notified > 1) {
 9735:             $notifylist = join(',',@notified);
 9736:         } else {
 9737:             $notifylist = $notified[0];
 9738:         }
 9739:         $cenv{'internal.notifylist'} = $notifylist;
 9740:     }
 9741:     if (@badclasses > 0) {
 9742:         my %lt=&Apache::lonlocal::texthash(
 9743:                 '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',
 9744:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9745:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9746:         );
 9747:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9748:                            ' ('.$lt{'adby'}.')';
 9749:         if ($context eq 'auto') {
 9750:             $outcome .= $badclass_msg.$linefeed;
 9751:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9752:             foreach my $item (@badclasses) {
 9753:                 if ($context eq 'auto') {
 9754:                     $outcome .= " - $item\n";
 9755:                 } else {
 9756:                     $outcome .= "<li>$item</li>\n";
 9757:                 }
 9758:             }
 9759:             if ($context eq 'auto') {
 9760:                 $outcome .= $linefeed;
 9761:             } else {
 9762:                 $outcome .= "</ul><br /><br /></div>\n";
 9763:             }
 9764:         } 
 9765:     }
 9766:     if ($args->{'no_end_date'}) {
 9767:         $args->{'endaccess'} = 0;
 9768:     }
 9769:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9770:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9771:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9772:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9773:     if ($args->{'showphotos'}) {
 9774:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9775:     }
 9776:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9777:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9778:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9779:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9780:             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'); 
 9781:             if ($context eq 'auto') {
 9782:                 $outcome .= $krb_msg;
 9783:             } else {
 9784:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9785:             }
 9786:             $outcome .= $linefeed;
 9787:         }
 9788:     }
 9789:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9790:        if ($args->{'setpolicy'}) {
 9791:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9792:        }
 9793:        if ($args->{'setcontent'}) {
 9794:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9795:        }
 9796:     }
 9797:     if ($args->{'reshome'}) {
 9798: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9799: 	$cenv{'reshome'}=~s/\/+$/\//;
 9800:     }
 9801: #
 9802: # course has keyed access
 9803: #
 9804:     if ($args->{'setkeys'}) {
 9805:        $cenv{'keyaccess'}='yes';
 9806:     }
 9807: # if specified, key authority is not course, but user
 9808: # only active if keyaccess is yes
 9809:     if ($args->{'keyauth'}) {
 9810: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9811: 	$user = &LONCAPA::clean_username($user);
 9812: 	$domain = &LONCAPA::clean_username($domain);
 9813: 	if ($user ne '' && $domain ne '') {
 9814: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9815: 	}
 9816:     }
 9817: 
 9818:     if ($args->{'disresdis'}) {
 9819:         $cenv{'pch.roles.denied'}='st';
 9820:     }
 9821:     if ($args->{'disablechat'}) {
 9822:         $cenv{'plc.roles.denied'}='st';
 9823:     }
 9824: 
 9825:     # Record we've not yet viewed the Course Initialization Helper for this 
 9826:     # course
 9827:     $cenv{'course.helper.not.run'} = 1;
 9828:     #
 9829:     # Use new Randomseed
 9830:     #
 9831:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9832:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9833:     #
 9834:     # The encryption code and receipt prefix for this course
 9835:     #
 9836:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9837:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9838:     #
 9839:     # By default, use standard grading
 9840:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9841: 
 9842:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9843:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9844: #
 9845: # Open all assignments
 9846: #
 9847:     if ($args->{'openall'}) {
 9848:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9849:        my %storecontent = ($storeunder         => time,
 9850:                            $storeunder.'.type' => 'date_start');
 9851:        
 9852:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9853:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9854:    }
 9855: #
 9856: # Set first page
 9857: #
 9858:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9859: 	    || ($cloneid)) {
 9860: 	use LONCAPA::map;
 9861: 	$outcome .= &mt('Setting first resource').': ';
 9862: 
 9863: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9864:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9865: 
 9866:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9867:         my $title; my $url;
 9868:         if ($args->{'firstres'} eq 'syl') {
 9869: 	    $title=&mt('Syllabus');
 9870:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9871:         } else {
 9872:             $title=&mt('Navigate Contents');
 9873:             $url='/adm/navmaps';
 9874:         }
 9875: 
 9876:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9877: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9878: 
 9879: 	if ($errtext) { $fatal=2; }
 9880:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9881:     }
 9882: 
 9883:     return (1,$outcome);
 9884: }
 9885: 
 9886: ############################################################
 9887: ############################################################
 9888: 
 9889: sub course_type {
 9890:     my ($cid) = @_;
 9891:     if (!defined($cid)) {
 9892:         $cid = $env{'request.course.id'};
 9893:     }
 9894:     if (defined($env{'course.'.$cid.'.type'})) {
 9895:         return $env{'course.'.$cid.'.type'};
 9896:     } else {
 9897:         return 'Course';
 9898:     }
 9899: }
 9900: 
 9901: sub group_term {
 9902:     my $crstype = &course_type();
 9903:     my %names = (
 9904:                   'Course' => 'group',
 9905:                   'Group' => 'team',
 9906:                 );
 9907:     return $names{$crstype};
 9908: }
 9909: 
 9910: sub icon {
 9911:     my ($file)=@_;
 9912:     my $curfext = lc((split(/\./,$file))[-1]);
 9913:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9914:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9915:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9916: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9917: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9918: 	            $curfext.".gif") {
 9919: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9920: 		$curfext.".gif";
 9921: 	}
 9922:     }
 9923:     return &lonhttpdurl($iconname);
 9924: } 
 9925: 
 9926: sub lonhttpdurl {
 9927: #
 9928: # Had been used for "small fry" static images on separate port 8080.
 9929: # Modify here if lightweight http functionality desired again.
 9930: # Currently eliminated due to increasing firewall issues.
 9931: #
 9932:     my ($url)=@_;
 9933:     return $url;
 9934: }
 9935: 
 9936: sub connection_aborted {
 9937:     my ($r)=@_;
 9938:     $r->print(" ");$r->rflush();
 9939:     my $c = $r->connection;
 9940:     return $c->aborted();
 9941: }
 9942: 
 9943: #    Escapes strings that may have embedded 's that will be put into
 9944: #    strings as 'strings'.
 9945: sub escape_single {
 9946:     my ($input) = @_;
 9947:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9948:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9949:     return $input;
 9950: }
 9951: 
 9952: #  Same as escape_single, but escape's "'s  This 
 9953: #  can be used for  "strings"
 9954: sub escape_double {
 9955:     my ($input) = @_;
 9956:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9957:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9958:     return $input;
 9959: }
 9960:  
 9961: #   Escapes the last element of a full URL.
 9962: sub escape_url {
 9963:     my ($url)   = @_;
 9964:     my @urlslices = split(/\//, $url,-1);
 9965:     my $lastitem = &escape(pop(@urlslices));
 9966:     return join('/',@urlslices).'/'.$lastitem;
 9967: }
 9968: 
 9969: # -------------------------------------------------------- Initliaze user login
 9970: sub init_user_environment {
 9971:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9972:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9973: 
 9974:     my $public=($username eq 'public' && $domain eq 'public');
 9975: 
 9976: # See if old ID present, if so, remove
 9977: 
 9978:     my ($filename,$cookie,$userroles);
 9979:     my $now=time;
 9980: 
 9981:     if ($public) {
 9982: 	my $max_public=100;
 9983: 	my $oldest;
 9984: 	my $oldest_time=0;
 9985: 	for(my $next=1;$next<=$max_public;$next++) {
 9986: 	    if (-e $lonids."/publicuser_$next.id") {
 9987: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9988: 		if ($mtime<$oldest_time || !$oldest_time) {
 9989: 		    $oldest_time=$mtime;
 9990: 		    $oldest=$next;
 9991: 		}
 9992: 	    } else {
 9993: 		$cookie="publicuser_$next";
 9994: 		last;
 9995: 	    }
 9996: 	}
 9997: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9998:     } else {
 9999: 	# if this isn't a robot, kill any existing non-robot sessions
10000: 	if (!$args->{'robot'}) {
10001: 	    opendir(DIR,$lonids);
10002: 	    while ($filename=readdir(DIR)) {
10003: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10004: 		    unlink($lonids.'/'.$filename);
10005: 		}
10006: 	    }
10007: 	    closedir(DIR);
10008: 	}
10009: # Give them a new cookie
10010: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10011: 		                   : $now.$$.int(rand(10000)));
10012: 	$cookie="$username\_$id\_$domain\_$authhost";
10013:     
10014: # Initialize roles
10015: 
10016: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10017:     }
10018: # ------------------------------------ Check browser type and MathML capability
10019: 
10020:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10021:         $clientunicode,$clientos) = &decode_user_agent($r);
10022: 
10023: # -------------------------------------- Any accessibility options to remember?
10024:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
10025: 	foreach my $option ('imagesuppress','appletsuppress',
10026: 			    'embedsuppress','fontenhance','blackwhite') {
10027: 	    if ($form->{$option} eq 'true') {
10028: 		&Apache::lonnet::put('environment',{$option => 'on'},
10029: 				     $domain,$username);
10030: 	    } else {
10031: 		&Apache::lonnet::del('environment',[$option],
10032: 				     $domain,$username);
10033: 	    }
10034: 	}
10035:     }
10036: # ------------------------------------------------------------- Get environment
10037: 
10038:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10039:     my ($tmp) = keys(%userenv);
10040:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10041: 	# default remote control to off
10042: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10043:     } else {
10044: 	undef(%userenv);
10045:     }
10046:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10047: 	$form->{'interface'}=$userenv{'interface'};
10048:     }
10049:     $env{'environment.remote'}=$userenv{'remote'};
10050:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10051: 
10052: # --------------- Do not trust query string to be put directly into environment
10053:     foreach my $option ('imagesuppress','appletsuppress',
10054: 			'embedsuppress','fontenhance','blackwhite',
10055: 			'interface','localpath','localres') {
10056: 	$form->{$option}=~s/[\n\r\=]//gs;
10057:     }
10058: # --------------------------------------------------------- Write first profile
10059: 
10060:     {
10061: 	my %initial_env = 
10062: 	    ("user.name"          => $username,
10063: 	     "user.domain"        => $domain,
10064: 	     "user.home"          => $authhost,
10065: 	     "browser.type"       => $clientbrowser,
10066: 	     "browser.version"    => $clientversion,
10067: 	     "browser.mathml"     => $clientmathml,
10068: 	     "browser.unicode"    => $clientunicode,
10069: 	     "browser.os"         => $clientos,
10070: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10071: 	     "request.course.fn"  => '',
10072: 	     "request.course.uri" => '',
10073: 	     "request.course.sec" => '',
10074: 	     "request.role"       => 'cm',
10075: 	     "request.role.adv"   => $env{'user.adv'},
10076: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10077: 
10078:         if ($form->{'localpath'}) {
10079: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10080: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10081:         }
10082: 	
10083: 	if ($public) {
10084: 	    $initial_env{"environment.remote"} = "off";
10085: 	}
10086: 	if ($form->{'interface'}) {
10087: 	    $form->{'interface'}=~s/\W//gs;
10088: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10089: 	    $env{'browser.interface'}=$form->{'interface'};
10090: 	    foreach my $option ('imagesuppress','appletsuppress',
10091: 				'embedsuppress','fontenhance','blackwhite') {
10092: 		if (($form->{$option} eq 'true') ||
10093: 		    ($userenv{$option} eq 'on')) {
10094: 		    $initial_env{"browser.$option"} = "on";
10095: 		}
10096: 	    }
10097: 	}
10098: 
10099:         foreach my $tool ('aboutme','blog','portfolio') {
10100:             $userenv{'availabletools.'.$tool} = 
10101:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10102:         }
10103: 
10104:         foreach my $crstype ('official','unofficial') {
10105:             $userenv{'canrequest.'.$crstype} =
10106:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10107:                                                   'reload','requestcourses');
10108:         }
10109: 
10110: 	$env{'user.environment'} = "$lonids/$cookie.id";
10111: 	
10112: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10113: 		 &GDBM_WRCREAT(),0640)) {
10114: 	    &_add_to_env(\%disk_env,\%initial_env);
10115: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10116: 	    &_add_to_env(\%disk_env,$userroles);
10117: 	    if (ref($args->{'extra_env'})) {
10118: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10119: 	    }
10120: 	    untie(%disk_env);
10121: 	} else {
10122: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10123: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10124: 	    return 'error: '.$!;
10125: 	}
10126:     }
10127:     $env{'request.role'}='cm';
10128:     $env{'request.role.adv'}=$env{'user.adv'};
10129:     $env{'browser.type'}=$clientbrowser;
10130: 
10131:     return $cookie;
10132: 
10133: }
10134: 
10135: sub _add_to_env {
10136:     my ($idf,$env_data,$prefix) = @_;
10137:     if (ref($env_data) eq 'HASH') {
10138:         while (my ($key,$value) = each(%$env_data)) {
10139: 	    $idf->{$prefix.$key} = $value;
10140: 	    $env{$prefix.$key}   = $value;
10141:         }
10142:     }
10143: }
10144: 
10145: # --- Get the symbolic name of a problem and the url
10146: sub get_symb {
10147:     my ($request,$silent) = @_;
10148:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10149:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10150:     if ($symb eq '') {
10151:         if (!$silent) {
10152:             $request->print("Unable to handle ambiguous references:$url:.");
10153:             return ();
10154:         }
10155:     }
10156:     &Apache::lonenc::check_decrypt(\$symb);
10157:     return ($symb);
10158: }
10159: 
10160: # --------------------------------------------------------------Get annotation
10161: 
10162: sub get_annotation {
10163:     my ($symb,$enc) = @_;
10164: 
10165:     my $key = $symb;
10166:     if (!$enc) {
10167:         $key =
10168:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10169:     }
10170:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10171:     return $annotation{$key};
10172: }
10173: 
10174: sub clean_symb {
10175:     my ($symb,$delete_enc) = @_;
10176: 
10177:     &Apache::lonenc::check_decrypt(\$symb);
10178:     my $enc = $env{'request.enc'};
10179:     if ($delete_enc) {
10180:         delete($env{'request.enc'});
10181:     }
10182: 
10183:     return ($symb,$enc);
10184: }
10185: 
10186: =pod
10187: 
10188: =back
10189: 
10190: =cut
10191: 
10192: 1;
10193: __END__;
10194: 

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