File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.752: download - view: text, annotated - select for diffs
Sun Feb 22 18:30:27 2009 UTC (15 years, 3 months ago) by harmsja
Branches: MAIN
CVS tags: HEAD
deleted the resize feature after LC_columnSection. it resized LC_ContentBox and
LC_ContentBoxSpecial to 400px. If you want to change the size of an element please use LC_xxxBox for 300, 400, 500, 600 and 800px. example:
<div class="LC_ContentBox LC_400Box">

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.752 2009/02/22 18:30:27 harmsja 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">
  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">
  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 "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  606:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  607: }
  608: 
  609: sub selectauthor_link {
  610:    my ($form,$udom)=@_;
  611:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  612:           &mt('Select Author').'</a>';
  613: }
  614: 
  615: sub check_uncheck_jscript {
  616:     my $jscript = <<"ENDSCRT";
  617: function checkAll(field) {
  618:     if (field.length > 0) {
  619:         for (i = 0; i < field.length; i++) {
  620:             field[i].checked = true ;
  621:         }
  622:     } else {
  623:         field.checked = true
  624:     }
  625: }
  626:  
  627: function uncheckAll(field) {
  628:     if (field.length > 0) {
  629:         for (i = 0; i < field.length; i++) {
  630:             field[i].checked = false ;
  631:         }
  632:     } else {
  633:         field.checked = false ;
  634:     }
  635: }
  636: ENDSCRT
  637:     return $jscript;
  638: }
  639: 
  640: sub select_timezone {
  641:    my ($name,$selected,$onchange,$includeempty)=@_;
  642:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  643:    if ($includeempty) {
  644:        $output .= '<option value=""';
  645:        if (($selected eq '') || ($selected eq 'local')) {
  646:            $output .= ' selected="selected" ';
  647:        }
  648:        $output .= '> </option>';
  649:    }
  650:    my @timezones = DateTime::TimeZone->all_names;
  651:    foreach my $tzone (@timezones) {
  652:        $output.= '<option value="'.$tzone.'"';
  653:        if ($tzone eq $selected) {
  654:            $output.=' selected="selected"';
  655:        }
  656:        $output.=">$tzone</option>\n";
  657:    }
  658:    $output.="</select>";
  659:    return $output;
  660: }
  661: 
  662: sub select_datelocale {
  663:     my ($name,$selected,$onchange,$includeempty)=@_;
  664:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  665:     if ($includeempty) {
  666:         $output .= '<option value=""';
  667:         if ($selected eq '') {
  668:             $output .= ' selected="selected" ';
  669:         }
  670:         $output .= '> </option>';
  671:     }
  672:     my (@possibles,%locale_names);
  673:     my @locales = DateTime::Locale::Catalog::Locales;
  674:     foreach my $locale (@locales) {
  675:         if (ref($locale) eq 'HASH') {
  676:             my $id = $locale->{'id'};
  677:             if ($id ne '') {
  678:                 my $en_terr = $locale->{'en_territory'};
  679:                 my $native_terr = $locale->{'native_territory'};
  680:                 my @languages = &Apache::lonlocal::preferred_languages();
  681:                 if (grep(/^en$/,@languages) || !@languages) {
  682:                     if ($en_terr ne '') {
  683:                         $locale_names{$id} = '('.$en_terr.')';
  684:                     } elsif ($native_terr ne '') {
  685:                         $locale_names{$id} = $native_terr;
  686:                     }
  687:                 } else {
  688:                     if ($native_terr ne '') {
  689:                         $locale_names{$id} = $native_terr.' ';
  690:                     } elsif ($en_terr ne '') {
  691:                         $locale_names{$id} = '('.$en_terr.')';
  692:                     }
  693:                 }
  694:                 push (@possibles,$id);
  695:             }
  696:         }
  697:     }
  698:     foreach my $item (sort(@possibles)) {
  699:         $output.= '<option value="'.$item.'"';
  700:         if ($item eq $selected) {
  701:             $output.=' selected="selected"';
  702:         }
  703:         $output.=">$item";
  704:         if ($locale_names{$item} ne '') {
  705:             $output.="  $locale_names{$item}</option>\n";
  706:         }
  707:         $output.="</option>\n";
  708:     }
  709:     $output.="</select>";
  710:     return $output;
  711: }
  712: 
  713: =pod
  714: 
  715: =item * &linked_select_forms(...)
  716: 
  717: linked_select_forms returns a string containing a <script></script> block
  718: and html for two <select> menus.  The select menus will be linked in that
  719: changing the value of the first menu will result in new values being placed
  720: in the second menu.  The values in the select menu will appear in alphabetical
  721: order unless a defined order is provided.
  722: 
  723: linked_select_forms takes the following ordered inputs:
  724: 
  725: =over 4
  726: 
  727: =item * $formname, the name of the <form> tag
  728: 
  729: =item * $middletext, the text which appears between the <select> tags
  730: 
  731: =item * $firstdefault, the default value for the first menu
  732: 
  733: =item * $firstselectname, the name of the first <select> tag
  734: 
  735: =item * $secondselectname, the name of the second <select> tag
  736: 
  737: =item * $hashref, a reference to a hash containing the data for the menus.
  738: 
  739: =item * $menuorder, the order of values in the first menu
  740: 
  741: =back 
  742: 
  743: Below is an example of such a hash.  Only the 'text', 'default', and 
  744: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  745: values for the first select menu.  The text that coincides with the 
  746: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  747: and text for the second menu are given in the hash pointed to by 
  748: $menu{$choice1}->{'select2'}.  
  749: 
  750:  my %menu = ( A1 => { text =>"Choice A1" ,
  751:                        default => "B3",
  752:                        select2 => { 
  753:                            B1 => "Choice B1",
  754:                            B2 => "Choice B2",
  755:                            B3 => "Choice B3",
  756:                            B4 => "Choice B4"
  757:                            },
  758:                        order => ['B4','B3','B1','B2'],
  759:                    },
  760:                A2 => { text =>"Choice A2" ,
  761:                        default => "C2",
  762:                        select2 => { 
  763:                            C1 => "Choice C1",
  764:                            C2 => "Choice C2",
  765:                            C3 => "Choice C3"
  766:                            },
  767:                        order => ['C2','C1','C3'],
  768:                    },
  769:                A3 => { text =>"Choice A3" ,
  770:                        default => "D6",
  771:                        select2 => { 
  772:                            D1 => "Choice D1",
  773:                            D2 => "Choice D2",
  774:                            D3 => "Choice D3",
  775:                            D4 => "Choice D4",
  776:                            D5 => "Choice D5",
  777:                            D6 => "Choice D6",
  778:                            D7 => "Choice D7"
  779:                            },
  780:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  781:                    }
  782:                );
  783: 
  784: =cut
  785: 
  786: sub linked_select_forms {
  787:     my ($formname,
  788:         $middletext,
  789:         $firstdefault,
  790:         $firstselectname,
  791:         $secondselectname, 
  792:         $hashref,
  793:         $menuorder,
  794:         ) = @_;
  795:     my $second = "document.$formname.$secondselectname";
  796:     my $first = "document.$formname.$firstselectname";
  797:     # output the javascript to do the changing
  798:     my $result = '';
  799:     $result.="<script type=\"text/javascript\">\n";
  800:     $result.="var select2data = new Object();\n";
  801:     $" = '","';
  802:     my $debug = '';
  803:     foreach my $s1 (sort(keys(%$hashref))) {
  804:         $result.="select2data.d_$s1 = new Object();\n";        
  805:         $result.="select2data.d_$s1.def = new String('".
  806:             $hashref->{$s1}->{'default'}."');\n";
  807:         $result.="select2data.d_$s1.values = new Array(";
  808:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  809:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  810:             @s2values = @{$hashref->{$s1}->{'order'}};
  811:         }
  812:         $result.="\"@s2values\");\n";
  813:         $result.="select2data.d_$s1.texts = new Array(";        
  814:         my @s2texts;
  815:         foreach my $value (@s2values) {
  816:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  817:         }
  818:         $result.="\"@s2texts\");\n";
  819:     }
  820:     $"=' ';
  821:     $result.= <<"END";
  822: 
  823: function select1_changed() {
  824:     // Determine new choice
  825:     var newvalue = "d_" + $first.value;
  826:     // update select2
  827:     var values     = select2data[newvalue].values;
  828:     var texts      = select2data[newvalue].texts;
  829:     var select2def = select2data[newvalue].def;
  830:     var i;
  831:     // out with the old
  832:     for (i = 0; i < $second.options.length; i++) {
  833:         $second.options[i] = null;
  834:     }
  835:     // in with the nuclear
  836:     for (i=0;i<values.length; i++) {
  837:         $second.options[i] = new Option(values[i]);
  838:         $second.options[i].value = values[i];
  839:         $second.options[i].text = texts[i];
  840:         if (values[i] == select2def) {
  841:             $second.options[i].selected = true;
  842:         }
  843:     }
  844: }
  845: </script>
  846: END
  847:     # output the initial values for the selection lists
  848:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  849:     my @order = sort(keys(%{$hashref}));
  850:     if (ref($menuorder) eq 'ARRAY') {
  851:         @order = @{$menuorder};
  852:     }
  853:     foreach my $value (@order) {
  854:         $result.="    <option value=\"$value\" ";
  855:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  856:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  857:     }
  858:     $result .= "</select>\n";
  859:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  860:     $result .= $middletext;
  861:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  862:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  863:     
  864:     my @secondorder = sort(keys(%select2));
  865:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  866:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  867:     }
  868:     foreach my $value (@secondorder) {
  869:         $result.="    <option value=\"$value\" ";        
  870:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  871:         $result.=">".&mt($select2{$value})."</option>\n";
  872:     }
  873:     $result .= "</select>\n";
  874:     #    return $debug;
  875:     return $result;
  876: }   #  end of sub linked_select_forms {
  877: 
  878: =pod
  879: 
  880: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  881: 
  882: Returns a string corresponding to an HTML link to the given help
  883: $topic, where $topic corresponds to the name of a .tex file in
  884: /home/httpd/html/adm/help/tex, with underscores replaced by
  885: spaces. 
  886: 
  887: $text will optionally be linked to the same topic, allowing you to
  888: link text in addition to the graphic. If you do not want to link
  889: text, but wish to specify one of the later parameters, pass an
  890: empty string. 
  891: 
  892: $stayOnPage is a value that will be interpreted as a boolean. If true,
  893: the link will not open a new window. If false, the link will open
  894: a new window using Javascript. (Default is false.) 
  895: 
  896: $width and $height are optional numerical parameters that will
  897: override the width and height of the popped up window, which may
  898: be useful for certain help topics with big pictures included. 
  899: 
  900: =cut
  901: 
  902: sub help_open_topic {
  903:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  904:     $text = "" if (not defined $text);
  905:     $stayOnPage = 0 if (not defined $stayOnPage);
  906:     if ($env{'browser.interface'} eq 'textual') {
  907: 	$stayOnPage=1;
  908:     }
  909:     $width = 350 if (not defined $width);
  910:     $height = 400 if (not defined $height);
  911:     my $filename = $topic;
  912:     $filename =~ s/ /_/g;
  913: 
  914:     my $template = "";
  915:     my $link;
  916:     
  917:     $topic=~s/\W/\_/g;
  918: 
  919:     if (!$stayOnPage) {
  920: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  921:     } else {
  922: 	$link = "/adm/help/${filename}.hlp";
  923:     }
  924: 
  925:     # Add the text
  926:     if ($text ne "") {
  927: 	$template .= 
  928:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  929:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
  930:     }
  931: 
  932:     # Add the graphic
  933:     my $title = &mt('Online Help');
  934:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  935:     $template .= <<"ENDTEMPLATE";
  936:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  937: ENDTEMPLATE
  938:     if ($text ne '') { $template.='</td></tr></table>' };
  939:     return $template;
  940: 
  941: }
  942: 
  943: # This is a quicky function for Latex cheatsheet editing, since it 
  944: # appears in at least four places
  945: sub helpLatexCheatsheet {
  946:     my ($topic,$text,$not_author) = @_;
  947:     my $out;
  948:     my $addOther = '';
  949:     if ($topic) {
  950: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
  951: 						       undef, undef, 600).
  952: 							   '</td><td>';
  953:     }
  954:     $out = '<table><tr><td>'.
  955: 	   $addOther .
  956: 	   &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  957: 					       undef,undef,600).
  958: 	   '</td><td>'.
  959: 	   &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
  960: 					       undef,undef,600).
  961: 	   '</td>';
  962:     unless ($not_author) {
  963:         $out .= '<td>'.
  964: 	        &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
  965: 	                                            undef,undef,600).
  966: 	        '</td>';
  967:     }
  968:     $out .= '</tr></table>';
  969:     return $out;
  970: }
  971: 
  972: sub general_help {
  973:     my $helptopic='Student_Intro';
  974:     if ($env{'request.role'}=~/^(ca|au)/) {
  975: 	$helptopic='Authoring_Intro';
  976:     } elsif ($env{'request.role'}=~/^cc/) {
  977: 	$helptopic='Course_Coordination_Intro';
  978:     } elsif ($env{'request.role'}=~/^dc/) {
  979:         $helptopic='Domain_Coordination_Intro';
  980:     }
  981:     return $helptopic;
  982: }
  983: 
  984: sub update_help_link {
  985:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  986:     my $origurl = $ENV{'REQUEST_URI'};
  987:     $origurl=~s|^/~|/priv/|;
  988:     my $timestamp = time;
  989:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  990:         $$datum = &escape($$datum);
  991:     }
  992: 
  993:     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";
  994:     my $output .= <<"ENDOUTPUT";
  995: <script type="text/javascript">
  996: banner_link = '$banner_link';
  997: </script>
  998: ENDOUTPUT
  999:     return $output;
 1000: }
 1001: 
 1002: # now just updates the help link and generates a blue icon
 1003: sub help_open_menu {
 1004:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1005: 	= @_;    
 1006:     $stayOnPage = 0 if (not defined $stayOnPage);
 1007:     # only use pop-up help (stayOnPage == 0)
 1008:     # if environment.remote is on (using remote control UI)
 1009:     if ($env{'browser.interface'} eq 'textual' ||
 1010:     	$env{'environment.remote'} eq 'off' ) {
 1011:         $stayOnPage=1;
 1012:     }
 1013:     my $output;
 1014:     if ($component_help) {
 1015: 	if (!$text) {
 1016: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1017: 				       $width,$height);
 1018: 	} else {
 1019: 	    my $help_text;
 1020: 	    $help_text=&unescape($topic);
 1021: 	    $output='<table><tr><td>'.
 1022: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1023: 				 $width,$height).'</td></tr></table>';
 1024: 	}
 1025:     }
 1026:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1027:     return $output.$banner_link;
 1028: }
 1029: 
 1030: sub top_nav_help {
 1031:     my ($text) = @_;
 1032:     $text = &mt($text);
 1033:     my $stay_on_page = 
 1034: 	($env{'browser.interface'}  eq 'textual' ||
 1035: 	 $env{'environment.remote'} eq 'off' );
 1036:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1037: 	                     : "javascript:helpMenu('open')";
 1038:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1039: 
 1040:     my $title = &mt('Get help');
 1041: 
 1042:     return <<"END";
 1043: $banner_link
 1044:  <a href="$link" title="$title">$text</a>
 1045: END
 1046: }
 1047: 
 1048: sub help_menu_js {
 1049:     my ($text) = @_;
 1050: 
 1051:     my $stayOnPage = 
 1052: 	($env{'browser.interface'}  eq 'textual' ||
 1053: 	 $env{'environment.remote'} eq 'off' );
 1054: 
 1055:     my $width = 620;
 1056:     my $height = 600;
 1057:     my $helptopic=&general_help();
 1058:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1059:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1060:     my $start_page =
 1061:         &Apache::loncommon::start_page('Help Menu', undef,
 1062: 				       {'frameset'    => 1,
 1063: 					'js_ready'    => 1,
 1064: 					'add_entries' => {
 1065: 					    'border' => '0',
 1066: 					    'rows'   => "110,*",},});
 1067:     my $end_page =
 1068:         &Apache::loncommon::end_page({'frameset' => 1,
 1069: 				      'js_ready' => 1,});
 1070: 
 1071:     my $template .= <<"ENDTEMPLATE";
 1072: <script type="text/javascript">
 1073: // <!-- BEGIN LON-CAPA Internal
 1074: // <![CDATA[
 1075: var banner_link = '';
 1076: function helpMenu(target) {
 1077:     var caller = this;
 1078:     if (target == 'open') {
 1079:         var newWindow = null;
 1080:         try {
 1081:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1082:         }
 1083:         catch(error) {
 1084:             writeHelp(caller);
 1085:             return;
 1086:         }
 1087:         if (newWindow) {
 1088:             caller = newWindow;
 1089:         }
 1090:     }
 1091:     writeHelp(caller);
 1092:     return;
 1093: }
 1094: function writeHelp(caller) {
 1095:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1096:     caller.document.close()
 1097:     caller.focus()
 1098: }
 1099: // ]]>
 1100: // END LON-CAPA Internal -->
 1101: </script>
 1102: ENDTEMPLATE
 1103:     return $template;
 1104: }
 1105: 
 1106: sub help_open_bug {
 1107:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1108:     unless ($env{'user.adv'}) { return ''; }
 1109:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1110:     $text = "" if (not defined $text);
 1111:     $stayOnPage = 0 if (not defined $stayOnPage);
 1112:     if ($env{'browser.interface'} eq 'textual' ||
 1113: 	$env{'environment.remote'} eq 'off' ) {
 1114: 	$stayOnPage=1;
 1115:     }
 1116:     $width = 600 if (not defined $width);
 1117:     $height = 600 if (not defined $height);
 1118: 
 1119:     $topic=~s/\W+/\+/g;
 1120:     my $link='';
 1121:     my $template='';
 1122:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1123: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1124:     if (!$stayOnPage)
 1125:     {
 1126: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1127:     }
 1128:     else
 1129:     {
 1130: 	$link = $url;
 1131:     }
 1132:     # Add the text
 1133:     if ($text ne "")
 1134:     {
 1135: 	$template .= 
 1136:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1137:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1138:     }
 1139: 
 1140:     # Add the graphic
 1141:     my $title = &mt('Report a Bug');
 1142:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1143:     $template .= <<"ENDTEMPLATE";
 1144:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1145: ENDTEMPLATE
 1146:     if ($text ne '') { $template.='</td></tr></table>' };
 1147:     return $template;
 1148: 
 1149: }
 1150: 
 1151: sub help_open_faq {
 1152:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1153:     unless ($env{'user.adv'}) { return ''; }
 1154:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1155:     $text = "" if (not defined $text);
 1156:     $stayOnPage = 0 if (not defined $stayOnPage);
 1157:     if ($env{'browser.interface'} eq 'textual' ||
 1158: 	$env{'environment.remote'} eq 'off' ) {
 1159: 	$stayOnPage=1;
 1160:     }
 1161:     $width = 350 if (not defined $width);
 1162:     $height = 400 if (not defined $height);
 1163: 
 1164:     $topic=~s/\W+/\+/g;
 1165:     my $link='';
 1166:     my $template='';
 1167:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1168:     if (!$stayOnPage)
 1169:     {
 1170: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1171:     }
 1172:     else
 1173:     {
 1174: 	$link = $url;
 1175:     }
 1176: 
 1177:     # Add the text
 1178:     if ($text ne "")
 1179:     {
 1180: 	$template .= 
 1181:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1182:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1183:     }
 1184: 
 1185:     # Add the graphic
 1186:     my $title = &mt('View the FAQ');
 1187:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1188:     $template .= <<"ENDTEMPLATE";
 1189:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1190: ENDTEMPLATE
 1191:     if ($text ne '') { $template.='</td></tr></table>' };
 1192:     return $template;
 1193: 
 1194: }
 1195: 
 1196: ###############################################################
 1197: ###############################################################
 1198: 
 1199: =pod
 1200: 
 1201: =item * &change_content_javascript():
 1202: 
 1203: This and the next function allow you to create small sections of an
 1204: otherwise static HTML page that you can update on the fly with
 1205: Javascript, even in Netscape 4.
 1206: 
 1207: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1208: must be written to the HTML page once. It will prove the Javascript
 1209: function "change(name, content)". Calling the change function with the
 1210: name of the section 
 1211: you want to update, matching the name passed to C<changable_area>, and
 1212: the new content you want to put in there, will put the content into
 1213: that area.
 1214: 
 1215: B<Note>: Netscape 4 only reserves enough space for the changable area
 1216: to contain room for the original contents. You need to "make space"
 1217: for whatever changes you wish to make, and be B<sure> to check your
 1218: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1219: it's adequate for updating a one-line status display, but little more.
 1220: This script will set the space to 100% width, so you only need to
 1221: worry about height in Netscape 4.
 1222: 
 1223: Modern browsers are much less limiting, and if you can commit to the
 1224: user not using Netscape 4, this feature may be used freely with
 1225: pretty much any HTML.
 1226: 
 1227: =cut
 1228: 
 1229: sub change_content_javascript {
 1230:     # If we're on Netscape 4, we need to use Layer-based code
 1231:     if ($env{'browser.type'} eq 'netscape' &&
 1232: 	$env{'browser.version'} =~ /^4\./) {
 1233: 	return (<<NETSCAPE4);
 1234: 	function change(name, content) {
 1235: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1236: 	    doc.open();
 1237: 	    doc.write(content);
 1238: 	    doc.close();
 1239: 	}
 1240: NETSCAPE4
 1241:     } else {
 1242: 	# Otherwise, we need to use semi-standards-compliant code
 1243: 	# (technically, "innerHTML" isn't standard but the equivalent
 1244: 	# is really scary, and every useful browser supports it
 1245: 	return (<<DOMBASED);
 1246: 	function change(name, content) {
 1247: 	    element = document.getElementById(name);
 1248: 	    element.innerHTML = content;
 1249: 	}
 1250: DOMBASED
 1251:     }
 1252: }
 1253: 
 1254: =pod
 1255: 
 1256: =item * &changable_area($name,$origContent):
 1257: 
 1258: This provides a "changable area" that can be modified on the fly via
 1259: the Javascript code provided in C<change_content_javascript>. $name is
 1260: the name you will use to reference the area later; do not repeat the
 1261: same name on a given HTML page more then once. $origContent is what
 1262: the area will originally contain, which can be left blank.
 1263: 
 1264: =cut
 1265: 
 1266: sub changable_area {
 1267:     my ($name, $origContent) = @_;
 1268: 
 1269:     if ($env{'browser.type'} eq 'netscape' &&
 1270: 	$env{'browser.version'} =~ /^4\./) {
 1271: 	# If this is netscape 4, we need to use the Layer tag
 1272: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1273:     } else {
 1274: 	return "<span id='$name'>$origContent</span>";
 1275:     }
 1276: }
 1277: 
 1278: =pod
 1279: 
 1280: =item * &viewport_geometry_js 
 1281: 
 1282: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1283: 
 1284: =cut
 1285: 
 1286: 
 1287: sub viewport_geometry_js { 
 1288:     return <<"GEOMETRY";
 1289: var Geometry = {};
 1290: function init_geometry() {
 1291:     if (Geometry.init) { return };
 1292:     Geometry.init=1;
 1293:     if (window.innerHeight) {
 1294:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1295:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1296:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1297:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1298:     }
 1299:     else if (document.documentElement && document.documentElement.clientHeight) {
 1300:         Geometry.getViewportHeight =
 1301:             function() { return document.documentElement.clientHeight; };
 1302:         Geometry.getViewportWidth =
 1303:             function() { return document.documentElement.clientWidth; };
 1304: 
 1305:         Geometry.getHorizontalScroll =
 1306:             function() { return document.documentElement.scrollLeft; };
 1307:         Geometry.getVerticalScroll =
 1308:             function() { return document.documentElement.scrollTop; };
 1309:     }
 1310:     else if (document.body.clientHeight) {
 1311:         Geometry.getViewportHeight =
 1312:             function() { return document.body.clientHeight; };
 1313:         Geometry.getViewportWidth =
 1314:             function() { return document.body.clientWidth; };
 1315:         Geometry.getHorizontalScroll =
 1316:             function() { return document.body.scrollLeft; };
 1317:         Geometry.getVerticalScroll =
 1318:             function() { return document.body.scrollTop; };
 1319:     }
 1320: }
 1321: 
 1322: GEOMETRY
 1323: }
 1324: 
 1325: =pod
 1326: 
 1327: =item * &viewport_size_js()
 1328: 
 1329: 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. 
 1330: 
 1331: =cut
 1332: 
 1333: sub viewport_size_js {
 1334:     my $geometry = &viewport_geometry_js();
 1335:     return <<"DIMS";
 1336: 
 1337: $geometry
 1338: 
 1339: function getViewportDims(width,height) {
 1340:     init_geometry();
 1341:     width.value = Geometry.getViewportWidth();
 1342:     height.value = Geometry.getViewportHeight();
 1343:     return;
 1344: }
 1345: 
 1346: DIMS
 1347: }
 1348: 
 1349: =pod
 1350: 
 1351: =item * &resize_textarea_js()
 1352: 
 1353: emits the needed javascript to resize a textarea to be as big as possible
 1354: 
 1355: creates a function resize_textrea that takes two IDs first should be
 1356: the id of the element to resize, second should be the id of a div that
 1357: surrounds everything that comes after the textarea, this routine needs
 1358: to be attached to the <body> for the onload and onresize events.
 1359: 
 1360: =back
 1361: 
 1362: =cut
 1363: 
 1364: sub resize_textarea_js {
 1365:     my $geometry = &viewport_geometry_js();
 1366:     return <<"RESIZE";
 1367:     <script type="text/javascript">
 1368: $geometry
 1369: 
 1370: function getX(element) {
 1371:     var x = 0;
 1372:     while (element) {
 1373: 	x += element.offsetLeft;
 1374: 	element = element.offsetParent;
 1375:     }
 1376:     return x;
 1377: }
 1378: function getY(element) {
 1379:     var y = 0;
 1380:     while (element) {
 1381: 	y += element.offsetTop;
 1382: 	element = element.offsetParent;
 1383:     }
 1384:     return y;
 1385: }
 1386: 
 1387: 
 1388: function resize_textarea(textarea_id,bottom_id) {
 1389:     init_geometry();
 1390:     var textarea        = document.getElementById(textarea_id);
 1391:     //alert(textarea);
 1392: 
 1393:     var textarea_top    = getY(textarea);
 1394:     var textarea_height = textarea.offsetHeight;
 1395:     var bottom          = document.getElementById(bottom_id);
 1396:     var bottom_top      = getY(bottom);
 1397:     var bottom_height   = bottom.offsetHeight;
 1398:     var window_height   = Geometry.getViewportHeight();
 1399:     var fudge           = 23;
 1400:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1401:     if (new_height < 300) {
 1402: 	new_height = 300;
 1403:     }
 1404:     textarea.style.height=new_height+'px';
 1405: }
 1406: </script>
 1407: RESIZE
 1408: 
 1409: }
 1410: 
 1411: =pod
 1412: 
 1413: =head1 Excel and CSV file utility routines
 1414: 
 1415: =over 4
 1416: 
 1417: =cut
 1418: 
 1419: ###############################################################
 1420: ###############################################################
 1421: 
 1422: =pod
 1423: 
 1424: =item * &csv_translate($text) 
 1425: 
 1426: Translate $text to allow it to be output as a 'comma separated values' 
 1427: format.
 1428: 
 1429: =cut
 1430: 
 1431: ###############################################################
 1432: ###############################################################
 1433: sub csv_translate {
 1434:     my $text = shift;
 1435:     $text =~ s/\"/\"\"/g;
 1436:     $text =~ s/\n/ /g;
 1437:     return $text;
 1438: }
 1439: 
 1440: ###############################################################
 1441: ###############################################################
 1442: 
 1443: =pod
 1444: 
 1445: =item * &define_excel_formats()
 1446: 
 1447: Define some commonly used Excel cell formats.
 1448: 
 1449: Currently supported formats:
 1450: 
 1451: =over 4
 1452: 
 1453: =item header
 1454: 
 1455: =item bold
 1456: 
 1457: =item h1
 1458: 
 1459: =item h2
 1460: 
 1461: =item h3
 1462: 
 1463: =item h4
 1464: 
 1465: =item i
 1466: 
 1467: =item date
 1468: 
 1469: =back
 1470: 
 1471: Inputs: $workbook
 1472: 
 1473: Returns: $format, a hash reference.
 1474: 
 1475: =cut
 1476: 
 1477: ###############################################################
 1478: ###############################################################
 1479: sub define_excel_formats {
 1480:     my ($workbook) = @_;
 1481:     my $format;
 1482:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1483:                                                 bottom    => 1,
 1484:                                                 align     => 'center');
 1485:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1486:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1487:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1488:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1489:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1490:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1491:     $format->{'date'} = $workbook->add_format(num_format=>
 1492:                                             'mm/dd/yyyy hh:mm:ss');
 1493:     return $format;
 1494: }
 1495: 
 1496: ###############################################################
 1497: ###############################################################
 1498: 
 1499: =pod
 1500: 
 1501: =item * &create_workbook()
 1502: 
 1503: Create an Excel worksheet.  If it fails, output message on the
 1504: request object and return undefs.
 1505: 
 1506: Inputs: Apache request object
 1507: 
 1508: Returns (undef) on failure, 
 1509:     Excel worksheet object, scalar with filename, and formats 
 1510:     from &Apache::loncommon::define_excel_formats on success
 1511: 
 1512: =cut
 1513: 
 1514: ###############################################################
 1515: ###############################################################
 1516: sub create_workbook {
 1517:     my ($r) = @_;
 1518:         #
 1519:     # Create the excel spreadsheet
 1520:     my $filename = '/prtspool/'.
 1521:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1522:         time.'_'.rand(1000000000).'.xls';
 1523:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1524:     if (! defined($workbook)) {
 1525:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1526:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1527:                             "This error has been logged.  ".
 1528:                             "Please alert your LON-CAPA administrator").
 1529:                   '</p>');
 1530:         return (undef);
 1531:     }
 1532:     #
 1533:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1534:     #
 1535:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1536:     return ($workbook,$filename,$format);
 1537: }
 1538: 
 1539: ###############################################################
 1540: ###############################################################
 1541: 
 1542: =pod
 1543: 
 1544: =item * &create_text_file()
 1545: 
 1546: Create a file to write to and eventually make available to the user.
 1547: If file creation fails, outputs an error message on the request object and 
 1548: return undefs.
 1549: 
 1550: Inputs: Apache request object, and file suffix
 1551: 
 1552: Returns (undef) on failure, 
 1553:     Filehandle and filename on success.
 1554: 
 1555: =cut
 1556: 
 1557: ###############################################################
 1558: ###############################################################
 1559: sub create_text_file {
 1560:     my ($r,$suffix) = @_;
 1561:     if (! defined($suffix)) { $suffix = 'txt'; };
 1562:     my $fh;
 1563:     my $filename = '/prtspool/'.
 1564:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1565:         time.'_'.rand(1000000000).'.'.$suffix;
 1566:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1567:     if (! defined($fh)) {
 1568:         $r->log_error("Couldn't open $filename for output $!");
 1569:         $r->print(&mt('Problems occurred in creating the output file. '
 1570:                      .'This error has been logged. '
 1571:                      .'Please alert your LON-CAPA administrator.'));
 1572:     }
 1573:     return ($fh,$filename)
 1574: }
 1575: 
 1576: 
 1577: =pod 
 1578: 
 1579: =back
 1580: 
 1581: =cut
 1582: 
 1583: ###############################################################
 1584: ##        Home server <option> list generating code          ##
 1585: ###############################################################
 1586: 
 1587: # ------------------------------------------
 1588: 
 1589: sub domain_select {
 1590:     my ($name,$value,$multiple)=@_;
 1591:     my %domains=map { 
 1592: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1593:     } &Apache::lonnet::all_domains();
 1594:     if ($multiple) {
 1595: 	$domains{''}=&mt('Any domain');
 1596: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1597: 	return &multiple_select_form($name,$value,4,\%domains);
 1598:     } else {
 1599: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1600: 	return &select_form($name,$value,%domains);
 1601:     }
 1602: }
 1603: 
 1604: #-------------------------------------------
 1605: 
 1606: =pod
 1607: 
 1608: =head1 Routines for form select boxes
 1609: 
 1610: =over 4
 1611: 
 1612: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1613: 
 1614: Returns a string containing a <select> element int multiple mode
 1615: 
 1616: 
 1617: Args:
 1618:   $name - name of the <select> element
 1619:   $value - scalar or array ref of values that should already be selected
 1620:   $size - number of rows long the select element is
 1621:   $hash - the elements should be 'option' => 'shown text'
 1622:           (shown text should already have been &mt())
 1623:   $order - (optional) array ref of the order to show the elements in
 1624: 
 1625: =cut
 1626: 
 1627: #-------------------------------------------
 1628: sub multiple_select_form {
 1629:     my ($name,$value,$size,$hash,$order)=@_;
 1630:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1631:     my $output='';
 1632:     if (! defined($size)) {
 1633:         $size = 4;
 1634:         if (scalar(keys(%$hash))<4) {
 1635:             $size = scalar(keys(%$hash));
 1636:         }
 1637:     }
 1638:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1639:     my @order;
 1640:     if (ref($order) eq 'ARRAY')  {
 1641:         @order = @{$order};
 1642:     } else {
 1643:         @order = sort(keys(%$hash));
 1644:     }
 1645:     if (exists($$hash{'select_form_order'})) {
 1646:         @order = @{$$hash{'select_form_order'}};
 1647:     }
 1648:         
 1649:     foreach my $key (@order) {
 1650:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1651:         $output.='selected="selected" ' if ($selected{$key});
 1652:         $output.='>'.$hash->{$key}."</option>\n";
 1653:     }
 1654:     $output.="</select>\n";
 1655:     return $output;
 1656: }
 1657: 
 1658: #-------------------------------------------
 1659: 
 1660: =pod
 1661: 
 1662: =item * &select_form($defdom,$name,%hash)
 1663: 
 1664: Returns a string containing a <select name='$name' size='1'> form to 
 1665: allow a user to select options from a hash option_name => displayed text.  
 1666: See lonrights.pm for an example invocation and use.
 1667: 
 1668: =cut
 1669: 
 1670: #-------------------------------------------
 1671: sub select_form {
 1672:     my ($def,$name,%hash) = @_;
 1673:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1674:     my @keys;
 1675:     if (exists($hash{'select_form_order'})) {
 1676: 	@keys=@{$hash{'select_form_order'}};
 1677:     } else {
 1678: 	@keys=sort(keys(%hash));
 1679:     }
 1680:     foreach my $key (@keys) {
 1681:         $selectform.=
 1682: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1683:             ($key eq $def ? 'selected="selected" ' : '').
 1684:                 ">".&mt($hash{$key})."</option>\n";
 1685:     }
 1686:     $selectform.="</select>";
 1687:     return $selectform;
 1688: }
 1689: 
 1690: # For display filters
 1691: 
 1692: sub display_filter {
 1693:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1694:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1695:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1696: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1697: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1698: 	   '</label></span> <span class="LC_nobreak">'.
 1699:            &mt('Filter [_1]',
 1700: 	   &select_form($env{'form.displayfilter'},
 1701: 			'displayfilter',
 1702: 			('currentfolder' => 'Current folder/page',
 1703: 			 'containing' => 'Containing phrase',
 1704: 			 'none' => 'None'))).
 1705: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1706: }
 1707: 
 1708: sub gradeleveldescription {
 1709:     my $gradelevel=shift;
 1710:     my %gradelevels=(0 => 'Not specified',
 1711: 		     1 => 'Grade 1',
 1712: 		     2 => 'Grade 2',
 1713: 		     3 => 'Grade 3',
 1714: 		     4 => 'Grade 4',
 1715: 		     5 => 'Grade 5',
 1716: 		     6 => 'Grade 6',
 1717: 		     7 => 'Grade 7',
 1718: 		     8 => 'Grade 8',
 1719: 		     9 => 'Grade 9',
 1720: 		     10 => 'Grade 10',
 1721: 		     11 => 'Grade 11',
 1722: 		     12 => 'Grade 12',
 1723: 		     13 => 'Grade 13',
 1724: 		     14 => '100 Level',
 1725: 		     15 => '200 Level',
 1726: 		     16 => '300 Level',
 1727: 		     17 => '400 Level',
 1728: 		     18 => 'Graduate Level');
 1729:     return &mt($gradelevels{$gradelevel});
 1730: }
 1731: 
 1732: sub select_level_form {
 1733:     my ($deflevel,$name)=@_;
 1734:     unless ($deflevel) { $deflevel=0; }
 1735:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1736:     for (my $i=0; $i<=18; $i++) {
 1737:         $selectform.="<option value=\"$i\" ".
 1738:             ($i==$deflevel ? 'selected="selected" ' : '').
 1739:                 ">".&gradeleveldescription($i)."</option>\n";
 1740:     }
 1741:     $selectform.="</select>";
 1742:     return $selectform;
 1743: }
 1744: 
 1745: #-------------------------------------------
 1746: 
 1747: =pod
 1748: 
 1749: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1750: 
 1751: Returns a string containing a <select name='$name' size='1'> form to 
 1752: allow a user to select the domain to preform an operation in.  
 1753: See loncreateuser.pm for an example invocation and use.
 1754: 
 1755: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1756: selected");
 1757: 
 1758: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1759: 
 1760: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1761: 
 1762: =cut
 1763: 
 1764: #-------------------------------------------
 1765: sub select_dom_form {
 1766:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1767:     my $onchange;
 1768:     if ($autosubmit) {
 1769:         $onchange = ' onchange="this.form.submit()"';
 1770:     }
 1771:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1772:     if ($includeempty) { @domains=('',@domains); }
 1773:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1774:     foreach my $dom (@domains) {
 1775:         $selectdomain.="<option value=\"$dom\" ".
 1776:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1777:         if ($showdomdesc) {
 1778:             if ($dom ne '') {
 1779:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1780:                 if ($domdesc ne '') {
 1781:                     $selectdomain .= ' ('.$domdesc.')';
 1782:                 }
 1783:             } 
 1784:         }
 1785:         $selectdomain .= "</option>\n";
 1786:     }
 1787:     $selectdomain.="</select>";
 1788:     return $selectdomain;
 1789: }
 1790: 
 1791: #-------------------------------------------
 1792: 
 1793: =pod
 1794: 
 1795: =item * &home_server_form_item($domain,$name,$defaultflag)
 1796: 
 1797: input: 4 arguments (two required, two optional) - 
 1798:     $domain - domain of new user
 1799:     $name - name of form element
 1800:     $default - Value of 'default' causes a default item to be first 
 1801:                             option, and selected by default. 
 1802:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1803:                             if 1 server found, or default, if 0 found.
 1804: output: returns 2 items: 
 1805: (a) form element which contains either:
 1806:    (i) <select name="$name">
 1807:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1808:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1809:        </select>
 1810:        form item if there are multiple library servers in $domain, or
 1811:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1812:        if there is only one library server in $domain.
 1813: 
 1814: (b) number of library servers found.
 1815: 
 1816: See loncreateuser.pm for example of use.
 1817: 
 1818: =cut
 1819: 
 1820: #-------------------------------------------
 1821: sub home_server_form_item {
 1822:     my ($domain,$name,$default,$hide) = @_;
 1823:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1824:     my $result;
 1825:     my $numlib = keys(%servers);
 1826:     if ($numlib > 1) {
 1827:         $result .= '<select name="'.$name.'" />'."\n";
 1828:         if ($default) {
 1829:             $result .= '<option value="default" selected>'.&mt('default').
 1830:                        '</option>'."\n";
 1831:         }
 1832:         foreach my $hostid (sort(keys(%servers))) {
 1833:             $result.= '<option value="'.$hostid.'">'.
 1834: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1835:         }
 1836:         $result .= '</select>'."\n";
 1837:     } elsif ($numlib == 1) {
 1838:         my $hostid;
 1839:         foreach my $item (keys(%servers)) {
 1840:             $hostid = $item;
 1841:         }
 1842:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1843:                    $hostid.'" />';
 1844:                    if (!$hide) {
 1845:                        $result .= $hostid.' '.$servers{$hostid};
 1846:                    }
 1847:                    $result .= "\n";
 1848:     } elsif ($default) {
 1849:         $result .= '<input type="hidden" name="'.$name.
 1850:                    '" value="default" />';
 1851:                    if (!$hide) {
 1852:                        $result .= &mt('default');
 1853:                    }
 1854:                    $result .= "\n";
 1855:     }
 1856:     return ($result,$numlib);
 1857: }
 1858: 
 1859: =pod
 1860: 
 1861: =back 
 1862: 
 1863: =cut
 1864: 
 1865: ###############################################################
 1866: ##                  Decoding User Agent                      ##
 1867: ###############################################################
 1868: 
 1869: =pod
 1870: 
 1871: =head1 Decoding the User Agent
 1872: 
 1873: =over 4
 1874: 
 1875: =item * &decode_user_agent()
 1876: 
 1877: Inputs: $r
 1878: 
 1879: Outputs:
 1880: 
 1881: =over 4
 1882: 
 1883: =item * $httpbrowser
 1884: 
 1885: =item * $clientbrowser
 1886: 
 1887: =item * $clientversion
 1888: 
 1889: =item * $clientmathml
 1890: 
 1891: =item * $clientunicode
 1892: 
 1893: =item * $clientos
 1894: 
 1895: =back
 1896: 
 1897: =back 
 1898: 
 1899: =cut
 1900: 
 1901: ###############################################################
 1902: ###############################################################
 1903: sub decode_user_agent {
 1904:     my ($r)=@_;
 1905:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1906:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1907:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1908:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1909:     my $clientbrowser='unknown';
 1910:     my $clientversion='0';
 1911:     my $clientmathml='';
 1912:     my $clientunicode='0';
 1913:     for (my $i=0;$i<=$#browsertype;$i++) {
 1914:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1915: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1916: 	    $clientbrowser=$bname;
 1917:             $httpbrowser=~/$vreg/i;
 1918: 	    $clientversion=$1;
 1919:             $clientmathml=($clientversion>=$minv);
 1920:             $clientunicode=($clientversion>=$univ);
 1921: 	}
 1922:     }
 1923:     my $clientos='unknown';
 1924:     if (($httpbrowser=~/linux/i) ||
 1925:         ($httpbrowser=~/unix/i) ||
 1926:         ($httpbrowser=~/ux/i) ||
 1927:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1928:     if (($httpbrowser=~/vax/i) ||
 1929:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1930:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1931:     if (($httpbrowser=~/mac/i) ||
 1932:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1933:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1934:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1935:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1936:             $clientunicode,$clientos,);
 1937: }
 1938: 
 1939: ###############################################################
 1940: ##    Authentication changing form generation subroutines    ##
 1941: ###############################################################
 1942: ##
 1943: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1944: ## hash, and have reasonable default values.
 1945: ##
 1946: ##    formname = the name given in the <form> tag.
 1947: #-------------------------------------------
 1948: 
 1949: =pod
 1950: 
 1951: =head1 Authentication Routines
 1952: 
 1953: =over 4
 1954: 
 1955: =item * &authform_xxxxxx()
 1956: 
 1957: The authform_xxxxxx subroutines provide javascript and html forms which 
 1958: handle some of the conveniences required for authentication forms.  
 1959: This is not an optimal method, but it works.  
 1960: 
 1961: =over 4
 1962: 
 1963: =item * authform_header
 1964: 
 1965: =item * authform_authorwarning
 1966: 
 1967: =item * authform_nochange
 1968: 
 1969: =item * authform_kerberos
 1970: 
 1971: =item * authform_internal
 1972: 
 1973: =item * authform_filesystem
 1974: 
 1975: =back
 1976: 
 1977: See loncreateuser.pm for invocation and use examples.
 1978: 
 1979: =cut
 1980: 
 1981: #-------------------------------------------
 1982: sub authform_header{  
 1983:     my %in = (
 1984:         formname => 'cu',
 1985:         kerb_def_dom => '',
 1986:         @_,
 1987:     );
 1988:     $in{'formname'} = 'document.' . $in{'formname'};
 1989:     my $result='';
 1990: 
 1991: #---------------------------------------------- Code for upper case translation
 1992:     my $Javascript_toUpperCase;
 1993:     unless ($in{kerb_def_dom}) {
 1994:         $Javascript_toUpperCase =<<"END";
 1995:         switch (choice) {
 1996:            case 'krb': currentform.elements[choicearg].value =
 1997:                currentform.elements[choicearg].value.toUpperCase();
 1998:                break;
 1999:            default:
 2000:         }
 2001: END
 2002:     } else {
 2003:         $Javascript_toUpperCase = "";
 2004:     }
 2005: 
 2006:     my $radioval = "'nochange'";
 2007:     if (defined($in{'curr_authtype'})) {
 2008:         if ($in{'curr_authtype'} ne '') {
 2009:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2010:         }
 2011:     }
 2012:     my $argfield = 'null';
 2013:     if (defined($in{'mode'})) {
 2014:         if ($in{'mode'} eq 'modifycourse')  {
 2015:             if (defined($in{'curr_autharg'})) {
 2016:                 if ($in{'curr_autharg'} ne '') {
 2017:                     $argfield = "'$in{'curr_autharg'}'";
 2018:                 }
 2019:             }
 2020:         }
 2021:     }
 2022: 
 2023:     $result.=<<"END";
 2024: var current = new Object();
 2025: current.radiovalue = $radioval;
 2026: current.argfield = $argfield;
 2027: 
 2028: function changed_radio(choice,currentform) {
 2029:     var choicearg = choice + 'arg';
 2030:     // If a radio button in changed, we need to change the argfield
 2031:     if (current.radiovalue != choice) {
 2032:         current.radiovalue = choice;
 2033:         if (current.argfield != null) {
 2034:             currentform.elements[current.argfield].value = '';
 2035:         }
 2036:         if (choice == 'nochange') {
 2037:             current.argfield = null;
 2038:         } else {
 2039:             current.argfield = choicearg;
 2040:             switch(choice) {
 2041:                 case 'krb': 
 2042:                     currentform.elements[current.argfield].value = 
 2043:                         "$in{'kerb_def_dom'}";
 2044:                 break;
 2045:               default:
 2046:                 break;
 2047:             }
 2048:         }
 2049:     }
 2050:     return;
 2051: }
 2052: 
 2053: function changed_text(choice,currentform) {
 2054:     var choicearg = choice + 'arg';
 2055:     if (currentform.elements[choicearg].value !='') {
 2056:         $Javascript_toUpperCase
 2057:         // clear old field
 2058:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2059:             currentform.elements[current.argfield].value = '';
 2060:         }
 2061:         current.argfield = choicearg;
 2062:     }
 2063:     set_auth_radio_buttons(choice,currentform);
 2064:     return;
 2065: }
 2066: 
 2067: function set_auth_radio_buttons(newvalue,currentform) {
 2068:     var i=0;
 2069:     while (i < currentform.login.length) {
 2070:         if (currentform.login[i].value == newvalue) { break; }
 2071:         i++;
 2072:     }
 2073:     if (i == currentform.login.length) {
 2074:         return;
 2075:     }
 2076:     current.radiovalue = newvalue;
 2077:     currentform.login[i].checked = true;
 2078:     return;
 2079: }
 2080: END
 2081:     return $result;
 2082: }
 2083: 
 2084: sub authform_authorwarning{
 2085:     my $result='';
 2086:     $result='<i>'.
 2087:         &mt('As a general rule, only authors or co-authors should be '.
 2088:             'filesystem authenticated '.
 2089:             '(which allows access to the server filesystem).')."</i>\n";
 2090:     return $result;
 2091: }
 2092: 
 2093: sub authform_nochange{  
 2094:     my %in = (
 2095:               formname => 'document.cu',
 2096:               kerb_def_dom => 'MSU.EDU',
 2097:               @_,
 2098:           );
 2099:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2100:     my $result;
 2101:     if (keys(%can_assign) == 0) {
 2102:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2103:     } else {
 2104:         $result = '<label>'.&mt('[_1] Do not change login data',
 2105:                   '<input type="radio" name="login" value="nochange" '.
 2106:                   'checked="checked" onclick="'.
 2107:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2108: 	    '</label>';
 2109:     }
 2110:     return $result;
 2111: }
 2112: 
 2113: sub authform_kerberos {
 2114:     my %in = (
 2115:               formname => 'document.cu',
 2116:               kerb_def_dom => 'MSU.EDU',
 2117:               kerb_def_auth => 'krb4',
 2118:               @_,
 2119:               );
 2120:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2121:         $autharg,$jscall);
 2122:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2123:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2124:        $check5 = ' checked="on"';
 2125:     } else {
 2126:        $check4 = ' checked="on"';
 2127:     }
 2128:     $krbarg = $in{'kerb_def_dom'};
 2129:     if (defined($in{'curr_authtype'})) {
 2130:         if ($in{'curr_authtype'} eq 'krb') {
 2131:             $krbcheck = ' checked="on"';
 2132:             if (defined($in{'mode'})) {
 2133:                 if ($in{'mode'} eq 'modifyuser') {
 2134:                     $krbcheck = '';
 2135:                 }
 2136:             }
 2137:             if (defined($in{'curr_kerb_ver'})) {
 2138:                 if ($in{'curr_krb_ver'} eq '5') {
 2139:                     $check5 = ' checked="on"';
 2140:                     $check4 = '';
 2141:                 } else {
 2142:                     $check4 = ' checked="on"';
 2143:                     $check5 = '';
 2144:                 }
 2145:             }
 2146:             if (defined($in{'curr_autharg'})) {
 2147:                 $krbarg = $in{'curr_autharg'};
 2148:             }
 2149:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2150:                 if (defined($in{'curr_autharg'})) {
 2151:                     $result = 
 2152:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2153:         $in{'curr_autharg'},$krbver);
 2154:                 } else {
 2155:                     $result =
 2156:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2157:                 }
 2158:                 return $result; 
 2159:             }
 2160:         }
 2161:     } else {
 2162:         if ($authnum == 1) {
 2163:             $authtype = '<input type="hidden" name="login" value="krb">';
 2164:         }
 2165:     }
 2166:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2167:         return;
 2168:     } elsif ($authtype eq '') {
 2169:         if (defined($in{'mode'})) {
 2170:             if ($in{'mode'} eq 'modifycourse') {
 2171:                 if ($authnum == 1) {
 2172:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2173:                 }
 2174:             }
 2175:         }
 2176:     }
 2177:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2178:     if ($authtype eq '') {
 2179:         $authtype = '<input type="radio" name="login" value="krb" '.
 2180:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2181:                     $krbcheck.' />';
 2182:     }
 2183:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2184:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2185:          $in{'curr_authtype'} eq 'krb5') ||
 2186:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2187:          $in{'curr_authtype'} eq 'krb4')) {
 2188:         $result .= &mt
 2189:         ('[_1] Kerberos authenticated with domain [_2] '.
 2190:          '[_3] Version 4 [_4] Version 5 [_5]',
 2191:          '<label>'.$authtype,
 2192:          '</label><input type="text" size="10" name="krbarg" '.
 2193:              'value="'.$krbarg.'" '.
 2194:              'onchange="'.$jscall.'" />',
 2195:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2196:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2197: 	 '</label>');
 2198:     } elsif ($can_assign{'krb4'}) {
 2199:         $result .= &mt
 2200:         ('[_1] Kerberos authenticated with domain [_2] '.
 2201:          '[_3] Version 4 [_4]',
 2202:          '<label>'.$authtype,
 2203:          '</label><input type="text" size="10" name="krbarg" '.
 2204:              'value="'.$krbarg.'" '.
 2205:              'onchange="'.$jscall.'" />',
 2206:          '<label><input type="hidden" name="krbver" value="4" />',
 2207:          '</label>');
 2208:     } elsif ($can_assign{'krb5'}) {
 2209:         $result .= &mt
 2210:         ('[_1] Kerberos authenticated with domain [_2] '.
 2211:          '[_3] Version 5 [_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="5" />',
 2217:          '</label>');
 2218:     }
 2219:     return $result;
 2220: }
 2221: 
 2222: sub authform_internal{  
 2223:     my %in = (
 2224:                 formname => 'document.cu',
 2225:                 kerb_def_dom => 'MSU.EDU',
 2226:                 @_,
 2227:                 );
 2228:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2229:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2230:     if (defined($in{'curr_authtype'})) {
 2231:         if ($in{'curr_authtype'} eq 'int') {
 2232:             if ($can_assign{'int'}) {
 2233:                 $intcheck = 'checked="on" ';
 2234:                 if (defined($in{'mode'})) {
 2235:                     if ($in{'mode'} eq 'modifyuser') {
 2236:                         $intcheck = '';
 2237:                     }
 2238:                 }
 2239:                 if (defined($in{'curr_autharg'})) {
 2240:                     $intarg = $in{'curr_autharg'};
 2241:                 }
 2242:             } else {
 2243:                 $result = &mt('Currently internally authenticated.');
 2244:                 return $result;
 2245:             }
 2246:         }
 2247:     } else {
 2248:         if ($authnum == 1) {
 2249:             $authtype = '<input type="hidden" name="login" value="int">';
 2250:         }
 2251:     }
 2252:     if (!$can_assign{'int'}) {
 2253:         return;
 2254:     } elsif ($authtype eq '') {
 2255:         if (defined($in{'mode'})) {
 2256:             if ($in{'mode'} eq 'modifycourse') {
 2257:                 if ($authnum == 1) {
 2258:                     $authtype = '<input type="hidden" name="login" value="int">';
 2259:                 }
 2260:             }
 2261:         }
 2262:     }
 2263:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2264:     if ($authtype eq '') {
 2265:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2266:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2267:     }
 2268:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2269:                $intarg.'" onchange="'.$jscall.'" />';
 2270:     $result = &mt
 2271:         ('[_1] Internally authenticated (with initial password [_2])',
 2272:          '<label>'.$authtype,'</label>'.$autharg);
 2273:     $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>';
 2274:     return $result;
 2275: }
 2276: 
 2277: sub authform_local{  
 2278:     my %in = (
 2279:               formname => 'document.cu',
 2280:               kerb_def_dom => 'MSU.EDU',
 2281:               @_,
 2282:               );
 2283:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2284:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2285:     if (defined($in{'curr_authtype'})) {
 2286:         if ($in{'curr_authtype'} eq 'loc') {
 2287:             if ($can_assign{'loc'}) {
 2288:                 $loccheck = 'checked="on" ';
 2289:                 if (defined($in{'mode'})) {
 2290:                     if ($in{'mode'} eq 'modifyuser') {
 2291:                         $loccheck = '';
 2292:                     }
 2293:                 }
 2294:                 if (defined($in{'curr_autharg'})) {
 2295:                     $locarg = $in{'curr_autharg'};
 2296:                 }
 2297:             } else {
 2298:                 $result = &mt('Currently using local (institutional) authentication.');
 2299:                 return $result;
 2300:             }
 2301:         }
 2302:     } else {
 2303:         if ($authnum == 1) {
 2304:             $authtype = '<input type="hidden" name="login" value="loc">';
 2305:         }
 2306:     }
 2307:     if (!$can_assign{'loc'}) {
 2308:         return;
 2309:     } elsif ($authtype eq '') {
 2310:         if (defined($in{'mode'})) {
 2311:             if ($in{'mode'} eq 'modifycourse') {
 2312:                 if ($authnum == 1) {
 2313:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2314:                 }
 2315:             }
 2316:         }
 2317:     }
 2318:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2319:     if ($authtype eq '') {
 2320:         $authtype = '<input type="radio" name="login" value="loc" '.
 2321:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2322:                     $jscall.'" />';
 2323:     }
 2324:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2325:                $locarg.'" onchange="'.$jscall.'" />';
 2326:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2327:                   '<label>'.$authtype,'</label>'.$autharg);
 2328:     return $result;
 2329: }
 2330: 
 2331: sub authform_filesystem{  
 2332:     my %in = (
 2333:               formname => 'document.cu',
 2334:               kerb_def_dom => 'MSU.EDU',
 2335:               @_,
 2336:               );
 2337:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2338:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2339:     if (defined($in{'curr_authtype'})) {
 2340:         if ($in{'curr_authtype'} eq 'fsys') {
 2341:             if ($can_assign{'fsys'}) {
 2342:                 $fsyscheck = 'checked="on" ';
 2343:                 if (defined($in{'mode'})) {
 2344:                     if ($in{'mode'} eq 'modifyuser') {
 2345:                         $fsyscheck = '';
 2346:                     }
 2347:                 }
 2348:             } else {
 2349:                 $result = &mt('Currently Filesystem Authenticated.');
 2350:                 return $result;
 2351:             }           
 2352:         }
 2353:     } else {
 2354:         if ($authnum == 1) {
 2355:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2356:         }
 2357:     }
 2358:     if (!$can_assign{'fsys'}) {
 2359:         return;
 2360:     } elsif ($authtype eq '') {
 2361:         if (defined($in{'mode'})) {
 2362:             if ($in{'mode'} eq 'modifycourse') {
 2363:                 if ($authnum == 1) {
 2364:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2365:                 }
 2366:             }
 2367:         }
 2368:     }
 2369:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2370:     if ($authtype eq '') {
 2371:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2372:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2373:                     $jscall.'" />';
 2374:     }
 2375:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2376:                ' onchange="'.$jscall.'" />';
 2377:     $result = &mt
 2378:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2379:          '<label><input type="radio" name="login" value="fsys" '.
 2380:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2381:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2382:                   'onchange="'.$jscall.'" />');
 2383:     return $result;
 2384: }
 2385: 
 2386: sub get_assignable_auth {
 2387:     my ($dom) = @_;
 2388:     if ($dom eq '') {
 2389:         $dom = $env{'request.role.domain'};
 2390:     }
 2391:     my %can_assign = (
 2392:                           krb4 => 1,
 2393:                           krb5 => 1,
 2394:                           int  => 1,
 2395:                           loc  => 1,
 2396:                      );
 2397:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2398:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2399:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2400:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2401:             my $context;
 2402:             if ($env{'request.role'} =~ /^au/) {
 2403:                 $context = 'author';
 2404:             } elsif ($env{'request.role'} =~ /^dc/) {
 2405:                 $context = 'domain';
 2406:             } elsif ($env{'request.course.id'}) {
 2407:                 $context = 'course';
 2408:             }
 2409:             if ($context) {
 2410:                 if (ref($authhash->{$context}) eq 'HASH') {
 2411:                    %can_assign = %{$authhash->{$context}}; 
 2412:                 }
 2413:             }
 2414:         }
 2415:     }
 2416:     my $authnum = 0;
 2417:     foreach my $key (keys(%can_assign)) {
 2418:         if ($can_assign{$key}) {
 2419:             $authnum ++;
 2420:         }
 2421:     }
 2422:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2423:         $authnum --;
 2424:     }
 2425:     return ($authnum,%can_assign);
 2426: }
 2427: 
 2428: ###############################################################
 2429: ##    Get Kerberos Defaults for Domain                 ##
 2430: ###############################################################
 2431: ##
 2432: ## Returns default kerberos version and an associated argument
 2433: ## as listed in file domain.tab. If not listed, provides
 2434: ## appropriate default domain and kerberos version.
 2435: ##
 2436: #-------------------------------------------
 2437: 
 2438: =pod
 2439: 
 2440: =item * &get_kerberos_defaults()
 2441: 
 2442: get_kerberos_defaults($target_domain) returns the default kerberos
 2443: version and domain. If not found, it defaults to version 4 and the 
 2444: domain of the server.
 2445: 
 2446: =over 4
 2447: 
 2448: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2449: 
 2450: =back
 2451: 
 2452: =back
 2453: 
 2454: =cut
 2455: 
 2456: #-------------------------------------------
 2457: sub get_kerberos_defaults {
 2458:     my $domain=shift;
 2459:     my ($krbdef,$krbdefdom);
 2460:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2461:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2462:         $krbdef = $domdefaults{'auth_def'};
 2463:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2464:     } else {
 2465:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2466:         my $krbdefdom=$1;
 2467:         $krbdefdom=~tr/a-z/A-Z/;
 2468:         $krbdef = "krb4";
 2469:     }
 2470:     return ($krbdef,$krbdefdom);
 2471: }
 2472: 
 2473: 
 2474: ###############################################################
 2475: ##                Thesaurus Functions                        ##
 2476: ###############################################################
 2477: 
 2478: =pod
 2479: 
 2480: =head1 Thesaurus Functions
 2481: 
 2482: =over 4
 2483: 
 2484: =item * &initialize_keywords()
 2485: 
 2486: Initializes the package variable %Keywords if it is empty.  Uses the
 2487: package variable $thesaurus_db_file.
 2488: 
 2489: =cut
 2490: 
 2491: ###################################################
 2492: 
 2493: sub initialize_keywords {
 2494:     return 1 if (scalar keys(%Keywords));
 2495:     # If we are here, %Keywords is empty, so fill it up
 2496:     #   Make sure the file we need exists...
 2497:     if (! -e $thesaurus_db_file) {
 2498:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2499:                                  " failed because it does not exist");
 2500:         return 0;
 2501:     }
 2502:     #   Set up the hash as a database
 2503:     my %thesaurus_db;
 2504:     if (! tie(%thesaurus_db,'GDBM_File',
 2505:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2506:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2507:                                  $thesaurus_db_file);
 2508:         return 0;
 2509:     } 
 2510:     #  Get the average number of appearances of a word.
 2511:     my $avecount = $thesaurus_db{'average.count'};
 2512:     #  Put keywords (those that appear > average) into %Keywords
 2513:     while (my ($word,$data)=each (%thesaurus_db)) {
 2514:         my ($count,undef) = split /:/,$data;
 2515:         $Keywords{$word}++ if ($count > $avecount);
 2516:     }
 2517:     untie %thesaurus_db;
 2518:     # Remove special values from %Keywords.
 2519:     foreach my $value ('total.count','average.count') {
 2520:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2521:   }
 2522:     return 1;
 2523: }
 2524: 
 2525: ###################################################
 2526: 
 2527: =pod
 2528: 
 2529: =item * &keyword($word)
 2530: 
 2531: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2532: than the average number of times in the thesaurus database.  Calls 
 2533: &initialize_keywords
 2534: 
 2535: =cut
 2536: 
 2537: ###################################################
 2538: 
 2539: sub keyword {
 2540:     return if (!&initialize_keywords());
 2541:     my $word=lc(shift());
 2542:     $word=~s/\W//g;
 2543:     return exists($Keywords{$word});
 2544: }
 2545: 
 2546: ###############################################################
 2547: 
 2548: =pod 
 2549: 
 2550: =item * &get_related_words()
 2551: 
 2552: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2553: an array of words.  If the keyword is not in the thesaurus, an empty array
 2554: will be returned.  The order of the words returned is determined by the
 2555: database which holds them.
 2556: 
 2557: Uses global $thesaurus_db_file.
 2558: 
 2559: =cut
 2560: 
 2561: ###############################################################
 2562: sub get_related_words {
 2563:     my $keyword = shift;
 2564:     my %thesaurus_db;
 2565:     if (! -e $thesaurus_db_file) {
 2566:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2567:                                  "failed because the file does not exist");
 2568:         return ();
 2569:     }
 2570:     if (! tie(%thesaurus_db,'GDBM_File',
 2571:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2572:         return ();
 2573:     } 
 2574:     my @Words=();
 2575:     my $count=0;
 2576:     if (exists($thesaurus_db{$keyword})) {
 2577: 	# The first element is the number of times
 2578: 	# the word appears.  We do not need it now.
 2579: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2580: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2581: 	my $threshold=$mostfrequentcount/10;
 2582:         foreach my $possibleword (@RelatedWords) {
 2583:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2584:             if ($wordcount>$threshold) {
 2585: 		push(@Words,$word);
 2586:                 $count++;
 2587:                 if ($count>10) { last; }
 2588: 	    }
 2589:         }
 2590:     }
 2591:     untie %thesaurus_db;
 2592:     return @Words;
 2593: }
 2594: 
 2595: =pod
 2596: 
 2597: =back
 2598: 
 2599: =cut
 2600: 
 2601: # -------------------------------------------------------------- Plaintext name
 2602: =pod
 2603: 
 2604: =head1 User Name Functions
 2605: 
 2606: =over 4
 2607: 
 2608: =item * &plainname($uname,$udom,$first)
 2609: 
 2610: Takes a users logon name and returns it as a string in
 2611: "first middle last generation" form 
 2612: if $first is set to 'lastname' then it returns it as
 2613: 'lastname generation, firstname middlename' if their is a lastname
 2614: 
 2615: =cut
 2616: 
 2617: 
 2618: ###############################################################
 2619: sub plainname {
 2620:     my ($uname,$udom,$first)=@_;
 2621:     return if (!defined($uname) || !defined($udom));
 2622:     my %names=&getnames($uname,$udom);
 2623:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2624: 					  $names{'middlename'},
 2625: 					  $names{'lastname'},
 2626: 					  $names{'generation'},$first);
 2627:     $name=~s/^\s+//;
 2628:     $name=~s/\s+$//;
 2629:     $name=~s/\s+/ /g;
 2630:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2631:     return $name;
 2632: }
 2633: 
 2634: # -------------------------------------------------------------------- Nickname
 2635: =pod
 2636: 
 2637: =item * &nickname($uname,$udom)
 2638: 
 2639: Gets a users name and returns it as a string as
 2640: 
 2641: "&quot;nickname&quot;"
 2642: 
 2643: if the user has a nickname or
 2644: 
 2645: "first middle last generation"
 2646: 
 2647: if the user does not
 2648: 
 2649: =cut
 2650: 
 2651: sub nickname {
 2652:     my ($uname,$udom)=@_;
 2653:     return if (!defined($uname) || !defined($udom));
 2654:     my %names=&getnames($uname,$udom);
 2655:     my $name=$names{'nickname'};
 2656:     if ($name) {
 2657:        $name='&quot;'.$name.'&quot;'; 
 2658:     } else {
 2659:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2660: 	     $names{'lastname'}.' '.$names{'generation'};
 2661:        $name=~s/\s+$//;
 2662:        $name=~s/\s+/ /g;
 2663:     }
 2664:     return $name;
 2665: }
 2666: 
 2667: sub getnames {
 2668:     my ($uname,$udom)=@_;
 2669:     return if (!defined($uname) || !defined($udom));
 2670:     if ($udom eq 'public' && $uname eq 'public') {
 2671: 	return ('lastname' => &mt('Public'));
 2672:     }
 2673:     my $id=$uname.':'.$udom;
 2674:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2675:     if ($cached) {
 2676: 	return %{$names};
 2677:     } else {
 2678: 	my %loadnames=&Apache::lonnet::get('environment',
 2679:                     ['firstname','middlename','lastname','generation','nickname'],
 2680: 					 $udom,$uname);
 2681: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2682: 	return %loadnames;
 2683:     }
 2684: }
 2685: 
 2686: # -------------------------------------------------------------------- getemails
 2687: 
 2688: =pod
 2689: 
 2690: =item * &getemails($uname,$udom)
 2691: 
 2692: Gets a user's email information and returns it as a hash with keys:
 2693: notification, critnotification, permanentemail
 2694: 
 2695: For notification and critnotification, values are comma-separated lists 
 2696: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2697:  
 2698: 
 2699: =cut
 2700: 
 2701: 
 2702: sub getemails {
 2703:     my ($uname,$udom)=@_;
 2704:     if ($udom eq 'public' && $uname eq 'public') {
 2705: 	return;
 2706:     }
 2707:     if (!$udom) { $udom=$env{'user.domain'}; }
 2708:     if (!$uname) { $uname=$env{'user.name'}; }
 2709:     my $id=$uname.':'.$udom;
 2710:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2711:     if ($cached) {
 2712: 	return %{$names};
 2713:     } else {
 2714: 	my %loadnames=&Apache::lonnet::get('environment',
 2715:                     			   ['notification','critnotification',
 2716: 					    'permanentemail'],
 2717: 					   $udom,$uname);
 2718: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2719: 	return %loadnames;
 2720:     }
 2721: }
 2722: 
 2723: sub flush_email_cache {
 2724:     my ($uname,$udom)=@_;
 2725:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2726:     if (!$uname) { $uname=$env{'user.name'};   }
 2727:     return if ($udom eq 'public' && $uname eq 'public');
 2728:     my $id=$uname.':'.$udom;
 2729:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2730: }
 2731: 
 2732: # -------------------------------------------------------------------- getlangs
 2733: 
 2734: =pod
 2735: 
 2736: =item * &getlangs($uname,$udom)
 2737: 
 2738: Gets a user's language preference and returns it as a hash with key:
 2739: language.
 2740: 
 2741: =cut
 2742: 
 2743: 
 2744: sub getlangs {
 2745:     my ($uname,$udom) = @_;
 2746:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2747:     if (!$uname) { $uname=$env{'user.name'};   }
 2748:     my $id=$uname.':'.$udom;
 2749:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2750:     if ($cached) {
 2751:         return %{$langs};
 2752:     } else {
 2753:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2754:                                            $udom,$uname);
 2755:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2756:         return %loadlangs;
 2757:     }
 2758: }
 2759: 
 2760: sub flush_langs_cache {
 2761:     my ($uname,$udom)=@_;
 2762:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2763:     if (!$uname) { $uname=$env{'user.name'};   }
 2764:     return if ($udom eq 'public' && $uname eq 'public');
 2765:     my $id=$uname.':'.$udom;
 2766:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2767: }
 2768: 
 2769: # ------------------------------------------------------------------ Screenname
 2770: 
 2771: =pod
 2772: 
 2773: =item * &screenname($uname,$udom)
 2774: 
 2775: Gets a users screenname and returns it as a string
 2776: 
 2777: =cut
 2778: 
 2779: sub screenname {
 2780:     my ($uname,$udom)=@_;
 2781:     if ($uname eq $env{'user.name'} &&
 2782: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2783:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2784:     return $names{'screenname'};
 2785: }
 2786: 
 2787: 
 2788: # ------------------------------------------------------------- Message Wrapper
 2789: 
 2790: sub messagewrapper {
 2791:     my ($link,$username,$domain,$subject,$text)=@_;
 2792:     return 
 2793:         '<a href="/adm/email?compose=individual&amp;'.
 2794:         'recname='.$username.'&amp;recdom='.$domain.
 2795: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2796:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2797: }
 2798: # --------------------------------------------------------------- Notes Wrapper
 2799: 
 2800: sub noteswrapper {
 2801:     my ($link,$un,$do)=@_;
 2802:     return 
 2803: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2804: }
 2805: # ------------------------------------------------------------- Aboutme Wrapper
 2806: 
 2807: sub aboutmewrapper {
 2808:     my ($link,$username,$domain,$target)=@_;
 2809:     if (!defined($username)  && !defined($domain)) {
 2810:         return;
 2811:     }
 2812:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2813: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2814: }
 2815: 
 2816: # ------------------------------------------------------------ Syllabus Wrapper
 2817: 
 2818: 
 2819: sub syllabuswrapper {
 2820:     my ($linktext,$coursedir,$domain)=@_;
 2821:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2822: }
 2823: 
 2824: sub track_student_link {
 2825:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2826:     my $link ="/adm/trackstudent?";
 2827:     my $title = 'View recent activity';
 2828:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2829:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2830:         $link .= "selected_student=$sname:$sdom";
 2831:         $title .= ' of this student';
 2832:     } 
 2833:     if (defined($target) && $target !~ /^\s*$/) {
 2834:         $target = qq{target="$target"};
 2835:     } else {
 2836:         $target = '';
 2837:     }
 2838:     if ($start) { $link.='&amp;start='.$start; }
 2839:     $title = &mt($title);
 2840:     $linktext = &mt($linktext);
 2841:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2842: 	&help_open_topic('View_recent_activity');
 2843: }
 2844: 
 2845: # ===================================================== Display a student photo
 2846: 
 2847: 
 2848: sub student_image_tag {
 2849:     my ($domain,$user)=@_;
 2850:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2851:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2852: 	return '<img src="'.$imgsrc.'" align="right" />';
 2853:     } else {
 2854: 	return '';
 2855:     }
 2856: }
 2857: 
 2858: =pod
 2859: 
 2860: =back
 2861: 
 2862: =head1 Access .tab File Data
 2863: 
 2864: =over 4
 2865: 
 2866: =item * &languageids() 
 2867: 
 2868: returns list of all language ids
 2869: 
 2870: =cut
 2871: 
 2872: sub languageids {
 2873:     return sort(keys(%language));
 2874: }
 2875: 
 2876: =pod
 2877: 
 2878: =item * &languagedescription() 
 2879: 
 2880: returns description of a specified language id
 2881: 
 2882: =cut
 2883: 
 2884: sub languagedescription {
 2885:     my $code=shift;
 2886:     return  ($supported_language{$code}?'* ':'').
 2887:             $language{$code}.
 2888: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2889: }
 2890: 
 2891: sub plainlanguagedescription {
 2892:     my $code=shift;
 2893:     return $language{$code};
 2894: }
 2895: 
 2896: sub supportedlanguagecode {
 2897:     my $code=shift;
 2898:     return $supported_language{$code};
 2899: }
 2900: 
 2901: =pod
 2902: 
 2903: =item * &copyrightids() 
 2904: 
 2905: returns list of all copyrights
 2906: 
 2907: =cut
 2908: 
 2909: sub copyrightids {
 2910:     return sort(keys(%cprtag));
 2911: }
 2912: 
 2913: =pod
 2914: 
 2915: =item * &copyrightdescription() 
 2916: 
 2917: returns description of a specified copyright id
 2918: 
 2919: =cut
 2920: 
 2921: sub copyrightdescription {
 2922:     return &mt($cprtag{shift(@_)});
 2923: }
 2924: 
 2925: =pod
 2926: 
 2927: =item * &source_copyrightids() 
 2928: 
 2929: returns list of all source copyrights
 2930: 
 2931: =cut
 2932: 
 2933: sub source_copyrightids {
 2934:     return sort(keys(%scprtag));
 2935: }
 2936: 
 2937: =pod
 2938: 
 2939: =item * &source_copyrightdescription() 
 2940: 
 2941: returns description of a specified source copyright id
 2942: 
 2943: =cut
 2944: 
 2945: sub source_copyrightdescription {
 2946:     return &mt($scprtag{shift(@_)});
 2947: }
 2948: 
 2949: =pod
 2950: 
 2951: =item * &filecategories() 
 2952: 
 2953: returns list of all file categories
 2954: 
 2955: =cut
 2956: 
 2957: sub filecategories {
 2958:     return sort(keys(%category_extensions));
 2959: }
 2960: 
 2961: =pod
 2962: 
 2963: =item * &filecategorytypes() 
 2964: 
 2965: returns list of file types belonging to a given file
 2966: category
 2967: 
 2968: =cut
 2969: 
 2970: sub filecategorytypes {
 2971:     my ($cat) = @_;
 2972:     return @{$category_extensions{lc($cat)}};
 2973: }
 2974: 
 2975: =pod
 2976: 
 2977: =item * &fileembstyle() 
 2978: 
 2979: returns embedding style for a specified file type
 2980: 
 2981: =cut
 2982: 
 2983: sub fileembstyle {
 2984:     return $fe{lc(shift(@_))};
 2985: }
 2986: 
 2987: sub filemimetype {
 2988:     return $fm{lc(shift(@_))};
 2989: }
 2990: 
 2991: 
 2992: sub filecategoryselect {
 2993:     my ($name,$value)=@_;
 2994:     return &select_form($value,$name,
 2995: 			'' => &mt('Any category'),
 2996: 			map { $_,$_ } sort(keys(%category_extensions)));
 2997: }
 2998: 
 2999: =pod
 3000: 
 3001: =item * &filedescription() 
 3002: 
 3003: returns description for a specified file type
 3004: 
 3005: =cut
 3006: 
 3007: sub filedescription {
 3008:     my $file_description = $fd{lc(shift())};
 3009:     $file_description =~ s:([\[\]]):~$1:g;
 3010:     return &mt($file_description);
 3011: }
 3012: 
 3013: =pod
 3014: 
 3015: =item * &filedescriptionex() 
 3016: 
 3017: returns description for a specified file type with
 3018: extra formatting
 3019: 
 3020: =cut
 3021: 
 3022: sub filedescriptionex {
 3023:     my $ex=shift;
 3024:     my $file_description = $fd{lc($ex)};
 3025:     $file_description =~ s:([\[\]]):~$1:g;
 3026:     return '.'.$ex.' '.&mt($file_description);
 3027: }
 3028: 
 3029: # End of .tab access
 3030: =pod
 3031: 
 3032: =back
 3033: 
 3034: =cut
 3035: 
 3036: # ------------------------------------------------------------------ File Types
 3037: sub fileextensions {
 3038:     return sort(keys(%fe));
 3039: }
 3040: 
 3041: # ----------------------------------------------------------- Display Languages
 3042: # returns a hash with all desired display languages
 3043: #
 3044: 
 3045: sub display_languages {
 3046:     my %languages=();
 3047:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3048: 	$languages{$lang}=1;
 3049:     }
 3050:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3051:     if ($env{'form.displaylanguage'}) {
 3052: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3053: 	    $languages{$lang}=1;
 3054:         }
 3055:     }
 3056:     return %languages;
 3057: }
 3058: 
 3059: sub languages {
 3060:     my ($possible_langs) = @_;
 3061:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3062:     if (!ref($possible_langs)) {
 3063: 	if( wantarray ) {
 3064: 	    return @preferred_langs;
 3065: 	} else {
 3066: 	    return $preferred_langs[0];
 3067: 	}
 3068:     }
 3069:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3070:     my @preferred_possibilities;
 3071:     foreach my $preferred_lang (@preferred_langs) {
 3072: 	if (exists($possibilities{$preferred_lang})) {
 3073: 	    push(@preferred_possibilities, $preferred_lang);
 3074: 	}
 3075:     }
 3076:     if( wantarray ) {
 3077: 	return @preferred_possibilities;
 3078:     }
 3079:     return $preferred_possibilities[0];
 3080: }
 3081: 
 3082: sub user_lang {
 3083:     my ($touname,$toudom,$fromcid) = @_;
 3084:     my @userlangs;
 3085:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3086:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3087:                     $env{'course.'.$fromcid.'.languages'}));
 3088:     } else {
 3089:         my %langhash = &getlangs($touname,$toudom);
 3090:         if ($langhash{'languages'} ne '') {
 3091:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3092:         } else {
 3093:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3094:             if ($domdefs{'lang_def'} ne '') {
 3095:                 @userlangs = ($domdefs{'lang_def'});
 3096:             }
 3097:         }
 3098:     }
 3099:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3100:     my $user_lh = Apache::localize->get_handle(@languages);
 3101:     return $user_lh;
 3102: }
 3103: 
 3104: 
 3105: ###############################################################
 3106: ##               Student Answer Attempts                     ##
 3107: ###############################################################
 3108: 
 3109: =pod
 3110: 
 3111: =head1 Alternate Problem Views
 3112: 
 3113: =over 4
 3114: 
 3115: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3116:     $getattempt, $regexp, $gradesub)
 3117: 
 3118: Return string with previous attempt on problem. Arguments:
 3119: 
 3120: =over 4
 3121: 
 3122: =item * $symb: Problem, including path
 3123: 
 3124: =item * $username: username of the desired student
 3125: 
 3126: =item * $domain: domain of the desired student
 3127: 
 3128: =item * $course: Course ID
 3129: 
 3130: =item * $getattempt: Leave blank for all attempts, otherwise put
 3131:     something
 3132: 
 3133: =item * $regexp: if string matches this regexp, the string will be
 3134:     sent to $gradesub
 3135: 
 3136: =item * $gradesub: routine that processes the string if it matches $regexp
 3137: 
 3138: =back
 3139: 
 3140: The output string is a table containing all desired attempts, if any.
 3141: 
 3142: =cut
 3143: 
 3144: sub get_previous_attempt {
 3145:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3146:   my $prevattempts='';
 3147:   no strict 'refs';
 3148:   if ($symb) {
 3149:     my (%returnhash)=
 3150:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3151:     if ($returnhash{'version'}) {
 3152:       my %lasthash=();
 3153:       my $version;
 3154:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3155:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3156: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3157:         }
 3158:       }
 3159:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3160:       $prevattempts.='<th>'.&mt('History').'</th>';
 3161:       foreach my $key (sort(keys(%lasthash))) {
 3162: 	my ($ign,@parts) = split(/\./,$key);
 3163: 	if ($#parts > 0) {
 3164: 	  my $data=$parts[-1];
 3165: 	  pop(@parts);
 3166: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3167: 	} else {
 3168: 	  if ($#parts == 0) {
 3169: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3170: 	  } else {
 3171: 	    $prevattempts.='<th>'.$ign.'</th>';
 3172: 	  }
 3173: 	}
 3174:       }
 3175:       $prevattempts.=&end_data_table_header_row();
 3176:       if ($getattempt eq '') {
 3177: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3178: 	  $prevattempts.=&start_data_table_row().
 3179: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3180: 	    foreach my $key (sort(keys(%lasthash))) {
 3181: 		my $value = &format_previous_attempt_value($key,
 3182: 							   $returnhash{$version.':'.$key});
 3183: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3184: 	    }
 3185: 	  $prevattempts.=&end_data_table_row();
 3186: 	 }
 3187:       }
 3188:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3189:       foreach my $key (sort(keys(%lasthash))) {
 3190: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3191: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3192: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3193:       }
 3194:       $prevattempts.= &end_data_table_row().&end_data_table();
 3195:     } else {
 3196:       $prevattempts=
 3197: 	  &start_data_table().&start_data_table_row().
 3198: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3199: 	  &end_data_table_row().&end_data_table();
 3200:     }
 3201:   } else {
 3202:     $prevattempts=
 3203: 	  &start_data_table().&start_data_table_row().
 3204: 	  '<td>'.&mt('No data.').'</td>'.
 3205: 	  &end_data_table_row().&end_data_table();
 3206:   }
 3207: }
 3208: 
 3209: sub format_previous_attempt_value {
 3210:     my ($key,$value) = @_;
 3211:     if ($key =~ /timestamp/) {
 3212: 	$value = &Apache::lonlocal::locallocaltime($value);
 3213:     } elsif (ref($value) eq 'ARRAY') {
 3214: 	$value = '('.join(', ', @{ $value }).')';
 3215:     } else {
 3216: 	$value = &unescape($value);
 3217:     }
 3218:     return $value;
 3219: }
 3220: 
 3221: 
 3222: sub relative_to_absolute {
 3223:     my ($url,$output)=@_;
 3224:     my $parser=HTML::TokeParser->new(\$output);
 3225:     my $token;
 3226:     my $thisdir=$url;
 3227:     my @rlinks=();
 3228:     while ($token=$parser->get_token) {
 3229: 	if ($token->[0] eq 'S') {
 3230: 	    if ($token->[1] eq 'a') {
 3231: 		if ($token->[2]->{'href'}) {
 3232: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3233: 		}
 3234: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3235: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3236: 	    } elsif ($token->[1] eq 'base') {
 3237: 		$thisdir=$token->[2]->{'href'};
 3238: 	    }
 3239: 	}
 3240:     }
 3241:     $thisdir=~s-/[^/]*$--;
 3242:     foreach my $link (@rlinks) {
 3243: 	unless (($link=~/^https?\:\/\//i) ||
 3244: 		($link=~/^\//) ||
 3245: 		($link=~/^javascript:/i) ||
 3246: 		($link=~/^mailto:/i) ||
 3247: 		($link=~/^\#/)) {
 3248: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3249: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3250: 	}
 3251:     }
 3252: # -------------------------------------------------- Deal with Applet codebases
 3253:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3254:     return $output;
 3255: }
 3256: 
 3257: =pod
 3258: 
 3259: =item * &get_student_view()
 3260: 
 3261: show a snapshot of what student was looking at
 3262: 
 3263: =cut
 3264: 
 3265: sub get_student_view {
 3266:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3267:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3268:   my (%form);
 3269:   my @elements=('symb','courseid','domain','username');
 3270:   foreach my $element (@elements) {
 3271:       $form{'grade_'.$element}=eval '$'.$element #'
 3272:   }
 3273:   if (defined($moreenv)) {
 3274:       %form=(%form,%{$moreenv});
 3275:   }
 3276:   if (defined($target)) { $form{'grade_target'} = $target; }
 3277:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3278:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3279:   $userview=~s/\<body[^\>]*\>//gi;
 3280:   $userview=~s/\<\/body\>//gi;
 3281:   $userview=~s/\<html\>//gi;
 3282:   $userview=~s/\<\/html\>//gi;
 3283:   $userview=~s/\<head\>//gi;
 3284:   $userview=~s/\<\/head\>//gi;
 3285:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3286:   $userview=&relative_to_absolute($feedurl,$userview);
 3287:   if (wantarray) {
 3288:      return ($userview,$response);
 3289:   } else {
 3290:      return $userview;
 3291:   }
 3292: }
 3293: 
 3294: sub get_student_view_with_retries {
 3295:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3296: 
 3297:     my $ok = 0;                 # True if we got a good response.
 3298:     my $content;
 3299:     my $response;
 3300: 
 3301:     # Try to get the student_view done. within the retries count:
 3302:     
 3303:     do {
 3304:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3305:          $ok      = $response->is_success;
 3306:          if (!$ok) {
 3307:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3308:          }
 3309:          $retries--;
 3310:     } while (!$ok && ($retries > 0));
 3311:     
 3312:     if (!$ok) {
 3313:        $content = '';          # On error return an empty content.
 3314:     }
 3315:     if (wantarray) {
 3316:        return ($content, $response);
 3317:     } else {
 3318:        return $content;
 3319:     }
 3320: }
 3321: 
 3322: =pod
 3323: 
 3324: =item * &get_student_answers() 
 3325: 
 3326: show a snapshot of how student was answering problem
 3327: 
 3328: =cut
 3329: 
 3330: sub get_student_answers {
 3331:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3332:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3333:   my (%moreenv);
 3334:   my @elements=('symb','courseid','domain','username');
 3335:   foreach my $element (@elements) {
 3336:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3337:   }
 3338:   $moreenv{'grade_target'}='answer';
 3339:   %moreenv=(%form,%moreenv);
 3340:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3341:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3342:   return $userview;
 3343: }
 3344: 
 3345: =pod
 3346: 
 3347: =item * &submlink()
 3348: 
 3349: Inputs: $text $uname $udom $symb $target
 3350: 
 3351: Returns: A link to grades.pm such as to see the SUBM view of a student
 3352: 
 3353: =cut
 3354: 
 3355: ###############################################
 3356: sub submlink {
 3357:     my ($text,$uname,$udom,$symb,$target)=@_;
 3358:     if (!($uname && $udom)) {
 3359: 	(my $cursymb, my $courseid,$udom,$uname)=
 3360: 	    &Apache::lonnet::whichuser($symb);
 3361: 	if (!$symb) { $symb=$cursymb; }
 3362:     }
 3363:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3364:     $symb=&escape($symb);
 3365:     if ($target) { $target="target=\"$target\""; }
 3366:     return '<a href="/adm/grades?&command=submission&'.
 3367: 	'symb='.$symb.'&student='.$uname.
 3368: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3369: }
 3370: ##############################################
 3371: 
 3372: =pod
 3373: 
 3374: =item * &pgrdlink()
 3375: 
 3376: Inputs: $text $uname $udom $symb $target
 3377: 
 3378: Returns: A link to grades.pm such as to see the PGRD view of a student
 3379: 
 3380: =cut
 3381: 
 3382: ###############################################
 3383: sub pgrdlink {
 3384:     my $link=&submlink(@_);
 3385:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3386:     return $link;
 3387: }
 3388: ##############################################
 3389: 
 3390: =pod
 3391: 
 3392: =item * &pprmlink()
 3393: 
 3394: Inputs: $text $uname $udom $symb $target
 3395: 
 3396: Returns: A link to parmset.pm such as to see the PPRM view of a
 3397: student and a specific resource
 3398: 
 3399: =cut
 3400: 
 3401: ###############################################
 3402: sub pprmlink {
 3403:     my ($text,$uname,$udom,$symb,$target)=@_;
 3404:     if (!($uname && $udom)) {
 3405: 	(my $cursymb, my $courseid,$udom,$uname)=
 3406: 	    &Apache::lonnet::whichuser($symb);
 3407: 	if (!$symb) { $symb=$cursymb; }
 3408:     }
 3409:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3410:     $symb=&escape($symb);
 3411:     if ($target) { $target="target=\"$target\""; }
 3412:     return '<a href="/adm/parmset?command=set&amp;'.
 3413: 	'symb='.$symb.'&amp;uname='.$uname.
 3414: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3415: }
 3416: ##############################################
 3417: 
 3418: =pod
 3419: 
 3420: =back
 3421: 
 3422: =cut
 3423: 
 3424: ###############################################
 3425: 
 3426: 
 3427: sub timehash {
 3428:     my ($thistime) = @_;
 3429:     my $timezone = &Apache::lonlocal::gettimezone();
 3430:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3431:                      ->set_time_zone($timezone);
 3432:     my $wday = $dt->day_of_week();
 3433:     if ($wday == 7) { $wday = 0; }
 3434:     return ( 'second' => $dt->second(),
 3435:              'minute' => $dt->minute(),
 3436:              'hour'   => $dt->hour(),
 3437:              'day'     => $dt->day_of_month(),
 3438:              'month'   => $dt->month(),
 3439:              'year'    => $dt->year(),
 3440:              'weekday' => $wday,
 3441:              'dayyear' => $dt->day_of_year(),
 3442:              'dlsav'   => $dt->is_dst() );
 3443: }
 3444: 
 3445: sub utc_string {
 3446:     my ($date)=@_;
 3447:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3448: }
 3449: 
 3450: sub maketime {
 3451:     my %th=@_;
 3452:     my ($epoch_time,$timezone,$dt);
 3453:     $timezone = &Apache::lonlocal::gettimezone();
 3454:     eval {
 3455:         $dt = DateTime->new( year   => $th{'year'},
 3456:                              month  => $th{'month'},
 3457:                              day    => $th{'day'},
 3458:                              hour   => $th{'hour'},
 3459:                              minute => $th{'minute'},
 3460:                              second => $th{'second'},
 3461:                              time_zone => $timezone,
 3462:                          );
 3463:     };
 3464:     if (!$@) {
 3465:         $epoch_time = $dt->epoch;
 3466:         if ($epoch_time) {
 3467:             return $epoch_time;
 3468:         }
 3469:     }
 3470:     return POSIX::mktime(
 3471:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3472:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3473: }
 3474: 
 3475: #########################################
 3476: 
 3477: sub findallcourses {
 3478:     my ($roles,$uname,$udom) = @_;
 3479:     my %roles;
 3480:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3481:     my %courses;
 3482:     my $now=time;
 3483:     if (!defined($uname)) {
 3484:         $uname = $env{'user.name'};
 3485:     }
 3486:     if (!defined($udom)) {
 3487:         $udom = $env{'user.domain'};
 3488:     }
 3489:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3490:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3491:         if (!%roles) {
 3492:             %roles = (
 3493:                        cc => 1,
 3494:                        in => 1,
 3495:                        ep => 1,
 3496:                        ta => 1,
 3497:                        cr => 1,
 3498:                        st => 1,
 3499:              );
 3500:         }
 3501:         foreach my $entry (keys(%roleshash)) {
 3502:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3503:             if ($trole =~ /^cr/) { 
 3504:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3505:             } else {
 3506:                 next if (!exists($roles{$trole}));
 3507:             }
 3508:             if ($tend) {
 3509:                 next if ($tend < $now);
 3510:             }
 3511:             if ($tstart) {
 3512:                 next if ($tstart > $now);
 3513:             }
 3514:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3515:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3516:             if ($secpart eq '') {
 3517:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3518:                 $sec = 'none';
 3519:                 $realsec = '';
 3520:             } else {
 3521:                 $cnum = $cnumpart;
 3522:                 ($sec,$role) = split(/_/,$secpart);
 3523:                 $realsec = $sec;
 3524:             }
 3525:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3526:         }
 3527:     } else {
 3528:         foreach my $key (keys(%env)) {
 3529: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3530:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3531: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3532: 	        next if ($role eq 'ca' || $role eq 'aa');
 3533: 	        next if (%roles && !exists($roles{$role}));
 3534: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3535:                 my $active=1;
 3536:                 if ($starttime) {
 3537: 		    if ($now<$starttime) { $active=0; }
 3538:                 }
 3539:                 if ($endtime) {
 3540:                     if ($now>$endtime) { $active=0; }
 3541:                 }
 3542:                 if ($active) {
 3543:                     if ($sec eq '') {
 3544:                         $sec = 'none';
 3545:                     }
 3546:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3547:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3548:                 }
 3549:             }
 3550:         }
 3551:     }
 3552:     return %courses;
 3553: }
 3554: 
 3555: ###############################################
 3556: 
 3557: sub blockcheck {
 3558:     my ($setters,$activity,$uname,$udom) = @_;
 3559: 
 3560:     if (!defined($udom)) {
 3561:         $udom = $env{'user.domain'};
 3562:     }
 3563:     if (!defined($uname)) {
 3564:         $uname = $env{'user.name'};
 3565:     }
 3566: 
 3567:     # If uname and udom are for a course, check for blocks in the course.
 3568: 
 3569:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3570:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3571:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3572:         return ($startblock,$endblock);
 3573:     }
 3574: 
 3575:     my $startblock = 0;
 3576:     my $endblock = 0;
 3577:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3578: 
 3579:     # If uname is for a user, and activity is course-specific, i.e.,
 3580:     # boards, chat or groups, check for blocking in current course only.
 3581: 
 3582:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3583:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3584:         foreach my $key (keys(%live_courses)) {
 3585:             if ($key ne $env{'request.course.id'}) {
 3586:                 delete($live_courses{$key});
 3587:             }
 3588:         }
 3589:     }
 3590: 
 3591:     my $otheruser = 0;
 3592:     my %own_courses;
 3593:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3594:         # Resource belongs to user other than current user.
 3595:         $otheruser = 1;
 3596:         # Gather courses for current user
 3597:         %own_courses = 
 3598:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3599:     }
 3600: 
 3601:     # Gather active course roles - course coordinator, instructor, 
 3602:     # exam proctor, ta, student, or custom role.
 3603: 
 3604:     foreach my $course (keys(%live_courses)) {
 3605:         my ($cdom,$cnum);
 3606:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3607:             $cdom = $env{'course.'.$course.'.domain'};
 3608:             $cnum = $env{'course.'.$course.'.num'};
 3609:         } else {
 3610:             ($cdom,$cnum) = split(/_/,$course); 
 3611:         }
 3612:         my $no_ownblock = 0;
 3613:         my $no_userblock = 0;
 3614:         if ($otheruser && $activity ne 'com') {
 3615:             # Check if current user has 'evb' priv for this
 3616:             if (defined($own_courses{$course})) {
 3617:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3618:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3619:                     if ($sec ne 'none') {
 3620:                         $checkrole .= '/'.$sec;
 3621:                     }
 3622:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3623:                         $no_ownblock = 1;
 3624:                         last;
 3625:                     }
 3626:                 }
 3627:             }
 3628:             # if they have 'evb' priv and are currently not playing student
 3629:             next if (($no_ownblock) &&
 3630:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3631:         }
 3632:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3633:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3634:             if ($sec ne 'none') {
 3635:                 $checkrole .= '/'.$sec;
 3636:             }
 3637:             if ($otheruser) {
 3638:                 # Resource belongs to user other than current user.
 3639:                 # Assemble privs for that user, and check for 'evb' priv.
 3640:                 my ($trole,$tdom,$tnum,$tsec);
 3641:                 my $entry = $live_courses{$course}{$sec};
 3642:                 if ($entry =~ /^cr/) {
 3643:                     ($trole,$tdom,$tnum,$tsec) = 
 3644:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3645:                 } else {
 3646:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3647:                 }
 3648:                 my ($spec,$area,$trest,%allroles,%userroles);
 3649:                 $area = '/'.$tdom.'/'.$tnum;
 3650:                 $trest = $tnum;
 3651:                 if ($tsec ne '') {
 3652:                     $area .= '/'.$tsec;
 3653:                     $trest .= '/'.$tsec;
 3654:                 }
 3655:                 $spec = $trole.'.'.$area;
 3656:                 if ($trole =~ /^cr/) {
 3657:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3658:                                                       $tdom,$spec,$trest,$area);
 3659:                 } else {
 3660:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3661:                                                        $tdom,$spec,$trest,$area);
 3662:                 }
 3663:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3664:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3665:                     if ($1) {
 3666:                         $no_userblock = 1;
 3667:                         last;
 3668:                     }
 3669:                 }
 3670:             } else {
 3671:                 # Resource belongs to current user
 3672:                 # Check for 'evb' priv via lonnet::allowed().
 3673:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3674:                     $no_ownblock = 1;
 3675:                     last;
 3676:                 }
 3677:             }
 3678:         }
 3679:         # if they have the evb priv and are currently not playing student
 3680:         next if (($no_ownblock) &&
 3681:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3682:         next if ($no_userblock);
 3683: 
 3684:         # Retrieve blocking times and identity of blocker for course
 3685:         # of specified user, unless user has 'evb' privilege.
 3686:         
 3687:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3688:         if (($start != 0) && 
 3689:             (($startblock == 0) || ($startblock > $start))) {
 3690:             $startblock = $start;
 3691:         }
 3692:         if (($end != 0)  &&
 3693:             (($endblock == 0) || ($endblock < $end))) {
 3694:             $endblock = $end;
 3695:         }
 3696:     }
 3697:     return ($startblock,$endblock);
 3698: }
 3699: 
 3700: sub get_blocks {
 3701:     my ($setters,$activity,$cdom,$cnum) = @_;
 3702:     my $startblock = 0;
 3703:     my $endblock = 0;
 3704:     my $course = $cdom.'_'.$cnum;
 3705:     $setters->{$course} = {};
 3706:     $setters->{$course}{'staff'} = [];
 3707:     $setters->{$course}{'times'} = [];
 3708:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3709:     foreach my $record (keys(%records)) {
 3710:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3711:         if ($start <= time && $end >= time) {
 3712:             my ($staff_name,$staff_dom,$title,$blocks) =
 3713:                 &parse_block_record($records{$record});
 3714:             if ($blocks->{$activity} eq 'on') {
 3715:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3716:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3717:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3718:                     $startblock = $start;
 3719:                 }
 3720:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3721:                     $endblock = $end;
 3722:                 }
 3723:             }
 3724:         }
 3725:     }
 3726:     return ($startblock,$endblock);
 3727: }
 3728: 
 3729: sub parse_block_record {
 3730:     my ($record) = @_;
 3731:     my ($setuname,$setudom,$title,$blocks);
 3732:     if (ref($record) eq 'HASH') {
 3733:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3734:         $title = &unescape($record->{'event'});
 3735:         $blocks = $record->{'blocks'};
 3736:     } else {
 3737:         my @data = split(/:/,$record,3);
 3738:         if (scalar(@data) eq 2) {
 3739:             $title = $data[1];
 3740:             ($setuname,$setudom) = split(/@/,$data[0]);
 3741:         } else {
 3742:             ($setuname,$setudom,$title) = @data;
 3743:         }
 3744:         $blocks = { 'com' => 'on' };
 3745:     }
 3746:     return ($setuname,$setudom,$title,$blocks);
 3747: }
 3748: 
 3749: sub build_block_table {
 3750:     my ($startblock,$endblock,$setters) = @_;
 3751:     my %lt = &Apache::lonlocal::texthash(
 3752:         'cacb' => 'Currently active communication blocks',
 3753:         'cour' => 'Course',
 3754:         'dura' => 'Duration',
 3755:         'blse' => 'Block set by'
 3756:     );
 3757:     my $output;
 3758:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3759:     $output .= &start_data_table();
 3760:     $output .= '
 3761: <tr>
 3762:  <th>'.$lt{'cour'}.'</th>
 3763:  <th>'.$lt{'dura'}.'</th>
 3764:  <th>'.$lt{'blse'}.'</th>
 3765: </tr>
 3766: ';
 3767:     foreach my $course (keys(%{$setters})) {
 3768:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3769:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3770:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3771:             my $fullname = &plainname($uname,$udom);
 3772:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3773:                 && $env{'user.name'} ne 'public' 
 3774:                 && $env{'user.domain'} ne 'public') {
 3775:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3776:             }
 3777:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3778:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3779:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3780:             $output .= &Apache::loncommon::start_data_table_row().
 3781:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3782:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3783:                        '<td>'.$fullname.'</td>'.
 3784:                         &Apache::loncommon::end_data_table_row();
 3785:         }
 3786:     }
 3787:     $output .= &end_data_table();
 3788: }
 3789: 
 3790: sub blocking_status {
 3791:     my ($activity,$uname,$udom) = @_;
 3792:     my %setters;
 3793:     my ($blocked,$output,$ownitem,$is_course);
 3794:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3795:     if ($startblock && $endblock) {
 3796:         $blocked = 1;
 3797:         if (wantarray) {
 3798:             my $category;
 3799:             if ($activity eq 'boards') {
 3800:                 $category = 'Discussion posts in this course';
 3801:             } elsif ($activity eq 'blogs') {
 3802:                 $category = 'Blogs';
 3803:             } elsif ($activity eq 'port') {
 3804:                 if (defined($uname) && defined($udom)) {
 3805:                     if ($uname eq $env{'user.name'} &&
 3806:                         $udom eq $env{'user.domain'}) {
 3807:                         $ownitem = 1;
 3808:                     }
 3809:                 }
 3810:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3811:                 if ($ownitem) { 
 3812:                     $category = 'Your portfolio files';  
 3813:                 } elsif ($is_course) {
 3814:                     my $coursedesc;
 3815:                     foreach my $course (keys(%setters)) {
 3816:                         my %courseinfo =
 3817:                              &Apache::lonnet::coursedescription($course);
 3818:                         $coursedesc = $courseinfo{'description'};
 3819:                     }
 3820:                     $category = "Group files in the course '$coursedesc'";
 3821:                 } else {
 3822:                     $category = 'Portfolio files belonging to ';
 3823:                     if ($env{'user.name'} eq 'public' && 
 3824:                         $env{'user.domain'} eq 'public') {
 3825:                         $category .= &plainname($uname,$udom);
 3826:                     } else {
 3827:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3828:                     }
 3829:                 }
 3830:             } elsif ($activity eq 'groups') {
 3831:                 $category = 'Groups in this course';
 3832:             }
 3833:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3834:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3835:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3836:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3837:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3838:             }
 3839:         }
 3840:     }
 3841:     if (wantarray) {
 3842:         return ($blocked,$output);
 3843:     } else {
 3844:         return $blocked;
 3845:     }
 3846: }
 3847: 
 3848: ###############################################
 3849: 
 3850: sub check_ip_acc {
 3851:     my ($acc)=@_;
 3852:     &Apache::lonxml::debug("acc is $acc");
 3853:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3854:         return 1;
 3855:     }
 3856:     my $allowed=0;
 3857:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3858: 
 3859:     my $name;
 3860:     foreach my $pattern (split(',',$acc)) {
 3861:         $pattern =~ s/^\s*//;
 3862:         $pattern =~ s/\s*$//;
 3863:         if ($pattern =~ /\*$/) {
 3864:             #35.8.*
 3865:             $pattern=~s/\*//;
 3866:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3867:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3868:             #35.8.3.[34-56]
 3869:             my $low=$2;
 3870:             my $high=$3;
 3871:             $pattern=$1;
 3872:             if ($ip =~ /^\Q$pattern\E/) {
 3873:                 my $last=(split(/\./,$ip))[3];
 3874:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3875:             }
 3876:         } elsif ($pattern =~ /^\*/) {
 3877:             #*.msu.edu
 3878:             $pattern=~s/\*//;
 3879:             if (!defined($name)) {
 3880:                 use Socket;
 3881:                 my $netaddr=inet_aton($ip);
 3882:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3883:             }
 3884:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3885:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3886:             #127.0.0.1
 3887:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3888:         } else {
 3889:             #some.name.com
 3890:             if (!defined($name)) {
 3891:                 use Socket;
 3892:                 my $netaddr=inet_aton($ip);
 3893:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3894:             }
 3895:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3896:         }
 3897:         if ($allowed) { last; }
 3898:     }
 3899:     return $allowed;
 3900: }
 3901: 
 3902: ###############################################
 3903: 
 3904: =pod
 3905: 
 3906: =head1 Domain Template Functions
 3907: 
 3908: =over 4
 3909: 
 3910: =item * &determinedomain()
 3911: 
 3912: Inputs: $domain (usually will be undef)
 3913: 
 3914: Returns: Determines which domain should be used for designs
 3915: 
 3916: =cut
 3917: 
 3918: ###############################################
 3919: sub determinedomain {
 3920:     my $domain=shift;
 3921:     if (! $domain) {
 3922:         # Determine domain if we have not been given one
 3923:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3924:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3925:         if ($env{'request.role.domain'}) { 
 3926:             $domain=$env{'request.role.domain'}; 
 3927:         }
 3928:     }
 3929:     return $domain;
 3930: }
 3931: ###############################################
 3932: 
 3933: sub devalidate_domconfig_cache {
 3934:     my ($udom)=@_;
 3935:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3936: }
 3937: 
 3938: # ---------------------- Get domain configuration for a domain
 3939: sub get_domainconf {
 3940:     my ($udom) = @_;
 3941:     my $cachetime=1800;
 3942:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3943:     if (defined($cached)) { return %{$result}; }
 3944: 
 3945:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3946: 					     ['login','rolecolors'],$udom);
 3947:     my (%designhash,%legacy);
 3948:     if (keys(%domconfig) > 0) {
 3949:         if (ref($domconfig{'login'}) eq 'HASH') {
 3950:             if (keys(%{$domconfig{'login'}})) {
 3951:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3952:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3953:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3954:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3955:                                 $domconfig{'login'}{$key}{$img};
 3956:                         }
 3957:                     } else {
 3958:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3959:                     }
 3960:                 }
 3961:             } else {
 3962:                 $legacy{'login'} = 1;
 3963:             }
 3964:         } else {
 3965:             $legacy{'login'} = 1;
 3966:         }
 3967:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3968:             if (keys(%{$domconfig{'rolecolors'}})) {
 3969:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3970:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3971:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3972:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3973:                         }
 3974:                     }
 3975:                 }
 3976:             } else {
 3977:                 $legacy{'rolecolors'} = 1;
 3978:             }
 3979:         } else {
 3980:             $legacy{'rolecolors'} = 1;
 3981:         }
 3982:         if (keys(%legacy) > 0) {
 3983:             my %legacyhash = &get_legacy_domconf($udom);
 3984:             foreach my $item (keys(%legacyhash)) {
 3985:                 if ($item =~ /^\Q$udom\E\.login/) {
 3986:                     if ($legacy{'login'}) { 
 3987:                         $designhash{$item} = $legacyhash{$item};
 3988:                     }
 3989:                 } else {
 3990:                     if ($legacy{'rolecolors'}) {
 3991:                         $designhash{$item} = $legacyhash{$item};
 3992:                     }
 3993:                 }
 3994:             }
 3995:         }
 3996:     } else {
 3997:         %designhash = &get_legacy_domconf($udom); 
 3998:     }
 3999:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4000: 				  $cachetime);
 4001:     return %designhash;
 4002: }
 4003: 
 4004: sub get_legacy_domconf {
 4005:     my ($udom) = @_;
 4006:     my %legacyhash;
 4007:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4008:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4009:     if (-e $designfile) {
 4010:         if ( open (my $fh,"<$designfile") ) {
 4011:             while (my $line = <$fh>) {
 4012:                 next if ($line =~ /^\#/);
 4013:                 chomp($line);
 4014:                 my ($key,$val)=(split(/\=/,$line));
 4015:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4016:             }
 4017:             close($fh);
 4018:         }
 4019:     }
 4020:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4021:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4022:     }
 4023:     return %legacyhash;
 4024: }
 4025: 
 4026: =pod
 4027: 
 4028: =item * &domainlogo()
 4029: 
 4030: Inputs: $domain (usually will be undef)
 4031: 
 4032: Returns: A link to a domain logo, if the domain logo exists.
 4033: If the domain logo does not exist, a description of the domain.
 4034: 
 4035: =cut
 4036: 
 4037: ###############################################
 4038: sub domainlogo {
 4039:     my $domain = &determinedomain(shift);
 4040:     my %designhash = &get_domainconf($domain);    
 4041:     # See if there is a logo
 4042:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4043:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4044:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4045: 	    if ($imgsrc =~ m{^/res/}) {
 4046: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4047: 		&Apache::lonnet::repcopy($local_name);
 4048: 	    }
 4049: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4050:         } 
 4051:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4052:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4053:         return &Apache::lonnet::domain($domain,'description');
 4054:     } else {
 4055:         return '';
 4056:     }
 4057: }
 4058: ##############################################
 4059: 
 4060: =pod
 4061: 
 4062: =item * &designparm()
 4063: 
 4064: Inputs: $which parameter; $domain (usually will be undef)
 4065: 
 4066: Returns: value of designparamter $which
 4067: 
 4068: =cut
 4069: 
 4070: 
 4071: ##############################################
 4072: sub designparm {
 4073:     my ($which,$domain)=@_;
 4074:     if ($env{'browser.blackwhite'} eq 'on') {
 4075: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4076: 	    return '#000000';
 4077: 	}
 4078: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4079: 	    return '#FFFFFF';
 4080: 	}
 4081: 	if ($which=~/\.tabbg$/) {
 4082: 	    return '#CCCCCC';
 4083: 	}
 4084:     }
 4085:     if (exists($env{'environment.color.'.$which})) {
 4086: 	return $env{'environment.color.'.$which};
 4087:     }
 4088:     $domain=&determinedomain($domain);
 4089:     my %domdesign = &get_domainconf($domain);
 4090:     my $output;
 4091:     if ($domdesign{$domain.'.'.$which} ne '') {
 4092: 	$output = $domdesign{$domain.'.'.$which};
 4093:     } else {
 4094:         $output = $defaultdesign{$which};
 4095:     }
 4096:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4097:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4098:         if ($output =~ m{^/(adm|res)/}) {
 4099: 	    if ($output =~ m{^/res/}) {
 4100: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4101: 		&Apache::lonnet::repcopy($local_name);
 4102: 	    }
 4103:             $output = &lonhttpdurl($output);
 4104:         }
 4105:     }
 4106:     return $output;
 4107: }
 4108: 
 4109: ###############################################
 4110: ###############################################
 4111: 
 4112: =pod
 4113: 
 4114: =back
 4115: 
 4116: =head1 HTML Helpers
 4117: 
 4118: =over 4
 4119: 
 4120: =item * &bodytag()
 4121: 
 4122: Returns a uniform header for LON-CAPA web pages.
 4123: 
 4124: Inputs: 
 4125: 
 4126: =over 4
 4127: 
 4128: =item * $title, A title to be displayed on the page.
 4129: 
 4130: =item * $function, the current role (can be undef).
 4131: 
 4132: =item * $addentries, extra parameters for the <body> tag.
 4133: 
 4134: =item * $bodyonly, if defined, only return the <body> tag.
 4135: 
 4136: =item * $domain, if defined, force a given domain.
 4137: 
 4138: =item * $forcereg, if page should register as content page (relevant for 
 4139:             text interface only)
 4140: 
 4141: =item * $customtitle, alternate text to use instead of $title
 4142:                       in the title box that appears, this text
 4143:                       is not auto translated like the $title is
 4144: 
 4145: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4146:                    navigational links
 4147: 
 4148: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4149: 
 4150: =item * $notitle, if true keep the nav controls, but remove the title bar
 4151: 
 4152: =item * $no_inline_link, if true and in remote mode, don't show the 
 4153:          'Switch To Inline Menu' link
 4154: 
 4155: =item * $args, optional argument valid values are
 4156:             no_auto_mt_title -> prevents &mt()ing the title arg
 4157:             inherit_jsmath -> when creating popup window in a page,
 4158:                               should it have jsmath forced on by the
 4159:                               current page
 4160: 
 4161: =back
 4162: 
 4163: Returns: A uniform header for LON-CAPA web pages.  
 4164: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4165: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4166: other decorations will be returned.
 4167: 
 4168: =cut
 4169: 
 4170: sub bodytag {
 4171:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4172: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4173: 
 4174:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4175: 
 4176:     $function = &get_users_function() if (!$function);
 4177:     my $img =    &designparm($function.'.img',$domain);
 4178:     my $font =   &designparm($function.'.font',$domain);
 4179:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4180: 
 4181:     my %design = ( 'style'   => 'margin-top: 0px',
 4182: 		   'bgcolor' => $pgbg,
 4183: 		   'text'    => $font,
 4184:                    'alink'   => &designparm($function.'.alink',$domain),
 4185: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4186: 		   'link'    => &designparm($function.'.link',$domain),);
 4187:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4188: 
 4189:  # role and realm
 4190:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4191:     if ($role  eq 'ca') {
 4192:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4193:         $realm = &plainname($rname,$rdom);
 4194:     } 
 4195: # realm
 4196:     if ($env{'request.course.id'}) {
 4197:         if ($env{'request.role'} !~ /^cr/) {
 4198:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4199:         }
 4200: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4201:     } else {
 4202:         $role = &Apache::lonnet::plaintext($role);
 4203:     }
 4204: 
 4205:     if (!$realm) { $realm='&nbsp;'; }
 4206: # Set messages
 4207:     my $messages=&domainlogo($domain);
 4208: 
 4209:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4210: 
 4211: # construct main body tag
 4212:     my $bodytag = "<body $extra_body_attr>".
 4213: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4214: 
 4215:     if ($bodyonly) {
 4216:         return $bodytag;
 4217:     } elsif ($env{'browser.interface'} eq 'textual') {
 4218: # Accessibility
 4219:           
 4220: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4221: 	if (!$notitle) {
 4222: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4223: 	}
 4224: 	return $bodytag;
 4225:     }
 4226: 
 4227:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4228:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4229: 	undef($role);
 4230:     } else {
 4231: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4232:     }
 4233:     
 4234:     my $roleinfo=(<<ENDROLE);
 4235: <td class="LC_title_bar_who">
 4236: <div class="LC_title_bar_name">
 4237:     $name
 4238:     &nbsp;
 4239: </div>
 4240: <div class="LC_title_bar_role">
 4241: $role&nbsp;
 4242: </div>
 4243: <div class="LC_title_bar_realm">
 4244: $realm&nbsp;
 4245: </div>
 4246: </td>
 4247: ENDROLE
 4248: 
 4249:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4250:     if ($customtitle) {
 4251:         $titleinfo = $customtitle;
 4252:     }
 4253:     #
 4254:     # Extra info if you are the DC
 4255:     my $dc_info = '';
 4256:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4257:                         $env{'course.'.$env{'request.course.id'}.
 4258:                                  '.domain'}.'/'})) {
 4259:         my $cid = $env{'request.course.id'};
 4260:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4261:         $dc_info =~ s/\s+$//;
 4262:         $dc_info = '('.$dc_info.')';
 4263:     }
 4264: 
 4265:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4266:         # No Remote
 4267: 	if ($env{'request.state'} eq 'construct') {
 4268: 	    $forcereg=1;
 4269: 	}
 4270: 
 4271: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4272: 	    # this is for resources; directories have customtitle, and crumbs
 4273:             # and select recent are created in lonpubdir.pm  
 4274: 	    my ($uname,$thisdisfn)=
 4275: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4276: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4277: 	    $formaction=~s/\/+/\//g;
 4278: 
 4279: 	    my $parentpath = '';
 4280: 	    my $lastitem = '';
 4281: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4282: 		$parentpath = $1;
 4283: 		$lastitem = $2;
 4284: 	    } else {
 4285: 		$lastitem = $thisdisfn;
 4286: 	    }
 4287: 	    $titleinfo = 
 4288: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4289: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4290: 		.'<form name="dirs" method="post" action="'.$formaction
 4291: 		.'" target="_top"><tt><b>'
 4292: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4293: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4294: 		.'</form>'
 4295: 		.&Apache::lonmenu::constspaceform();
 4296:         }
 4297: 
 4298:         my $titletable;
 4299: 	if (!$notitle) {
 4300: 	    $titletable =
 4301: 		'<table id="LC_title_bar">'.
 4302:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4303: 			 '</tr></table>';
 4304: 	}
 4305: 	if ($notopbar) {
 4306: 	    $bodytag .= $titletable;
 4307: 	} else {
 4308: 	    if ($env{'request.state'} eq 'construct') {
 4309:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4310: 							  $titletable);
 4311:             } else {
 4312:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4313: 		    $titletable;
 4314:             }
 4315:         }
 4316:         return $bodytag;
 4317:     }
 4318: 
 4319: #
 4320: # Top frame rendering, Remote is up
 4321: #
 4322: 
 4323:     my $imgsrc = $img;
 4324:     if ($img =~ /^\/adm/) {
 4325:         $imgsrc = &lonhttpdurl($img);
 4326:     }
 4327:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4328: 
 4329:     # Explicit link to get inline menu
 4330:     my $menu= ($no_inline_link?''
 4331: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4332:     #
 4333:     if ($notitle) {
 4334: 	return $bodytag;
 4335:     }
 4336:     return(<<ENDBODY);
 4337: $bodytag
 4338: <table id="LC_title_bar" class="LC_with_remote">
 4339: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4340:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4341: </tr>
 4342: <tr><td>$titleinfo $dc_info $menu</td>
 4343: $roleinfo
 4344: </tr>
 4345: </table>
 4346: ENDBODY
 4347: }
 4348: 
 4349: sub make_attr_string {
 4350:     my ($register,$attr_ref) = @_;
 4351: 
 4352:     if ($attr_ref && !ref($attr_ref)) {
 4353: 	die("addentries Must be a hash ref ".
 4354: 	    join(':',caller(1))." ".
 4355: 	    join(':',caller(0))." ");
 4356:     }
 4357: 
 4358:     if ($register) {
 4359: 	my ($on_load,$on_unload);
 4360: 	foreach my $key (keys(%{$attr_ref})) {
 4361: 	    if      (lc($key) eq 'onload') {
 4362: 		$on_load.=$attr_ref->{$key}.';';
 4363: 		delete($attr_ref->{$key});
 4364: 
 4365: 	    } elsif (lc($key) eq 'onunload') {
 4366: 		$on_unload.=$attr_ref->{$key}.';';
 4367: 		delete($attr_ref->{$key});
 4368: 	    }
 4369: 	}
 4370: 	$attr_ref->{'onload'}  =
 4371: 	    &Apache::lonmenu::loadevents().  $on_load;
 4372: 	$attr_ref->{'onunload'}=
 4373: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4374:     }
 4375: 
 4376: # Accessibility font enhance
 4377:     if ($env{'browser.fontenhance'} eq 'on') {
 4378: 	my $style;
 4379: 	foreach my $key (keys(%{$attr_ref})) {
 4380: 	    if (lc($key) eq 'style') {
 4381: 		$style.=$attr_ref->{$key}.';';
 4382: 		delete($attr_ref->{$key});
 4383: 	    }
 4384: 	}
 4385: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4386:     }
 4387: 
 4388:     if ($env{'browser.blackwhite'} eq 'on') {
 4389: 	delete($attr_ref->{'font'});
 4390: 	delete($attr_ref->{'link'});
 4391: 	delete($attr_ref->{'alink'});
 4392: 	delete($attr_ref->{'vlink'});
 4393: 	delete($attr_ref->{'bgcolor'});
 4394: 	delete($attr_ref->{'background'});
 4395:     }
 4396: 
 4397:     my $attr_string;
 4398:     foreach my $attr (keys(%$attr_ref)) {
 4399: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4400:     }
 4401:     return $attr_string;
 4402: }
 4403: 
 4404: 
 4405: ###############################################
 4406: ###############################################
 4407: 
 4408: =pod
 4409: 
 4410: =item * &endbodytag()
 4411: 
 4412: Returns a uniform footer for LON-CAPA web pages.
 4413: 
 4414: Inputs: 1 - optional reference to an args hash
 4415: If in the hash, key for noredirectlink has a value which evaluates to true,
 4416: a 'Continue' link is not displayed if the page contains an
 4417: internal redirect in the <head></head> section,
 4418: i.e., $env{'internal.head.redirect'} exists   
 4419: 
 4420: =cut
 4421: 
 4422: sub endbodytag {
 4423:     my ($args) = @_;
 4424:     my $endbodytag='</body>';
 4425:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4426:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4427:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4428: 	    $endbodytag=
 4429: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4430: 	        &mt('Continue').'</a>'.
 4431: 	        $endbodytag;
 4432:         }
 4433:     }
 4434:     return $endbodytag;
 4435: }
 4436: 
 4437: =pod
 4438: 
 4439: =item * &standard_css()
 4440: 
 4441: Returns a style sheet
 4442: 
 4443: Inputs: (all optional)
 4444:             domain         -> force to color decorate a page for a specific
 4445:                                domain
 4446:             function       -> force usage of a specific rolish color scheme
 4447:             bgcolor        -> override the default page bgcolor
 4448: 
 4449: =cut
 4450: 
 4451: sub standard_css {
 4452:     my ($function,$domain,$bgcolor) = @_;
 4453:     $function  = &get_users_function() if (!$function);
 4454:     my $img    = &designparm($function.'.img',   $domain);
 4455:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4456:     my $font   = &designparm($function.'.font',  $domain);
 4457:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4458:     my $pgbg_or_bgcolor =
 4459: 	         $bgcolor ||
 4460: 	         &designparm($function.'.pgbg',  $domain);
 4461:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4462:     my $alink  = &designparm($function.'.alink', $domain);
 4463:     my $vlink  = &designparm($function.'.vlink', $domain);
 4464:     my $link   = &designparm($function.'.link',  $domain);
 4465: 
 4466:     my $loginbg = &designparm('login.sidebg',$domain);
 4467:     my $bgcol = &designparm('login.bgcol',$domain);
 4468:     my $textcol = &designparm('login.textcol',$domain);
 4469: 
 4470:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4471:     my $mono                 = 'monospace';
 4472:     my $data_table_head      = $tabbg;
 4473:     my $data_table_light     = '#EEEEEE';
 4474:     my $data_table_dark      = '#DDDDDD';
 4475:     my $data_table_darker    = '#CCCCCC';
 4476:     my $data_table_highlight = '#FFFF00';
 4477:     my $mail_new             = '#FFBB77';
 4478:     my $mail_new_hover       = '#DD9955';
 4479:     my $mail_read            = '#BBBB77';
 4480:     my $mail_read_hover      = '#999944';
 4481:     my $mail_replied         = '#AAAA88';
 4482:     my $mail_replied_hover   = '#888855';
 4483:     my $mail_other           = '#99BBBB';
 4484:     my $mail_other_hover     = '#669999';
 4485:     my $table_header         = '#DDDDDD';
 4486:     my $feedback_link_bg     = '#BBBBBB';
 4487:     my $lg_border_color	     = '#C8C8C8';
 4488: 
 4489:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4490: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4491: 	                                                 : '0px 3px 0px 4px';
 4492: 
 4493: 
 4494:     return <<END;
 4495: body{
 4496:      font-family: $sans;
 4497:      line-height:130%;
 4498:      font-size:0.83em;
 4499:      color:$font;
 4500:   }
 4501: a:link, a:visited { font-size:100%; }
 4502: 
 4503: a:focus { color: red; background: yellow } 
 4504: table.thinborder,
 4505: table.thinborder tr th {
 4506:   border-style: solid;
 4507:   border-width: 1px;
 4508:   border-color: $lg_border_color;
 4509:   background: $tabbg;
 4510: }
 4511: table.thinborder tr td {
 4512:   border-style: solid;
 4513:   border-width: 1px;
 4514:   border-color: $lg_border_color;
 4515: }
 4516: 
 4517: form, .inline { display: inline; }
 4518: 
 4519: .LC_center { text-align: center; }
 4520: .LC_left { text-align:left; }
 4521: .LC_right {text-align:right;}
 4522: .LC_middle {vertical-align:middle;}
 4523: .LC_top {vertical-align:top;}
 4524: .LC_bottom {vertical-align:bottom;}
 4525: 
 4526: /* just for tests */
 4527: .LC_300Box { width:300px; }
 4528: .LC_400Box {width:400px; }
 4529: .LC_500Box {width:500px; }
 4530: .LC_600Box {width:600px; }
 4531: .LC_800Box {width:800px;}
 4532: /* end */
 4533: 
 4534: .LC_filename {font-family: $mono; white-space:pre;}
 4535: .LC_error {
 4536:   color: red;
 4537:   font-size: larger;
 4538: }
 4539: .LC_warning,
 4540: .LC_diff_removed {
 4541:   color: red;
 4542: }
 4543: 
 4544: .LC_info,
 4545: .LC_success,
 4546: .LC_diff_added {
 4547:   color: green;
 4548: }
 4549: .LC_unknown {
 4550:   color: yellow;
 4551: }
 4552: 
 4553: .LC_icon {
 4554:   border: 0px;
 4555: }
 4556: .LC_indexer_icon {
 4557:   border: 0px;
 4558:   height: 22px;
 4559: }
 4560: .LC_docs_spacer {
 4561:   width: 25px;
 4562:   height: 1px;
 4563:   border: 0px;
 4564: }
 4565: 
 4566: .LC_internal_info {
 4567:   color: #999999;
 4568: }
 4569: 
 4570: table.LC_pastsubmission {
 4571:   border: 1px solid black;
 4572:   margin: 2px;
 4573: }
 4574: 
 4575: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4576:   width: 100%;
 4577:   background: $pgbg;
 4578:   border: 2px;
 4579:   border-collapse: separate;
 4580:   padding: 0px;
 4581: }
 4582: 
 4583: table#LC_title_bar, table.LC_breadcrumbs, 
 4584: table#LC_title_bar.LC_with_remote {
 4585:   width: 100%;
 4586:   border-color: $pgbg;
 4587:   border-style: solid;
 4588:   border-width: $border;
 4589: 
 4590:   background: $pgbg;
 4591:   font-family: $sans;
 4592:   border-collapse: collapse;
 4593:   padding: 0px;
 4594: }
 4595: table.LC_docs_path {
 4596:   width: 100%;
 4597:   border: 0;
 4598:   background: $pgbg;
 4599:   font-family: $sans;
 4600:   border-collapse: collapse;
 4601:   padding: 0px;
 4602: }
 4603: 
 4604: table#LC_title_bar td {
 4605:   background: $tabbg;
 4606: }
 4607: table#LC_title_bar td.LC_title_bar_who {
 4608:   background: $tabbg;
 4609:   color: $font;
 4610:   font: small $sans;
 4611:   text-align: right;
 4612: }
 4613: span.LC_metadata {
 4614:     font-family: $sans;
 4615: }
 4616: span.LC_title_bar_title {
 4617:   font: bold x-large $sans;
 4618: }
 4619: table#LC_title_bar td.LC_title_bar_domain_logo {
 4620:   background: $sidebg;
 4621:   text-align: right;
 4622:   padding: 0px;
 4623: }
 4624: table#LC_title_bar td.LC_title_bar_role_logo {
 4625:   background: $sidebg;
 4626:   padding: 0px;
 4627: }
 4628: 
 4629: table#LC_menubuttons img{
 4630:   border: 0px;
 4631: }
 4632: table#LC_top_nav td {
 4633:   background: $tabbg;
 4634:   border: 0px;
 4635:   font-size: small;
 4636:   vertical-align:top;
 4637:   padding:2px 5px 2px 5px;
 4638: }
 4639: table#LC_top_nav td a, div#LC_top_nav a {
 4640:   color: $font;
 4641:   font-family: $sans;
 4642: }
 4643: table#LC_top_nav td.LC_top_nav_logo {
 4644:   background: $tabbg;
 4645:   text-align: left;
 4646:   white-space: nowrap;
 4647:   width: 31px;
 4648: }
 4649: table#LC_top_nav td.LC_top_nav_logo img {
 4650:   border: 0px;
 4651:   vertical-align: bottom;
 4652: }
 4653: table#LC_top_nav td.LC_top_nav_exit,
 4654: table#LC_top_nav td.LC_top_nav_help {
 4655:   width: 2.0em;
 4656: }
 4657: table#LC_top_nav td.LC_top_nav_login {
 4658:   width: 4.0em;
 4659:   text-align: center;
 4660: }
 4661: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4662:   background: $tabbg;
 4663:   color: $font;
 4664:   font-family: $sans;
 4665:   font-size: smaller;
 4666: }
 4667: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4668: table.LC_docs_path td.LC_docs_path_component {
 4669:   background: $tabbg;
 4670:   color: $font;
 4671:   font-family: $sans;
 4672:   font-size: larger;
 4673:   text-align: right;
 4674: }
 4675: td.LC_table_cell_checkbox {
 4676:   text-align: center;
 4677: }
 4678: table#LC_mainmenu td.LC_mainmenu_column {
 4679:     vertical-align: top;
 4680: }
 4681: 
 4682: .LC_fontsize_small
 4683: {
 4684:  font-size: 70%;
 4685: }
 4686: 
 4687: .LC_fontsize_medium
 4688: {
 4689:  font-size: 85%;
 4690: }
 4691: 
 4692: .LC_fontsize_large
 4693: {
 4694:  font-size: 120%;
 4695: }
 4696: 
 4697: .LC_fontcolor_red
 4698: {
 4699:  color: #FF0000;
 4700: }
 4701: 
 4702: .LC_menubuttons_inline_text {
 4703:   color: $font;
 4704:   font-family: $sans;
 4705:   font-size: 90%;
 4706:   padding-left:3px;
 4707: }
 4708: 
 4709: .LC_menubuttons_link {
 4710:   text-decoration: none;
 4711: }
 4712: /*2008--9-5: new menu style sheet.Changed category*/
 4713: .LC_menubuttons_category {
 4714:   color: $font;
 4715:   background: $pgbg;
 4716:   font-family: $sans;
 4717:   font-size: larger;
 4718:   font-weight: bold;
 4719: }
 4720: 
 4721: td.LC_menubuttons_text {
 4722:  	color: $font; 	
 4723: }
 4724: 
 4725: 
 4726: 
 4727: .LC_current_location {
 4728:   font-family: $sans;
 4729:   background: $tabbg;
 4730: }
 4731: .LC_new_mail {
 4732:   font-family: $sans;
 4733:   background: $tabbg;
 4734:   font-weight: bold;
 4735: }
 4736: 
 4737: 
 4738: .LC_dropadd_labeltext {
 4739:   font-family: $sans;
 4740:   text-align: right;
 4741: }
 4742: 
 4743: .LC_preferences_labeltext {
 4744:   font-family: $sans;
 4745:   text-align: right;
 4746: }
 4747: 
 4748: .LC_roleslog_note {
 4749:   font-size: small;
 4750: }
 4751: 
 4752: .LC_mail_functions {
 4753:     font-weight: bold;
 4754: }
 4755: 
 4756: table.LC_aboutme_port {
 4757:   border: 0px;
 4758:   border-collapse: collapse;
 4759:   border-spacing: 0px;
 4760: }
 4761: table.LC_data_table, table.LC_mail_list {
 4762:   border: 1px solid #000000;
 4763:   border-collapse: separate;
 4764:   border-spacing: 1px;
 4765:   background: $pgbg;
 4766: }
 4767: .LC_data_table_dense {
 4768:   font-size: small;
 4769: }
 4770: table.LC_nested_outer {
 4771:   border: 1px solid #000000;
 4772:   border-collapse: collapse;
 4773:   border-spacing: 0px;
 4774:   width: 100%;
 4775: }
 4776: table.LC_nested {
 4777:   border: 0px;
 4778:   border-collapse: collapse;
 4779:   border-spacing: 0px;
 4780:   width: 100%;
 4781: }
 4782: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4783: table.LC_prior_tries tr th {
 4784:   font-weight: bold;
 4785:   background-color: $data_table_head;
 4786:   font-size:90%;
 4787: }
 4788: table.LC_data_table tr.LC_info_row > td {
 4789:   background-color: #CCCCCC;
 4790:   font-weight: bold;
 4791:   text-align: left;
 4792: }
 4793: table.LC_data_table tr.LC_odd_row > td, 
 4794: table.LC_pick_box tr > td.LC_odd_row,
 4795: table.LC_aboutme_port tr td {
 4796:   background-color: $data_table_light;
 4797:   padding: 2px;
 4798: }
 4799: table.LC_data_table tr.LC_even_row > td,
 4800: table.LC_pick_box tr > td.LC_even_row,
 4801: table.LC_aboutme_port tr.LC_even_row td {
 4802:   background-color: $data_table_dark;
 4803:   padding: 2px;
 4804: }
 4805: table.LC_data_table tr.LC_data_table_highlight td {
 4806:   background-color: $data_table_darker;
 4807: }
 4808: table.LC_data_table tr td.LC_leftcol_header {
 4809:   background-color: $data_table_head;
 4810:   font-weight: bold;
 4811: }
 4812: table.LC_data_table tr.LC_empty_row td,
 4813: table.LC_nested tr.LC_empty_row td {
 4814:   background-color: #FFFFFF;
 4815:   font-weight: bold;
 4816:   font-style: italic;
 4817:   text-align: center;
 4818:   padding: 8px;
 4819: }
 4820: table.LC_nested tr.LC_empty_row td {
 4821:   padding: 4ex
 4822: }
 4823: table.LC_nested_outer tr th {
 4824:   font-weight: bold;
 4825:   background-color: $data_table_head;
 4826:   font-size: small;
 4827:   border-bottom: 1px solid #000000;
 4828: }
 4829: table.LC_nested_outer tr td.LC_subheader {
 4830:   background-color: $data_table_head;
 4831:   font-weight: bold;
 4832:   font-size: small;
 4833:   border-bottom: 1px solid #000000;
 4834:   text-align: right;
 4835: }
 4836: table.LC_nested tr.LC_info_row td {
 4837:   background-color: #CCCCCC;
 4838:   font-weight: bold;
 4839:   font-size: small;
 4840:   text-align: center;
 4841: }
 4842: table.LC_nested tr.LC_info_row td.LC_left_item,
 4843: table.LC_nested_outer tr th.LC_left_item {
 4844:   text-align: left;
 4845: }
 4846: table.LC_nested td {
 4847:   background-color: #FFFFFF;
 4848:   font-size: small;
 4849: }
 4850: table.LC_nested_outer tr th.LC_right_item,
 4851: table.LC_nested tr.LC_info_row td.LC_right_item,
 4852: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4853: table.LC_nested tr td.LC_right_item {
 4854:   text-align: right;
 4855: }
 4856: 
 4857: table.LC_nested tr.LC_odd_row td {
 4858:   background-color: #EEEEEE;
 4859: }
 4860: 
 4861: table.LC_createuser {
 4862: }
 4863: 
 4864: table.LC_createuser tr.LC_section_row td {
 4865:   font-size: small;
 4866: }
 4867: 
 4868: table.LC_createuser tr.LC_info_row td  {
 4869:   background-color: #CCCCCC;
 4870:   font-weight: bold;
 4871:   text-align: center;
 4872: }
 4873: 
 4874: table.LC_calendar {
 4875:   border: 1px solid #000000;
 4876:   border-collapse: collapse;
 4877: }
 4878: table.LC_calendar_pickdate {
 4879:   font-size: xx-small;
 4880: }
 4881: table.LC_calendar tr td {
 4882:   border: 1px solid #000000;
 4883:   vertical-align: top;
 4884: }
 4885: table.LC_calendar tr td.LC_calendar_day_empty {
 4886:   background-color: $data_table_dark;
 4887: }
 4888: table.LC_calendar tr td.LC_calendar_day_current {
 4889:   background-color: $data_table_highlight;
 4890: }
 4891: 
 4892: table.LC_mail_list tr.LC_mail_new {
 4893:   background-color: $mail_new;
 4894: }
 4895: table.LC_mail_list tr.LC_mail_new:hover {
 4896:   background-color: $mail_new_hover;
 4897: }
 4898: table.LC_mail_list tr.LC_mail_read {
 4899:   background-color: $mail_read;
 4900: }
 4901: table.LC_mail_list tr.LC_mail_read:hover {
 4902:   background-color: $mail_read_hover;
 4903: }
 4904: table.LC_mail_list tr.LC_mail_replied {
 4905:   background-color: $mail_replied;
 4906: }
 4907: table.LC_mail_list tr.LC_mail_replied:hover {
 4908:   background-color: $mail_replied_hover;
 4909: }
 4910: table.LC_mail_list tr.LC_mail_other {
 4911:   background-color: $mail_other;
 4912: }
 4913: table.LC_mail_list tr.LC_mail_other:hover {
 4914:   background-color: $mail_other_hover;
 4915: }
 4916: table.LC_mail_list tr.LC_mail_even {
 4917: }
 4918: table.LC_mail_list tr.LC_mail_odd {
 4919: }
 4920: 
 4921: table.LC_data_table tr > td.LC_browser_file,
 4922: table.LC_data_table tr > td.LC_browser_file_published {
 4923:   background: #CCFF88;
 4924: }
 4925: table.LC_data_table tr > td.LC_browser_file_locked,
 4926: table.LC_data_table tr > td.LC_browser_file_unpublished {
 4927:   background: #FFAA99;
 4928: }
 4929: table.LC_data_table tr > td.LC_browser_file_obsolete {
 4930:   background: #AAAAAA;
 4931: }
 4932: table.LC_data_table tr > td.LC_browser_file_modified,
 4933: table.LC_data_table tr > td.LC_browser_file_metamodified {
 4934:   background: #FFFF77;
 4935: }
 4936: table.LC_data_table tr.LC_browser_folder > td {
 4937:   background: #CCCCFF;
 4938: }
 4939: 
 4940: table.LC_data_table tr > td.LC_roles_is {
 4941: /*  background: #77FF77; */
 4942: }
 4943: table.LC_data_table tr > td.LC_roles_future {
 4944:   background: #FFFF77;
 4945: }
 4946: table.LC_data_table tr > td.LC_roles_will {
 4947:   background: #FFAA77;
 4948: }
 4949: table.LC_data_table tr > td.LC_roles_expired {
 4950:   background: #FF7777;
 4951: }
 4952: table.LC_data_table tr > td.LC_roles_will_not {
 4953:   background: #AAFF77;
 4954: }
 4955: table.LC_data_table tr > td.LC_roles_selected {
 4956:   background: #11CC55;
 4957: }
 4958: 
 4959: span.LC_current_location {
 4960:   font-size:larger;
 4961:   background: $pgbg;
 4962: }
 4963: 
 4964: span.LC_parm_menu_item {
 4965:   font-size: larger;
 4966:   font-family: $sans;
 4967: }
 4968: span.LC_parm_scope_all {
 4969:   color: red;
 4970: }
 4971: span.LC_parm_scope_folder {
 4972:   color: green;
 4973: }
 4974: span.LC_parm_scope_resource {
 4975:   color: orange;
 4976: }
 4977: span.LC_parm_part {
 4978:   color: blue;
 4979: }
 4980: span.LC_parm_folder, span.LC_parm_symb {
 4981:   font-size: x-small;
 4982:   font-family: $mono;
 4983:   color: #AAAAAA;
 4984: }
 4985: 
 4986: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4987: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4988:   border: 1px solid black;
 4989:   border-collapse: collapse;
 4990: }
 4991: table.LC_parm_overview_restrictions td {
 4992:   border-width: 1px 4px 1px 4px;
 4993:   border-style: solid;
 4994:   border-color: $pgbg;
 4995:   text-align: center;
 4996: }
 4997: table.LC_parm_overview_restrictions th {
 4998:   background: $tabbg;
 4999:   border-width: 1px 4px 1px 4px;
 5000:   border-style: solid;
 5001:   border-color: $pgbg;
 5002: }
 5003: table#LC_helpmenu {
 5004:   border: 0px;
 5005:   height: 55px;
 5006:   border-spacing: 0px;
 5007: }
 5008: 
 5009: table#LC_helpmenu fieldset legend {
 5010:   font-size: larger;
 5011:   font-weight: bold;
 5012: }
 5013: table#LC_helpmenu_links {
 5014:   width: 100%;
 5015:   border: 1px solid black;
 5016:   background: $pgbg;
 5017:   padding: 0px;
 5018:   border-spacing: 1px;
 5019: }
 5020: table#LC_helpmenu_links tr td {
 5021:   padding: 1px;
 5022:   background: $tabbg;
 5023:   text-align: center;
 5024:   font-weight: bold;
 5025: }
 5026: 
 5027: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5028: table#LC_helpmenu_links a:active {
 5029:   text-decoration: none;
 5030:   color: $font;
 5031: }
 5032: table#LC_helpmenu_links a:hover {
 5033:   text-decoration: underline;
 5034:   color: $vlink;
 5035: }
 5036: 
 5037: .LC_chrt_popup_exists {
 5038:   border: 1px solid #339933;
 5039:   margin: -1px;
 5040: }
 5041: .LC_chrt_popup_up {
 5042:   border: 1px solid yellow;
 5043:   margin: -1px;
 5044: }
 5045: .LC_chrt_popup {
 5046:   border: 1px solid #8888FF;
 5047:   background: #CCCCFF;
 5048: }
 5049: table.LC_pick_box {
 5050:   border-collapse: separate;
 5051:   background: white;
 5052:   border: 1px solid black;
 5053:   border-spacing: 1px;
 5054: }
 5055: table.LC_pick_box td.LC_pick_box_title {
 5056:   background: $tabbg;
 5057:   font-weight: bold;
 5058:   text-align: right;
 5059:   vertical-align: top;
 5060:   width: 184px;
 5061:   padding: 8px;
 5062: }
 5063: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5064:   background: $tabbg;
 5065:   font-weight: bold;
 5066:   text-align: right;
 5067:   width: 350px;
 5068:   padding: 8px;
 5069: }
 5070: 
 5071: table.LC_pick_box td.LC_pick_box_value {
 5072:   text-align: left;
 5073:   padding: 8px;
 5074: }
 5075: table.LC_pick_box td.LC_pick_box_select {
 5076:   text-align: left;
 5077:   padding: 8px;
 5078: }
 5079: table.LC_pick_box td.LC_pick_box_separator {
 5080:   padding: 0px;
 5081:   height: 1px;
 5082:   background: black;
 5083: }
 5084: table.LC_pick_box td.LC_pick_box_submit {
 5085:   text-align: right;
 5086: }
 5087: table.LC_pick_box td.LC_evenrow_value {
 5088:   text-align: left;
 5089:   padding: 8px;
 5090:   background-color: $data_table_light;
 5091: }
 5092: table.LC_pick_box td.LC_oddrow_value {
 5093:   text-align: left;
 5094:   padding: 8px;
 5095:   background-color: $data_table_light;
 5096: }
 5097: table.LC_helpform_receipt {
 5098:   width: 620px;
 5099:   border-collapse: separate;
 5100:   background: white;
 5101:   border: 1px solid black;
 5102:   border-spacing: 1px;
 5103: }
 5104: table.LC_helpform_receipt td.LC_pick_box_title {
 5105:   background: $tabbg;
 5106:   font-weight: bold;
 5107:   text-align: right;
 5108:   width: 184px;
 5109:   padding: 8px;
 5110: }
 5111: table.LC_helpform_receipt td.LC_evenrow_value {
 5112:   text-align: left;
 5113:   padding: 8px;
 5114:   background-color: $data_table_light;
 5115: }
 5116: table.LC_helpform_receipt td.LC_oddrow_value {
 5117:   text-align: left;
 5118:   padding: 8px;
 5119:   background-color: $data_table_light;
 5120: }
 5121: table.LC_helpform_receipt td.LC_pick_box_separator {
 5122:   padding: 0px;
 5123:   height: 1px;
 5124:   background: black;
 5125: }
 5126: span.LC_helpform_receipt_cat {
 5127:   font-weight: bold;
 5128: }
 5129: table.LC_group_priv_box {
 5130:   background: white;
 5131:   border: 1px solid black;
 5132:   border-spacing: 1px;
 5133: }
 5134: table.LC_group_priv_box td.LC_pick_box_title {
 5135:   background: $tabbg;
 5136:   font-weight: bold;
 5137:   text-align: right;
 5138:   width: 184px;
 5139: }
 5140: table.LC_group_priv_box td.LC_groups_fixed {
 5141:   background: $data_table_light;
 5142:   text-align: center;
 5143: }
 5144: table.LC_group_priv_box td.LC_groups_optional {
 5145:   background: $data_table_dark;
 5146:   text-align: center;
 5147: }
 5148: table.LC_group_priv_box td.LC_groups_functionality {
 5149:   background: $data_table_darker;
 5150:   text-align: center;
 5151:   font-weight: bold;
 5152: }
 5153: table.LC_group_priv td {
 5154:   text-align: left;
 5155:   padding: 0px;
 5156: }
 5157: 
 5158: table.LC_notify_front_page {
 5159:   background: white;
 5160:   border: 1px solid black;
 5161:   padding: 8px;
 5162: }
 5163: table.LC_notify_front_page td {
 5164:   padding: 8px;
 5165: }
 5166: .LC_navbuttons {
 5167:   margin: 2ex 0ex 2ex 0ex;
 5168: }
 5169: .LC_topic_bar {
 5170:   font-family: $sans;
 5171:   font-weight: bold;
 5172:   width: 100%;
 5173:   background: $tabbg;
 5174:   vertical-align: middle;
 5175:   margin: 2ex 0ex 2ex 0ex;
 5176: }
 5177: .LC_topic_bar span {
 5178:   vertical-align: middle;
 5179: }
 5180: .LC_topic_bar img {
 5181:   vertical-align: bottom;
 5182: }
 5183: table.LC_course_group_status {
 5184:   margin: 20px;
 5185: }
 5186: table.LC_status_selector td {
 5187:   vertical-align: top;
 5188:   text-align: center;
 5189:   padding: 4px;
 5190: }
 5191: table.LC_descriptive_input td.LC_description {
 5192:   vertical-align: top;
 5193:   text-align: right;
 5194:   font-weight: bold;
 5195: }
 5196: div.LC_feedback_link {
 5197:   clear: both;
 5198:   background: white;
 5199:   width: 100%;  
 5200: }
 5201: span.LC_feedback_link {
 5202:   background: $feedback_link_bg;
 5203:   font-size: larger;
 5204: }
 5205: span.LC_message_link {
 5206:   background: $feedback_link_bg;
 5207:   font-size: larger;
 5208:   position: absolute;
 5209:   right: 1em;
 5210: }
 5211: 
 5212: table.LC_prior_tries {
 5213:   border: 1px solid #000000;
 5214:   border-collapse: separate;
 5215:   border-spacing: 1px;
 5216: }
 5217: 
 5218: table.LC_prior_tries td {
 5219:   padding: 2px;
 5220: }
 5221: 
 5222: .LC_answer_correct {
 5223:   background: #AAFFAA;
 5224:   color: black;
 5225: }
 5226: .LC_answer_charged_try {
 5227:   background: #FFAAAA ! important;
 5228:   color: black;
 5229: }
 5230: .LC_answer_not_charged_try, 
 5231: .LC_answer_no_grade,
 5232: .LC_answer_late {
 5233:   background: #FFFFAA;
 5234:   color: black;
 5235: }
 5236: .LC_answer_previous {
 5237:   background: #AAAAFF;
 5238:   color: black;
 5239: }
 5240: .LC_answer_no_message {
 5241:   background: #FFFFFF;
 5242:   color: black;
 5243: }
 5244: .LC_answer_unknown {
 5245:   background: orange;
 5246:   color: black;
 5247: }
 5248: 
 5249: 
 5250: span.LC_prior_numerical,
 5251: span.LC_prior_string,
 5252: span.LC_prior_custom,
 5253: span.LC_prior_reaction,
 5254: span.LC_prior_math {
 5255:   font-family: monospace;
 5256:   white-space: pre;
 5257: }
 5258: 
 5259: span.LC_prior_string {
 5260:   font-family: monospace;
 5261:   white-space: pre;
 5262: }
 5263: 
 5264: table.LC_prior_option {
 5265:   width: 100%;
 5266:   border-collapse: collapse;
 5267: }
 5268: table.LC_prior_rank, table.LC_prior_match {
 5269:   border-collapse: collapse;
 5270: }
 5271: table.LC_prior_option tr td,
 5272: table.LC_prior_rank tr td,
 5273: table.LC_prior_match tr td {
 5274:   border: 1px solid #000000;
 5275: }
 5276: 
 5277: span.LC_nobreak {
 5278:   white-space: nowrap;
 5279: }
 5280: 
 5281: span.LC_cusr_emph {
 5282:   font-style: italic;
 5283: }
 5284: 
 5285: span.LC_cusr_subheading {
 5286:   font-weight: normal;
 5287:   font-size: 85%;
 5288: }
 5289: 
 5290: table.LC_docs_documents {
 5291:   background: #BBBBBB;
 5292:   border-width: 0px;
 5293:   border-collapse: collapse;
 5294: }
 5295: 
 5296: table.LC_docs_documents td.LC_docs_document {
 5297:   border: 2px solid black;
 5298:   padding: 4px;
 5299: }
 5300: 
 5301: .LC_docs_entry_move {
 5302:   border: 0px;
 5303:   border-collapse: collapse;
 5304: }
 5305: 
 5306: .LC_docs_entry_move td {
 5307:   border: 2px solid #BBBBBB;
 5308:   background: #DDDDDD;
 5309: }
 5310: 
 5311: .LC_docs_editor td.LC_docs_entry_commands {
 5312:   background: #DDDDDD;
 5313:   font-size: x-small;
 5314: }
 5315: .LC_docs_copy {
 5316:   color: #000099;
 5317: }
 5318: .LC_docs_cut {
 5319:   color: #550044;
 5320: }
 5321: .LC_docs_rename {
 5322:   color: #009900;
 5323: }
 5324: .LC_docs_remove {
 5325:   color: #990000;
 5326: }
 5327: 
 5328: .LC_docs_reinit_warn,
 5329: .LC_docs_ext_edit {
 5330:   font-size: x-small;
 5331: }
 5332: 
 5333: .LC_docs_editor td.LC_docs_entry_title,
 5334: .LC_docs_editor td.LC_docs_entry_icon {
 5335:   background: #FFFFBB;
 5336: }
 5337: .LC_docs_editor td.LC_docs_entry_parameter {
 5338:   background: #BBBBFF;
 5339:   font-size: x-small;
 5340:   white-space: nowrap;
 5341: }
 5342: 
 5343: table.LC_docs_adddocs td,
 5344: table.LC_docs_adddocs th {
 5345:   border: 1px solid #BBBBBB;
 5346:   padding: 4px;
 5347:   background: #DDDDDD;
 5348: }
 5349: 
 5350: table.LC_sty_begin {
 5351:   background: #BBFFBB;
 5352: }
 5353: table.LC_sty_end {
 5354:   background: #FFBBBB;
 5355: }
 5356: 
 5357: table.LC_double_column {
 5358:   border-width: 0px;
 5359:   border-collapse: collapse;
 5360:   width: 100%;
 5361:   padding: 2px;
 5362: }
 5363: 
 5364: table.LC_double_column tr td.LC_left_col {
 5365:   top: 2px;
 5366:   left: 2px;
 5367:   width: 47%;
 5368:   vertical-align: top;
 5369: }
 5370: 
 5371: table.LC_double_column tr td.LC_right_col {
 5372:   top: 2px;
 5373:   right: 2px; 
 5374:   width: 47%;
 5375:   vertical-align: top;
 5376: }
 5377: 
 5378: span.LC_role_level {
 5379:   font-weight: bold;
 5380: }
 5381: 
 5382: div.LC_left_float {
 5383:   float: left;
 5384:   padding-right: 5%;
 5385:   padding-bottom: 4px;
 5386: }
 5387: 
 5388: div.LC_clear_float_header {
 5389:   padding-bottom: 2px;
 5390: }
 5391: 
 5392: div.LC_clear_float_footer {
 5393:   padding-top: 10px;
 5394:   clear: both;
 5395: }
 5396: 
 5397: 
 5398: div.LC_grade_show_user {
 5399:   margin-top: 20px;
 5400:   border: 1px solid black;
 5401: }
 5402: div.LC_grade_user_name {
 5403:   background: #DDDDEE;
 5404:   border-bottom: 1px solid black;
 5405:   font-weight: bold;
 5406:   font-size: large;
 5407: }
 5408: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5409:   background: #DDEEDD;
 5410: }
 5411: 
 5412: div.LC_grade_show_problem,
 5413: div.LC_grade_submissions,
 5414: div.LC_grade_message_center,
 5415: div.LC_grade_info_links,
 5416: div.LC_grade_assign {
 5417:   margin: 5px;
 5418:   width: 99%;
 5419:   background: #FFFFFF;
 5420: }
 5421: div.LC_grade_show_problem_header,
 5422: div.LC_grade_submissions_header,
 5423: div.LC_grade_message_center_header,
 5424: div.LC_grade_assign_header {
 5425:   font-weight: bold;
 5426:   font-size: large;
 5427: }
 5428: div.LC_grade_show_problem_problem,
 5429: div.LC_grade_submissions_body,
 5430: div.LC_grade_message_center_body,
 5431: div.LC_grade_assign_body {
 5432:   border: 1px solid black;
 5433:   width: 99%;
 5434:   background: #FFFFFF;
 5435: }
 5436: span.LC_grade_check_note {
 5437:   font-weight: normal;
 5438:   font-size: medium;
 5439:   display: inline;
 5440:   position: absolute;
 5441:   right: 1em;
 5442: }
 5443: 
 5444: table.LC_scantron_action {
 5445:   width: 100%;
 5446: }
 5447: table.LC_scantron_action tr th {
 5448:   font-weight:bold;
 5449:   font-style:normal;
 5450: }
 5451: .LC_edit_problem_header, 
 5452: div.LC_edit_problem_footer {
 5453:   font-weight: normal;
 5454:   font-size:  medium;
 5455:   margin: 2px;
 5456: }
 5457: div.LC_edit_problem_header,
 5458: div.LC_edit_problem_header div,
 5459: div.LC_edit_problem_footer,
 5460: div.LC_edit_problem_footer div,
 5461: div.LC_edit_problem_editxml_header,
 5462: div.LC_edit_problem_editxml_header div {
 5463:   margin-top: 5px;
 5464: }
 5465: div.LC_edit_problem_header_edit_row {
 5466:   background: $tabbg;
 5467:   padding: 3px;
 5468:   margin-bottom: 5px;
 5469: }
 5470: div.LC_edit_problem_header_title {
 5471:   font-weight: bold;
 5472:   font-size: larger;
 5473:   background: $tabbg;
 5474:   padding: 3px;
 5475: }
 5476: table.LC_edit_problem_header_title {
 5477:   font-size: larger;
 5478:   font-weight:  bold;
 5479:   width: 100%;
 5480:   border-color: $pgbg;
 5481:   border-style: solid;
 5482:   border-width: $border;
 5483: 
 5484:   background: $tabbg;
 5485:   border-collapse: collapse;
 5486:   padding: 0px
 5487: }
 5488: 
 5489: div.LC_edit_problem_discards {
 5490:   float: left;
 5491:   padding-bottom: 5px;
 5492: }
 5493: div.LC_edit_problem_saves {
 5494:   float: right;
 5495:   padding-bottom: 5px;
 5496: }
 5497: hr.LC_edit_problem_divide {
 5498:   clear: both;
 5499:   color: $tabbg;
 5500:   background-color: $tabbg;
 5501:   height: 3px;
 5502:   border: 0px;
 5503: }
 5504: img.stift{
 5505:   border-width:0;
 5506:   vertical-align:middle;
 5507: }
 5508: 
 5509: table#LC_mainmenu{
 5510:  margin-top:10px;
 5511:  width:80%;
 5512: 
 5513: }
 5514: 
 5515: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5516:   vertical-align: top;
 5517:   width: 45%;
 5518: }
 5519: .LC_mainmenu_fieldset_category {
 5520:   color: $font;
 5521:   background: $pgbg;
 5522:   font-family: $sans;
 5523:   font-size: small;
 5524:   font-weight: bold;
 5525: }
 5526: 
 5527: div.LC_createcourse {
 5528:     margin: 10px 10px 10px 10px;
 5529: }
 5530: 
 5531: /* ---- Remove when done ----
 5532: # The following styles is part of the redesign of LON-CAPA and are
 5533: # subject to change during this project.
 5534: # Don't rely on their current functionality as they might be 
 5535: # changed or removed.
 5536: # --------------------------*/
 5537: 
 5538: a:hover,
 5539: ol.LC_smallMenu a:hover,
 5540: ol#LC_MenuBreadcrumbs a:hover,
 5541: ol#LC_PathBreadcrumbs a:hover,
 5542: ul#LC_TabMainMenuContent a:hover,
 5543: .LC_FormSectionClearButton input:hover
 5544: ul.LC_TabContent   li:hover a{
 5545: 	color:#BF2317;
 5546:         text-decoration:none;
 5547: }
 5548: 
 5549: h1 { 
 5550: 	padding:5px 10px 5px 20px;
 5551: 	line-height:130%;
 5552: }
 5553: 
 5554: h2,h3,h4,h5,h6
 5555: {
 5556: 	margin:5px 0px 5px 0px;
 5557: 	padding:0px;
 5558: 	line-height:130%;
 5559: }
 5560: .LC_hcell{
 5561:         padding:3px 15px 3px 15px;
 5562:         margin:0px;
 5563: 	background-color:$tabbg;
 5564: 	border-bottom:solid 1px $lg_border_color;       
 5565: }
 5566: .LC_noBorder {
 5567:         border:0px;
 5568: }
 5569: 
 5570: .LC_bgLightGrey{
 5571: 	background:URL(/adm/lonIcons/lightGreyBG.png) repeat-x left bottom;
 5572: }
 5573: 
 5574: 
 5575: /* Main Header with discription of Person, Course, etc. */
 5576: .LC_HeadRight {
 5577: 	text-align: right;
 5578: 	float: right;
 5579: 	margin: 0px;
 5580: 	padding: 0px;
 5581:         right:0;
 5582:         position:absolute;
 5583:         overflow:hidden;
 5584: }
 5585: 
 5586: p, .LC_ContentBox {
 5587: 	padding: 10px;
 5588: 
 5589: }
 5590: .LC_FormSectionClearButton input {
 5591:         background-color:transparent;    	    
 5592:         border:0px;
 5593:         cursor:pointer;
 5594:         text-decoration:underline;
 5595: }
 5596: 
 5597: 
 5598: dl,ul,div,fieldset {
 5599: 	margin: 10px 10px 10px 0px;
 5600: 	overflow:hidden;
 5601: }
 5602: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5603: 	margin: 0px;
 5604: }
 5605: 
 5606: ol.LC_smallMenu li {
 5607: 	display: inline;
 5608: 	padding: 5px 5px 0px 10px;
 5609: 	vertical-align: top;
 5610: }
 5611: 
 5612: ol.LC_smallMenu li img {
 5613: 	vertical-align: bottom;
 5614: }
 5615: 
 5616: ol.LC_smallMenu a {
 5617: 	font-size: 90%;
 5618: 	color: RGB(80, 80, 80);
 5619: 	text-decoration: none;
 5620: }
 5621: ol#LC_TabMainMenueContent, ul.LC_TabContent ,
 5622: ul.LC_TabContentBigger {
 5623: 	display:block;
 5624: 	list-style:none;
 5625: 	margin: 0px;
 5626: 	padding: 0px;
 5627: }
 5628: 
 5629: ol#LC_TabMainMenuContent li, ul.LC_TabContent li,
 5630: ul.LC_TabContentBigger li{
 5631: 	display: inline;
 5632: 	border-right: solid 1px $lg_border_color;
 5633: 	float:left;
 5634: 	line-height:140%;
 5635: 	white-space:nowrap;
 5636: }
 5637: ol#LC_TabMainMenuContent li{
 5638: 	vertical-align: bottom;
 5639: 	border-bottom: solid 1px RGB(175, 175, 175);
 5640: 	padding: 5px 10px 5px 10px;
 5641: 	margin-right:5px;
 5642: 	margin-bottom:3px;
 5643: 	font-weight: bold;
 5644: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5645: }
 5646: 
 5647: ol#LC_TabMainMenuContent li a{
 5648: 	color: RGB(47, 47, 47);
 5649: 	text-decoration: none;
 5650: }
 5651: ul.LC_TabContent {
 5652: 	min-height:1.6em;
 5653: }
 5654: ul.LC_TabContent li{
 5655: 	vertical-align:middle;
 5656: 	padding:0px 10px 0px 10px;
 5657: 	background-color:$tabbg;
 5658: 	border-bottom:solid 1px $lg_border_color;
 5659: }
 5660: ul.LC_TabContent li a, ul.LC_TabContent li{ 
 5661: 	color:rgb(47,47,47);
 5662: 	text-decoration:none;
 5663: 	font-size:95%;
 5664: 	font-weight:bold;
 5665: }
 5666: ul.LC_TabContent li:hover, ul.LC_TabContent li.active{
 5667: 	background-color:#FFFFFF;
 5668: 	border-bottom:solid 1px #FFFFFF;
 5669: }
 5670: ul.LC_TabContentBigger li{
 5671: 	vertical-align:bottom;
 5672: 	border-top:solid 1px $lg_border_color;
 5673: 	border-left:solid 1px $lg_border_color;
 5674: 	padding:5px 10px 5px 10px;
 5675: 	margin-left:2px;
 5676: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5677: }
 5678: ul.LC_TabContentBigger li:hover, ul.LC_TabContentBigger li.active{
 5679: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5680: }
 5681: ul.LC_TabContentBigger li, ul.LC_TabContentBigger li a{
 5682: 	font-size:110%;
 5683: 	font-weight:bold;
 5684: }
 5685: #LC_CourseDocuments, #LC_SupplementalCourseDocuments
 5686: {
 5687: 	margin:0px;
 5688: }
 5689: 
 5690: .LC_hideThis
 5691: {
 5692: 	display:none;
 5693: 	visibility:hidden;
 5694: }
 5695: 
 5696: ol#LC_MenuBreadcrumbs, ol#LC_PathBreadcrumbs {
 5697: 	border-top: solid 1px RGB(255, 255, 255);
 5698: 	height: 20px;
 5699: 	line-height: 20px;
 5700: 	vertical-align: bottom;
 5701: 	margin: 0px 0px 30px 0px;
 5702: 	padding-left: 10px;
 5703: 	list-style-position: inside;
 5704: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5705: }
 5706: 
 5707: ol#LC_MenuBreadcrumbs li, ol#LC_PathBreadcrumbs li {
 5708: /*
 5709: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5710: */	
 5711: 	display: inline;
 5712: 	padding: 0px 0px 0px 10px;
 5713: 	vertical-align: bottom;
 5714: 	overflow:hidden;
 5715: }
 5716: 
 5717: ol#LC_MenuBreadcrumbs li a {
 5718: 	text-decoration: none;
 5719: 	font-size:90%;
 5720: }
 5721: ol#LC_PathBreadcrumbs li a{
 5722: 	text-decoration:none;
 5723: 	font-size:100%;
 5724: 	font-weight:bold;
 5725: }
 5726: .LC_ContentBoxSpecial
 5727: {
 5728: 	border: solid 1px $lg_border_color;
 5729: }
 5730: .LC_ContentBoxSpecialContactInfo
 5731: {
 5732: 	border: solid 1px $lg_border_color;
 5733: 	max-width:25%;
 5734: 	min-width:25%;
 5735: }
 5736: .LC_AboutMe_Image
 5737: {
 5738: 	float:left;
 5739: 	margin-right:10px;
 5740: }
 5741: .LC_Clear_AboutMe_Image
 5742: {
 5743: 	clear:left;
 5744: }
 5745: dl.LC_ListStyleClean dt {
 5746: 	padding-right: 5px;
 5747: 	display: table-header-group;
 5748: }
 5749: 
 5750: dl.LC_ListStyleClean dd {
 5751: 	display: table-row;
 5752: }
 5753: 
 5754: .LC_ListStyleClean,
 5755: .LC_ListStyleSimple,
 5756: .LC_ListStyleNormal,
 5757: .LC_ListStyleNormal_Border,
 5758: .LC_ListStyleSpecial
 5759: 	{
 5760: 	/*display:block;	*/
 5761: 	list-style-position: inside;
 5762: 	list-style-type: none;
 5763: 	overflow: hidden;
 5764: 	padding: 0px;
 5765: }
 5766: 
 5767: .LC_ListStyleSimple li,
 5768: .LC_ListStyleSimple dd,
 5769: .LC_ListStyleNormal li,
 5770: .LC_ListStyleNormal dd,
 5771: .LC_ListStyleSpecial li,
 5772: .LC_ListStyleSpecial dd
 5773: 	{
 5774: 	margin: 0px;
 5775: 	padding: 5px 5px 5px 10px;
 5776: 	clear: both;
 5777: }
 5778: 
 5779: .LC_ListStyleClean li,
 5780: .LC_ListStyleClean dd {
 5781: 	padding-top: 0px;
 5782: 	padding-bottom: 0px;
 5783: }
 5784: 
 5785: .LC_ListStyleSimple dd,
 5786: .LC_ListStyleSimple li{
 5787: 	border-bottom: solid 1px $lg_border_color;
 5788: }
 5789: 
 5790: .LC_ListStyleSpecial li,
 5791: .LC_ListStyleSpecial dd {
 5792: 	list-style-type: none;
 5793: 	background-color: RGB(220, 220, 220);
 5794: 	margin-bottom: 4px;
 5795: }
 5796: 
 5797: table.LC_SimpleTable {
 5798: 	margin:5px;
 5799: 	border:solid 1px $lg_border_color;
 5800: 	}
 5801: 
 5802: table.LC_SimpleTable tr {
 5803: 	padding:0px;
 5804: 	border:solid 1px $lg_border_color;
 5805: }
 5806: table.LC_SimpleTable thead{
 5807: 	 background:rgb(220,220,220);
 5808: }
 5809: 
 5810: div.LC_columnSection {
 5811: 	display: block;
 5812: 	clear: both;
 5813: 	overflow: hidden;
 5814: 	margin:0px;
 5815: }
 5816: 
 5817: div.LC_columnSection>* {
 5818: 	float: left;
 5819: 	margin: 10px 20px 10px 0px;
 5820: 	overflow:hidden;
 5821: }
 5822: 
 5823: .ContentBoxSpecialTemplate
 5824: {
 5825:         border: solid 1px $lg_border_color;
 5826: }
 5827: .ContentBoxTemplate {
 5828:         padding:10px;
 5829: }
 5830: 
 5831: div.LC_columnSection > .ContentBoxTemplate,
 5832: div.LC_columnSection > .ContentBoxSpecialTemplate
 5833:         {
 5834:         width: 600px;
 5835: }
 5836: .clear{
 5837: 	clear: both;
 5838: 	line-height: 0px;
 5839: 	font-size: 0px;
 5840: 	height: 0px;
 5841: }
 5842: 
 5843: .LC_loginpage_container {
 5844: 	text-align:left;
 5845: 	margin : 0 auto;
 5846: 	width:65%;
 5847: 	padding: 10px;
 5848: 	height: auto;
 5849: 	background-color:#FFFFFF;
 5850: 	border:1px solid #CCCCCC;
 5851: }
 5852: 
 5853: 
 5854: .LC_loginpage_loginContainer {
 5855: 	float:left;
 5856: 	width: 182px;
 5857: 	border:1px solid #CCCCCC;
 5858: 	background-color:$loginbg;
 5859: }
 5860: 
 5861: .LC_loginpage_loginContainer h2{
 5862: 	margin-top:0;
 5863: 	display:block;
 5864: 	background:$bgcol;
 5865: 	color:$textcol;
 5866: 	padding-left:5px;
 5867: }
 5868: .LC_loginpage_loginInfo {
 5869: 	margin-left:20px;
 5870: 	float:left;
 5871: 	width:30%;
 5872: 	border:1px solid #CCCCCC;
 5873: 	padding:10px;
 5874: }
 5875: 
 5876: .LC_loginpage_loginDomain {
 5877: 	margin-right:20px;
 5878: 	width:20%;
 5879: 	float:left;
 5880: 	padding:10px;
 5881: }
 5882: 
 5883: .LC_loginpage_space {
 5884: 	clear:both;
 5885: 	margin-bottom:20px;
 5886: 	border-bottom: 1px solid #CCCCCC;
 5887: }
 5888: 
 5889: table em{
 5890: 	font-weight:bold;
 5891: 	font-style:normal;
 5892: }
 5893: 
 5894: END
 5895: }
 5896: 
 5897: =pod
 5898: 
 5899: =item * &headtag()
 5900: 
 5901: Returns a uniform footer for LON-CAPA web pages.
 5902: 
 5903: Inputs: $title - optional title for the head
 5904:         $head_extra - optional extra HTML to put inside the <head>
 5905:         $args - optional arguments
 5906:             force_register - if is true call registerurl so the remote is 
 5907:                              informed
 5908:             redirect       -> array ref of
 5909:                                    1- seconds before redirect occurs
 5910:                                    2- url to redirect to
 5911:                                    3- whether the side effect should occur
 5912:                            (side effect of setting 
 5913:                                $env{'internal.head.redirect'} to the url 
 5914:                                redirected too)
 5915:             domain         -> force to color decorate a page for a specific
 5916:                                domain
 5917:             function       -> force usage of a specific rolish color scheme
 5918:             bgcolor        -> override the default page bgcolor
 5919:             no_auto_mt_title
 5920:                            -> prevent &mt()ing the title arg
 5921: 
 5922: =cut
 5923: 
 5924: sub headtag {
 5925:     my ($title,$head_extra,$args) = @_;
 5926:     
 5927:     my $function = $args->{'function'} || &get_users_function();
 5928:     my $domain   = $args->{'domain'}   || &determinedomain();
 5929:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5930:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5931: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5932: 		   #time(),
 5933: 		   $env{'environment.color.timestamp'},
 5934: 		   $function,$domain,$bgcolor);
 5935: 
 5936:     $url = '/adm/css/'.&escape($url).'.css';
 5937: 
 5938:     my $result =
 5939: 	'<head>'.
 5940: 	&font_settings();
 5941: 
 5942:     if (!$args->{'frameset'}) {
 5943: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5944:     }
 5945:     if ($args->{'force_register'}) {
 5946: 	$result .= &Apache::lonmenu::registerurl(1);
 5947:     }
 5948:     if (!$args->{'no_nav_bar'} 
 5949: 	&& !$args->{'only_body'}
 5950: 	&& !$args->{'frameset'}) {
 5951: 	$result .= &help_menu_js();
 5952:     }
 5953: 
 5954:     if (ref($args->{'redirect'})) {
 5955: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5956: 	$url = &Apache::lonenc::check_encrypt($url);
 5957: 	if (!$inhibit_continue) {
 5958: 	    $env{'internal.head.redirect'} = $url;
 5959: 	}
 5960: 	$result.=<<ADDMETA
 5961: <meta http-equiv="pragma" content="no-cache" />
 5962: <meta http-equiv="Refresh" content="$time; url=$url" />
 5963: ADDMETA
 5964:     }
 5965:     if (!defined($title)) {
 5966: 	$title = 'The LearningOnline Network with CAPA';
 5967:     }
 5968:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5969:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5970: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5971: 	.$head_extra;
 5972:     return $result;
 5973: }
 5974: 
 5975: =pod
 5976: 
 5977: =item * &font_settings()
 5978: 
 5979: Returns neccessary <meta> to set the proper encoding
 5980: 
 5981: Inputs: none
 5982: 
 5983: =cut
 5984: 
 5985: sub font_settings {
 5986:     my $headerstring='';
 5987:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5988: 	$headerstring.=
 5989: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5990:     }
 5991:     return $headerstring;
 5992: }
 5993: 
 5994: =pod
 5995: 
 5996: =item * &xml_begin()
 5997: 
 5998: Returns the needed doctype and <html>
 5999: 
 6000: Inputs: none
 6001: 
 6002: =cut
 6003: 
 6004: sub xml_begin {
 6005:     my $output='';
 6006: 
 6007:     if ($env{'internal.start_page'}==1) {
 6008: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6009:     }
 6010: 
 6011:     if ($env{'browser.mathml'}) {
 6012: 	$output='<?xml version="1.0"?>'
 6013:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6014: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6015:             
 6016: #	    .'<!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">] >'
 6017: 	    .'<!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">'
 6018:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6019: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6020:     } else {
 6021: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6022:     }
 6023:     return $output;
 6024: }
 6025: 
 6026: =pod
 6027: 
 6028: =item * &endheadtag()
 6029: 
 6030: Returns a uniform </head> for LON-CAPA web pages.
 6031: 
 6032: Inputs: none
 6033: 
 6034: =cut
 6035: 
 6036: sub endheadtag {
 6037:     return '</head>';
 6038: }
 6039: 
 6040: =pod
 6041: 
 6042: =item * &head()
 6043: 
 6044: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6045: 
 6046: Inputs:
 6047: 
 6048: =over 4
 6049: 
 6050: $title - optional title for the page
 6051: 
 6052: $head_extra - optional extra HTML to put inside the <head>
 6053: 
 6054: =back
 6055: 
 6056: =cut
 6057: 
 6058: sub head {
 6059:     my ($title,$head_extra,$args) = @_;
 6060:     return &headtag($title,$head_extra,$args).&endheadtag();
 6061: }
 6062: 
 6063: =pod
 6064: 
 6065: =item * &start_page()
 6066: 
 6067: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6068: 
 6069: Inputs:
 6070: 
 6071: =over 4
 6072: 
 6073: $title - optional title for the page
 6074: 
 6075: $head_extra - optional extra HTML to incude inside the <head>
 6076: 
 6077: $args - additional optional args supported are:
 6078: 
 6079: =over 8
 6080: 
 6081:              only_body      -> is true will set &bodytag() onlybodytag
 6082:                                     arg on
 6083:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6084:              add_entries    -> additional attributes to add to the  <body>
 6085:              domain         -> force to color decorate a page for a 
 6086:                                     specific domain
 6087:              function       -> force usage of a specific rolish color
 6088:                                     scheme
 6089:              redirect       -> see &headtag()
 6090:              bgcolor        -> override the default page bg color
 6091:              js_ready       -> return a string ready for being used in 
 6092:                                     a javascript writeln
 6093:              html_encode    -> return a string ready for being used in 
 6094:                                     a html attribute
 6095:              force_register -> if is true will turn on the &bodytag()
 6096:                                     $forcereg arg
 6097:              body_title     -> alternate text to use instead of $title
 6098:                                     in the title box that appears, this text
 6099:                                     is not auto translated like the $title is
 6100:              frameset       -> if true will start with a <frameset>
 6101:                                     rather than <body>
 6102:              no_title       -> if true the title bar won't be shown
 6103:              skip_phases    -> hash ref of 
 6104:                                     head -> skip the <html><head> generation
 6105:                                     body -> skip all <body> generation
 6106:              no_inline_link -> if true and in remote mode, don't show the 
 6107:                                     'Switch To Inline Menu' link
 6108:              no_auto_mt_title -> prevent &mt()ing the title arg
 6109:              inherit_jsmath -> when creating popup window in a page,
 6110:                                     should it have jsmath forced on by the
 6111:                                     current page
 6112: 
 6113: =back
 6114: 
 6115: =back
 6116: 
 6117: =cut
 6118: 
 6119: sub start_page {
 6120:     my ($title,$head_extra,$args) = @_;
 6121:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6122:     my %head_args;
 6123:     foreach my $arg ('redirect','force_register','domain','function',
 6124: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6125: 		     'no_auto_mt_title') {
 6126: 	if (defined($args->{$arg})) {
 6127: 	    $head_args{$arg} = $args->{$arg};
 6128: 	}
 6129:     }
 6130: 
 6131:     $env{'internal.start_page'}++;
 6132:     my $result;
 6133:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6134: 	$result.=
 6135: 	    &xml_begin().
 6136: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6137:     }
 6138:     
 6139:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6140: 	if ($args->{'frameset'}) {
 6141: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6142: 						$args->{'add_entries'});
 6143: 	    $result .= "\n<frameset $attr_string>\n";
 6144: 	} else {
 6145: 	    $result .=
 6146: 		&bodytag($title, 
 6147: 			 $args->{'function'},       $args->{'add_entries'},
 6148: 			 $args->{'only_body'},      $args->{'domain'},
 6149: 			 $args->{'force_register'}, $args->{'body_title'},
 6150: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6151: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6152: 			 $args);
 6153: 	}
 6154:     }
 6155: 
 6156:     if ($args->{'js_ready'}) {
 6157: 		$result = &js_ready($result);
 6158:     }
 6159:     if ($args->{'html_encode'}) {
 6160: 		$result = &html_encode($result);
 6161:     }
 6162: 
 6163:     if (exists($args->{'bread_crumbs'})) {
 6164:         &Apache::lonhtmlcommon::clear_breadcrumbs();
 6165:         if (ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6166:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6167:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6168:             }
 6169:         }
 6170:         $result .= &Apache::lonhtmlcommon::breadcrumbs();
 6171:     }
 6172: 
 6173:     return $result;
 6174: }
 6175: 
 6176: 
 6177: =pod
 6178: 
 6179: =item * &head()
 6180: 
 6181: Returns a complete </body></html> section for LON-CAPA web pages.
 6182: 
 6183: Inputs:         $args - additional optional args supported are:
 6184:                  js_ready     -> return a string ready for being used in 
 6185:                                  a javascript writeln
 6186:                  html_encode  -> return a string ready for being used in 
 6187:                                  a html attribute
 6188:                  frameset     -> if true will start with a <frameset>
 6189:                                  rather than <body>
 6190:                  dicsussion   -> if true will get discussion from
 6191:                                   lonxml::xmlend
 6192:                                  (you can pass the target and parser arguments
 6193:                                   through optional 'target' and 'parser' args
 6194:                                   to this routine)
 6195: 
 6196: =cut
 6197: 
 6198: sub end_page {
 6199:     my ($args) = @_;
 6200:     $env{'internal.end_page'}++;
 6201:     my $result;
 6202:     if ($args->{'discussion'}) {
 6203: 	my ($target,$parser);
 6204: 	if (ref($args->{'discussion'})) {
 6205: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6206: 				$args->{'discussion'}{'parser'});
 6207: 	}
 6208: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6209:     }
 6210: 
 6211:     if ($args->{'frameset'}) {
 6212: 	$result .= '</frameset>';
 6213:     } else {
 6214: 	$result .= &endbodytag($args);
 6215:     }
 6216:     $result .= "\n</html>";
 6217: 
 6218:     if ($args->{'js_ready'}) {
 6219: 	$result = &js_ready($result);
 6220:     }
 6221: 
 6222:     if ($args->{'html_encode'}) {
 6223: 	$result = &html_encode($result);
 6224:     }
 6225: 
 6226:     return $result;
 6227: }
 6228: 
 6229: sub html_encode {
 6230:     my ($result) = @_;
 6231: 
 6232:     $result = &HTML::Entities::encode($result,'<>&"');
 6233:     
 6234:     return $result;
 6235: }
 6236: sub js_ready {
 6237:     my ($result) = @_;
 6238: 
 6239:     $result =~ s/[\n\r]/ /xmsg;
 6240:     $result =~ s/\\/\\\\/xmsg;
 6241:     $result =~ s/'/\\'/xmsg;
 6242:     $result =~ s{</}{<\\/}xmsg;
 6243:     
 6244:     return $result;
 6245: }
 6246: 
 6247: sub validate_page {
 6248:     if (  exists($env{'internal.start_page'})
 6249: 	  &&     $env{'internal.start_page'} > 1) {
 6250: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6251: 				 $env{'internal.start_page'}.' '.
 6252: 				 $ENV{'request.filename'});
 6253:     }
 6254:     if (  exists($env{'internal.end_page'})
 6255: 	  &&     $env{'internal.end_page'} > 1) {
 6256: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6257: 				 $env{'internal.end_page'}.' '.
 6258: 				 $env{'request.filename'});
 6259:     }
 6260:     if (     exists($env{'internal.start_page'})
 6261: 	&& ! exists($env{'internal.end_page'})) {
 6262: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6263: 				 $env{'request.filename'});
 6264:     }
 6265:     if (   ! exists($env{'internal.start_page'})
 6266: 	&&   exists($env{'internal.end_page'})) {
 6267: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6268: 				 $env{'request.filename'});
 6269:     }
 6270: }
 6271: 
 6272: sub simple_error_page {
 6273:     my ($r,$title,$msg) = @_;
 6274:     my $page =
 6275: 	&Apache::loncommon::start_page($title).
 6276: 	&mt($msg).
 6277: 	&Apache::loncommon::end_page();
 6278:     if (ref($r)) {
 6279: 	$r->print($page);
 6280: 	return;
 6281:     }
 6282:     return $page;
 6283: }
 6284: 
 6285: {
 6286:     my @row_count;
 6287:     sub start_data_table {
 6288: 	my ($add_class) = @_;
 6289: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6290: 	unshift(@row_count,0);
 6291: 	return '<table class="'.$css_class.'">'."\n";
 6292:     }
 6293: 
 6294:     sub end_data_table {
 6295: 	shift(@row_count);
 6296: 	return '</table>'."\n";;
 6297:     }
 6298: 
 6299:     sub start_data_table_row {
 6300: 	my ($add_class) = @_;
 6301: 	$row_count[0]++;
 6302: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6303: 	$css_class = (join(' ',$css_class,$add_class));
 6304: 	return  '<tr class="'.$css_class.'">'."\n";;
 6305:     }
 6306:     
 6307:     sub continue_data_table_row {
 6308: 	my ($add_class) = @_;
 6309: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6310: 	$css_class = (join(' ',$css_class,$add_class));
 6311: 	return  '<tr class="'.$css_class.'">'."\n";;
 6312:     }
 6313: 
 6314:     sub end_data_table_row {
 6315: 	return '</tr>'."\n";;
 6316:     }
 6317: 
 6318:     sub start_data_table_empty_row {
 6319: #	$row_count[0]++;
 6320: 	return  '<tr class="LC_empty_row" >'."\n";;
 6321:     }
 6322: 
 6323:     sub end_data_table_empty_row {
 6324: 	return '</tr>'."\n";;
 6325:     }
 6326: 
 6327:     sub start_data_table_header_row {
 6328: 	return  '<tr class="LC_header_row">'."\n";;
 6329:     }
 6330: 
 6331:     sub end_data_table_header_row {
 6332: 	return '</tr>'."\n";;
 6333:     }
 6334: }
 6335: 
 6336: =pod
 6337: 
 6338: =item * &inhibit_menu_check($arg)
 6339: 
 6340: Checks for a inhibitmenu state and generates output to preserve it
 6341: 
 6342: Inputs:         $arg - can be any of
 6343:                      - undef - in which case the return value is a string 
 6344:                                to add  into arguments list of a uri
 6345:                      - 'input' - in which case the return value is a HTML
 6346:                                  <form> <input> field of type hidden to
 6347:                                  preserve the value
 6348:                      - a url - in which case the return value is the url with
 6349:                                the neccesary cgi args added to preserve the
 6350:                                inhibitmenu state
 6351:                      - a ref to a url - no return value, but the string is
 6352:                                         updated to include the neccessary cgi
 6353:                                         args to preserve the inhibitmenu state
 6354: 
 6355: =cut
 6356: 
 6357: sub inhibit_menu_check {
 6358:     my ($arg) = @_;
 6359:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6360:     if ($arg eq 'input') {
 6361: 	if ($env{'form.inhibitmenu'}) {
 6362: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6363: 	} else {
 6364: 	    return
 6365: 	}
 6366:     }
 6367:     if ($env{'form.inhibitmenu'}) {
 6368: 	if (ref($arg)) {
 6369: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6370: 	} elsif ($arg eq '') {
 6371: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6372: 	} else {
 6373: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6374: 	}
 6375:     }
 6376:     if (!ref($arg)) {
 6377: 	return $arg;
 6378:     }
 6379: }
 6380: 
 6381: ###############################################
 6382: 
 6383: =pod
 6384: 
 6385: =back
 6386: 
 6387: =head1 User Information Routines
 6388: 
 6389: =over 4
 6390: 
 6391: =item * &get_users_function()
 6392: 
 6393: Used by &bodytag to determine the current users primary role.
 6394: Returns either 'student','coordinator','admin', or 'author'.
 6395: 
 6396: =cut
 6397: 
 6398: ###############################################
 6399: sub get_users_function {
 6400:     my $function = 'student';
 6401:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6402:         $function='coordinator';
 6403:     }
 6404:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6405:         $function='admin';
 6406:     }
 6407:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6408:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6409:         $function='author';
 6410:     }
 6411:     return $function;
 6412: }
 6413: 
 6414: ###############################################
 6415: 
 6416: =pod
 6417: 
 6418: =item * &check_user_status()
 6419: 
 6420: Determines current status of supplied role for a
 6421: specific user. Roles can be active, previous or future.
 6422: 
 6423: Inputs: 
 6424: user's domain, user's username, course's domain,
 6425: course's number, optional section ID.
 6426: 
 6427: Outputs:
 6428: role status: active, previous or future. 
 6429: 
 6430: =cut
 6431: 
 6432: sub check_user_status {
 6433:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6434:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6435:     my @uroles = keys %userinfo;
 6436:     my $srchstr;
 6437:     my $active_chk = 'none';
 6438:     my $now = time;
 6439:     if (@uroles > 0) {
 6440:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6441:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6442:         } else {
 6443:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6444:         }
 6445:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6446:             my $role_end = 0;
 6447:             my $role_start = 0;
 6448:             $active_chk = 'active';
 6449:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6450:                 $role_end = $1;
 6451:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6452:                     $role_start = $1;
 6453:                 }
 6454:             }
 6455:             if ($role_start > 0) {
 6456:                 if ($now < $role_start) {
 6457:                     $active_chk = 'future';
 6458:                 }
 6459:             }
 6460:             if ($role_end > 0) {
 6461:                 if ($now > $role_end) {
 6462:                     $active_chk = 'previous';
 6463:                 }
 6464:             }
 6465:         }
 6466:     }
 6467:     return $active_chk;
 6468: }
 6469: 
 6470: ###############################################
 6471: 
 6472: =pod
 6473: 
 6474: =item * &get_sections()
 6475: 
 6476: Determines all the sections for a course including
 6477: sections with students and sections containing other roles.
 6478: Incoming parameters: 
 6479: 
 6480: 1. domain
 6481: 2. course number 
 6482: 3. reference to array containing roles for which sections should 
 6483: be gathered (optional).
 6484: 4. reference to array containing status types for which sections 
 6485: should be gathered (optional).
 6486: 
 6487: If the third argument is undefined, sections are gathered for any role. 
 6488: If the fourth argument is undefined, sections are gathered for any status.
 6489: Permissible values are 'active' or 'future' or 'previous'.
 6490:  
 6491: Returns section hash (keys are section IDs, values are
 6492: number of users in each section), subject to the
 6493: optional roles filter, optional status filter 
 6494: 
 6495: =cut
 6496: 
 6497: ###############################################
 6498: sub get_sections {
 6499:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6500:     if (!defined($cdom) || !defined($cnum)) {
 6501:         my $cid =  $env{'request.course.id'};
 6502: 
 6503: 	return if (!defined($cid));
 6504: 
 6505:         $cdom = $env{'course.'.$cid.'.domain'};
 6506:         $cnum = $env{'course.'.$cid.'.num'};
 6507:     }
 6508: 
 6509:     my %sectioncount;
 6510:     my $now = time;
 6511: 
 6512:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6513: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6514: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6515: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6516:         my $start_index = &Apache::loncoursedata::CL_START();
 6517:         my $end_index = &Apache::loncoursedata::CL_END();
 6518:         my $status;
 6519: 	while (my ($student,$data) = each(%$classlist)) {
 6520: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6521: 				                     $data->[$status_index],
 6522:                                                      $data->[$start_index],
 6523:                                                      $data->[$end_index]);
 6524:             if ($stu_status eq 'Active') {
 6525:                 $status = 'active';
 6526:             } elsif ($end < $now) {
 6527:                 $status = 'previous';
 6528:             } elsif ($start > $now) {
 6529:                 $status = 'future';
 6530:             } 
 6531: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6532:                 if ((!defined($possible_status)) || (($status ne '') && 
 6533:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6534: 		    $sectioncount{$section}++;
 6535:                 }
 6536: 	    }
 6537: 	}
 6538:     }
 6539:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6540:     foreach my $user (sort(keys(%courseroles))) {
 6541: 	if ($user !~ /^(\w{2})/) { next; }
 6542: 	my ($role) = ($user =~ /^(\w{2})/);
 6543: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6544: 	my ($section,$status);
 6545: 	if ($role eq 'cr' &&
 6546: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6547: 	    $section=$1;
 6548: 	}
 6549: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6550: 	if (!defined($section) || $section eq '-1') { next; }
 6551:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6552:         if ($end == -1 && $start == -1) {
 6553:             next; #deleted role
 6554:         }
 6555:         if (!defined($possible_status)) { 
 6556:             $sectioncount{$section}++;
 6557:         } else {
 6558:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6559:                 $status = 'active';
 6560:             } elsif ($end < $now) {
 6561:                 $status = 'future';
 6562:             } elsif ($start > $now) {
 6563:                 $status = 'previous';
 6564:             }
 6565:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6566:                 $sectioncount{$section}++;
 6567:             }
 6568:         }
 6569:     }
 6570:     return %sectioncount;
 6571: }
 6572: 
 6573: ###############################################
 6574: 
 6575: =pod
 6576: 
 6577: =item * &get_course_users()
 6578: 
 6579: Retrieves usernames:domains for users in the specified course
 6580: with specific role(s), and access status. 
 6581: 
 6582: Incoming parameters:
 6583: 1. course domain
 6584: 2. course number
 6585: 3. access status: users must have - either active, 
 6586: previous, future, or all.
 6587: 4. reference to array of permissible roles
 6588: 5. reference to array of section restrictions (optional)
 6589: 6. reference to results object (hash of hashes).
 6590: 7. reference to optional userdata hash
 6591: 8. reference to optional statushash
 6592: 9. flag if privileged users (except those set to unhide in
 6593:    course settings) should be excluded    
 6594: Keys of top level results hash are roles.
 6595: Keys of inner hashes are username:domain, with 
 6596: values set to access type.
 6597: Optional userdata hash returns an array with arguments in the 
 6598: same order as loncoursedata::get_classlist() for student data.
 6599: 
 6600: Optional statushash returns
 6601: 
 6602: Entries for end, start, section and status are blank because
 6603: of the possibility of multiple values for non-student roles.
 6604: 
 6605: =cut
 6606: 
 6607: ###############################################
 6608: 
 6609: sub get_course_users {
 6610:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6611:     my %idx = ();
 6612:     my %seclists;
 6613: 
 6614:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6615:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6616:     $idx{end} = &Apache::loncoursedata::CL_END();
 6617:     $idx{start} = &Apache::loncoursedata::CL_START();
 6618:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6619:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6620:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6621:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6622: 
 6623:     if (grep(/^st$/,@{$roles})) {
 6624:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6625:         my $now = time;
 6626:         foreach my $student (keys(%{$classlist})) {
 6627:             my $match = 0;
 6628:             my $secmatch = 0;
 6629:             my $section = $$classlist{$student}[$idx{section}];
 6630:             my $status = $$classlist{$student}[$idx{status}];
 6631:             if ($section eq '') {
 6632:                 $section = 'none';
 6633:             }
 6634:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6635:                 if (grep(/^all$/,@{$sections})) {
 6636:                     $secmatch = 1;
 6637:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6638:                     if (grep(/^none$/,@{$sections})) {
 6639:                         $secmatch = 1;
 6640:                     }
 6641:                 } else {  
 6642: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6643: 		        $secmatch = 1;
 6644:                     }
 6645: 		}
 6646:                 if (!$secmatch) {
 6647:                     next;
 6648:                 }
 6649:             }
 6650:             if (defined($$types{'active'})) {
 6651:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6652:                     push(@{$$users{st}{$student}},'active');
 6653:                     $match = 1;
 6654:                 }
 6655:             }
 6656:             if (defined($$types{'previous'})) {
 6657:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6658:                     push(@{$$users{st}{$student}},'previous');
 6659:                     $match = 1;
 6660:                 }
 6661:             }
 6662:             if (defined($$types{'future'})) {
 6663:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6664:                     push(@{$$users{st}{$student}},'future');
 6665:                     $match = 1;
 6666:                 }
 6667:             }
 6668:             if ($match) {
 6669:                 push(@{$seclists{$student}},$section);
 6670:                 if (ref($userdata) eq 'HASH') {
 6671:                     $$userdata{$student} = $$classlist{$student};
 6672:                 }
 6673:                 if (ref($statushash) eq 'HASH') {
 6674:                     $statushash->{$student}{'st'}{$section} = $status;
 6675:                 }
 6676:             }
 6677:         }
 6678:     }
 6679:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6680:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6681:         my $now = time;
 6682:         my %displaystatus = ( previous => 'Expired',
 6683:                               active   => 'Active',
 6684:                               future   => 'Future',
 6685:                             );
 6686:         my %nothide;
 6687:         if ($hidepriv) {
 6688:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6689:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6690:                 if ($user !~ /:/) {
 6691:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6692:                 } else {
 6693:                     $nothide{$user} = 1;
 6694:                 }
 6695:             }
 6696:         }
 6697:         foreach my $person (sort(keys(%coursepersonnel))) {
 6698:             my $match = 0;
 6699:             my $secmatch = 0;
 6700:             my $status;
 6701:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6702:             $user =~ s/:$//;
 6703:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6704:             if ($end == -1 || $start == -1) {
 6705:                 next;
 6706:             }
 6707:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6708:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6709:                 my ($uname,$udom) = split(/:/,$user);
 6710:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6711:                     if (grep(/^all$/,@{$sections})) {
 6712:                         $secmatch = 1;
 6713:                     } elsif ($usec eq '') {
 6714:                         if (grep(/^none$/,@{$sections})) {
 6715:                             $secmatch = 1;
 6716:                         }
 6717:                     } else {
 6718:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6719:                             $secmatch = 1;
 6720:                         }
 6721:                     }
 6722:                     if (!$secmatch) {
 6723:                         next;
 6724:                     }
 6725:                 }
 6726:                 if ($usec eq '') {
 6727:                     $usec = 'none';
 6728:                 }
 6729:                 if ($uname ne '' && $udom ne '') {
 6730:                     if ($hidepriv) {
 6731:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6732:                             (!$nothide{$uname.':'.$udom})) {
 6733:                             next;
 6734:                         }
 6735:                     }
 6736:                     if ($end > 0 && $end < $now) {
 6737:                         $status = 'previous';
 6738:                     } elsif ($start > $now) {
 6739:                         $status = 'future';
 6740:                     } else {
 6741:                         $status = 'active';
 6742:                     }
 6743:                     foreach my $type (keys(%{$types})) { 
 6744:                         if ($status eq $type) {
 6745:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6746:                                 push(@{$$users{$role}{$user}},$type);
 6747:                             }
 6748:                             $match = 1;
 6749:                         }
 6750:                     }
 6751:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6752:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6753: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6754:                         }
 6755:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6756:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6757:                         }
 6758:                         if (ref($statushash) eq 'HASH') {
 6759:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6760:                         }
 6761:                     }
 6762:                 }
 6763:             }
 6764:         }
 6765:         if (grep(/^ow$/,@{$roles})) {
 6766:             if ((defined($cdom)) && (defined($cnum))) {
 6767:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6768:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6769:                     my $owner = $csettings{'internal.courseowner'};
 6770:                     next if ($owner eq '');
 6771:                     my ($ownername,$ownerdom);
 6772:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6773:                         $ownername = $1;
 6774:                         $ownerdom = $2;
 6775:                     } else {
 6776:                         $ownername = $owner;
 6777:                         $ownerdom = $cdom;
 6778:                         $owner = $ownername.':'.$ownerdom;
 6779:                     }
 6780:                     @{$$users{'ow'}{$owner}} = 'any';
 6781:                     if (defined($userdata) && 
 6782: 			!exists($$userdata{$owner})) {
 6783: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6784:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6785:                             push(@{$seclists{$owner}},'none');
 6786:                         }
 6787:                         if (ref($statushash) eq 'HASH') {
 6788:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6789:                         }
 6790: 		    }
 6791:                 }
 6792:             }
 6793:         }
 6794:         foreach my $user (keys(%seclists)) {
 6795:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6796:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6797:         }
 6798:     }
 6799:     return;
 6800: }
 6801: 
 6802: sub get_user_info {
 6803:     my ($udom,$uname,$idx,$userdata) = @_;
 6804:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6805: 	&plainname($uname,$udom,'lastname');
 6806:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6807:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6808:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6809:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6810:     return;
 6811: }
 6812: 
 6813: ###############################################
 6814: 
 6815: =pod
 6816: 
 6817: =item * &get_user_quota()
 6818: 
 6819: Retrieves quota assigned for storage of portfolio files for a user  
 6820: 
 6821: Incoming parameters:
 6822: 1. user's username
 6823: 2. user's domain
 6824: 
 6825: Returns:
 6826: 1. Disk quota (in Mb) assigned to student.
 6827: 2. (Optional) Type of setting: custom or default
 6828:    (individually assigned or default for user's 
 6829:    institutional status).
 6830: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6831:    or student - types as defined in localenroll::inst_usertypes 
 6832:    for user's domain, which determines default quota for user.
 6833: 4. (Optional) - Default quota which would apply to the user.
 6834: 
 6835: If a value has been stored in the user's environment, 
 6836: it will return that, otherwise it returns the maximal default
 6837: defined for the user's instituional status(es) in the domain.
 6838: 
 6839: =cut
 6840: 
 6841: ###############################################
 6842: 
 6843: 
 6844: sub get_user_quota {
 6845:     my ($uname,$udom) = @_;
 6846:     my ($quota,$quotatype,$settingstatus,$defquota);
 6847:     if (!defined($udom)) {
 6848:         $udom = $env{'user.domain'};
 6849:     }
 6850:     if (!defined($uname)) {
 6851:         $uname = $env{'user.name'};
 6852:     }
 6853:     if (($udom eq '' || $uname eq '') ||
 6854:         ($udom eq 'public') && ($uname eq 'public')) {
 6855:         $quota = 0;
 6856:         $quotatype = 'default';
 6857:         $defquota = 0; 
 6858:     } else {
 6859:         my $inststatus;
 6860:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6861:             $quota = $env{'environment.portfolioquota'};
 6862:             $inststatus = $env{'environment.inststatus'};
 6863:         } else {
 6864:             my %userenv = 
 6865:                 &Apache::lonnet::get('environment',['portfolioquota',
 6866:                                      'inststatus'],$udom,$uname);
 6867:             my ($tmp) = keys(%userenv);
 6868:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6869:                 $quota = $userenv{'portfolioquota'};
 6870:                 $inststatus = $userenv{'inststatus'};
 6871:             } else {
 6872:                 undef(%userenv);
 6873:             }
 6874:         }
 6875:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6876:         if ($quota eq '') {
 6877:             $quota = $defquota;
 6878:             $quotatype = 'default';
 6879:         } else {
 6880:             $quotatype = 'custom';
 6881:         }
 6882:     }
 6883:     if (wantarray) {
 6884:         return ($quota,$quotatype,$settingstatus,$defquota);
 6885:     } else {
 6886:         return $quota;
 6887:     }
 6888: }
 6889: 
 6890: ###############################################
 6891: 
 6892: =pod
 6893: 
 6894: =item * &default_quota()
 6895: 
 6896: Retrieves default quota assigned for storage of user portfolio files,
 6897: given an (optional) user's institutional status.
 6898: 
 6899: Incoming parameters:
 6900: 1. domain
 6901: 2. (Optional) institutional status(es).  This is a : separated list of 
 6902:    status types (e.g., faculty, staff, student etc.)
 6903:    which apply to the user for whom the default is being retrieved.
 6904:    If the institutional status string in undefined, the domain
 6905:    default quota will be returned. 
 6906: 
 6907: Returns:
 6908: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6909: 2. (Optional) institutional type which determined the value of the
 6910:    default quota.
 6911: 
 6912: If a value has been stored in the domain's configuration db,
 6913: it will return that, otherwise it returns 20 (for backwards 
 6914: compatibility with domains which have not set up a configuration
 6915: db file; the original statically defined portfolio quota was 20 Mb). 
 6916: 
 6917: If the user's status includes multiple types (e.g., staff and student),
 6918: the largest default quota which applies to the user determines the
 6919: default quota returned.
 6920: 
 6921: =cut
 6922: 
 6923: ###############################################
 6924: 
 6925: 
 6926: sub default_quota {
 6927:     my ($udom,$inststatus) = @_;
 6928:     my ($defquota,$settingstatus);
 6929:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6930:                                             ['quotas'],$udom);
 6931:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6932:         if ($inststatus ne '') {
 6933:             my @statuses = split(/:/,$inststatus);
 6934:             foreach my $item (@statuses) {
 6935:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6936:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6937:                         if ($defquota eq '') {
 6938:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6939:                             $settingstatus = $item;
 6940:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6941:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6942:                             $settingstatus = $item;
 6943:                         }
 6944:                     }
 6945:                 } else {
 6946:                     if ($quotahash{'quotas'}{$item} ne '') {
 6947:                         if ($defquota eq '') {
 6948:                             $defquota = $quotahash{'quotas'}{$item};
 6949:                             $settingstatus = $item;
 6950:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6951:                             $defquota = $quotahash{'quotas'}{$item};
 6952:                             $settingstatus = $item;
 6953:                         }
 6954:                     }
 6955:                 }
 6956:             }
 6957:         }
 6958:         if ($defquota eq '') {
 6959:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6960:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6961:             } else {
 6962:                 $defquota = $quotahash{'quotas'}{'default'};
 6963:             }
 6964:             $settingstatus = 'default';
 6965:         }
 6966:     } else {
 6967:         $settingstatus = 'default';
 6968:         $defquota = 20;
 6969:     }
 6970:     if (wantarray) {
 6971:         return ($defquota,$settingstatus);
 6972:     } else {
 6973:         return $defquota;
 6974:     }
 6975: }
 6976: 
 6977: sub get_secgrprole_info {
 6978:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6979:     my %sections_count = &get_sections($cdom,$cnum);
 6980:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6981:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6982:     my @groups = sort(keys(%curr_groups));
 6983:     my $allroles = [];
 6984:     my $rolehash;
 6985:     my $accesshash = {
 6986:                      active => 'Currently has access',
 6987:                      future => 'Will have future access',
 6988:                      previous => 'Previously had access',
 6989:                   };
 6990:     if ($needroles) {
 6991:         $rolehash = {'all' => 'all'};
 6992:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6993: 	if (&Apache::lonnet::error(%user_roles)) {
 6994: 	    undef(%user_roles);
 6995: 	}
 6996:         foreach my $item (keys(%user_roles)) {
 6997:             my ($role)=split(/\:/,$item,2);
 6998:             if ($role eq 'cr') { next; }
 6999:             if ($role =~ /^cr/) {
 7000:                 $$rolehash{$role} = (split('/',$role))[3];
 7001:             } else {
 7002:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7003:             }
 7004:         }
 7005:         foreach my $key (sort(keys(%{$rolehash}))) {
 7006:             push(@{$allroles},$key);
 7007:         }
 7008:         push (@{$allroles},'st');
 7009:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7010:     }
 7011:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7012: }
 7013: 
 7014: sub user_picker {
 7015:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7016:     my $currdom = $dom;
 7017:     my %curr_selected = (
 7018:                         srchin => 'dom',
 7019:                         srchby => 'lastname',
 7020:                       );
 7021:     my $srchterm;
 7022:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7023:         if ($srch->{'srchby'} ne '') {
 7024:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7025:         }
 7026:         if ($srch->{'srchin'} ne '') {
 7027:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7028:         }
 7029:         if ($srch->{'srchtype'} ne '') {
 7030:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7031:         }
 7032:         if ($srch->{'srchdomain'} ne '') {
 7033:             $currdom = $srch->{'srchdomain'};
 7034:         }
 7035:         $srchterm = $srch->{'srchterm'};
 7036:     }
 7037:     my %lt=&Apache::lonlocal::texthash(
 7038:                     'usr'       => 'Search criteria',
 7039:                     'doma'      => 'Domain/institution to search',
 7040:                     'uname'     => 'username',
 7041:                     'lastname'  => 'last name',
 7042:                     'lastfirst' => 'last name, first name',
 7043:                     'crs'       => 'in this course',
 7044:                     'dom'       => 'in selected LON-CAPA domain', 
 7045:                     'alc'       => 'all LON-CAPA',
 7046:                     'instd'     => 'in institutional directory for selected domain',
 7047:                     'exact'     => 'is',
 7048:                     'contains'  => 'contains',
 7049:                     'begins'    => 'begins with',
 7050:                     'youm'      => "You must include some text to search for.",
 7051:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7052:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7053:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7054:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7055:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7056:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7057:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7058:                                        );
 7059:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7060:     my $srchinsel = ' <select name="srchin">';
 7061: 
 7062:     my @srchins = ('crs','dom','alc','instd');
 7063: 
 7064:     foreach my $option (@srchins) {
 7065:         # FIXME 'alc' option unavailable until 
 7066:         #       loncreateuser::print_user_query_page()
 7067:         #       has been completed.
 7068:         next if ($option eq 'alc');
 7069:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7070:         if ($curr_selected{'srchin'} eq $option) {
 7071:             $srchinsel .= ' 
 7072:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7073:         } else {
 7074:             $srchinsel .= '
 7075:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7076:         }
 7077:     }
 7078:     $srchinsel .= "\n  </select>\n";
 7079: 
 7080:     my $srchbysel =  ' <select name="srchby">';
 7081:     foreach my $option ('lastname','lastfirst','uname') {
 7082:         if ($curr_selected{'srchby'} eq $option) {
 7083:             $srchbysel .= '
 7084:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7085:         } else {
 7086:             $srchbysel .= '
 7087:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7088:          }
 7089:     }
 7090:     $srchbysel .= "\n  </select>\n";
 7091: 
 7092:     my $srchtypesel = ' <select name="srchtype">';
 7093:     foreach my $option ('begins','contains','exact') {
 7094:         if ($curr_selected{'srchtype'} eq $option) {
 7095:             $srchtypesel .= '
 7096:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7097:         } else {
 7098:             $srchtypesel .= '
 7099:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7100:         }
 7101:     }
 7102:     $srchtypesel .= "\n  </select>\n";
 7103: 
 7104:     my ($newuserscript,$new_user_create);
 7105: 
 7106:     if ($forcenewuser) {
 7107:         if (ref($srch) eq 'HASH') {
 7108:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7109:                 if ($cancreate) {
 7110:                     $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>';
 7111:                 } else {
 7112:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7113:                     my %usertypetext = (
 7114:                         official   => 'institutional',
 7115:                         unofficial => 'non-institutional',
 7116:                     );
 7117:                     $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 />';
 7118:                 }
 7119:             }
 7120:         }
 7121: 
 7122:         $newuserscript = <<"ENDSCRIPT";
 7123: 
 7124: function setSearch(createnew,callingForm) {
 7125:     if (createnew == 1) {
 7126:         for (var i=0; i<callingForm.srchby.length; i++) {
 7127:             if (callingForm.srchby.options[i].value == 'uname') {
 7128:                 callingForm.srchby.selectedIndex = i;
 7129:             }
 7130:         }
 7131:         for (var i=0; i<callingForm.srchin.length; i++) {
 7132:             if ( callingForm.srchin.options[i].value == 'dom') {
 7133: 		callingForm.srchin.selectedIndex = i;
 7134:             }
 7135:         }
 7136:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7137:             if (callingForm.srchtype.options[i].value == 'exact') {
 7138:                 callingForm.srchtype.selectedIndex = i;
 7139:             }
 7140:         }
 7141:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7142:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7143:                 callingForm.srchdomain.selectedIndex = i;
 7144:             }
 7145:         }
 7146:     }
 7147: }
 7148: ENDSCRIPT
 7149: 
 7150:     }
 7151: 
 7152:     my $output = <<"END_BLOCK";
 7153: <script type="text/javascript">
 7154: function validateEntry(callingForm) {
 7155: 
 7156:     var checkok = 1;
 7157:     var srchin;
 7158:     for (var i=0; i<callingForm.srchin.length; i++) {
 7159: 	if ( callingForm.srchin[i].checked ) {
 7160: 	    srchin = callingForm.srchin[i].value;
 7161: 	}
 7162:     }
 7163: 
 7164:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7165:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7166:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7167:     var srchterm =  callingForm.srchterm.value;
 7168:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7169:     var msg = "";
 7170: 
 7171:     if (srchterm == "") {
 7172:         checkok = 0;
 7173:         msg += "$lt{'youm'}\\n";
 7174:     }
 7175: 
 7176:     if (srchtype== 'begins') {
 7177:         if (srchterm.length < 2) {
 7178:             checkok = 0;
 7179:             msg += "$lt{'thte'}\\n";
 7180:         }
 7181:     }
 7182: 
 7183:     if (srchtype== 'contains') {
 7184:         if (srchterm.length < 3) {
 7185:             checkok = 0;
 7186:             msg += "$lt{'thet'}\\n";
 7187:         }
 7188:     }
 7189:     if (srchin == 'instd') {
 7190:         if (srchdomain == '') {
 7191:             checkok = 0;
 7192:             msg += "$lt{'yomc'}\\n";
 7193:         }
 7194:     }
 7195:     if (srchin == 'dom') {
 7196:         if (srchdomain == '') {
 7197:             checkok = 0;
 7198:             msg += "$lt{'ymcd'}\\n";
 7199:         }
 7200:     }
 7201:     if (srchby == 'lastfirst') {
 7202:         if (srchterm.indexOf(",") == -1) {
 7203:             checkok = 0;
 7204:             msg += "$lt{'whus'}\\n";
 7205:         }
 7206:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7207:             checkok = 0;
 7208:             msg += "$lt{'whse'}\\n";
 7209:         }
 7210:     }
 7211:     if (checkok == 0) {
 7212:         alert("$lt{'thfo'}\\n"+msg);
 7213:         return;
 7214:     }
 7215:     if (checkok == 1) {
 7216:         callingForm.submit();
 7217:     }
 7218: }
 7219: 
 7220: $newuserscript
 7221: 
 7222: </script>
 7223: 
 7224: $new_user_create
 7225: 
 7226: <table>
 7227:  <tr>
 7228:   <td>$lt{'doma'}:</td>
 7229:   <td>$domform</td>
 7230:   </td>
 7231:  </tr>
 7232:  <tr>
 7233:   <td>$lt{'usr'}:</td>
 7234:   <td>$srchbysel
 7235:       $srchtypesel 
 7236:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7237:       $srchinsel 
 7238:   </td>
 7239:  </tr>
 7240: </table>
 7241: <br />
 7242: END_BLOCK
 7243: 
 7244:     return $output;
 7245: }
 7246: 
 7247: sub user_rule_check {
 7248:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7249:     my $response;
 7250:     if (ref($usershash) eq 'HASH') {
 7251:         foreach my $user (keys(%{$usershash})) {
 7252:             my ($uname,$udom) = split(/:/,$user);
 7253:             next if ($udom eq '' || $uname eq '');
 7254:             my ($id,$newuser);
 7255:             if (ref($usershash->{$user}) eq 'HASH') {
 7256:                 $newuser = $usershash->{$user}->{'newuser'};
 7257:                 $id = $usershash->{$user}->{'id'};
 7258:             }
 7259:             my $inst_response;
 7260:             if (ref($checks) eq 'HASH') {
 7261:                 if (defined($checks->{'username'})) {
 7262:                     ($inst_response,%{$inst_results->{$user}}) = 
 7263:                         &Apache::lonnet::get_instuser($udom,$uname);
 7264:                 } elsif (defined($checks->{'id'})) {
 7265:                     ($inst_response,%{$inst_results->{$user}}) =
 7266:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7267:                 }
 7268:             } else {
 7269:                 ($inst_response,%{$inst_results->{$user}}) =
 7270:                     &Apache::lonnet::get_instuser($udom,$uname);
 7271:                 return;
 7272:             }
 7273:             if (!$got_rules->{$udom}) {
 7274:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7275:                                                   ['usercreation'],$udom);
 7276:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7277:                     foreach my $item ('username','id') {
 7278:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7279:                             $$curr_rules{$udom}{$item} = 
 7280:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7281:                         }
 7282:                     }
 7283:                 }
 7284:                 $got_rules->{$udom} = 1;  
 7285:             }
 7286:             foreach my $item (keys(%{$checks})) {
 7287:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7288:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7289:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7290:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7291:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7292:                                 if ($rule_check{$rule}) {
 7293:                                     $$rulematch{$user}{$item} = $rule;
 7294:                                     if ($inst_response eq 'ok') {
 7295:                                         if (ref($inst_results) eq 'HASH') {
 7296:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7297:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7298:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7299:                                                 }
 7300:                                             }
 7301:                                         }
 7302:                                     }
 7303:                                     last;
 7304:                                 }
 7305:                             }
 7306:                         }
 7307:                     }
 7308:                 }
 7309:             }
 7310:         }
 7311:     }
 7312:     return;
 7313: }
 7314: 
 7315: sub user_rule_formats {
 7316:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7317:     my %text = ( 
 7318:                  'username' => 'Usernames',
 7319:                  'id'       => 'IDs',
 7320:                );
 7321:     my $output;
 7322:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7323:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7324:         if (@{$ruleorder} > 0) {
 7325:             $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>';
 7326:             foreach my $rule (@{$ruleorder}) {
 7327:                 if (ref($curr_rules) eq 'ARRAY') {
 7328:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7329:                         if (ref($rules->{$rule}) eq 'HASH') {
 7330:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7331:                                         $rules->{$rule}{'desc'}.'</li>';
 7332:                         }
 7333:                     }
 7334:                 }
 7335:             }
 7336:             $output .= '</ul>';
 7337:         }
 7338:     }
 7339:     return $output;
 7340: }
 7341: 
 7342: sub instrule_disallow_msg {
 7343:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7344:     my $response;
 7345:     my %text = (
 7346:                   item   => 'username',
 7347:                   items  => 'usernames',
 7348:                   match  => 'matches',
 7349:                   do     => 'does',
 7350:                   action => 'a username',
 7351:                   one    => 'one',
 7352:                );
 7353:     if ($count > 1) {
 7354:         $text{'item'} = 'usernames';
 7355:         $text{'match'} ='match';
 7356:         $text{'do'} = 'do';
 7357:         $text{'action'} = 'usernames',
 7358:         $text{'one'} = 'ones';
 7359:     }
 7360:     if ($checkitem eq 'id') {
 7361:         $text{'items'} = 'IDs';
 7362:         $text{'item'} = 'ID';
 7363:         $text{'action'} = 'an ID';
 7364:         if ($count > 1) {
 7365:             $text{'item'} = 'IDs';
 7366:             $text{'action'} = 'IDs';
 7367:         }
 7368:     }
 7369:     $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 />';
 7370:     if ($mode eq 'upload') {
 7371:         if ($checkitem eq 'username') {
 7372:             $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'}.");
 7373:         } elsif ($checkitem eq 'id') {
 7374:             $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.");
 7375:         }
 7376:     } elsif ($mode eq 'selfcreate') {
 7377:         if ($checkitem eq 'id') {
 7378:             $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.");
 7379:         }
 7380:     } else {
 7381:         if ($checkitem eq 'username') {
 7382:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7383:         } elsif ($checkitem eq 'id') {
 7384:             $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.");
 7385:         }
 7386:     }
 7387:     return $response;
 7388: }
 7389: 
 7390: sub personal_data_fieldtitles {
 7391:     my %fieldtitles = &Apache::lonlocal::texthash (
 7392:                         id => 'Student/Employee ID',
 7393:                         permanentemail => 'E-mail address',
 7394:                         lastname => 'Last Name',
 7395:                         firstname => 'First Name',
 7396:                         middlename => 'Middle Name',
 7397:                         generation => 'Generation',
 7398:                         gen => 'Generation',
 7399:                    );
 7400:     return %fieldtitles;
 7401: }
 7402: 
 7403: sub sorted_inst_types {
 7404:     my ($dom) = @_;
 7405:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7406:     my $othertitle = &mt('All users');
 7407:     if ($env{'request.course.id'}) {
 7408:         $othertitle  = &mt('Any users');
 7409:     }
 7410:     my @types;
 7411:     if (ref($order) eq 'ARRAY') {
 7412:         @types = @{$order};
 7413:     }
 7414:     if (@types == 0) {
 7415:         if (ref($usertypes) eq 'HASH') {
 7416:             @types = sort(keys(%{$usertypes}));
 7417:         }
 7418:     }
 7419:     if (keys(%{$usertypes}) > 0) {
 7420:         $othertitle = &mt('Other users');
 7421:     }
 7422:     return ($othertitle,$usertypes,\@types);
 7423: }
 7424: 
 7425: sub get_institutional_codes {
 7426:     my ($settings,$allcourses,$LC_code) = @_;
 7427: # Get complete list of course sections to update
 7428:     my @currsections = ();
 7429:     my @currxlists = ();
 7430:     my $coursecode = $$settings{'internal.coursecode'};
 7431: 
 7432:     if ($$settings{'internal.sectionnums'} ne '') {
 7433:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7434:     }
 7435: 
 7436:     if ($$settings{'internal.crosslistings'} ne '') {
 7437:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7438:     }
 7439: 
 7440:     if (@currxlists > 0) {
 7441:         foreach (@currxlists) {
 7442:             if (m/^([^:]+):(\w*)$/) {
 7443:                 unless (grep/^$1$/,@{$allcourses}) {
 7444:                     push @{$allcourses},$1;
 7445:                     $$LC_code{$1} = $2;
 7446:                 }
 7447:             }
 7448:         }
 7449:     }
 7450:  
 7451:     if (@currsections > 0) {
 7452:         foreach (@currsections) {
 7453:             if (m/^(\w+):(\w*)$/) {
 7454:                 my $sec = $coursecode.$1;
 7455:                 my $lc_sec = $2;
 7456:                 unless (grep/^$sec$/,@{$allcourses}) {
 7457:                     push @{$allcourses},$sec;
 7458:                     $$LC_code{$sec} = $lc_sec;
 7459:                 }
 7460:             }
 7461:         }
 7462:     }
 7463:     return;
 7464: }
 7465: 
 7466: =pod
 7467: 
 7468: =back
 7469: 
 7470: =head1 HTTP Helpers
 7471: 
 7472: =over 4
 7473: 
 7474: =item * &get_unprocessed_cgi($query,$possible_names)
 7475: 
 7476: Modify the %env hash to contain unprocessed CGI form parameters held in
 7477: $query.  The parameters listed in $possible_names (an array reference),
 7478: will be set in $env{'form.name'} if they do not already exist.
 7479: 
 7480: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7481: $possible_names is an ref to an array of form element names.  As an example:
 7482: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7483: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7484: 
 7485: =cut
 7486: 
 7487: sub get_unprocessed_cgi {
 7488:   my ($query,$possible_names)= @_;
 7489:   # $Apache::lonxml::debug=1;
 7490:   foreach my $pair (split(/&/,$query)) {
 7491:     my ($name, $value) = split(/=/,$pair);
 7492:     $name = &unescape($name);
 7493:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7494:       $value =~ tr/+/ /;
 7495:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7496:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7497:     }
 7498:   }
 7499: }
 7500: 
 7501: =pod
 7502: 
 7503: =item * &cacheheader() 
 7504: 
 7505: returns cache-controlling header code
 7506: 
 7507: =cut
 7508: 
 7509: sub cacheheader {
 7510:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7511:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7512:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7513:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7514:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7515:     return $output;
 7516: }
 7517: 
 7518: =pod
 7519: 
 7520: =item * &no_cache($r) 
 7521: 
 7522: specifies header code to not have cache
 7523: 
 7524: =cut
 7525: 
 7526: sub no_cache {
 7527:     my ($r) = @_;
 7528:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7529: 	$env{'request.method'} ne 'GET') { return ''; }
 7530:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7531:     $r->no_cache(1);
 7532:     $r->header_out("Expires" => $date);
 7533:     $r->header_out("Pragma" => "no-cache");
 7534: }
 7535: 
 7536: sub content_type {
 7537:     my ($r,$type,$charset) = @_;
 7538:     if ($r) {
 7539: 	#  Note that printout.pl calls this with undef for $r.
 7540: 	&no_cache($r);
 7541:     }
 7542:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7543:     unless ($charset) {
 7544: 	$charset=&Apache::lonlocal::current_encoding;
 7545:     }
 7546:     if ($charset) { $type.='; charset='.$charset; }
 7547:     if ($r) {
 7548: 	$r->content_type($type);
 7549:     } else {
 7550: 	print("Content-type: $type\n\n");
 7551:     }
 7552: }
 7553: 
 7554: =pod
 7555: 
 7556: =item * &add_to_env($name,$value) 
 7557: 
 7558: adds $name to the %env hash with value
 7559: $value, if $name already exists, the entry is converted to an array
 7560: reference and $value is added to the array.
 7561: 
 7562: =cut
 7563: 
 7564: sub add_to_env {
 7565:   my ($name,$value)=@_;
 7566:   if (defined($env{$name})) {
 7567:     if (ref($env{$name})) {
 7568:       #already have multiple values
 7569:       push(@{ $env{$name} },$value);
 7570:     } else {
 7571:       #first time seeing multiple values, convert hash entry to an arrayref
 7572:       my $first=$env{$name};
 7573:       undef($env{$name});
 7574:       push(@{ $env{$name} },$first,$value);
 7575:     }
 7576:   } else {
 7577:     $env{$name}=$value;
 7578:   }
 7579: }
 7580: 
 7581: =pod
 7582: 
 7583: =item * &get_env_multiple($name) 
 7584: 
 7585: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7586: values may be defined and end up as an array ref.
 7587: 
 7588: returns an array of values
 7589: 
 7590: =cut
 7591: 
 7592: sub get_env_multiple {
 7593:     my ($name) = @_;
 7594:     my @values;
 7595:     if (defined($env{$name})) {
 7596:         # exists is it an array
 7597:         if (ref($env{$name})) {
 7598:             @values=@{ $env{$name} };
 7599:         } else {
 7600:             $values[0]=$env{$name};
 7601:         }
 7602:     }
 7603:     return(@values);
 7604: }
 7605: 
 7606: sub ask_for_embedded_content {
 7607:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7608:     my $upload_output = '
 7609:    <form name="upload_embedded" action="'.$actionurl.'"
 7610:                   method="post" enctype="multipart/form-data">';
 7611:     $upload_output .= $state;
 7612:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7613: 
 7614:     my $num = 0;
 7615:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7616:         $upload_output .= &start_data_table_row().
 7617:             '<td>'.$embed_file.'</td><td>';
 7618:         if ($args->{'ignore_remote_references'}
 7619:             && $embed_file =~ m{^\w+://}) {
 7620:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7621:         } elsif ($args->{'error_on_invalid_names'}
 7622:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7623: 
 7624:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7625: 
 7626:         } else {
 7627:             $upload_output .='
 7628:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7629:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7630:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7631:             $upload_output .=
 7632:                 "\n\t\t".
 7633:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7634:                 $attrib.'" />';
 7635:             if (exists($$codebase{$embed_file})) {
 7636:                 $upload_output .=
 7637:                     "\n\t\t".
 7638:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7639:                     &escape($$codebase{$embed_file}).'" />';
 7640:             }
 7641:         }
 7642:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7643:         $num++;
 7644:     }
 7645:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7646:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7647:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7648:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7649:    </form>';
 7650:     return $upload_output;
 7651: }
 7652: 
 7653: sub upload_embedded {
 7654:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7655:         $current_disk_usage) = @_;
 7656:     my $output;
 7657:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7658:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7659:         my $orig_uploaded_filename =
 7660:             $env{'form.embedded_item_'.$i.'.filename'};
 7661: 
 7662:         $env{'form.embedded_orig_'.$i} =
 7663:             &unescape($env{'form.embedded_orig_'.$i});
 7664:         my ($path,$fname) =
 7665:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7666:         # no path, whole string is fname
 7667:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7668: 
 7669:         $path = $env{'form.currentpath'}.$path;
 7670:         $fname = &Apache::lonnet::clean_filename($fname);
 7671:         # See if there is anything left
 7672:         next if ($fname eq '');
 7673: 
 7674:         # Check if file already exists as a file or directory.
 7675:         my ($state,$msg);
 7676:         if ($context eq 'portfolio') {
 7677:             my $port_path = $dirpath;
 7678:             if ($group ne '') {
 7679:                 $port_path = "groups/$group/$port_path";
 7680:             }
 7681:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7682:                                               $dir_root,$port_path,$disk_quota,
 7683:                                               $current_disk_usage,$uname,$udom);
 7684:             if ($state eq 'will_exceed_quota'
 7685:                 || $state eq 'file_locked'
 7686:                 || $state eq 'file_exists' ) {
 7687:                 $output .= $msg;
 7688:                 next;
 7689:             }
 7690:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7691:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7692:             if ($state eq 'exists') {
 7693:                 $output .= $msg;
 7694:                 next;
 7695:             }
 7696:         }
 7697:         # Check if extension is valid
 7698:         if (($fname =~ /\.(\w+)$/) &&
 7699:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7700:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7701:             next;
 7702:         } elsif (($fname =~ /\.(\w+)$/) &&
 7703:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7704:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7705:             next;
 7706:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7707:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7708:             next;
 7709:         }
 7710: 
 7711:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7712:         if ($context eq 'portfolio') {
 7713:             my $result=
 7714:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7715:                                                 $dirpath.$path);
 7716:             if ($result !~ m|^/uploaded/|) {
 7717:                 $output .= '<span class="LC_error">'
 7718:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7719:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7720:                       .'</span><br />';
 7721:                 next;
 7722:             } else {
 7723:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7724:                            $path.$fname.'</span>').'</p>';     
 7725:             }
 7726:         } else {
 7727: # Save the file
 7728:             my $target = $env{'form.embedded_item_'.$i};
 7729:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7730:             my $dest = $fullpath.$fname;
 7731:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7732:             my @parts=split(/\//,$fullpath);
 7733:             my $count;
 7734:             my $filepath = $dir_root;
 7735:             for ($count=4;$count<=$#parts;$count++) {
 7736:                 $filepath .= "/$parts[$count]";
 7737:                 if ((-e $filepath)!=1) {
 7738:                     mkdir($filepath,0770);
 7739:                 }
 7740:             }
 7741:             my $fh;
 7742:             if (!open($fh,'>'.$dest)) {
 7743:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7744:                 $output .= '<span class="LC_error">'.
 7745:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7746:                            '</span><br />';
 7747:             } else {
 7748:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7749:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7750:                     $output .= '<span class="LC_error">'.
 7751:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7752:                               '</span><br />';
 7753:                 } else {
 7754:                     if ($context eq 'testbank') {
 7755:                         $output .= &mt('Embedded file uploaded successfully:').
 7756:                                    '&nbsp;<a href="'.$url.'">'.
 7757:                                    $orig_uploaded_filename.'</a><br />';
 7758:                     } else {
 7759:                         $output .= '<span class=\"LC_fontsize_large\">'.
 7760:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7761:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 7762:                     }
 7763:                 }
 7764:                 close($fh);
 7765:             }
 7766:         }
 7767:     }
 7768:     return $output;
 7769: }
 7770: 
 7771: sub check_for_existing {
 7772:     my ($path,$fname,$element) = @_;
 7773:     my ($state,$msg);
 7774:     if (-d $path.'/'.$fname) {
 7775:         $state = 'exists';
 7776:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7777:     } elsif (-e $path.'/'.$fname) {
 7778:         $state = 'exists';
 7779:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7780:     }
 7781:     if ($state eq 'exists') {
 7782:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7783:     }
 7784:     return ($state,$msg);
 7785: }
 7786: 
 7787: sub check_for_upload {
 7788:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7789:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7790:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7791:     my $getpropath = 1;
 7792:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7793:                                             $getpropath);
 7794:     my $found_file = 0;
 7795:     my $locked_file = 0;
 7796:     foreach my $line (@dir_list) {
 7797:         my ($file_name)=split(/\&/,$line,2);
 7798:         if ($file_name eq $fname){
 7799:             $file_name = $path.$file_name;
 7800:             if ($group ne '') {
 7801:                 $file_name = $group.$file_name;
 7802:             }
 7803:             $found_file = 1;
 7804:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7805:                 $locked_file = 1;
 7806:             }
 7807:         }
 7808:     }
 7809:     if (($current_disk_usage + $filesize) > $disk_quota){
 7810:         my $msg = '<span class="LC_error">'.
 7811:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7812:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7813:         return ('will_exceed_quota',$msg);
 7814:     } elsif ($found_file) {
 7815:         if ($locked_file) {
 7816:             my $msg = '<span class="LC_error">';
 7817:             $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>');
 7818:             $msg .= '</span><br />';
 7819:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7820:             return ('file_locked',$msg);
 7821:         } else {
 7822:             my $msg = '<span class="LC_error">';
 7823:             $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'});
 7824:             $msg .= '</span>';
 7825:             $msg .= '<br />';
 7826:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7827:             return ('file_exists',$msg);
 7828:         }
 7829:     }
 7830: }
 7831: 
 7832: 
 7833: =pod
 7834: 
 7835: =back
 7836: 
 7837: =head1 CSV Upload/Handling functions
 7838: 
 7839: =over 4
 7840: 
 7841: =item * &upfile_store($r)
 7842: 
 7843: Store uploaded file, $r should be the HTTP Request object,
 7844: needs $env{'form.upfile'}
 7845: returns $datatoken to be put into hidden field
 7846: 
 7847: =cut
 7848: 
 7849: sub upfile_store {
 7850:     my $r=shift;
 7851:     $env{'form.upfile'}=~s/\r/\n/gs;
 7852:     $env{'form.upfile'}=~s/\f/\n/gs;
 7853:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7854:     $env{'form.upfile'}=~s/\n+$//gs;
 7855: 
 7856:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7857: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7858:     {
 7859:         my $datafile = $r->dir_config('lonDaemons').
 7860:                            '/tmp/'.$datatoken.'.tmp';
 7861:         if ( open(my $fh,">$datafile") ) {
 7862:             print $fh $env{'form.upfile'};
 7863:             close($fh);
 7864:         }
 7865:     }
 7866:     return $datatoken;
 7867: }
 7868: 
 7869: =pod
 7870: 
 7871: =item * &load_tmp_file($r)
 7872: 
 7873: Load uploaded file from tmp, $r should be the HTTP Request object,
 7874: needs $env{'form.datatoken'},
 7875: sets $env{'form.upfile'} to the contents of the file
 7876: 
 7877: =cut
 7878: 
 7879: sub load_tmp_file {
 7880:     my $r=shift;
 7881:     my @studentdata=();
 7882:     {
 7883:         my $studentfile = $r->dir_config('lonDaemons').
 7884:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7885:         if ( open(my $fh,"<$studentfile") ) {
 7886:             @studentdata=<$fh>;
 7887:             close($fh);
 7888:         }
 7889:     }
 7890:     $env{'form.upfile'}=join('',@studentdata);
 7891: }
 7892: 
 7893: =pod
 7894: 
 7895: =item * &upfile_record_sep()
 7896: 
 7897: Separate uploaded file into records
 7898: returns array of records,
 7899: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7900: 
 7901: =cut
 7902: 
 7903: sub upfile_record_sep {
 7904:     if ($env{'form.upfiletype'} eq 'xml') {
 7905:     } else {
 7906: 	my @records;
 7907: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7908: 	    if ($line=~/^\s*$/) { next; }
 7909: 	    push(@records,$line);
 7910: 	}
 7911: 	return @records;
 7912:     }
 7913: }
 7914: 
 7915: =pod
 7916: 
 7917: =item * &record_sep($record)
 7918: 
 7919: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7920: 
 7921: =cut
 7922: 
 7923: sub takeleft {
 7924:     my $index=shift;
 7925:     return substr('0000'.$index,-4,4);
 7926: }
 7927: 
 7928: sub record_sep {
 7929:     my $record=shift;
 7930:     my %components=();
 7931:     if ($env{'form.upfiletype'} eq 'xml') {
 7932:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7933:         my $i=0;
 7934:         foreach my $field (split(/\s+/,$record)) {
 7935:             $field=~s/^(\"|\')//;
 7936:             $field=~s/(\"|\')$//;
 7937:             $components{&takeleft($i)}=$field;
 7938:             $i++;
 7939:         }
 7940:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7941:         my $i=0;
 7942:         foreach my $field (split(/\t/,$record)) {
 7943:             $field=~s/^(\"|\')//;
 7944:             $field=~s/(\"|\')$//;
 7945:             $components{&takeleft($i)}=$field;
 7946:             $i++;
 7947:         }
 7948:     } else {
 7949:         my $separator=',';
 7950:         if ($env{'form.upfiletype'} eq 'semisv') {
 7951:             $separator=';';
 7952:         }
 7953:         my $i=0;
 7954: # the character we are looking for to indicate the end of a quote or a record 
 7955:         my $looking_for=$separator;
 7956: # do not add the characters to the fields
 7957:         my $ignore=0;
 7958: # we just encountered a separator (or the beginning of the record)
 7959:         my $just_found_separator=1;
 7960: # store the field we are working on here
 7961:         my $field='';
 7962: # work our way through all characters in record
 7963:         foreach my $character ($record=~/(.)/g) {
 7964:             if ($character eq $looking_for) {
 7965:                if ($character ne $separator) {
 7966: # Found the end of a quote, again looking for separator
 7967:                   $looking_for=$separator;
 7968:                   $ignore=1;
 7969:                } else {
 7970: # Found a separator, store away what we got
 7971:                   $components{&takeleft($i)}=$field;
 7972: 	          $i++;
 7973:                   $just_found_separator=1;
 7974:                   $ignore=0;
 7975:                   $field='';
 7976:                }
 7977:                next;
 7978:             }
 7979: # single or double quotation marks after a separator indicate beginning of a quote
 7980: # we are now looking for the end of the quote and need to ignore separators
 7981:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7982:                $looking_for=$character;
 7983:                next;
 7984:             }
 7985: # ignore would be true after we reached the end of a quote
 7986:             if ($ignore) { next; }
 7987:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7988:             $field.=$character;
 7989:             $just_found_separator=0; 
 7990:         }
 7991: # catch the very last entry, since we never encountered the separator
 7992:         $components{&takeleft($i)}=$field;
 7993:     }
 7994:     return %components;
 7995: }
 7996: 
 7997: ######################################################
 7998: ######################################################
 7999: 
 8000: =pod
 8001: 
 8002: =item * &upfile_select_html()
 8003: 
 8004: Return HTML code to select a file from the users machine and specify 
 8005: the file type.
 8006: 
 8007: =cut
 8008: 
 8009: ######################################################
 8010: ######################################################
 8011: sub upfile_select_html {
 8012:     my %Types = (
 8013:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8014:                  semisv => &mt('Semicolon separated values'),
 8015:                  space => &mt('Space separated'),
 8016:                  tab   => &mt('Tabulator separated'),
 8017: #                 xml   => &mt('HTML/XML'),
 8018:                  );
 8019:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8020:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8021:     foreach my $type (sort(keys(%Types))) {
 8022:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8023:     }
 8024:     $Str .= "</select>\n";
 8025:     return $Str;
 8026: }
 8027: 
 8028: sub get_samples {
 8029:     my ($records,$toget) = @_;
 8030:     my @samples=({});
 8031:     my $got=0;
 8032:     foreach my $rec (@$records) {
 8033: 	my %temp = &record_sep($rec);
 8034: 	if (! grep(/\S/, values(%temp))) { next; }
 8035: 	if (%temp) {
 8036: 	    $samples[$got]=\%temp;
 8037: 	    $got++;
 8038: 	    if ($got == $toget) { last; }
 8039: 	}
 8040:     }
 8041:     return \@samples;
 8042: }
 8043: 
 8044: ######################################################
 8045: ######################################################
 8046: 
 8047: =pod
 8048: 
 8049: =item * &csv_print_samples($r,$records)
 8050: 
 8051: Prints a table of sample values from each column uploaded $r is an
 8052: Apache Request ref, $records is an arrayref from
 8053: &Apache::loncommon::upfile_record_sep
 8054: 
 8055: =cut
 8056: 
 8057: ######################################################
 8058: ######################################################
 8059: sub csv_print_samples {
 8060:     my ($r,$records) = @_;
 8061:     my $samples = &get_samples($records,5);
 8062: 
 8063:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8064:               &start_data_table_header_row());
 8065:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8066:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8067:     $r->print(&end_data_table_header_row());
 8068:     foreach my $hash (@$samples) {
 8069: 	$r->print(&start_data_table_row());
 8070: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8071: 	    $r->print('<td>');
 8072: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8073: 	    $r->print('</td>');
 8074: 	}
 8075: 	$r->print(&end_data_table_row());
 8076:     }
 8077:     $r->print(&end_data_table().'<br />'."\n");
 8078: }
 8079: 
 8080: ######################################################
 8081: ######################################################
 8082: 
 8083: =pod
 8084: 
 8085: =item * &csv_print_select_table($r,$records,$d)
 8086: 
 8087: Prints a table to create associations between values and table columns.
 8088: 
 8089: $r is an Apache Request ref,
 8090: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8091: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8092: 
 8093: =cut
 8094: 
 8095: ######################################################
 8096: ######################################################
 8097: sub csv_print_select_table {
 8098:     my ($r,$records,$d) = @_;
 8099:     my $i=0;
 8100:     my $samples = &get_samples($records,1);
 8101:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8102: 	      &start_data_table().&start_data_table_header_row().
 8103:               '<th>'.&mt('Attribute').'</th>'.
 8104:               '<th>'.&mt('Column').'</th>'.
 8105:               &end_data_table_header_row()."\n");
 8106:     foreach my $array_ref (@$d) {
 8107: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8108: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8109: 
 8110: 	$r->print('<td><select name=f'.$i.
 8111: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8112: 	$r->print('<option value="none"></option>');
 8113: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8114: 	    $r->print('<option value="'.$sample.'"'.
 8115:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8116:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8117: 	}
 8118: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8119: 	$i++;
 8120:     }
 8121:     $r->print(&end_data_table());
 8122:     $i--;
 8123:     return $i;
 8124: }
 8125: 
 8126: ######################################################
 8127: ######################################################
 8128: 
 8129: =pod
 8130: 
 8131: =item * &csv_samples_select_table($r,$records,$d)
 8132: 
 8133: Prints a table of sample values from the upload and can make associate samples to internal names.
 8134: 
 8135: $r is an Apache Request ref,
 8136: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8137: $d is an array of 2 element arrays (internal name, displayed name)
 8138: 
 8139: =cut
 8140: 
 8141: ######################################################
 8142: ######################################################
 8143: sub csv_samples_select_table {
 8144:     my ($r,$records,$d) = @_;
 8145:     my $i=0;
 8146:     #
 8147:     my $max_samples = 5;
 8148:     my $samples = &get_samples($records,$max_samples);
 8149:     $r->print(&start_data_table().
 8150:               &start_data_table_header_row().'<th>'.
 8151:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8152:               &end_data_table_header_row());
 8153: 
 8154:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8155: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8156: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8157: 	foreach my $option (@$d) {
 8158: 	    my ($value,$display,$defaultcol)=@{ $option };
 8159: 	    $r->print('<option value="'.$value.'"'.
 8160:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8161:                       $display.'</option>');
 8162: 	}
 8163: 	$r->print('</select></td><td>');
 8164: 	foreach my $line (0..($max_samples-1)) {
 8165: 	    if (defined($samples->[$line]{$key})) { 
 8166: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8167: 	    }
 8168: 	}
 8169: 	$r->print('</td>'.&end_data_table_row());
 8170: 	$i++;
 8171:     }
 8172:     $r->print(&end_data_table());
 8173:     $i--;
 8174:     return($i);
 8175: }
 8176: 
 8177: ######################################################
 8178: ######################################################
 8179: 
 8180: =pod
 8181: 
 8182: =item * &clean_excel_name($name)
 8183: 
 8184: Returns a replacement for $name which does not contain any illegal characters.
 8185: 
 8186: =cut
 8187: 
 8188: ######################################################
 8189: ######################################################
 8190: sub clean_excel_name {
 8191:     my ($name) = @_;
 8192:     $name =~ s/[:\*\?\/\\]//g;
 8193:     if (length($name) > 31) {
 8194:         $name = substr($name,0,31);
 8195:     }
 8196:     return $name;
 8197: }
 8198: 
 8199: =pod
 8200: 
 8201: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8202: 
 8203: Returns either 1 or undef
 8204: 
 8205: 1 if the part is to be hidden, undef if it is to be shown
 8206: 
 8207: Arguments are:
 8208: 
 8209: $id the id of the part to be checked
 8210: $symb, optional the symb of the resource to check
 8211: $udom, optional the domain of the user to check for
 8212: $uname, optional the username of the user to check for
 8213: 
 8214: =cut
 8215: 
 8216: sub check_if_partid_hidden {
 8217:     my ($id,$symb,$udom,$uname) = @_;
 8218:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8219: 					 $symb,$udom,$uname);
 8220:     my $truth=1;
 8221:     #if the string starts with !, then the list is the list to show not hide
 8222:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8223:     my @hiddenlist=split(/,/,$hiddenparts);
 8224:     foreach my $checkid (@hiddenlist) {
 8225: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8226:     }
 8227:     return !$truth;
 8228: }
 8229: 
 8230: 
 8231: ############################################################
 8232: ############################################################
 8233: 
 8234: =pod
 8235: 
 8236: =back 
 8237: 
 8238: =head1 cgi-bin script and graphing routines
 8239: 
 8240: =over 4
 8241: 
 8242: =item * &get_cgi_id()
 8243: 
 8244: Inputs: none
 8245: 
 8246: Returns an id which can be used to pass environment variables
 8247: to various cgi-bin scripts.  These environment variables will
 8248: be removed from the users environment after a given time by
 8249: the routine &Apache::lonnet::transfer_profile_to_env.
 8250: 
 8251: =cut
 8252: 
 8253: ############################################################
 8254: ############################################################
 8255: my $uniq=0;
 8256: sub get_cgi_id {
 8257:     $uniq=($uniq+1)%100000;
 8258:     return (time.'_'.$$.'_'.$uniq);
 8259: }
 8260: 
 8261: ############################################################
 8262: ############################################################
 8263: 
 8264: =pod
 8265: 
 8266: =item * &DrawBarGraph()
 8267: 
 8268: Facilitates the plotting of data in a (stacked) bar graph.
 8269: Puts plot definition data into the users environment in order for 
 8270: graph.png to plot it.  Returns an <img> tag for the plot.
 8271: The bars on the plot are labeled '1','2',...,'n'.
 8272: 
 8273: Inputs:
 8274: 
 8275: =over 4
 8276: 
 8277: =item $Title: string, the title of the plot
 8278: 
 8279: =item $xlabel: string, text describing the X-axis of the plot
 8280: 
 8281: =item $ylabel: string, text describing the Y-axis of the plot
 8282: 
 8283: =item $Max: scalar, the maximum Y value to use in the plot
 8284: If $Max is < any data point, the graph will not be rendered.
 8285: 
 8286: =item $colors: array ref holding the colors to be used for the data sets when
 8287: they are plotted.  If undefined, default values will be used.
 8288: 
 8289: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8290: 
 8291: =item @Values: An array of array references.  Each array reference holds data
 8292: to be plotted in a stacked bar chart.
 8293: 
 8294: =item If the final element of @Values is a hash reference the key/value
 8295: pairs will be added to the graph definition.
 8296: 
 8297: =back
 8298: 
 8299: Returns:
 8300: 
 8301: An <img> tag which references graph.png and the appropriate identifying
 8302: information for the plot.
 8303: 
 8304: =cut
 8305: 
 8306: ############################################################
 8307: ############################################################
 8308: sub DrawBarGraph {
 8309:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8310:     #
 8311:     if (! defined($colors)) {
 8312:         $colors = ['#33ff00', 
 8313:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8314:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8315:                   ]; 
 8316:     }
 8317:     my $extra_settings = {};
 8318:     if (ref($Values[-1]) eq 'HASH') {
 8319:         $extra_settings = pop(@Values);
 8320:     }
 8321:     #
 8322:     my $identifier = &get_cgi_id();
 8323:     my $id = 'cgi.'.$identifier;        
 8324:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8325:         return '';
 8326:     }
 8327:     #
 8328:     my @Labels;
 8329:     if (defined($labels)) {
 8330:         @Labels = @$labels;
 8331:     } else {
 8332:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8333:             push (@Labels,$i+1);
 8334:         }
 8335:     }
 8336:     #
 8337:     my $NumBars = scalar(@{$Values[0]});
 8338:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8339:     my %ValuesHash;
 8340:     my $NumSets=1;
 8341:     foreach my $array (@Values) {
 8342:         next if (! ref($array));
 8343:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8344:             join(',',@$array);
 8345:     }
 8346:     #
 8347:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8348:     if ($NumBars < 3) {
 8349:         $width = 120+$NumBars*32;
 8350:         $xskip = 1;
 8351:         $bar_width = 30;
 8352:     } elsif ($NumBars < 5) {
 8353:         $width = 120+$NumBars*20;
 8354:         $xskip = 1;
 8355:         $bar_width = 20;
 8356:     } elsif ($NumBars < 10) {
 8357:         $width = 120+$NumBars*15;
 8358:         $xskip = 1;
 8359:         $bar_width = 15;
 8360:     } elsif ($NumBars <= 25) {
 8361:         $width = 120+$NumBars*11;
 8362:         $xskip = 5;
 8363:         $bar_width = 8;
 8364:     } elsif ($NumBars <= 50) {
 8365:         $width = 120+$NumBars*8;
 8366:         $xskip = 5;
 8367:         $bar_width = 4;
 8368:     } else {
 8369:         $width = 120+$NumBars*8;
 8370:         $xskip = 5;
 8371:         $bar_width = 4;
 8372:     }
 8373:     #
 8374:     $Max = 1 if ($Max < 1);
 8375:     if ( int($Max) < $Max ) {
 8376:         $Max++;
 8377:         $Max = int($Max);
 8378:     }
 8379:     $Title  = '' if (! defined($Title));
 8380:     $xlabel = '' if (! defined($xlabel));
 8381:     $ylabel = '' if (! defined($ylabel));
 8382:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8383:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8384:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8385:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8386:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8387:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8388:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8389:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8390:     $ValuesHash{$id.'.height'}   = $height;
 8391:     $ValuesHash{$id.'.width'}    = $width;
 8392:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8393:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8394:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8395:     #
 8396:     # Deal with other parameters
 8397:     while (my ($key,$value) = each(%$extra_settings)) {
 8398:         $ValuesHash{$id.'.'.$key} = $value;
 8399:     }
 8400:     #
 8401:     &Apache::lonnet::appenv(\%ValuesHash);
 8402:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8403: }
 8404: 
 8405: ############################################################
 8406: ############################################################
 8407: 
 8408: =pod
 8409: 
 8410: =item * &DrawXYGraph()
 8411: 
 8412: Facilitates the plotting of data in an XY graph.
 8413: Puts plot definition data into the users environment in order for 
 8414: graph.png to plot it.  Returns an <img> tag for the plot.
 8415: 
 8416: Inputs:
 8417: 
 8418: =over 4
 8419: 
 8420: =item $Title: string, the title of the plot
 8421: 
 8422: =item $xlabel: string, text describing the X-axis of the plot
 8423: 
 8424: =item $ylabel: string, text describing the Y-axis of the plot
 8425: 
 8426: =item $Max: scalar, the maximum Y value to use in the plot
 8427: If $Max is < any data point, the graph will not be rendered.
 8428: 
 8429: =item $colors: Array ref containing the hex color codes for the data to be 
 8430: plotted in.  If undefined, default values will be used.
 8431: 
 8432: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8433: 
 8434: =item $Ydata: Array ref containing Array refs.  
 8435: Each of the contained arrays will be plotted as a separate curve.
 8436: 
 8437: =item %Values: hash indicating or overriding any default values which are 
 8438: passed to graph.png.  
 8439: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8440: 
 8441: =back
 8442: 
 8443: Returns:
 8444: 
 8445: An <img> tag which references graph.png and the appropriate identifying
 8446: information for the plot.
 8447: 
 8448: =cut
 8449: 
 8450: ############################################################
 8451: ############################################################
 8452: sub DrawXYGraph {
 8453:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8454:     #
 8455:     # Create the identifier for the graph
 8456:     my $identifier = &get_cgi_id();
 8457:     my $id = 'cgi.'.$identifier;
 8458:     #
 8459:     $Title  = '' if (! defined($Title));
 8460:     $xlabel = '' if (! defined($xlabel));
 8461:     $ylabel = '' if (! defined($ylabel));
 8462:     my %ValuesHash = 
 8463:         (
 8464:          $id.'.title'  => &escape($Title),
 8465:          $id.'.xlabel' => &escape($xlabel),
 8466:          $id.'.ylabel' => &escape($ylabel),
 8467:          $id.'.y_max_value'=> $Max,
 8468:          $id.'.labels'     => join(',',@$Xlabels),
 8469:          $id.'.PlotType'   => 'XY',
 8470:          );
 8471:     #
 8472:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8473:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8474:     }
 8475:     #
 8476:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8477:         return '';
 8478:     }
 8479:     my $NumSets=1;
 8480:     foreach my $array (@{$Ydata}){
 8481:         next if (! ref($array));
 8482:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8483:     }
 8484:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8485:     #
 8486:     # Deal with other parameters
 8487:     while (my ($key,$value) = each(%Values)) {
 8488:         $ValuesHash{$id.'.'.$key} = $value;
 8489:     }
 8490:     #
 8491:     &Apache::lonnet::appenv(\%ValuesHash);
 8492:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8493: }
 8494: 
 8495: ############################################################
 8496: ############################################################
 8497: 
 8498: =pod
 8499: 
 8500: =item * &DrawXYYGraph()
 8501: 
 8502: Facilitates the plotting of data in an XY graph with two Y axes.
 8503: Puts plot definition data into the users environment in order for 
 8504: graph.png to plot it.  Returns an <img> tag for the plot.
 8505: 
 8506: Inputs:
 8507: 
 8508: =over 4
 8509: 
 8510: =item $Title: string, the title of the plot
 8511: 
 8512: =item $xlabel: string, text describing the X-axis of the plot
 8513: 
 8514: =item $ylabel: string, text describing the Y-axis of the plot
 8515: 
 8516: =item $colors: Array ref containing the hex color codes for the data to be 
 8517: plotted in.  If undefined, default values will be used.
 8518: 
 8519: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8520: 
 8521: =item $Ydata1: The first data set
 8522: 
 8523: =item $Min1: The minimum value of the left Y-axis
 8524: 
 8525: =item $Max1: The maximum value of the left Y-axis
 8526: 
 8527: =item $Ydata2: The second data set
 8528: 
 8529: =item $Min2: The minimum value of the right Y-axis
 8530: 
 8531: =item $Max2: The maximum value of the left Y-axis
 8532: 
 8533: =item %Values: hash indicating or overriding any default values which are 
 8534: passed to graph.png.  
 8535: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8536: 
 8537: =back
 8538: 
 8539: Returns:
 8540: 
 8541: An <img> tag which references graph.png and the appropriate identifying
 8542: information for the plot.
 8543: 
 8544: =cut
 8545: 
 8546: ############################################################
 8547: ############################################################
 8548: sub DrawXYYGraph {
 8549:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8550:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8551:     #
 8552:     # Create the identifier for the graph
 8553:     my $identifier = &get_cgi_id();
 8554:     my $id = 'cgi.'.$identifier;
 8555:     #
 8556:     $Title  = '' if (! defined($Title));
 8557:     $xlabel = '' if (! defined($xlabel));
 8558:     $ylabel = '' if (! defined($ylabel));
 8559:     my %ValuesHash = 
 8560:         (
 8561:          $id.'.title'  => &escape($Title),
 8562:          $id.'.xlabel' => &escape($xlabel),
 8563:          $id.'.ylabel' => &escape($ylabel),
 8564:          $id.'.labels' => join(',',@$Xlabels),
 8565:          $id.'.PlotType' => 'XY',
 8566:          $id.'.NumSets' => 2,
 8567:          $id.'.two_axes' => 1,
 8568:          $id.'.y1_max_value' => $Max1,
 8569:          $id.'.y1_min_value' => $Min1,
 8570:          $id.'.y2_max_value' => $Max2,
 8571:          $id.'.y2_min_value' => $Min2,
 8572:          );
 8573:     #
 8574:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8575:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8576:     }
 8577:     #
 8578:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8579:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8580:         return '';
 8581:     }
 8582:     my $NumSets=1;
 8583:     foreach my $array ($Ydata1,$Ydata2){
 8584:         next if (! ref($array));
 8585:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8586:     }
 8587:     #
 8588:     # Deal with other parameters
 8589:     while (my ($key,$value) = each(%Values)) {
 8590:         $ValuesHash{$id.'.'.$key} = $value;
 8591:     }
 8592:     #
 8593:     &Apache::lonnet::appenv(\%ValuesHash);
 8594:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8595: }
 8596: 
 8597: ############################################################
 8598: ############################################################
 8599: 
 8600: =pod
 8601: 
 8602: =back 
 8603: 
 8604: =head1 Statistics helper routines?  
 8605: 
 8606: Bad place for them but what the hell.
 8607: 
 8608: =over 4
 8609: 
 8610: =item * &chartlink()
 8611: 
 8612: Returns a link to the chart for a specific student.  
 8613: 
 8614: Inputs:
 8615: 
 8616: =over 4
 8617: 
 8618: =item $linktext: The text of the link
 8619: 
 8620: =item $sname: The students username
 8621: 
 8622: =item $sdomain: The students domain
 8623: 
 8624: =back
 8625: 
 8626: =back
 8627: 
 8628: =cut
 8629: 
 8630: ############################################################
 8631: ############################################################
 8632: sub chartlink {
 8633:     my ($linktext, $sname, $sdomain) = @_;
 8634:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8635:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8636:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8637:        '">'.$linktext.'</a>';
 8638: }
 8639: 
 8640: #######################################################
 8641: #######################################################
 8642: 
 8643: =pod
 8644: 
 8645: =head1 Course Environment Routines
 8646: 
 8647: =over 4
 8648: 
 8649: =item * &restore_course_settings()
 8650: 
 8651: =item * &store_course_settings()
 8652: 
 8653: Restores/Store indicated form parameters from the course environment.
 8654: Will not overwrite existing values of the form parameters.
 8655: 
 8656: Inputs: 
 8657: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8658: 
 8659: a hash ref describing the data to be stored.  For example:
 8660:    
 8661: %Save_Parameters = ('Status' => 'scalar',
 8662:     'chartoutputmode' => 'scalar',
 8663:     'chartoutputdata' => 'scalar',
 8664:     'Section' => 'array',
 8665:     'Group' => 'array',
 8666:     'StudentData' => 'array',
 8667:     'Maps' => 'array');
 8668: 
 8669: Returns: both routines return nothing
 8670: 
 8671: =back
 8672: 
 8673: =cut
 8674: 
 8675: #######################################################
 8676: #######################################################
 8677: sub store_course_settings {
 8678:     return &store_settings($env{'request.course.id'},@_);
 8679: }
 8680: 
 8681: sub store_settings {
 8682:     # save to the environment
 8683:     # appenv the same items, just to be safe
 8684:     my $udom  = $env{'user.domain'};
 8685:     my $uname = $env{'user.name'};
 8686:     my ($context,$prefix,$Settings) = @_;
 8687:     my %SaveHash;
 8688:     my %AppHash;
 8689:     while (my ($setting,$type) = each(%$Settings)) {
 8690:         my $basename = join('.','internal',$context,$prefix,$setting);
 8691:         my $envname = 'environment.'.$basename;
 8692:         if (exists($env{'form.'.$setting})) {
 8693:             # Save this value away
 8694:             if ($type eq 'scalar' &&
 8695:                 (! exists($env{$envname}) || 
 8696:                  $env{$envname} ne $env{'form.'.$setting})) {
 8697:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8698:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8699:             } elsif ($type eq 'array') {
 8700:                 my $stored_form;
 8701:                 if (ref($env{'form.'.$setting})) {
 8702:                     $stored_form = join(',',
 8703:                                         map {
 8704:                                             &escape($_);
 8705:                                         } sort(@{$env{'form.'.$setting}}));
 8706:                 } else {
 8707:                     $stored_form = 
 8708:                         &escape($env{'form.'.$setting});
 8709:                 }
 8710:                 # Determine if the array contents are the same.
 8711:                 if ($stored_form ne $env{$envname}) {
 8712:                     $SaveHash{$basename} = $stored_form;
 8713:                     $AppHash{$envname}   = $stored_form;
 8714:                 }
 8715:             }
 8716:         }
 8717:     }
 8718:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8719:                                           $udom,$uname);
 8720:     if ($put_result !~ /^(ok|delayed)/) {
 8721:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8722:                                  'got error:'.$put_result);
 8723:     }
 8724:     # Make sure these settings stick around in this session, too
 8725:     &Apache::lonnet::appenv(\%AppHash);
 8726:     return;
 8727: }
 8728: 
 8729: sub restore_course_settings {
 8730:     return &restore_settings($env{'request.course.id'},@_);
 8731: }
 8732: 
 8733: sub restore_settings {
 8734:     my ($context,$prefix,$Settings) = @_;
 8735:     while (my ($setting,$type) = each(%$Settings)) {
 8736:         next if (exists($env{'form.'.$setting}));
 8737:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8738:             '.'.$setting;
 8739:         if (exists($env{$envname})) {
 8740:             if ($type eq 'scalar') {
 8741:                 $env{'form.'.$setting} = $env{$envname};
 8742:             } elsif ($type eq 'array') {
 8743:                 $env{'form.'.$setting} = [ 
 8744:                                            map { 
 8745:                                                &unescape($_); 
 8746:                                            } split(',',$env{$envname})
 8747:                                            ];
 8748:             }
 8749:         }
 8750:     }
 8751: }
 8752: 
 8753: #######################################################
 8754: #######################################################
 8755: 
 8756: =pod
 8757: 
 8758: =head1 Domain E-mail Routines  
 8759: 
 8760: =over 4
 8761: 
 8762: =item * &build_recipient_list()
 8763: 
 8764: Build recipient lists for three types of e-mail:
 8765: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
 8766: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
 8767: 
 8768: Inputs:
 8769: defmail (scalar - email address of default recipient), 
 8770: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8771: defdom (domain for which to retrieve configuration settings),
 8772: origmail (scalar - email address of recipient from loncapa.conf, 
 8773: i.e., predates configuration by DC via domainprefs.pm 
 8774: 
 8775: Returns: comma separated list of addresses to which to send e-mail.
 8776: 
 8777: =back
 8778: 
 8779: =cut
 8780: 
 8781: ############################################################
 8782: ############################################################
 8783: sub build_recipient_list {
 8784:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8785:     my @recipients;
 8786:     my $otheremails;
 8787:     my %domconfig =
 8788:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8789:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8790:         if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8791:             my @contacts = ('adminemail','supportemail');
 8792:             foreach my $item (@contacts) {
 8793:                 if ($domconfig{'contacts'}{$mailing}{$item}) {
 8794:                     my $addr = $domconfig{'contacts'}{$item}; 
 8795:                     if (!grep(/^\Q$addr\E$/,@recipients)) {
 8796:                         push(@recipients,$addr);
 8797:                     }
 8798:                 }
 8799:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8800:             }
 8801:         }
 8802:     } elsif ($origmail ne '') {
 8803:         push(@recipients,$origmail);
 8804:     }
 8805:     if (defined($defmail)) {
 8806:         if ($defmail ne '') {
 8807:             push(@recipients,$defmail);
 8808:         }
 8809:     }
 8810:     if ($otheremails) {
 8811:         my @others;
 8812:         if ($otheremails =~ /,/) {
 8813:             @others = split(/,/,$otheremails);
 8814:         } else {
 8815:             push(@others,$otheremails);
 8816:         }
 8817:         foreach my $addr (@others) {
 8818:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8819:                 push(@recipients,$addr);
 8820:             }
 8821:         }
 8822:     }
 8823:     my $recipientlist = join(',',@recipients); 
 8824:     return $recipientlist;
 8825: }
 8826: 
 8827: ############################################################
 8828: ############################################################
 8829: 
 8830: =pod
 8831: 
 8832: =head1 Course Catalog Routines
 8833: 
 8834: =over 4
 8835: 
 8836: =item * &gather_categories()
 8837: 
 8838: Converts category definitions - keys of categories hash stored in  
 8839: coursecategories in configuration.db on the primary library server in a 
 8840: domain - to an array.  Also generates javascript and idx hash used to 
 8841: generate Domain Coordinator interface for editing Course Categories.
 8842: 
 8843: Inputs:
 8844: 
 8845: categories (reference to hash of category definitions).
 8846: 
 8847: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8848:       categories and subcategories).
 8849: 
 8850: idx (reference to hash of counters used in Domain Coordinator interface for 
 8851:       editing Course Categories).
 8852: 
 8853: jsarray (reference to array of categories used to create Javascript arrays for
 8854:          Domain Coordinator interface for editing Course Categories).
 8855: 
 8856: Returns: nothing
 8857: 
 8858: Side effects: populates cats, idx and jsarray. 
 8859: 
 8860: =cut
 8861: 
 8862: sub gather_categories {
 8863:     my ($categories,$cats,$idx,$jsarray) = @_;
 8864:     my %counters;
 8865:     my $num = 0;
 8866:     foreach my $item (keys(%{$categories})) {
 8867:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8868:         if ($container eq '' && $depth == 0) {
 8869:             $cats->[$depth][$categories->{$item}] = $cat;
 8870:         } else {
 8871:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8872:         }
 8873:         my ($escitem,$tail) = split(/:/,$item,2);
 8874:         if ($counters{$tail} eq '') {
 8875:             $counters{$tail} = $num;
 8876:             $num ++;
 8877:         }
 8878:         if (ref($idx) eq 'HASH') {
 8879:             $idx->{$item} = $counters{$tail};
 8880:         }
 8881:         if (ref($jsarray) eq 'ARRAY') {
 8882:             push(@{$jsarray->[$counters{$tail}]},$item);
 8883:         }
 8884:     }
 8885:     return;
 8886: }
 8887: 
 8888: =pod
 8889: 
 8890: =item * &extract_categories()
 8891: 
 8892: Used to generate breadcrumb trails for course categories.
 8893: 
 8894: Inputs:
 8895: 
 8896: categories (reference to hash of category definitions).
 8897: 
 8898: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8899:       categories and subcategories).
 8900: 
 8901: trails (reference to array of breacrumb trails for each category).
 8902: 
 8903: allitems (reference to hash - key is category key 
 8904:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8905: 
 8906: idx (reference to hash of counters used in Domain Coordinator interface for
 8907:       editing Course Categories).
 8908: 
 8909: jsarray (reference to array of categories used to create Javascript arrays for
 8910:          Domain Coordinator interface for editing Course Categories).
 8911: 
 8912: subcats (reference to hash of arrays containing all subcategories within each 
 8913:          category, -recursive)
 8914: 
 8915: Returns: nothing
 8916: 
 8917: Side effects: populates trails and allitems hash references.
 8918: 
 8919: =cut
 8920: 
 8921: sub extract_categories {
 8922:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8923:     if (ref($categories) eq 'HASH') {
 8924:         &gather_categories($categories,$cats,$idx,$jsarray);
 8925:         if (ref($cats->[0]) eq 'ARRAY') {
 8926:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8927:                 my $name = $cats->[0][$i];
 8928:                 my $item = &escape($name).'::0';
 8929:                 my $trailstr;
 8930:                 if ($name eq 'instcode') {
 8931:                     $trailstr = &mt('Official courses (with institutional codes)');
 8932:                 } else {
 8933:                     $trailstr = $name;
 8934:                 }
 8935:                 if ($allitems->{$item} eq '') {
 8936:                     push(@{$trails},$trailstr);
 8937:                     $allitems->{$item} = scalar(@{$trails})-1;
 8938:                 }
 8939:                 my @parents = ($name);
 8940:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8941:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8942:                         my $category = $cats->[1]{$name}[$j];
 8943:                         if (ref($subcats) eq 'HASH') {
 8944:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8945:                         }
 8946:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8947:                     }
 8948:                 } else {
 8949:                     if (ref($subcats) eq 'HASH') {
 8950:                         $subcats->{$item} = [];
 8951:                     }
 8952:                 }
 8953:             }
 8954:         }
 8955:     }
 8956:     return;
 8957: }
 8958: 
 8959: =pod
 8960: 
 8961: =item *&recurse_categories()
 8962: 
 8963: Recursively used to generate breadcrumb trails for course categories.
 8964: 
 8965: Inputs:
 8966: 
 8967: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8968:       categories and subcategories).
 8969: 
 8970: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8971: 
 8972: category (current course category, for which breadcrumb trail is being generated).
 8973: 
 8974: trails (reference to array of breadcrumb trails for each category).
 8975: 
 8976: allitems (reference to hash - key is category key
 8977:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8978: 
 8979: parents (array containing containers directories for current category, 
 8980:          back to top level). 
 8981: 
 8982: Returns: nothing
 8983: 
 8984: Side effects: populates trails and allitems hash references
 8985: 
 8986: =cut
 8987: 
 8988: sub recurse_categories {
 8989:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8990:     my $shallower = $depth - 1;
 8991:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8992:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8993:             my $name = $cats->[$depth]{$category}[$k];
 8994:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8995:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8996:             if ($allitems->{$item} eq '') {
 8997:                 push(@{$trails},$trailstr);
 8998:                 $allitems->{$item} = scalar(@{$trails})-1;
 8999:             }
 9000:             my $deeper = $depth+1;
 9001:             push(@{$parents},$category);
 9002:             if (ref($subcats) eq 'HASH') {
 9003:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9004:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9005:                     my $higher;
 9006:                     if ($j > 0) {
 9007:                         $higher = &escape($parents->[$j]).':'.
 9008:                                   &escape($parents->[$j-1]).':'.$j;
 9009:                     } else {
 9010:                         $higher = &escape($parents->[$j]).'::'.$j;
 9011:                     }
 9012:                     push(@{$subcats->{$higher}},$subcat);
 9013:                 }
 9014:             }
 9015:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9016:                                 $subcats);
 9017:             pop(@{$parents});
 9018:         }
 9019:     } else {
 9020:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9021:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9022:         if ($allitems->{$item} eq '') {
 9023:             push(@{$trails},$trailstr);
 9024:             $allitems->{$item} = scalar(@{$trails})-1;
 9025:         }
 9026:     }
 9027:     return;
 9028: }
 9029: 
 9030: =pod
 9031: 
 9032: =item *&assign_categories_table()
 9033: 
 9034: Create a datatable for display of hierarchical categories in a domain,
 9035: with checkboxes to allow a course to be categorized. 
 9036: 
 9037: Inputs:
 9038: 
 9039: cathash - reference to hash of categories defined for the domain (from
 9040:           configuration.db)
 9041: 
 9042: currcat - scalar with an & separated list of categories assigned to a course. 
 9043: 
 9044: Returns: $output (markup to be displayed) 
 9045: 
 9046: =cut
 9047: 
 9048: sub assign_categories_table {
 9049:     my ($cathash,$currcat) = @_;
 9050:     my $output;
 9051:     if (ref($cathash) eq 'HASH') {
 9052:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9053:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9054:         $maxdepth = scalar(@cats);
 9055:         if (@cats > 0) {
 9056:             my $itemcount = 0;
 9057:             if (ref($cats[0]) eq 'ARRAY') {
 9058:                 $output = &Apache::loncommon::start_data_table();
 9059:                 my @currcategories;
 9060:                 if ($currcat ne '') {
 9061:                     @currcategories = split('&',$currcat);
 9062:                 }
 9063:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9064:                     my $parent = $cats[0][$i];
 9065:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9066:                     next if ($parent eq 'instcode');
 9067:                     my $item = &escape($parent).'::0';
 9068:                     my $checked = '';
 9069:                     if (@currcategories > 0) {
 9070:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9071:                             $checked = ' checked="checked" ';
 9072:                         }
 9073:                     }
 9074:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9075:                                '<input type="checkbox" name="usecategory" value="'.
 9076:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9077:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9078:                     my $depth = 1;
 9079:                     push(@path,$parent);
 9080:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9081:                     pop(@path);
 9082:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9083:                     $itemcount ++;
 9084:                 }
 9085:                 $output .= &Apache::loncommon::end_data_table();
 9086:             }
 9087:         }
 9088:     }
 9089:     return $output;
 9090: }
 9091: 
 9092: =pod
 9093: 
 9094: =item *&assign_category_rows()
 9095: 
 9096: Create a datatable row for display of nested categories in a domain,
 9097: with checkboxes to allow a course to be categorized,called recursively.
 9098: 
 9099: Inputs:
 9100: 
 9101: itemcount - track row number for alternating colors
 9102: 
 9103: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9104:       categories and subcategories.
 9105: 
 9106: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9107: 
 9108: parent - parent of current category item
 9109: 
 9110: path - Array containing all categories back up through the hierarchy from the
 9111:        current category to the top level.
 9112: 
 9113: currcategories - reference to array of current categories assigned to the course
 9114: 
 9115: Returns: $output (markup to be displayed).
 9116: 
 9117: =cut
 9118: 
 9119: sub assign_category_rows {
 9120:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9121:     my ($text,$name,$item,$chgstr);
 9122:     if (ref($cats) eq 'ARRAY') {
 9123:         my $maxdepth = scalar(@{$cats});
 9124:         if (ref($cats->[$depth]) eq 'HASH') {
 9125:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9126:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9127:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9128:                 $text .= '<td><table class="LC_datatable">';
 9129:                 for (my $j=0; $j<$numchildren; $j++) {
 9130:                     $name = $cats->[$depth]{$parent}[$j];
 9131:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9132:                     my $deeper = $depth+1;
 9133:                     my $checked = '';
 9134:                     if (ref($currcategories) eq 'ARRAY') {
 9135:                         if (@{$currcategories} > 0) {
 9136:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9137:                                 $checked = ' checked="checked" ';
 9138:                             }
 9139:                         }
 9140:                     }
 9141:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9142:                              '<input type="checkbox" name="usecategory" value="'.
 9143:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9144:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9145:                              '</td><td>';
 9146:                     if (ref($path) eq 'ARRAY') {
 9147:                         push(@{$path},$name);
 9148:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9149:                         pop(@{$path});
 9150:                     }
 9151:                     $text .= '</td></tr>';
 9152:                 }
 9153:                 $text .= '</table></td>';
 9154:             }
 9155:         }
 9156:     }
 9157:     return $text;
 9158: }
 9159: 
 9160: ############################################################
 9161: ############################################################
 9162: 
 9163: 
 9164: sub commit_customrole {
 9165:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9166:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9167:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9168:                          ($end?', ending '.localtime($end):'').': <b>'.
 9169:               &Apache::lonnet::assigncustomrole(
 9170:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9171:                  '</b><br />';
 9172:     return $output;
 9173: }
 9174: 
 9175: sub commit_standardrole {
 9176:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9177:     my ($output,$logmsg,$linefeed);
 9178:     if ($context eq 'auto') {
 9179:         $linefeed = "\n";
 9180:     } else {
 9181:         $linefeed = "<br />\n";
 9182:     }  
 9183:     if ($three eq 'st') {
 9184:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9185:                                          $one,$two,$sec,$context);
 9186:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9187:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9188:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9189:         } else {
 9190:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9191:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9192:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9193:             if ($context eq 'auto') {
 9194:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9195:             } else {
 9196:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9197:                &mt('Add to classlist').': <b>ok</b>';
 9198:             }
 9199:             $output .= $linefeed;
 9200:         }
 9201:     } else {
 9202:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9203:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9204:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9205:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9206:         if ($context eq 'auto') {
 9207:             $output .= $result.$linefeed;
 9208:         } else {
 9209:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9210:         }
 9211:     }
 9212:     return $output;
 9213: }
 9214: 
 9215: sub commit_studentrole {
 9216:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9217:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9218:     if ($context eq 'auto') {
 9219:         $linefeed = "\n";
 9220:     } else {
 9221:         $linefeed = '<br />'."\n";
 9222:     }
 9223:     if (defined($one) && defined($two)) {
 9224:         my $cid=$one.'_'.$two;
 9225:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9226:         my $secchange = 0;
 9227:         my $expire_role_result;
 9228:         my $modify_section_result;
 9229:         if ($oldsec ne '-1') { 
 9230:             if ($oldsec ne $sec) {
 9231:                 $secchange = 1;
 9232:                 my $now = time;
 9233:                 my $uurl='/'.$cid;
 9234:                 $uurl=~s/\_/\//g;
 9235:                 if ($oldsec) {
 9236:                     $uurl.='/'.$oldsec;
 9237:                 }
 9238:                 $oldsecurl = $uurl;
 9239:                 $expire_role_result = 
 9240:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9241:                 if ($env{'request.course.sec'} ne '') { 
 9242:                     if ($expire_role_result eq 'refused') {
 9243:                         my @roles = ('st');
 9244:                         my @statuses = ('previous');
 9245:                         my @roledoms = ($one);
 9246:                         my $withsec = 1;
 9247:                         my %roleshash = 
 9248:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9249:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9250:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9251:                             my ($oldstart,$oldend) = 
 9252:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9253:                             if ($oldend > 0 && $oldend <= $now) {
 9254:                                 $expire_role_result = 'ok';
 9255:                             }
 9256:                         }
 9257:                     }
 9258:                 }
 9259:                 $result = $expire_role_result;
 9260:             }
 9261:         }
 9262:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9263:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9264:             if ($modify_section_result =~ /^ok/) {
 9265:                 if ($secchange == 1) {
 9266:                     if ($sec eq '') {
 9267:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9268:                     } else {
 9269:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9270:                     }
 9271:                 } elsif ($oldsec eq '-1') {
 9272:                     if ($sec eq '') {
 9273:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9274:                     } else {
 9275:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9276:                     }
 9277:                 } else {
 9278:                     if ($sec eq '') {
 9279:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9280:                     } else {
 9281:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9282:                     }
 9283:                 }
 9284:             } else {
 9285:                 if ($secchange) {       
 9286:                     $$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;
 9287:                 } else {
 9288:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9289:                 }
 9290:             }
 9291:             $result = $modify_section_result;
 9292:         } elsif ($secchange == 1) {
 9293:             if ($oldsec eq '') {
 9294:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9295:             } else {
 9296:                 $$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;
 9297:             }
 9298:             if ($expire_role_result eq 'refused') {
 9299:                 my $newsecurl = '/'.$cid;
 9300:                 $newsecurl =~ s/\_/\//g;
 9301:                 if ($sec ne '') {
 9302:                     $newsecurl.='/'.$sec;
 9303:                 }
 9304:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9305:                     if ($sec eq '') {
 9306:                         $$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;
 9307:                     } else {
 9308:                         $$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;
 9309:                     }
 9310:                 }
 9311:             }
 9312:         }
 9313:     } else {
 9314:         $$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;
 9315:         $result = "error: incomplete course id\n";
 9316:     }
 9317:     return $result;
 9318: }
 9319: 
 9320: ############################################################
 9321: ############################################################
 9322: 
 9323: sub check_clone {
 9324:     my ($args,$linefeed) = @_;
 9325:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9326:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9327:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9328:     my $clonemsg;
 9329:     my $can_clone = 0;
 9330: 
 9331:     if ($clonehome eq 'no_host') {
 9332:         $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'});     
 9333:     } else {
 9334: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9335: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9336: 	    $can_clone = 1;
 9337: 	} else {
 9338: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9339: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9340: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9341:             if (grep(/^\*$/,@cloners)) {
 9342:                 $can_clone = 1;
 9343:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9344:                 $can_clone = 1;
 9345:             } else {
 9346: 	        my %roleshash =
 9347: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9348: 					 $args->{'ccdomain'},
 9349:                                          'userroles',['active'],['cc'],
 9350: 					 [$args->{'clonedomain'}]);
 9351: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9352: 		    $can_clone = 1;
 9353: 	        } else {
 9354:                     $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'});
 9355: 	        }
 9356: 	    }
 9357:         }
 9358:     }
 9359:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9360: }
 9361: 
 9362: sub construct_course {
 9363:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9364:     my $outcome;
 9365:     my $linefeed =  '<br />'."\n";
 9366:     if ($context eq 'auto') {
 9367:         $linefeed = "\n";
 9368:     }
 9369: 
 9370: #
 9371: # Are we cloning?
 9372: #
 9373:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9374:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9375: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9376: 	if ($context ne 'auto') {
 9377:             if ($clonemsg ne '') {
 9378: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9379:             }
 9380: 	}
 9381: 	$outcome .= $clonemsg.$linefeed;
 9382: 
 9383:         if (!$can_clone) {
 9384: 	    return (0,$outcome);
 9385: 	}
 9386:     }
 9387: 
 9388: #
 9389: # Open course
 9390: #
 9391:     my $crstype = lc($args->{'crstype'});
 9392:     my %cenv=();
 9393:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9394:                                              $args->{'cdescr'},
 9395:                                              $args->{'curl'},
 9396:                                              $args->{'course_home'},
 9397:                                              $args->{'nonstandard'},
 9398:                                              $args->{'crscode'},
 9399:                                              $args->{'ccuname'}.':'.
 9400:                                              $args->{'ccdomain'},
 9401:                                              $args->{'crstype'});
 9402: 
 9403:     # Note: The testing routines depend on this being output; see 
 9404:     # Utils::Course. This needs to at least be output as a comment
 9405:     # if anyone ever decides to not show this, and Utils::Course::new
 9406:     # will need to be suitably modified.
 9407:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9408: #
 9409: # Check if created correctly
 9410: #
 9411:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9412:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9413:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9414: 
 9415: #
 9416: # Do the cloning
 9417: #   
 9418:     if ($can_clone && $cloneid) {
 9419: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9420: 	if ($context ne 'auto') {
 9421: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9422: 	}
 9423: 	$outcome .= $clonemsg.$linefeed;
 9424: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9425: # Copy all files
 9426: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9427: # Restore URL
 9428: 	$cenv{'url'}=$oldcenv{'url'};
 9429: # Restore title
 9430: 	$cenv{'description'}=$oldcenv{'description'};
 9431: # Mark as cloned
 9432: 	$cenv{'clonedfrom'}=$cloneid;
 9433: # Need to clone grading mode
 9434:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9435:         $cenv{'grading'}=$newenv{'grading'};
 9436: # Do not clone these environment entries
 9437:         &Apache::lonnet::del('environment',
 9438:                   ['default_enrollment_start_date',
 9439:                    'default_enrollment_end_date',
 9440:                    'question.email',
 9441:                    'policy.email',
 9442:                    'comment.email',
 9443:                    'pch.users.denied',
 9444:                    'plc.users.denied',
 9445:                    'hidefromcat',
 9446:                    'categories'],
 9447:                    $$crsudom,$$crsunum);
 9448:     }
 9449: 
 9450: #
 9451: # Set environment (will override cloned, if existing)
 9452: #
 9453:     my @sections = ();
 9454:     my @xlists = ();
 9455:     if ($args->{'crstype'}) {
 9456:         $cenv{'type'}=$args->{'crstype'};
 9457:     }
 9458:     if ($args->{'crsid'}) {
 9459:         $cenv{'courseid'}=$args->{'crsid'};
 9460:     }
 9461:     if ($args->{'crscode'}) {
 9462:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9463:     }
 9464:     if ($args->{'crsquota'} ne '') {
 9465:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9466:     } else {
 9467:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9468:     }
 9469:     if ($args->{'ccuname'}) {
 9470:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9471:                                         ':'.$args->{'ccdomain'};
 9472:     } else {
 9473:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9474:     }
 9475:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9476:     if ($args->{'crssections'}) {
 9477:         $cenv{'internal.sectionnums'} = '';
 9478:         if ($args->{'crssections'} =~ m/,/) {
 9479:             @sections = split/,/,$args->{'crssections'};
 9480:         } else {
 9481:             $sections[0] = $args->{'crssections'};
 9482:         }
 9483:         if (@sections > 0) {
 9484:             foreach my $item (@sections) {
 9485:                 my ($sec,$gp) = split/:/,$item;
 9486:                 my $class = $args->{'crscode'}.$sec;
 9487:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9488:                 $cenv{'internal.sectionnums'} .= $item.',';
 9489:                 unless ($addcheck eq 'ok') {
 9490:                     push @badclasses, $class;
 9491:                 }
 9492:             }
 9493:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9494:         }
 9495:     }
 9496: # do not hide course coordinator from staff listing, 
 9497: # even if privileged
 9498:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9499: # add crosslistings
 9500:     if ($args->{'crsxlist'}) {
 9501:         $cenv{'internal.crosslistings'}='';
 9502:         if ($args->{'crsxlist'} =~ m/,/) {
 9503:             @xlists = split/,/,$args->{'crsxlist'};
 9504:         } else {
 9505:             $xlists[0] = $args->{'crsxlist'};
 9506:         }
 9507:         if (@xlists > 0) {
 9508:             foreach my $item (@xlists) {
 9509:                 my ($xl,$gp) = split/:/,$item;
 9510:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9511:                 $cenv{'internal.crosslistings'} .= $item.',';
 9512:                 unless ($addcheck eq 'ok') {
 9513:                     push @badclasses, $xl;
 9514:                 }
 9515:             }
 9516:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9517:         }
 9518:     }
 9519:     if ($args->{'autoadds'}) {
 9520:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9521:     }
 9522:     if ($args->{'autodrops'}) {
 9523:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9524:     }
 9525: # check for notification of enrollment changes
 9526:     my @notified = ();
 9527:     if ($args->{'notify_owner'}) {
 9528:         if ($args->{'ccuname'} ne '') {
 9529:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9530:         }
 9531:     }
 9532:     if ($args->{'notify_dc'}) {
 9533:         if ($uname ne '') { 
 9534:             push(@notified,$uname.':'.$udom);
 9535:         }
 9536:     }
 9537:     if (@notified > 0) {
 9538:         my $notifylist;
 9539:         if (@notified > 1) {
 9540:             $notifylist = join(',',@notified);
 9541:         } else {
 9542:             $notifylist = $notified[0];
 9543:         }
 9544:         $cenv{'internal.notifylist'} = $notifylist;
 9545:     }
 9546:     if (@badclasses > 0) {
 9547:         my %lt=&Apache::lonlocal::texthash(
 9548:                 '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',
 9549:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9550:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9551:         );
 9552:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9553:                            ' ('.$lt{'adby'}.')';
 9554:         if ($context eq 'auto') {
 9555:             $outcome .= $badclass_msg.$linefeed;
 9556:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9557:             foreach my $item (@badclasses) {
 9558:                 if ($context eq 'auto') {
 9559:                     $outcome .= " - $item\n";
 9560:                 } else {
 9561:                     $outcome .= "<li>$item</li>\n";
 9562:                 }
 9563:             }
 9564:             if ($context eq 'auto') {
 9565:                 $outcome .= $linefeed;
 9566:             } else {
 9567:                 $outcome .= "</ul><br /><br /></div>\n";
 9568:             }
 9569:         } 
 9570:     }
 9571:     if ($args->{'no_end_date'}) {
 9572:         $args->{'endaccess'} = 0;
 9573:     }
 9574:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9575:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9576:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9577:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9578:     if ($args->{'showphotos'}) {
 9579:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9580:     }
 9581:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9582:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9583:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9584:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9585:             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'); 
 9586:             if ($context eq 'auto') {
 9587:                 $outcome .= $krb_msg;
 9588:             } else {
 9589:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9590:             }
 9591:             $outcome .= $linefeed;
 9592:         }
 9593:     }
 9594:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9595:        if ($args->{'setpolicy'}) {
 9596:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9597:        }
 9598:        if ($args->{'setcontent'}) {
 9599:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9600:        }
 9601:     }
 9602:     if ($args->{'reshome'}) {
 9603: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9604: 	$cenv{'reshome'}=~s/\/+$/\//;
 9605:     }
 9606: #
 9607: # course has keyed access
 9608: #
 9609:     if ($args->{'setkeys'}) {
 9610:        $cenv{'keyaccess'}='yes';
 9611:     }
 9612: # if specified, key authority is not course, but user
 9613: # only active if keyaccess is yes
 9614:     if ($args->{'keyauth'}) {
 9615: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9616: 	$user = &LONCAPA::clean_username($user);
 9617: 	$domain = &LONCAPA::clean_username($domain);
 9618: 	if ($user ne '' && $domain ne '') {
 9619: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9620: 	}
 9621:     }
 9622: 
 9623:     if ($args->{'disresdis'}) {
 9624:         $cenv{'pch.roles.denied'}='st';
 9625:     }
 9626:     if ($args->{'disablechat'}) {
 9627:         $cenv{'plc.roles.denied'}='st';
 9628:     }
 9629: 
 9630:     # Record we've not yet viewed the Course Initialization Helper for this 
 9631:     # course
 9632:     $cenv{'course.helper.not.run'} = 1;
 9633:     #
 9634:     # Use new Randomseed
 9635:     #
 9636:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9637:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9638:     #
 9639:     # The encryption code and receipt prefix for this course
 9640:     #
 9641:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9642:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9643:     #
 9644:     # By default, use standard grading
 9645:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9646: 
 9647:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9648:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9649: #
 9650: # Open all assignments
 9651: #
 9652:     if ($args->{'openall'}) {
 9653:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9654:        my %storecontent = ($storeunder         => time,
 9655:                            $storeunder.'.type' => 'date_start');
 9656:        
 9657:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9658:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9659:    }
 9660: #
 9661: # Set first page
 9662: #
 9663:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9664: 	    || ($cloneid)) {
 9665: 	use LONCAPA::map;
 9666: 	$outcome .= &mt('Setting first resource').': ';
 9667: 
 9668: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9669:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9670: 
 9671:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9672:         my $title; my $url;
 9673:         if ($args->{'firstres'} eq 'syl') {
 9674: 	    $title=&mt('Syllabus');
 9675:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9676:         } else {
 9677:             $title=&mt('Navigate Contents');
 9678:             $url='/adm/navmaps';
 9679:         }
 9680: 
 9681:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9682: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9683: 
 9684: 	if ($errtext) { $fatal=2; }
 9685:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9686:     }
 9687: 
 9688:     return (1,$outcome);
 9689: }
 9690: 
 9691: ############################################################
 9692: ############################################################
 9693: 
 9694: sub course_type {
 9695:     my ($cid) = @_;
 9696:     if (!defined($cid)) {
 9697:         $cid = $env{'request.course.id'};
 9698:     }
 9699:     if (defined($env{'course.'.$cid.'.type'})) {
 9700:         return $env{'course.'.$cid.'.type'};
 9701:     } else {
 9702:         return 'Course';
 9703:     }
 9704: }
 9705: 
 9706: sub group_term {
 9707:     my $crstype = &course_type();
 9708:     my %names = (
 9709:                   'Course' => 'group',
 9710:                   'Group' => 'team',
 9711:                 );
 9712:     return $names{$crstype};
 9713: }
 9714: 
 9715: sub icon {
 9716:     my ($file)=@_;
 9717:     my $curfext = lc((split(/\./,$file))[-1]);
 9718:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9719:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9720:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9721: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9722: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9723: 	            $curfext.".gif") {
 9724: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9725: 		$curfext.".gif";
 9726: 	}
 9727:     }
 9728:     return &lonhttpdurl($iconname);
 9729: } 
 9730: 
 9731: sub lonhttpdurl {
 9732: #
 9733: # Had been used for "small fry" static images on separate port 8080.
 9734: # Modify here if lightweight http functionality desired again.
 9735: # Currently eliminated due to increasing firewall issues.
 9736: #
 9737:     my ($url)=@_;
 9738:     return $url;
 9739: }
 9740: 
 9741: sub connection_aborted {
 9742:     my ($r)=@_;
 9743:     $r->print(" ");$r->rflush();
 9744:     my $c = $r->connection;
 9745:     return $c->aborted();
 9746: }
 9747: 
 9748: #    Escapes strings that may have embedded 's that will be put into
 9749: #    strings as 'strings'.
 9750: sub escape_single {
 9751:     my ($input) = @_;
 9752:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9753:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9754:     return $input;
 9755: }
 9756: 
 9757: #  Same as escape_single, but escape's "'s  This 
 9758: #  can be used for  "strings"
 9759: sub escape_double {
 9760:     my ($input) = @_;
 9761:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9762:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9763:     return $input;
 9764: }
 9765:  
 9766: #   Escapes the last element of a full URL.
 9767: sub escape_url {
 9768:     my ($url)   = @_;
 9769:     my @urlslices = split(/\//, $url,-1);
 9770:     my $lastitem = &escape(pop(@urlslices));
 9771:     return join('/',@urlslices).'/'.$lastitem;
 9772: }
 9773: 
 9774: # -------------------------------------------------------- Initliaze user login
 9775: sub init_user_environment {
 9776:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9777:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9778: 
 9779:     my $public=($username eq 'public' && $domain eq 'public');
 9780: 
 9781: # See if old ID present, if so, remove
 9782: 
 9783:     my ($filename,$cookie,$userroles);
 9784:     my $now=time;
 9785: 
 9786:     if ($public) {
 9787: 	my $max_public=100;
 9788: 	my $oldest;
 9789: 	my $oldest_time=0;
 9790: 	for(my $next=1;$next<=$max_public;$next++) {
 9791: 	    if (-e $lonids."/publicuser_$next.id") {
 9792: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9793: 		if ($mtime<$oldest_time || !$oldest_time) {
 9794: 		    $oldest_time=$mtime;
 9795: 		    $oldest=$next;
 9796: 		}
 9797: 	    } else {
 9798: 		$cookie="publicuser_$next";
 9799: 		last;
 9800: 	    }
 9801: 	}
 9802: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9803:     } else {
 9804: 	# if this isn't a robot, kill any existing non-robot sessions
 9805: 	if (!$args->{'robot'}) {
 9806: 	    opendir(DIR,$lonids);
 9807: 	    while ($filename=readdir(DIR)) {
 9808: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9809: 		    unlink($lonids.'/'.$filename);
 9810: 		}
 9811: 	    }
 9812: 	    closedir(DIR);
 9813: 	}
 9814: # Give them a new cookie
 9815: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9816: 		                   : $now.$$.int(rand(10000)));
 9817: 	$cookie="$username\_$id\_$domain\_$authhost";
 9818:     
 9819: # Initialize roles
 9820: 
 9821: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9822:     }
 9823: # ------------------------------------ Check browser type and MathML capability
 9824: 
 9825:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9826:         $clientunicode,$clientos) = &decode_user_agent($r);
 9827: 
 9828: # -------------------------------------- Any accessibility options to remember?
 9829:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9830: 	foreach my $option ('imagesuppress','appletsuppress',
 9831: 			    'embedsuppress','fontenhance','blackwhite') {
 9832: 	    if ($form->{$option} eq 'true') {
 9833: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9834: 				     $domain,$username);
 9835: 	    } else {
 9836: 		&Apache::lonnet::del('environment',[$option],
 9837: 				     $domain,$username);
 9838: 	    }
 9839: 	}
 9840:     }
 9841: # ------------------------------------------------------------- Get environment
 9842: 
 9843:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9844:     my ($tmp) = keys(%userenv);
 9845:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9846: 	# default remote control to off
 9847: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9848:     } else {
 9849: 	undef(%userenv);
 9850:     }
 9851:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9852: 	$form->{'interface'}=$userenv{'interface'};
 9853:     }
 9854:     $env{'environment.remote'}=$userenv{'remote'};
 9855:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9856: 
 9857: # --------------- Do not trust query string to be put directly into environment
 9858:     foreach my $option ('imagesuppress','appletsuppress',
 9859: 			'embedsuppress','fontenhance','blackwhite',
 9860: 			'interface','localpath','localres') {
 9861: 	$form->{$option}=~s/[\n\r\=]//gs;
 9862:     }
 9863: # --------------------------------------------------------- Write first profile
 9864: 
 9865:     {
 9866: 	my %initial_env = 
 9867: 	    ("user.name"          => $username,
 9868: 	     "user.domain"        => $domain,
 9869: 	     "user.home"          => $authhost,
 9870: 	     "browser.type"       => $clientbrowser,
 9871: 	     "browser.version"    => $clientversion,
 9872: 	     "browser.mathml"     => $clientmathml,
 9873: 	     "browser.unicode"    => $clientunicode,
 9874: 	     "browser.os"         => $clientos,
 9875: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9876: 	     "request.course.fn"  => '',
 9877: 	     "request.course.uri" => '',
 9878: 	     "request.course.sec" => '',
 9879: 	     "request.role"       => 'cm',
 9880: 	     "request.role.adv"   => $env{'user.adv'},
 9881: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9882: 
 9883:         if ($form->{'localpath'}) {
 9884: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9885: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9886:         }
 9887: 	
 9888: 	if ($public) {
 9889: 	    $initial_env{"environment.remote"} = "off";
 9890: 	}
 9891: 	if ($form->{'interface'}) {
 9892: 	    $form->{'interface'}=~s/\W//gs;
 9893: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9894: 	    $env{'browser.interface'}=$form->{'interface'};
 9895: 	    foreach my $option ('imagesuppress','appletsuppress',
 9896: 				'embedsuppress','fontenhance','blackwhite') {
 9897: 		if (($form->{$option} eq 'true') ||
 9898: 		    ($userenv{$option} eq 'on')) {
 9899: 		    $initial_env{"browser.$option"} = "on";
 9900: 		}
 9901: 	    }
 9902: 	}
 9903: 
 9904:         foreach my $tool ('aboutme','blog','portfolio') {
 9905:             $userenv{'availabletools.'.$tool} = 
 9906:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9907:         }
 9908: 
 9909: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9910: 	
 9911: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9912: 		 &GDBM_WRCREAT(),0640)) {
 9913: 	    &_add_to_env(\%disk_env,\%initial_env);
 9914: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9915: 	    &_add_to_env(\%disk_env,$userroles);
 9916: 	    if (ref($args->{'extra_env'})) {
 9917: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9918: 	    }
 9919: 	    untie(%disk_env);
 9920: 	} else {
 9921: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
 9922: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
 9923: 	    return 'error: '.$!;
 9924: 	}
 9925:     }
 9926:     $env{'request.role'}='cm';
 9927:     $env{'request.role.adv'}=$env{'user.adv'};
 9928:     $env{'browser.type'}=$clientbrowser;
 9929: 
 9930:     return $cookie;
 9931: 
 9932: }
 9933: 
 9934: sub _add_to_env {
 9935:     my ($idf,$env_data,$prefix) = @_;
 9936:     if (ref($env_data) eq 'HASH') {
 9937:         while (my ($key,$value) = each(%$env_data)) {
 9938: 	    $idf->{$prefix.$key} = $value;
 9939: 	    $env{$prefix.$key}   = $value;
 9940:         }
 9941:     }
 9942: }
 9943: 
 9944: # --- Get the symbolic name of a problem and the url
 9945: sub get_symb {
 9946:     my ($request,$silent) = @_;
 9947:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9948:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9949:     if ($symb eq '') {
 9950:         if (!$silent) {
 9951:             $request->print("Unable to handle ambiguous references:$url:.");
 9952:             return ();
 9953:         }
 9954:     }
 9955:     &Apache::lonenc::check_decrypt(\$symb);
 9956:     return ($symb);
 9957: }
 9958: 
 9959: # --------------------------------------------------------------Get annotation
 9960: 
 9961: sub get_annotation {
 9962:     my ($symb,$enc) = @_;
 9963: 
 9964:     my $key = $symb;
 9965:     if (!$enc) {
 9966:         $key =
 9967:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9968:     }
 9969:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9970:     return $annotation{$key};
 9971: }
 9972: 
 9973: sub clean_symb {
 9974:     my ($symb,$delete_enc) = @_;
 9975: 
 9976:     &Apache::lonenc::check_decrypt(\$symb);
 9977:     my $enc = $env{'request.enc'};
 9978:     if ($delete_enc) {
 9979:         delete($env{'request.enc'});
 9980:     }
 9981: 
 9982:     return ($symb,$enc);
 9983: }
 9984: 
 9985: =pod
 9986: 
 9987: =back
 9988: 
 9989: =cut
 9990: 
 9991: 1;
 9992: __END__;
 9993: 

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