File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.783: download - view: text, annotated - select for diffs
Wed Apr 1 14:22:11 2009 UTC (15 years, 2 months ago) by amueller
Branches: MAIN
CVS tags: HEAD
fit the use of the style LC_MenuBreadcrumbs in the side Edit Course in purpose to be conform with the idea in using styles. LC_MenuBreadcrumbs is declared as an id style but was used twice on this page.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.783 2009/04/01 14:22:11 amueller Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410:     var stdeditbrowser;
  411:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  412:         var url = '/adm/pickstudent?';
  413:         var filter;
  414: 	if (!ignorefilter) {
  415: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  416: 	}
  417:         if (filter != null) {
  418:            if (filter != '') {
  419:                url += 'filter='+filter+'&';
  420: 	   }
  421:         }
  422:         url += 'form=' + formname + '&unameelement='+uname+
  423:                                     '&udomelement='+udom;
  424: 	if (roleflag) { url+="&roles=1"; }
  425:         var title = 'Student_Browser';
  426:         var options = 'scrollbars=1,resizable=1,menubar=0';
  427:         options += ',width=700,height=600';
  428:         stdeditbrowser = open(url,title,options,'1');
  429:         stdeditbrowser.focus();
  430:     }
  431: </script>
  432: ENDSTDBRW
  433: }
  434: 
  435: sub selectstudent_link {
  436:    my ($form,$unameele,$udomele)=@_;
  437:    if ($env{'request.course.id'}) {  
  438:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  439: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  440: 					'/'.$env{'request.course.sec'})) {
  441: 	   return '';
  442:        }
  443:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  444:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  445:    }
  446:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  447:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  448:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  449:    }
  450:    return '';
  451: }
  452: 
  453: sub authorbrowser_javascript {
  454:     return <<"ENDAUTHORBRW";
  455: <script type="text/javascript" language="JavaScript">
  456: var stdeditbrowser;
  457: 
  458: function openauthorbrowser(formname,udom) {
  459:     var url = '/adm/pickauthor?';
  460:     url += 'form='+formname+'&roledom='+udom;
  461:     var title = 'Author_Browser';
  462:     var options = 'scrollbars=1,resizable=1,menubar=0';
  463:     options += ',width=700,height=600';
  464:     stdeditbrowser = open(url,title,options,'1');
  465:     stdeditbrowser.focus();
  466: }
  467: 
  468: </script>
  469: ENDAUTHORBRW
  470: }
  471: 
  472: sub coursebrowser_javascript {
  473:     my ($domainfilter,$sec_element,$formname)=@_;
  474:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  475:    my $output = '
  476: <script type="text/javascript" language="JavaScript">
  477:     var stdeditbrowser;'."\n";
  478:    $output .= <<"ENDSTDBRW";
  479:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  480:         var url = '/adm/pickcourse?';
  481:         var domainfilter = '';
  482:         var formid = getFormIdByName(formname);
  483:         if (formid > -1) {
  484:             var domid = getIndexByName(formid,udom);
  485:             if (domid > -1) {
  486:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  487:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  488:                 }
  489:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  490:                     domainfilter=document.forms[formid].elements[domid].value;
  491:                 }
  492:             }
  493:         }
  494:         if (domainfilter != null) {
  495:            if (domainfilter != '') {
  496:                url += 'domainfilter='+domainfilter+'&';
  497: 	   }
  498:         }
  499:         url += 'form=' + formname + '&cnumelement='+uname+
  500: 	                            '&cdomelement='+udom+
  501:                                     '&cnameelement='+desc;
  502:         if (extra_element !=null && extra_element != '') {
  503:             if (formname == 'rolechoice' || formname == 'studentform') {
  504:                 url += '&roleelement='+extra_element;
  505:                 if (domainfilter == null || domainfilter == '') {
  506:                     url += '&domainfilter='+extra_element;
  507:                 }
  508:             }
  509:             else {
  510:                 if (formname == 'portform') {
  511:                     url += '&setroles='+extra_element;
  512:                 }
  513:             }     
  514:         }
  515:         if (multflag !=null && multflag != '') {
  516:             url += '&multiple='+multflag;
  517:         }
  518:         if (crstype == 'Course/Group') {
  519:             if (formname == 'cu') {
  520:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  521:                 if (crstype == "") {
  522:                     alert("$crs_or_grp_alert");
  523:                     return;
  524:                 }
  525:             }
  526:         }
  527:         if (crstype !=null && crstype != '') {
  528:             url += '&type='+crstype;
  529:         }
  530:         var title = 'Course_Browser';
  531:         var options = 'scrollbars=1,resizable=1,menubar=0';
  532:         options += ',width=700,height=600';
  533:         stdeditbrowser = open(url,title,options,'1');
  534:         stdeditbrowser.focus();
  535:     }
  536: 
  537:     function getFormIdByName(formname) {
  538:         for (var i=0;i<document.forms.length;i++) {
  539:             if (document.forms[i].name == formname) {
  540:                 return i;
  541:             }
  542:         }
  543:         return -1; 
  544:     }
  545: 
  546:     function getIndexByName(formid,item) {
  547:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  548:             if (document.forms[formid].elements[i].name == item) {
  549:                 return i;
  550:             }
  551:         }
  552:         return -1;
  553:     }
  554: ENDSTDBRW
  555:     if ($sec_element ne '') {
  556:         $output .= &setsec_javascript($sec_element,$formname);
  557:     }
  558:     $output .= '
  559: </script>';
  560:     return $output;
  561: }
  562: 
  563: sub setsec_javascript {
  564:     my ($sec_element,$formname) = @_;
  565:     my $setsections = qq|
  566: function setSect(sectionlist) {
  567:     var sectionsArray = new Array();
  568:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  569:         sectionsArray = sectionlist.split(",");
  570:     }
  571:     var numSections = sectionsArray.length;
  572:     document.$formname.$sec_element.length = 0;
  573:     if (numSections == 0) {
  574:         document.$formname.$sec_element.multiple=false;
  575:         document.$formname.$sec_element.size=1;
  576:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  577:     } else {
  578:         if (numSections == 1) {
  579:             document.$formname.$sec_element.multiple=false;
  580:             document.$formname.$sec_element.size=1;
  581:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  582:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  583:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  584:         } else {
  585:             for (var i=0; i<numSections; i++) {
  586:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  587:             }
  588:             document.$formname.$sec_element.multiple=true
  589:             if (numSections < 3) {
  590:                 document.$formname.$sec_element.size=numSections;
  591:             } else {
  592:                 document.$formname.$sec_element.size=3;
  593:             }
  594:             document.$formname.$sec_element.options[0].selected = false
  595:         }
  596:     }
  597: }
  598: |;
  599:     return $setsections;
  600: }
  601: 
  602: 
  603: sub selectcourse_link {
  604:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  605:    return "<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" language="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.='<span class="LC_help_open_topic">'
  928:                   .'<a target="_top" href="'.$link.'">'
  929:                   .$text.'</a>';
  930:     }
  931: 
  932:     # (Always) Add the graphic
  933:     my $title = &mt('Online Help');
  934:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  935:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  936:               .'<img src="'.$helpicon.'" border="0"'
  937:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  938:               .' title="'.$title.'"' 
  939:               .' /></a>';
  940:     if ($text ne "") {	
  941:         $template.='</span>';
  942:     }
  943:     return $template;
  944: 
  945: }
  946: 
  947: # This is a quicky function for Latex cheatsheet editing, since it 
  948: # appears in at least four places
  949: sub helpLatexCheatsheet {
  950:     my ($topic,$text,$not_author) = @_;
  951:     my $out;
  952:     my $addOther = '';
  953:     if ($topic) {
  954: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  955: 							       undef, undef, 600).
  956: 								   '</span> ';
  957:     }
  958:     $out = '<span>' # Start cheatsheet
  959: 	  .$addOther
  960:           .'<span>'
  961: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  962: 					       undef,undef,600)
  963: 	  .'</span> <span>'
  964: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  965: 					       undef,undef,600)
  966: 	  .'</span>';
  967:     unless ($not_author) {
  968:         $out .= ' <span>'
  969: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  970: 	                                            undef,undef,600)
  971: 	       .'</span>';
  972:     }
  973:     $out .= '</span>'; # End cheatsheet
  974:     return $out;
  975: }
  976: 
  977: sub general_help {
  978:     my $helptopic='Student_Intro';
  979:     if ($env{'request.role'}=~/^(ca|au)/) {
  980: 	$helptopic='Authoring_Intro';
  981:     } elsif ($env{'request.role'}=~/^cc/) {
  982: 	$helptopic='Course_Coordination_Intro';
  983:     } elsif ($env{'request.role'}=~/^dc/) {
  984:         $helptopic='Domain_Coordination_Intro';
  985:     }
  986:     return $helptopic;
  987: }
  988: 
  989: sub update_help_link {
  990:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  991:     my $origurl = $ENV{'REQUEST_URI'};
  992:     $origurl=~s|^/~|/priv/|;
  993:     my $timestamp = time;
  994:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  995:         $$datum = &escape($$datum);
  996:     }
  997: 
  998:     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";
  999:     my $output .= <<"ENDOUTPUT";
 1000: <script type="text/javascript">
 1001: banner_link = '$banner_link';
 1002: </script>
 1003: ENDOUTPUT
 1004:     return $output;
 1005: }
 1006: 
 1007: # now just updates the help link and generates a blue icon
 1008: sub help_open_menu {
 1009:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1010: 	= @_;    
 1011:     $stayOnPage = 0 if (not defined $stayOnPage);
 1012:     # only use pop-up help (stayOnPage == 0)
 1013:     # if environment.remote is on (using remote control UI)
 1014:     if ($env{'browser.interface'} eq 'textual' ||
 1015:     	$env{'environment.remote'} eq 'off' ) {
 1016:         $stayOnPage=1;
 1017:     }
 1018:     my $output;
 1019:     if ($component_help) {
 1020: 	if (!$text) {
 1021: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1022: 				       $width,$height);
 1023: 	} else {
 1024: 	    my $help_text;
 1025: 	    $help_text=&unescape($topic);
 1026: 	    $output='<table><tr><td>'.
 1027: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1028: 				 $width,$height).'</td></tr></table>';
 1029: 	}
 1030:     }
 1031:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1032:     return $output.$banner_link;
 1033: }
 1034: 
 1035: sub top_nav_help {
 1036:     my ($text) = @_;
 1037:     $text = &mt($text);
 1038:     my $stay_on_page = 
 1039: 	($env{'browser.interface'}  eq 'textual' ||
 1040: 	 $env{'environment.remote'} eq 'off' );
 1041:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1042: 	                     : "javascript:helpMenu('open')";
 1043:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1044: 
 1045:     my $title = &mt('Get help');
 1046: 
 1047:     return <<"END";
 1048: $banner_link
 1049:  <a href="$link" title="$title">$text</a>
 1050: END
 1051: }
 1052: 
 1053: sub help_menu_js {
 1054:     my ($text) = @_;
 1055: 
 1056:     my $stayOnPage = 
 1057: 	($env{'browser.interface'}  eq 'textual' ||
 1058: 	 $env{'environment.remote'} eq 'off' );
 1059: 
 1060:     my $width = 620;
 1061:     my $height = 600;
 1062:     my $helptopic=&general_help();
 1063:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1064:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1065:     my $start_page =
 1066:         &Apache::loncommon::start_page('Help Menu', undef,
 1067: 				       {'frameset'    => 1,
 1068: 					'js_ready'    => 1,
 1069: 					'add_entries' => {
 1070: 					    'border' => '0',
 1071: 					    'rows'   => "110,*",},});
 1072:     my $end_page =
 1073:         &Apache::loncommon::end_page({'frameset' => 1,
 1074: 				      'js_ready' => 1,});
 1075: 
 1076:     my $template .= <<"ENDTEMPLATE";
 1077: <script type="text/javascript">
 1078: // <!-- BEGIN LON-CAPA Internal
 1079: // <![CDATA[
 1080: var banner_link = '';
 1081: function helpMenu(target) {
 1082:     var caller = this;
 1083:     if (target == 'open') {
 1084:         var newWindow = null;
 1085:         try {
 1086:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1087:         }
 1088:         catch(error) {
 1089:             writeHelp(caller);
 1090:             return;
 1091:         }
 1092:         if (newWindow) {
 1093:             caller = newWindow;
 1094:         }
 1095:     }
 1096:     writeHelp(caller);
 1097:     return;
 1098: }
 1099: function writeHelp(caller) {
 1100:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1101:     caller.document.close()
 1102:     caller.focus()
 1103: }
 1104: // ]]>
 1105: // END LON-CAPA Internal -->
 1106: </script>
 1107: ENDTEMPLATE
 1108:     return $template;
 1109: }
 1110: 
 1111: sub help_open_bug {
 1112:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1113:     unless ($env{'user.adv'}) { return ''; }
 1114:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1115:     $text = "" if (not defined $text);
 1116:     $stayOnPage = 0 if (not defined $stayOnPage);
 1117:     if ($env{'browser.interface'} eq 'textual' ||
 1118: 	$env{'environment.remote'} eq 'off' ) {
 1119: 	$stayOnPage=1;
 1120:     }
 1121:     $width = 600 if (not defined $width);
 1122:     $height = 600 if (not defined $height);
 1123: 
 1124:     $topic=~s/\W+/\+/g;
 1125:     my $link='';
 1126:     my $template='';
 1127:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1128: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1129:     if (!$stayOnPage)
 1130:     {
 1131: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1132:     }
 1133:     else
 1134:     {
 1135: 	$link = $url;
 1136:     }
 1137:     # Add the text
 1138:     if ($text ne "")
 1139:     {
 1140: 	$template .= 
 1141:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1142:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1143:     }
 1144: 
 1145:     # Add the graphic
 1146:     my $title = &mt('Report a Bug');
 1147:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1148:     $template .= <<"ENDTEMPLATE";
 1149:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1150: ENDTEMPLATE
 1151:     if ($text ne '') { $template.='</td></tr></table>' };
 1152:     return $template;
 1153: 
 1154: }
 1155: 
 1156: sub help_open_faq {
 1157:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1158:     unless ($env{'user.adv'}) { return ''; }
 1159:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1160:     $text = "" if (not defined $text);
 1161:     $stayOnPage = 0 if (not defined $stayOnPage);
 1162:     if ($env{'browser.interface'} eq 'textual' ||
 1163: 	$env{'environment.remote'} eq 'off' ) {
 1164: 	$stayOnPage=1;
 1165:     }
 1166:     $width = 350 if (not defined $width);
 1167:     $height = 400 if (not defined $height);
 1168: 
 1169:     $topic=~s/\W+/\+/g;
 1170:     my $link='';
 1171:     my $template='';
 1172:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1173:     if (!$stayOnPage)
 1174:     {
 1175: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1176:     }
 1177:     else
 1178:     {
 1179: 	$link = $url;
 1180:     }
 1181: 
 1182:     # Add the text
 1183:     if ($text ne "")
 1184:     {
 1185: 	$template .= 
 1186:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1187:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1188:     }
 1189: 
 1190:     # Add the graphic
 1191:     my $title = &mt('View the FAQ');
 1192:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1193:     $template .= <<"ENDTEMPLATE";
 1194:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1195: ENDTEMPLATE
 1196:     if ($text ne '') { $template.='</td></tr></table>' };
 1197:     return $template;
 1198: 
 1199: }
 1200: 
 1201: ###############################################################
 1202: ###############################################################
 1203: 
 1204: =pod
 1205: 
 1206: =item * &change_content_javascript():
 1207: 
 1208: This and the next function allow you to create small sections of an
 1209: otherwise static HTML page that you can update on the fly with
 1210: Javascript, even in Netscape 4.
 1211: 
 1212: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1213: must be written to the HTML page once. It will prove the Javascript
 1214: function "change(name, content)". Calling the change function with the
 1215: name of the section 
 1216: you want to update, matching the name passed to C<changable_area>, and
 1217: the new content you want to put in there, will put the content into
 1218: that area.
 1219: 
 1220: B<Note>: Netscape 4 only reserves enough space for the changable area
 1221: to contain room for the original contents. You need to "make space"
 1222: for whatever changes you wish to make, and be B<sure> to check your
 1223: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1224: it's adequate for updating a one-line status display, but little more.
 1225: This script will set the space to 100% width, so you only need to
 1226: worry about height in Netscape 4.
 1227: 
 1228: Modern browsers are much less limiting, and if you can commit to the
 1229: user not using Netscape 4, this feature may be used freely with
 1230: pretty much any HTML.
 1231: 
 1232: =cut
 1233: 
 1234: sub change_content_javascript {
 1235:     # If we're on Netscape 4, we need to use Layer-based code
 1236:     if ($env{'browser.type'} eq 'netscape' &&
 1237: 	$env{'browser.version'} =~ /^4\./) {
 1238: 	return (<<NETSCAPE4);
 1239: 	function change(name, content) {
 1240: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1241: 	    doc.open();
 1242: 	    doc.write(content);
 1243: 	    doc.close();
 1244: 	}
 1245: NETSCAPE4
 1246:     } else {
 1247: 	# Otherwise, we need to use semi-standards-compliant code
 1248: 	# (technically, "innerHTML" isn't standard but the equivalent
 1249: 	# is really scary, and every useful browser supports it
 1250: 	return (<<DOMBASED);
 1251: 	function change(name, content) {
 1252: 	    element = document.getElementById(name);
 1253: 	    element.innerHTML = content;
 1254: 	}
 1255: DOMBASED
 1256:     }
 1257: }
 1258: 
 1259: =pod
 1260: 
 1261: =item * &changable_area($name,$origContent):
 1262: 
 1263: This provides a "changable area" that can be modified on the fly via
 1264: the Javascript code provided in C<change_content_javascript>. $name is
 1265: the name you will use to reference the area later; do not repeat the
 1266: same name on a given HTML page more then once. $origContent is what
 1267: the area will originally contain, which can be left blank.
 1268: 
 1269: =cut
 1270: 
 1271: sub changable_area {
 1272:     my ($name, $origContent) = @_;
 1273: 
 1274:     if ($env{'browser.type'} eq 'netscape' &&
 1275: 	$env{'browser.version'} =~ /^4\./) {
 1276: 	# If this is netscape 4, we need to use the Layer tag
 1277: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1278:     } else {
 1279: 	return "<span id='$name'>$origContent</span>";
 1280:     }
 1281: }
 1282: 
 1283: =pod
 1284: 
 1285: =item * &viewport_geometry_js 
 1286: 
 1287: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1288: 
 1289: =cut
 1290: 
 1291: 
 1292: sub viewport_geometry_js { 
 1293:     return <<"GEOMETRY";
 1294: var Geometry = {};
 1295: function init_geometry() {
 1296:     if (Geometry.init) { return };
 1297:     Geometry.init=1;
 1298:     if (window.innerHeight) {
 1299:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1300:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1301:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1302:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1303:     }
 1304:     else if (document.documentElement && document.documentElement.clientHeight) {
 1305:         Geometry.getViewportHeight =
 1306:             function() { return document.documentElement.clientHeight; };
 1307:         Geometry.getViewportWidth =
 1308:             function() { return document.documentElement.clientWidth; };
 1309: 
 1310:         Geometry.getHorizontalScroll =
 1311:             function() { return document.documentElement.scrollLeft; };
 1312:         Geometry.getVerticalScroll =
 1313:             function() { return document.documentElement.scrollTop; };
 1314:     }
 1315:     else if (document.body.clientHeight) {
 1316:         Geometry.getViewportHeight =
 1317:             function() { return document.body.clientHeight; };
 1318:         Geometry.getViewportWidth =
 1319:             function() { return document.body.clientWidth; };
 1320:         Geometry.getHorizontalScroll =
 1321:             function() { return document.body.scrollLeft; };
 1322:         Geometry.getVerticalScroll =
 1323:             function() { return document.body.scrollTop; };
 1324:     }
 1325: }
 1326: 
 1327: GEOMETRY
 1328: }
 1329: 
 1330: =pod
 1331: 
 1332: =item * &viewport_size_js()
 1333: 
 1334: 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. 
 1335: 
 1336: =cut
 1337: 
 1338: sub viewport_size_js {
 1339:     my $geometry = &viewport_geometry_js();
 1340:     return <<"DIMS";
 1341: 
 1342: $geometry
 1343: 
 1344: function getViewportDims(width,height) {
 1345:     init_geometry();
 1346:     width.value = Geometry.getViewportWidth();
 1347:     height.value = Geometry.getViewportHeight();
 1348:     return;
 1349: }
 1350: 
 1351: DIMS
 1352: }
 1353: 
 1354: =pod
 1355: 
 1356: =item * &resize_textarea_js()
 1357: 
 1358: emits the needed javascript to resize a textarea to be as big as possible
 1359: 
 1360: creates a function resize_textrea that takes two IDs first should be
 1361: the id of the element to resize, second should be the id of a div that
 1362: surrounds everything that comes after the textarea, this routine needs
 1363: to be attached to the <body> for the onload and onresize events.
 1364: 
 1365: =back
 1366: 
 1367: =cut
 1368: 
 1369: sub resize_textarea_js {
 1370:     my $geometry = &viewport_geometry_js();
 1371:     return <<"RESIZE";
 1372:     <script type="text/javascript">
 1373: $geometry
 1374: 
 1375: function getX(element) {
 1376:     var x = 0;
 1377:     while (element) {
 1378: 	x += element.offsetLeft;
 1379: 	element = element.offsetParent;
 1380:     }
 1381:     return x;
 1382: }
 1383: function getY(element) {
 1384:     var y = 0;
 1385:     while (element) {
 1386: 	y += element.offsetTop;
 1387: 	element = element.offsetParent;
 1388:     }
 1389:     return y;
 1390: }
 1391: 
 1392: 
 1393: function resize_textarea(textarea_id,bottom_id) {
 1394:     init_geometry();
 1395:     var textarea        = document.getElementById(textarea_id);
 1396:     //alert(textarea);
 1397: 
 1398:     var textarea_top    = getY(textarea);
 1399:     var textarea_height = textarea.offsetHeight;
 1400:     var bottom          = document.getElementById(bottom_id);
 1401:     var bottom_top      = getY(bottom);
 1402:     var bottom_height   = bottom.offsetHeight;
 1403:     var window_height   = Geometry.getViewportHeight();
 1404:     var fudge           = 23;
 1405:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1406:     if (new_height < 300) {
 1407: 	new_height = 300;
 1408:     }
 1409:     textarea.style.height=new_height+'px';
 1410: }
 1411: </script>
 1412: RESIZE
 1413: 
 1414: }
 1415: 
 1416: =pod
 1417: 
 1418: =head1 Excel and CSV file utility routines
 1419: 
 1420: =over 4
 1421: 
 1422: =cut
 1423: 
 1424: ###############################################################
 1425: ###############################################################
 1426: 
 1427: =pod
 1428: 
 1429: =item * &csv_translate($text) 
 1430: 
 1431: Translate $text to allow it to be output as a 'comma separated values' 
 1432: format.
 1433: 
 1434: =cut
 1435: 
 1436: ###############################################################
 1437: ###############################################################
 1438: sub csv_translate {
 1439:     my $text = shift;
 1440:     $text =~ s/\"/\"\"/g;
 1441:     $text =~ s/\n/ /g;
 1442:     return $text;
 1443: }
 1444: 
 1445: ###############################################################
 1446: ###############################################################
 1447: 
 1448: =pod
 1449: 
 1450: =item * &define_excel_formats()
 1451: 
 1452: Define some commonly used Excel cell formats.
 1453: 
 1454: Currently supported formats:
 1455: 
 1456: =over 4
 1457: 
 1458: =item header
 1459: 
 1460: =item bold
 1461: 
 1462: =item h1
 1463: 
 1464: =item h2
 1465: 
 1466: =item h3
 1467: 
 1468: =item h4
 1469: 
 1470: =item i
 1471: 
 1472: =item date
 1473: 
 1474: =back
 1475: 
 1476: Inputs: $workbook
 1477: 
 1478: Returns: $format, a hash reference.
 1479: 
 1480: =cut
 1481: 
 1482: ###############################################################
 1483: ###############################################################
 1484: sub define_excel_formats {
 1485:     my ($workbook) = @_;
 1486:     my $format;
 1487:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1488:                                                 bottom    => 1,
 1489:                                                 align     => 'center');
 1490:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1491:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1492:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1493:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1494:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1495:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1496:     $format->{'date'} = $workbook->add_format(num_format=>
 1497:                                             'mm/dd/yyyy hh:mm:ss');
 1498:     return $format;
 1499: }
 1500: 
 1501: ###############################################################
 1502: ###############################################################
 1503: 
 1504: =pod
 1505: 
 1506: =item * &create_workbook()
 1507: 
 1508: Create an Excel worksheet.  If it fails, output message on the
 1509: request object and return undefs.
 1510: 
 1511: Inputs: Apache request object
 1512: 
 1513: Returns (undef) on failure, 
 1514:     Excel worksheet object, scalar with filename, and formats 
 1515:     from &Apache::loncommon::define_excel_formats on success
 1516: 
 1517: =cut
 1518: 
 1519: ###############################################################
 1520: ###############################################################
 1521: sub create_workbook {
 1522:     my ($r) = @_;
 1523:         #
 1524:     # Create the excel spreadsheet
 1525:     my $filename = '/prtspool/'.
 1526:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1527:         time.'_'.rand(1000000000).'.xls';
 1528:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1529:     if (! defined($workbook)) {
 1530:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1531:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1532:                             "This error has been logged.  ".
 1533:                             "Please alert your LON-CAPA administrator").
 1534:                   '</p>');
 1535:         return (undef);
 1536:     }
 1537:     #
 1538:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1539:     #
 1540:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1541:     return ($workbook,$filename,$format);
 1542: }
 1543: 
 1544: ###############################################################
 1545: ###############################################################
 1546: 
 1547: =pod
 1548: 
 1549: =item * &create_text_file()
 1550: 
 1551: Create a file to write to and eventually make available to the user.
 1552: If file creation fails, outputs an error message on the request object and 
 1553: return undefs.
 1554: 
 1555: Inputs: Apache request object, and file suffix
 1556: 
 1557: Returns (undef) on failure, 
 1558:     Filehandle and filename on success.
 1559: 
 1560: =cut
 1561: 
 1562: ###############################################################
 1563: ###############################################################
 1564: sub create_text_file {
 1565:     my ($r,$suffix) = @_;
 1566:     if (! defined($suffix)) { $suffix = 'txt'; };
 1567:     my $fh;
 1568:     my $filename = '/prtspool/'.
 1569:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1570:         time.'_'.rand(1000000000).'.'.$suffix;
 1571:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1572:     if (! defined($fh)) {
 1573:         $r->log_error("Couldn't open $filename for output $!");
 1574:         $r->print(&mt('Problems occurred in creating the output file. '
 1575:                      .'This error has been logged. '
 1576:                      .'Please alert your LON-CAPA administrator.'));
 1577:     }
 1578:     return ($fh,$filename)
 1579: }
 1580: 
 1581: 
 1582: =pod 
 1583: 
 1584: =back
 1585: 
 1586: =cut
 1587: 
 1588: ###############################################################
 1589: ##        Home server <option> list generating code          ##
 1590: ###############################################################
 1591: 
 1592: # ------------------------------------------
 1593: 
 1594: sub domain_select {
 1595:     my ($name,$value,$multiple)=@_;
 1596:     my %domains=map { 
 1597: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1598:     } &Apache::lonnet::all_domains();
 1599:     if ($multiple) {
 1600: 	$domains{''}=&mt('Any domain');
 1601: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1602: 	return &multiple_select_form($name,$value,4,\%domains);
 1603:     } else {
 1604: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1605: 	return &select_form($name,$value,%domains);
 1606:     }
 1607: }
 1608: 
 1609: #-------------------------------------------
 1610: 
 1611: =pod
 1612: 
 1613: =head1 Routines for form select boxes
 1614: 
 1615: =over 4
 1616: 
 1617: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1618: 
 1619: Returns a string containing a <select> element int multiple mode
 1620: 
 1621: 
 1622: Args:
 1623:   $name - name of the <select> element
 1624:   $value - scalar or array ref of values that should already be selected
 1625:   $size - number of rows long the select element is
 1626:   $hash - the elements should be 'option' => 'shown text'
 1627:           (shown text should already have been &mt())
 1628:   $order - (optional) array ref of the order to show the elements in
 1629: 
 1630: =cut
 1631: 
 1632: #-------------------------------------------
 1633: sub multiple_select_form {
 1634:     my ($name,$value,$size,$hash,$order)=@_;
 1635:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1636:     my $output='';
 1637:     if (! defined($size)) {
 1638:         $size = 4;
 1639:         if (scalar(keys(%$hash))<4) {
 1640:             $size = scalar(keys(%$hash));
 1641:         }
 1642:     }
 1643:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1644:     my @order;
 1645:     if (ref($order) eq 'ARRAY')  {
 1646:         @order = @{$order};
 1647:     } else {
 1648:         @order = sort(keys(%$hash));
 1649:     }
 1650:     if (exists($$hash{'select_form_order'})) {
 1651:         @order = @{$$hash{'select_form_order'}};
 1652:     }
 1653:         
 1654:     foreach my $key (@order) {
 1655:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1656:         $output.='selected="selected" ' if ($selected{$key});
 1657:         $output.='>'.$hash->{$key}."</option>\n";
 1658:     }
 1659:     $output.="</select>\n";
 1660:     return $output;
 1661: }
 1662: 
 1663: #-------------------------------------------
 1664: 
 1665: =pod
 1666: 
 1667: =item * &select_form($defdom,$name,%hash)
 1668: 
 1669: Returns a string containing a <select name='$name' size='1'> form to 
 1670: allow a user to select options from a hash option_name => displayed text.  
 1671: See lonrights.pm for an example invocation and use.
 1672: 
 1673: =cut
 1674: 
 1675: #-------------------------------------------
 1676: sub select_form {
 1677:     my ($def,$name,%hash) = @_;
 1678:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1679:     my @keys;
 1680:     if (exists($hash{'select_form_order'})) {
 1681: 	@keys=@{$hash{'select_form_order'}};
 1682:     } else {
 1683: 	@keys=sort(keys(%hash));
 1684:     }
 1685:     foreach my $key (@keys) {
 1686:         $selectform.=
 1687: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1688:             ($key eq $def ? 'selected="selected" ' : '').
 1689:                 ">".&mt($hash{$key})."</option>\n";
 1690:     }
 1691:     $selectform.="</select>";
 1692:     return $selectform;
 1693: }
 1694: 
 1695: # For display filters
 1696: 
 1697: sub display_filter {
 1698:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1699:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1700:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1701: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1702: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1703: 	   '</label></span> <span class="LC_nobreak">'.
 1704:            &mt('Filter [_1]',
 1705: 	   &select_form($env{'form.displayfilter'},
 1706: 			'displayfilter',
 1707: 			('currentfolder' => 'Current folder/page',
 1708: 			 'containing' => 'Containing phrase',
 1709: 			 'none' => 'None'))).
 1710: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1711: }
 1712: 
 1713: sub gradeleveldescription {
 1714:     my $gradelevel=shift;
 1715:     my %gradelevels=(0 => 'Not specified',
 1716: 		     1 => 'Grade 1',
 1717: 		     2 => 'Grade 2',
 1718: 		     3 => 'Grade 3',
 1719: 		     4 => 'Grade 4',
 1720: 		     5 => 'Grade 5',
 1721: 		     6 => 'Grade 6',
 1722: 		     7 => 'Grade 7',
 1723: 		     8 => 'Grade 8',
 1724: 		     9 => 'Grade 9',
 1725: 		     10 => 'Grade 10',
 1726: 		     11 => 'Grade 11',
 1727: 		     12 => 'Grade 12',
 1728: 		     13 => 'Grade 13',
 1729: 		     14 => '100 Level',
 1730: 		     15 => '200 Level',
 1731: 		     16 => '300 Level',
 1732: 		     17 => '400 Level',
 1733: 		     18 => 'Graduate Level');
 1734:     return &mt($gradelevels{$gradelevel});
 1735: }
 1736: 
 1737: sub select_level_form {
 1738:     my ($deflevel,$name)=@_;
 1739:     unless ($deflevel) { $deflevel=0; }
 1740:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1741:     for (my $i=0; $i<=18; $i++) {
 1742:         $selectform.="<option value=\"$i\" ".
 1743:             ($i==$deflevel ? 'selected="selected" ' : '').
 1744:                 ">".&gradeleveldescription($i)."</option>\n";
 1745:     }
 1746:     $selectform.="</select>";
 1747:     return $selectform;
 1748: }
 1749: 
 1750: #-------------------------------------------
 1751: 
 1752: =pod
 1753: 
 1754: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1755: 
 1756: Returns a string containing a <select name='$name' size='1'> form to 
 1757: allow a user to select the domain to preform an operation in.  
 1758: See loncreateuser.pm for an example invocation and use.
 1759: 
 1760: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1761: selected");
 1762: 
 1763: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1764: 
 1765: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1766: 
 1767: =cut
 1768: 
 1769: #-------------------------------------------
 1770: sub select_dom_form {
 1771:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1772:     my $onchange;
 1773:     if ($autosubmit) {
 1774:         $onchange = ' onchange="this.form.submit()"';
 1775:     }
 1776:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1777:     if ($includeempty) { @domains=('',@domains); }
 1778:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1779:     foreach my $dom (@domains) {
 1780:         $selectdomain.="<option value=\"$dom\" ".
 1781:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1782:         if ($showdomdesc) {
 1783:             if ($dom ne '') {
 1784:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1785:                 if ($domdesc ne '') {
 1786:                     $selectdomain .= ' ('.$domdesc.')';
 1787:                 }
 1788:             } 
 1789:         }
 1790:         $selectdomain .= "</option>\n";
 1791:     }
 1792:     $selectdomain.="</select>";
 1793:     return $selectdomain;
 1794: }
 1795: 
 1796: #-------------------------------------------
 1797: 
 1798: =pod
 1799: 
 1800: =item * &home_server_form_item($domain,$name,$defaultflag)
 1801: 
 1802: input: 4 arguments (two required, two optional) - 
 1803:     $domain - domain of new user
 1804:     $name - name of form element
 1805:     $default - Value of 'default' causes a default item to be first 
 1806:                             option, and selected by default. 
 1807:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1808:                             if 1 server found, or default, if 0 found.
 1809: output: returns 2 items: 
 1810: (a) form element which contains either:
 1811:    (i) <select name="$name">
 1812:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1813:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1814:        </select>
 1815:        form item if there are multiple library servers in $domain, or
 1816:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1817:        if there is only one library server in $domain.
 1818: 
 1819: (b) number of library servers found.
 1820: 
 1821: See loncreateuser.pm for example of use.
 1822: 
 1823: =cut
 1824: 
 1825: #-------------------------------------------
 1826: sub home_server_form_item {
 1827:     my ($domain,$name,$default,$hide) = @_;
 1828:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1829:     my $result;
 1830:     my $numlib = keys(%servers);
 1831:     if ($numlib > 1) {
 1832:         $result .= '<select name="'.$name.'" />'."\n";
 1833:         if ($default) {
 1834:             $result .= '<option value="default" selected>'.&mt('default').
 1835:                        '</option>'."\n";
 1836:         }
 1837:         foreach my $hostid (sort(keys(%servers))) {
 1838:             $result.= '<option value="'.$hostid.'">'.
 1839: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1840:         }
 1841:         $result .= '</select>'."\n";
 1842:     } elsif ($numlib == 1) {
 1843:         my $hostid;
 1844:         foreach my $item (keys(%servers)) {
 1845:             $hostid = $item;
 1846:         }
 1847:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1848:                    $hostid.'" />';
 1849:                    if (!$hide) {
 1850:                        $result .= $hostid.' '.$servers{$hostid};
 1851:                    }
 1852:                    $result .= "\n";
 1853:     } elsif ($default) {
 1854:         $result .= '<input type="hidden" name="'.$name.
 1855:                    '" value="default" />';
 1856:                    if (!$hide) {
 1857:                        $result .= &mt('default');
 1858:                    }
 1859:                    $result .= "\n";
 1860:     }
 1861:     return ($result,$numlib);
 1862: }
 1863: 
 1864: =pod
 1865: 
 1866: =back 
 1867: 
 1868: =cut
 1869: 
 1870: ###############################################################
 1871: ##                  Decoding User Agent                      ##
 1872: ###############################################################
 1873: 
 1874: =pod
 1875: 
 1876: =head1 Decoding the User Agent
 1877: 
 1878: =over 4
 1879: 
 1880: =item * &decode_user_agent()
 1881: 
 1882: Inputs: $r
 1883: 
 1884: Outputs:
 1885: 
 1886: =over 4
 1887: 
 1888: =item * $httpbrowser
 1889: 
 1890: =item * $clientbrowser
 1891: 
 1892: =item * $clientversion
 1893: 
 1894: =item * $clientmathml
 1895: 
 1896: =item * $clientunicode
 1897: 
 1898: =item * $clientos
 1899: 
 1900: =back
 1901: 
 1902: =back 
 1903: 
 1904: =cut
 1905: 
 1906: ###############################################################
 1907: ###############################################################
 1908: sub decode_user_agent {
 1909:     my ($r)=@_;
 1910:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1911:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1912:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1913:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1914:     my $clientbrowser='unknown';
 1915:     my $clientversion='0';
 1916:     my $clientmathml='';
 1917:     my $clientunicode='0';
 1918:     for (my $i=0;$i<=$#browsertype;$i++) {
 1919:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1920: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1921: 	    $clientbrowser=$bname;
 1922:             $httpbrowser=~/$vreg/i;
 1923: 	    $clientversion=$1;
 1924:             $clientmathml=($clientversion>=$minv);
 1925:             $clientunicode=($clientversion>=$univ);
 1926: 	}
 1927:     }
 1928:     my $clientos='unknown';
 1929:     if (($httpbrowser=~/linux/i) ||
 1930:         ($httpbrowser=~/unix/i) ||
 1931:         ($httpbrowser=~/ux/i) ||
 1932:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1933:     if (($httpbrowser=~/vax/i) ||
 1934:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1935:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1936:     if (($httpbrowser=~/mac/i) ||
 1937:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1938:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1939:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1940:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1941:             $clientunicode,$clientos,);
 1942: }
 1943: 
 1944: ###############################################################
 1945: ##    Authentication changing form generation subroutines    ##
 1946: ###############################################################
 1947: ##
 1948: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1949: ## hash, and have reasonable default values.
 1950: ##
 1951: ##    formname = the name given in the <form> tag.
 1952: #-------------------------------------------
 1953: 
 1954: =pod
 1955: 
 1956: =head1 Authentication Routines
 1957: 
 1958: =over 4
 1959: 
 1960: =item * &authform_xxxxxx()
 1961: 
 1962: The authform_xxxxxx subroutines provide javascript and html forms which 
 1963: handle some of the conveniences required for authentication forms.  
 1964: This is not an optimal method, but it works.  
 1965: 
 1966: =over 4
 1967: 
 1968: =item * authform_header
 1969: 
 1970: =item * authform_authorwarning
 1971: 
 1972: =item * authform_nochange
 1973: 
 1974: =item * authform_kerberos
 1975: 
 1976: =item * authform_internal
 1977: 
 1978: =item * authform_filesystem
 1979: 
 1980: =back
 1981: 
 1982: See loncreateuser.pm for invocation and use examples.
 1983: 
 1984: =cut
 1985: 
 1986: #-------------------------------------------
 1987: sub authform_header{  
 1988:     my %in = (
 1989:         formname => 'cu',
 1990:         kerb_def_dom => '',
 1991:         @_,
 1992:     );
 1993:     $in{'formname'} = 'document.' . $in{'formname'};
 1994:     my $result='';
 1995: 
 1996: #---------------------------------------------- Code for upper case translation
 1997:     my $Javascript_toUpperCase;
 1998:     unless ($in{kerb_def_dom}) {
 1999:         $Javascript_toUpperCase =<<"END";
 2000:         switch (choice) {
 2001:            case 'krb': currentform.elements[choicearg].value =
 2002:                currentform.elements[choicearg].value.toUpperCase();
 2003:                break;
 2004:            default:
 2005:         }
 2006: END
 2007:     } else {
 2008:         $Javascript_toUpperCase = "";
 2009:     }
 2010: 
 2011:     my $radioval = "'nochange'";
 2012:     if (defined($in{'curr_authtype'})) {
 2013:         if ($in{'curr_authtype'} ne '') {
 2014:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2015:         }
 2016:     }
 2017:     my $argfield = 'null';
 2018:     if (defined($in{'mode'})) {
 2019:         if ($in{'mode'} eq 'modifycourse')  {
 2020:             if (defined($in{'curr_autharg'})) {
 2021:                 if ($in{'curr_autharg'} ne '') {
 2022:                     $argfield = "'$in{'curr_autharg'}'";
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027: 
 2028:     $result.=<<"END";
 2029: var current = new Object();
 2030: current.radiovalue = $radioval;
 2031: current.argfield = $argfield;
 2032: 
 2033: function changed_radio(choice,currentform) {
 2034:     var choicearg = choice + 'arg';
 2035:     // If a radio button in changed, we need to change the argfield
 2036:     if (current.radiovalue != choice) {
 2037:         current.radiovalue = choice;
 2038:         if (current.argfield != null) {
 2039:             currentform.elements[current.argfield].value = '';
 2040:         }
 2041:         if (choice == 'nochange') {
 2042:             current.argfield = null;
 2043:         } else {
 2044:             current.argfield = choicearg;
 2045:             switch(choice) {
 2046:                 case 'krb': 
 2047:                     currentform.elements[current.argfield].value = 
 2048:                         "$in{'kerb_def_dom'}";
 2049:                 break;
 2050:               default:
 2051:                 break;
 2052:             }
 2053:         }
 2054:     }
 2055:     return;
 2056: }
 2057: 
 2058: function changed_text(choice,currentform) {
 2059:     var choicearg = choice + 'arg';
 2060:     if (currentform.elements[choicearg].value !='') {
 2061:         $Javascript_toUpperCase
 2062:         // clear old field
 2063:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2064:             currentform.elements[current.argfield].value = '';
 2065:         }
 2066:         current.argfield = choicearg;
 2067:     }
 2068:     set_auth_radio_buttons(choice,currentform);
 2069:     return;
 2070: }
 2071: 
 2072: function set_auth_radio_buttons(newvalue,currentform) {
 2073:     var i=0;
 2074:     while (i < currentform.login.length) {
 2075:         if (currentform.login[i].value == newvalue) { break; }
 2076:         i++;
 2077:     }
 2078:     if (i == currentform.login.length) {
 2079:         return;
 2080:     }
 2081:     current.radiovalue = newvalue;
 2082:     currentform.login[i].checked = true;
 2083:     return;
 2084: }
 2085: END
 2086:     return $result;
 2087: }
 2088: 
 2089: sub authform_authorwarning{
 2090:     my $result='';
 2091:     $result='<i>'.
 2092:         &mt('As a general rule, only authors or co-authors should be '.
 2093:             'filesystem authenticated '.
 2094:             '(which allows access to the server filesystem).')."</i>\n";
 2095:     return $result;
 2096: }
 2097: 
 2098: sub authform_nochange{  
 2099:     my %in = (
 2100:               formname => 'document.cu',
 2101:               kerb_def_dom => 'MSU.EDU',
 2102:               @_,
 2103:           );
 2104:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2105:     my $result;
 2106:     if (keys(%can_assign) == 0) {
 2107:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2108:     } else {
 2109:         $result = '<label>'.&mt('[_1] Do not change login data',
 2110:                   '<input type="radio" name="login" value="nochange" '.
 2111:                   'checked="checked" onclick="'.
 2112:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2113: 	    '</label>';
 2114:     }
 2115:     return $result;
 2116: }
 2117: 
 2118: sub authform_kerberos {
 2119:     my %in = (
 2120:               formname => 'document.cu',
 2121:               kerb_def_dom => 'MSU.EDU',
 2122:               kerb_def_auth => 'krb4',
 2123:               @_,
 2124:               );
 2125:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2126:         $autharg,$jscall);
 2127:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2128:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2129:        $check5 = ' checked="checked"';
 2130:     } else {
 2131:        $check4 = ' checked="checked"';
 2132:     }
 2133:     $krbarg = $in{'kerb_def_dom'};
 2134:     if (defined($in{'curr_authtype'})) {
 2135:         if ($in{'curr_authtype'} eq 'krb') {
 2136:             $krbcheck = ' checked="checked"';
 2137:             if (defined($in{'mode'})) {
 2138:                 if ($in{'mode'} eq 'modifyuser') {
 2139:                     $krbcheck = '';
 2140:                 }
 2141:             }
 2142:             if (defined($in{'curr_kerb_ver'})) {
 2143:                 if ($in{'curr_krb_ver'} eq '5') {
 2144:                     $check5 = ' checked="checked"';
 2145:                     $check4 = '';
 2146:                 } else {
 2147:                     $check4 = ' checked="checked"';
 2148:                     $check5 = '';
 2149:                 }
 2150:             }
 2151:             if (defined($in{'curr_autharg'})) {
 2152:                 $krbarg = $in{'curr_autharg'};
 2153:             }
 2154:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2155:                 if (defined($in{'curr_autharg'})) {
 2156:                     $result = 
 2157:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2158:         $in{'curr_autharg'},$krbver);
 2159:                 } else {
 2160:                     $result =
 2161:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2162:                 }
 2163:                 return $result; 
 2164:             }
 2165:         }
 2166:     } else {
 2167:         if ($authnum == 1) {
 2168:             $authtype = '<input type="hidden" name="login" value="krb">';
 2169:         }
 2170:     }
 2171:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2172:         return;
 2173:     } elsif ($authtype eq '') {
 2174:         if (defined($in{'mode'})) {
 2175:             if ($in{'mode'} eq 'modifycourse') {
 2176:                 if ($authnum == 1) {
 2177:                     $authtype = '<input type="hidden" name="login" value="krb">';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2183:     if ($authtype eq '') {
 2184:         $authtype = '<input type="radio" name="login" value="krb" '.
 2185:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2186:                     $krbcheck.' />';
 2187:     }
 2188:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2189:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2190:          $in{'curr_authtype'} eq 'krb5') ||
 2191:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2192:          $in{'curr_authtype'} eq 'krb4')) {
 2193:         $result .= &mt
 2194:         ('[_1] Kerberos authenticated with domain [_2] '.
 2195:          '[_3] Version 4 [_4] Version 5 [_5]',
 2196:          '<label>'.$authtype,
 2197:          '</label><input type="text" size="10" name="krbarg" '.
 2198:              'value="'.$krbarg.'" '.
 2199:              'onchange="'.$jscall.'" />',
 2200:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2201:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2202: 	 '</label>');
 2203:     } elsif ($can_assign{'krb4'}) {
 2204:         $result .= &mt
 2205:         ('[_1] Kerberos authenticated with domain [_2] '.
 2206:          '[_3] Version 4 [_4]',
 2207:          '<label>'.$authtype,
 2208:          '</label><input type="text" size="10" name="krbarg" '.
 2209:              'value="'.$krbarg.'" '.
 2210:              'onchange="'.$jscall.'" />',
 2211:          '<label><input type="hidden" name="krbver" value="4" />',
 2212:          '</label>');
 2213:     } elsif ($can_assign{'krb5'}) {
 2214:         $result .= &mt
 2215:         ('[_1] Kerberos authenticated with domain [_2] '.
 2216:          '[_3] Version 5 [_4]',
 2217:          '<label>'.$authtype,
 2218:          '</label><input type="text" size="10" name="krbarg" '.
 2219:              'value="'.$krbarg.'" '.
 2220:              'onchange="'.$jscall.'" />',
 2221:          '<label><input type="hidden" name="krbver" value="5" />',
 2222:          '</label>');
 2223:     }
 2224:     return $result;
 2225: }
 2226: 
 2227: sub authform_internal{  
 2228:     my %in = (
 2229:                 formname => 'document.cu',
 2230:                 kerb_def_dom => 'MSU.EDU',
 2231:                 @_,
 2232:                 );
 2233:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2234:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2235:     if (defined($in{'curr_authtype'})) {
 2236:         if ($in{'curr_authtype'} eq 'int') {
 2237:             if ($can_assign{'int'}) {
 2238:                 $intcheck = 'checked="checked" ';
 2239:                 if (defined($in{'mode'})) {
 2240:                     if ($in{'mode'} eq 'modifyuser') {
 2241:                         $intcheck = '';
 2242:                     }
 2243:                 }
 2244:                 if (defined($in{'curr_autharg'})) {
 2245:                     $intarg = $in{'curr_autharg'};
 2246:                 }
 2247:             } else {
 2248:                 $result = &mt('Currently internally authenticated.');
 2249:                 return $result;
 2250:             }
 2251:         }
 2252:     } else {
 2253:         if ($authnum == 1) {
 2254:             $authtype = '<input type="hidden" name="login" value="int">';
 2255:         }
 2256:     }
 2257:     if (!$can_assign{'int'}) {
 2258:         return;
 2259:     } elsif ($authtype eq '') {
 2260:         if (defined($in{'mode'})) {
 2261:             if ($in{'mode'} eq 'modifycourse') {
 2262:                 if ($authnum == 1) {
 2263:                     $authtype = '<input type="hidden" name="login" value="int">';
 2264:                 }
 2265:             }
 2266:         }
 2267:     }
 2268:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2269:     if ($authtype eq '') {
 2270:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2271:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2272:     }
 2273:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2274:                $intarg.'" onchange="'.$jscall.'" />';
 2275:     $result = &mt
 2276:         ('[_1] Internally authenticated (with initial password [_2])',
 2277:          '<label>'.$authtype,'</label>'.$autharg);
 2278:     $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>';
 2279:     return $result;
 2280: }
 2281: 
 2282: sub authform_local{  
 2283:     my %in = (
 2284:               formname => 'document.cu',
 2285:               kerb_def_dom => 'MSU.EDU',
 2286:               @_,
 2287:               );
 2288:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2289:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2290:     if (defined($in{'curr_authtype'})) {
 2291:         if ($in{'curr_authtype'} eq 'loc') {
 2292:             if ($can_assign{'loc'}) {
 2293:                 $loccheck = 'checked="checked" ';
 2294:                 if (defined($in{'mode'})) {
 2295:                     if ($in{'mode'} eq 'modifyuser') {
 2296:                         $loccheck = '';
 2297:                     }
 2298:                 }
 2299:                 if (defined($in{'curr_autharg'})) {
 2300:                     $locarg = $in{'curr_autharg'};
 2301:                 }
 2302:             } else {
 2303:                 $result = &mt('Currently using local (institutional) authentication.');
 2304:                 return $result;
 2305:             }
 2306:         }
 2307:     } else {
 2308:         if ($authnum == 1) {
 2309:             $authtype = '<input type="hidden" name="login" value="loc">';
 2310:         }
 2311:     }
 2312:     if (!$can_assign{'loc'}) {
 2313:         return;
 2314:     } elsif ($authtype eq '') {
 2315:         if (defined($in{'mode'})) {
 2316:             if ($in{'mode'} eq 'modifycourse') {
 2317:                 if ($authnum == 1) {
 2318:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2319:                 }
 2320:             }
 2321:         }
 2322:     }
 2323:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2324:     if ($authtype eq '') {
 2325:         $authtype = '<input type="radio" name="login" value="loc" '.
 2326:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2327:                     $jscall.'" />';
 2328:     }
 2329:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2330:                $locarg.'" onchange="'.$jscall.'" />';
 2331:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2332:                   '<label>'.$authtype,'</label>'.$autharg);
 2333:     return $result;
 2334: }
 2335: 
 2336: sub authform_filesystem{  
 2337:     my %in = (
 2338:               formname => 'document.cu',
 2339:               kerb_def_dom => 'MSU.EDU',
 2340:               @_,
 2341:               );
 2342:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2343:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2344:     if (defined($in{'curr_authtype'})) {
 2345:         if ($in{'curr_authtype'} eq 'fsys') {
 2346:             if ($can_assign{'fsys'}) {
 2347:                 $fsyscheck = 'checked="checked" ';
 2348:                 if (defined($in{'mode'})) {
 2349:                     if ($in{'mode'} eq 'modifyuser') {
 2350:                         $fsyscheck = '';
 2351:                     }
 2352:                 }
 2353:             } else {
 2354:                 $result = &mt('Currently Filesystem Authenticated.');
 2355:                 return $result;
 2356:             }           
 2357:         }
 2358:     } else {
 2359:         if ($authnum == 1) {
 2360:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2361:         }
 2362:     }
 2363:     if (!$can_assign{'fsys'}) {
 2364:         return;
 2365:     } elsif ($authtype eq '') {
 2366:         if (defined($in{'mode'})) {
 2367:             if ($in{'mode'} eq 'modifycourse') {
 2368:                 if ($authnum == 1) {
 2369:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2370:                 }
 2371:             }
 2372:         }
 2373:     }
 2374:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2375:     if ($authtype eq '') {
 2376:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2377:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2378:                     $jscall.'" />';
 2379:     }
 2380:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2381:                ' onchange="'.$jscall.'" />';
 2382:     $result = &mt
 2383:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2384:          '<label><input type="radio" name="login" value="fsys" '.
 2385:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2386:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2387:                   'onchange="'.$jscall.'" />');
 2388:     return $result;
 2389: }
 2390: 
 2391: sub get_assignable_auth {
 2392:     my ($dom) = @_;
 2393:     if ($dom eq '') {
 2394:         $dom = $env{'request.role.domain'};
 2395:     }
 2396:     my %can_assign = (
 2397:                           krb4 => 1,
 2398:                           krb5 => 1,
 2399:                           int  => 1,
 2400:                           loc  => 1,
 2401:                      );
 2402:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2403:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2404:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2405:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2406:             my $context;
 2407:             if ($env{'request.role'} =~ /^au/) {
 2408:                 $context = 'author';
 2409:             } elsif ($env{'request.role'} =~ /^dc/) {
 2410:                 $context = 'domain';
 2411:             } elsif ($env{'request.course.id'}) {
 2412:                 $context = 'course';
 2413:             }
 2414:             if ($context) {
 2415:                 if (ref($authhash->{$context}) eq 'HASH') {
 2416:                    %can_assign = %{$authhash->{$context}}; 
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     my $authnum = 0;
 2422:     foreach my $key (keys(%can_assign)) {
 2423:         if ($can_assign{$key}) {
 2424:             $authnum ++;
 2425:         }
 2426:     }
 2427:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2428:         $authnum --;
 2429:     }
 2430:     return ($authnum,%can_assign);
 2431: }
 2432: 
 2433: ###############################################################
 2434: ##    Get Kerberos Defaults for Domain                 ##
 2435: ###############################################################
 2436: ##
 2437: ## Returns default kerberos version and an associated argument
 2438: ## as listed in file domain.tab. If not listed, provides
 2439: ## appropriate default domain and kerberos version.
 2440: ##
 2441: #-------------------------------------------
 2442: 
 2443: =pod
 2444: 
 2445: =item * &get_kerberos_defaults()
 2446: 
 2447: get_kerberos_defaults($target_domain) returns the default kerberos
 2448: version and domain. If not found, it defaults to version 4 and the 
 2449: domain of the server.
 2450: 
 2451: =over 4
 2452: 
 2453: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2454: 
 2455: =back
 2456: 
 2457: =back
 2458: 
 2459: =cut
 2460: 
 2461: #-------------------------------------------
 2462: sub get_kerberos_defaults {
 2463:     my $domain=shift;
 2464:     my ($krbdef,$krbdefdom);
 2465:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2466:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2467:         $krbdef = $domdefaults{'auth_def'};
 2468:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2469:     } else {
 2470:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2471:         my $krbdefdom=$1;
 2472:         $krbdefdom=~tr/a-z/A-Z/;
 2473:         $krbdef = "krb4";
 2474:     }
 2475:     return ($krbdef,$krbdefdom);
 2476: }
 2477: 
 2478: 
 2479: ###############################################################
 2480: ##                Thesaurus Functions                        ##
 2481: ###############################################################
 2482: 
 2483: =pod
 2484: 
 2485: =head1 Thesaurus Functions
 2486: 
 2487: =over 4
 2488: 
 2489: =item * &initialize_keywords()
 2490: 
 2491: Initializes the package variable %Keywords if it is empty.  Uses the
 2492: package variable $thesaurus_db_file.
 2493: 
 2494: =cut
 2495: 
 2496: ###################################################
 2497: 
 2498: sub initialize_keywords {
 2499:     return 1 if (scalar keys(%Keywords));
 2500:     # If we are here, %Keywords is empty, so fill it up
 2501:     #   Make sure the file we need exists...
 2502:     if (! -e $thesaurus_db_file) {
 2503:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2504:                                  " failed because it does not exist");
 2505:         return 0;
 2506:     }
 2507:     #   Set up the hash as a database
 2508:     my %thesaurus_db;
 2509:     if (! tie(%thesaurus_db,'GDBM_File',
 2510:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2511:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2512:                                  $thesaurus_db_file);
 2513:         return 0;
 2514:     } 
 2515:     #  Get the average number of appearances of a word.
 2516:     my $avecount = $thesaurus_db{'average.count'};
 2517:     #  Put keywords (those that appear > average) into %Keywords
 2518:     while (my ($word,$data)=each (%thesaurus_db)) {
 2519:         my ($count,undef) = split /:/,$data;
 2520:         $Keywords{$word}++ if ($count > $avecount);
 2521:     }
 2522:     untie %thesaurus_db;
 2523:     # Remove special values from %Keywords.
 2524:     foreach my $value ('total.count','average.count') {
 2525:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2526:   }
 2527:     return 1;
 2528: }
 2529: 
 2530: ###################################################
 2531: 
 2532: =pod
 2533: 
 2534: =item * &keyword($word)
 2535: 
 2536: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2537: than the average number of times in the thesaurus database.  Calls 
 2538: &initialize_keywords
 2539: 
 2540: =cut
 2541: 
 2542: ###################################################
 2543: 
 2544: sub keyword {
 2545:     return if (!&initialize_keywords());
 2546:     my $word=lc(shift());
 2547:     $word=~s/\W//g;
 2548:     return exists($Keywords{$word});
 2549: }
 2550: 
 2551: ###############################################################
 2552: 
 2553: =pod 
 2554: 
 2555: =item * &get_related_words()
 2556: 
 2557: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2558: an array of words.  If the keyword is not in the thesaurus, an empty array
 2559: will be returned.  The order of the words returned is determined by the
 2560: database which holds them.
 2561: 
 2562: Uses global $thesaurus_db_file.
 2563: 
 2564: =cut
 2565: 
 2566: ###############################################################
 2567: sub get_related_words {
 2568:     my $keyword = shift;
 2569:     my %thesaurus_db;
 2570:     if (! -e $thesaurus_db_file) {
 2571:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2572:                                  "failed because the file does not exist");
 2573:         return ();
 2574:     }
 2575:     if (! tie(%thesaurus_db,'GDBM_File',
 2576:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2577:         return ();
 2578:     } 
 2579:     my @Words=();
 2580:     my $count=0;
 2581:     if (exists($thesaurus_db{$keyword})) {
 2582: 	# The first element is the number of times
 2583: 	# the word appears.  We do not need it now.
 2584: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2585: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2586: 	my $threshold=$mostfrequentcount/10;
 2587:         foreach my $possibleword (@RelatedWords) {
 2588:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2589:             if ($wordcount>$threshold) {
 2590: 		push(@Words,$word);
 2591:                 $count++;
 2592:                 if ($count>10) { last; }
 2593: 	    }
 2594:         }
 2595:     }
 2596:     untie %thesaurus_db;
 2597:     return @Words;
 2598: }
 2599: 
 2600: =pod
 2601: 
 2602: =back
 2603: 
 2604: =cut
 2605: 
 2606: # -------------------------------------------------------------- Plaintext name
 2607: =pod
 2608: 
 2609: =head1 User Name Functions
 2610: 
 2611: =over 4
 2612: 
 2613: =item * &plainname($uname,$udom,$first)
 2614: 
 2615: Takes a users logon name and returns it as a string in
 2616: "first middle last generation" form 
 2617: if $first is set to 'lastname' then it returns it as
 2618: 'lastname generation, firstname middlename' if their is a lastname
 2619: 
 2620: =cut
 2621: 
 2622: 
 2623: ###############################################################
 2624: sub plainname {
 2625:     my ($uname,$udom,$first)=@_;
 2626:     return if (!defined($uname) || !defined($udom));
 2627:     my %names=&getnames($uname,$udom);
 2628:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2629: 					  $names{'middlename'},
 2630: 					  $names{'lastname'},
 2631: 					  $names{'generation'},$first);
 2632:     $name=~s/^\s+//;
 2633:     $name=~s/\s+$//;
 2634:     $name=~s/\s+/ /g;
 2635:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2636:     return $name;
 2637: }
 2638: 
 2639: # -------------------------------------------------------------------- Nickname
 2640: =pod
 2641: 
 2642: =item * &nickname($uname,$udom)
 2643: 
 2644: Gets a users name and returns it as a string as
 2645: 
 2646: "&quot;nickname&quot;"
 2647: 
 2648: if the user has a nickname or
 2649: 
 2650: "first middle last generation"
 2651: 
 2652: if the user does not
 2653: 
 2654: =cut
 2655: 
 2656: sub nickname {
 2657:     my ($uname,$udom)=@_;
 2658:     return if (!defined($uname) || !defined($udom));
 2659:     my %names=&getnames($uname,$udom);
 2660:     my $name=$names{'nickname'};
 2661:     if ($name) {
 2662:        $name='&quot;'.$name.'&quot;'; 
 2663:     } else {
 2664:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2665: 	     $names{'lastname'}.' '.$names{'generation'};
 2666:        $name=~s/\s+$//;
 2667:        $name=~s/\s+/ /g;
 2668:     }
 2669:     return $name;
 2670: }
 2671: 
 2672: sub getnames {
 2673:     my ($uname,$udom)=@_;
 2674:     return if (!defined($uname) || !defined($udom));
 2675:     if ($udom eq 'public' && $uname eq 'public') {
 2676: 	return ('lastname' => &mt('Public'));
 2677:     }
 2678:     my $id=$uname.':'.$udom;
 2679:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2680:     if ($cached) {
 2681: 	return %{$names};
 2682:     } else {
 2683: 	my %loadnames=&Apache::lonnet::get('environment',
 2684:                     ['firstname','middlename','lastname','generation','nickname'],
 2685: 					 $udom,$uname);
 2686: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2687: 	return %loadnames;
 2688:     }
 2689: }
 2690: 
 2691: # -------------------------------------------------------------------- getemails
 2692: 
 2693: =pod
 2694: 
 2695: =item * &getemails($uname,$udom)
 2696: 
 2697: Gets a user's email information and returns it as a hash with keys:
 2698: notification, critnotification, permanentemail
 2699: 
 2700: For notification and critnotification, values are comma-separated lists 
 2701: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2702:  
 2703: 
 2704: =cut
 2705: 
 2706: 
 2707: sub getemails {
 2708:     my ($uname,$udom)=@_;
 2709:     if ($udom eq 'public' && $uname eq 'public') {
 2710: 	return;
 2711:     }
 2712:     if (!$udom) { $udom=$env{'user.domain'}; }
 2713:     if (!$uname) { $uname=$env{'user.name'}; }
 2714:     my $id=$uname.':'.$udom;
 2715:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2716:     if ($cached) {
 2717: 	return %{$names};
 2718:     } else {
 2719: 	my %loadnames=&Apache::lonnet::get('environment',
 2720:                     			   ['notification','critnotification',
 2721: 					    'permanentemail'],
 2722: 					   $udom,$uname);
 2723: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2724: 	return %loadnames;
 2725:     }
 2726: }
 2727: 
 2728: sub flush_email_cache {
 2729:     my ($uname,$udom)=@_;
 2730:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2731:     if (!$uname) { $uname=$env{'user.name'};   }
 2732:     return if ($udom eq 'public' && $uname eq 'public');
 2733:     my $id=$uname.':'.$udom;
 2734:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2735: }
 2736: 
 2737: # -------------------------------------------------------------------- getlangs
 2738: 
 2739: =pod
 2740: 
 2741: =item * &getlangs($uname,$udom)
 2742: 
 2743: Gets a user's language preference and returns it as a hash with key:
 2744: language.
 2745: 
 2746: =cut
 2747: 
 2748: 
 2749: sub getlangs {
 2750:     my ($uname,$udom) = @_;
 2751:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2752:     if (!$uname) { $uname=$env{'user.name'};   }
 2753:     my $id=$uname.':'.$udom;
 2754:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2755:     if ($cached) {
 2756:         return %{$langs};
 2757:     } else {
 2758:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2759:                                            $udom,$uname);
 2760:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2761:         return %loadlangs;
 2762:     }
 2763: }
 2764: 
 2765: sub flush_langs_cache {
 2766:     my ($uname,$udom)=@_;
 2767:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2768:     if (!$uname) { $uname=$env{'user.name'};   }
 2769:     return if ($udom eq 'public' && $uname eq 'public');
 2770:     my $id=$uname.':'.$udom;
 2771:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2772: }
 2773: 
 2774: # ------------------------------------------------------------------ Screenname
 2775: 
 2776: =pod
 2777: 
 2778: =item * &screenname($uname,$udom)
 2779: 
 2780: Gets a users screenname and returns it as a string
 2781: 
 2782: =cut
 2783: 
 2784: sub screenname {
 2785:     my ($uname,$udom)=@_;
 2786:     if ($uname eq $env{'user.name'} &&
 2787: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2788:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2789:     return $names{'screenname'};
 2790: }
 2791: 
 2792: 
 2793: # ------------------------------------------------------------- Message Wrapper
 2794: 
 2795: sub messagewrapper {
 2796:     my ($link,$username,$domain,$subject,$text)=@_;
 2797:     return 
 2798:         '<a href="/adm/email?compose=individual&amp;'.
 2799:         'recname='.$username.'&amp;recdom='.$domain.
 2800: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2801:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2802: }
 2803: # --------------------------------------------------------------- Notes Wrapper
 2804: 
 2805: sub noteswrapper {
 2806:     my ($link,$un,$do)=@_;
 2807:     return 
 2808: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2809: }
 2810: # ------------------------------------------------------------- Aboutme Wrapper
 2811: 
 2812: sub aboutmewrapper {
 2813:     my ($link,$username,$domain,$target)=@_;
 2814:     if (!defined($username)  && !defined($domain)) {
 2815:         return;
 2816:     }
 2817:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2818: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2819: }
 2820: 
 2821: # ------------------------------------------------------------ Syllabus Wrapper
 2822: 
 2823: 
 2824: sub syllabuswrapper {
 2825:     my ($linktext,$coursedir,$domain)=@_;
 2826:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2827: }
 2828: 
 2829: sub track_student_link {
 2830:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2831:     my $link ="/adm/trackstudent?";
 2832:     my $title = 'View recent activity';
 2833:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2834:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2835:         $link .= "selected_student=$sname:$sdom";
 2836:         $title .= ' of this student';
 2837:     } 
 2838:     if (defined($target) && $target !~ /^\s*$/) {
 2839:         $target = qq{target="$target"};
 2840:     } else {
 2841:         $target = '';
 2842:     }
 2843:     if ($start) { $link.='&amp;start='.$start; }
 2844:     $title = &mt($title);
 2845:     $linktext = &mt($linktext);
 2846:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2847: 	&help_open_topic('View_recent_activity');
 2848: }
 2849: 
 2850: sub slot_reservations_link {
 2851:     my ($linktext,$sname,$sdom,$target) = @_;
 2852:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2853:     my $title = 'View slot reservation history';
 2854:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2855:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2856:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2857:         $title .= ' of this student';
 2858:     }
 2859:     if (defined($target) && $target !~ /^\s*$/) {
 2860:         $target = qq{target="$target"};
 2861:     } else {
 2862:         $target = '';
 2863:     }
 2864:     $title = &mt($title);
 2865:     $linktext = &mt($linktext);
 2866:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2867: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2868: 
 2869: }
 2870: 
 2871: # ===================================================== Display a student photo
 2872: 
 2873: 
 2874: sub student_image_tag {
 2875:     my ($domain,$user)=@_;
 2876:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2877:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2878: 	return '<img src="'.$imgsrc.'" align="right" />';
 2879:     } else {
 2880: 	return '';
 2881:     }
 2882: }
 2883: 
 2884: =pod
 2885: 
 2886: =back
 2887: 
 2888: =head1 Access .tab File Data
 2889: 
 2890: =over 4
 2891: 
 2892: =item * &languageids() 
 2893: 
 2894: returns list of all language ids
 2895: 
 2896: =cut
 2897: 
 2898: sub languageids {
 2899:     return sort(keys(%language));
 2900: }
 2901: 
 2902: =pod
 2903: 
 2904: =item * &languagedescription() 
 2905: 
 2906: returns description of a specified language id
 2907: 
 2908: =cut
 2909: 
 2910: sub languagedescription {
 2911:     my $code=shift;
 2912:     return  ($supported_language{$code}?'* ':'').
 2913:             $language{$code}.
 2914: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2915: }
 2916: 
 2917: sub plainlanguagedescription {
 2918:     my $code=shift;
 2919:     return $language{$code};
 2920: }
 2921: 
 2922: sub supportedlanguagecode {
 2923:     my $code=shift;
 2924:     return $supported_language{$code};
 2925: }
 2926: 
 2927: =pod
 2928: 
 2929: =item * &copyrightids() 
 2930: 
 2931: returns list of all copyrights
 2932: 
 2933: =cut
 2934: 
 2935: sub copyrightids {
 2936:     return sort(keys(%cprtag));
 2937: }
 2938: 
 2939: =pod
 2940: 
 2941: =item * &copyrightdescription() 
 2942: 
 2943: returns description of a specified copyright id
 2944: 
 2945: =cut
 2946: 
 2947: sub copyrightdescription {
 2948:     return &mt($cprtag{shift(@_)});
 2949: }
 2950: 
 2951: =pod
 2952: 
 2953: =item * &source_copyrightids() 
 2954: 
 2955: returns list of all source copyrights
 2956: 
 2957: =cut
 2958: 
 2959: sub source_copyrightids {
 2960:     return sort(keys(%scprtag));
 2961: }
 2962: 
 2963: =pod
 2964: 
 2965: =item * &source_copyrightdescription() 
 2966: 
 2967: returns description of a specified source copyright id
 2968: 
 2969: =cut
 2970: 
 2971: sub source_copyrightdescription {
 2972:     return &mt($scprtag{shift(@_)});
 2973: }
 2974: 
 2975: =pod
 2976: 
 2977: =item * &filecategories() 
 2978: 
 2979: returns list of all file categories
 2980: 
 2981: =cut
 2982: 
 2983: sub filecategories {
 2984:     return sort(keys(%category_extensions));
 2985: }
 2986: 
 2987: =pod
 2988: 
 2989: =item * &filecategorytypes() 
 2990: 
 2991: returns list of file types belonging to a given file
 2992: category
 2993: 
 2994: =cut
 2995: 
 2996: sub filecategorytypes {
 2997:     my ($cat) = @_;
 2998:     return @{$category_extensions{lc($cat)}};
 2999: }
 3000: 
 3001: =pod
 3002: 
 3003: =item * &fileembstyle() 
 3004: 
 3005: returns embedding style for a specified file type
 3006: 
 3007: =cut
 3008: 
 3009: sub fileembstyle {
 3010:     return $fe{lc(shift(@_))};
 3011: }
 3012: 
 3013: sub filemimetype {
 3014:     return $fm{lc(shift(@_))};
 3015: }
 3016: 
 3017: 
 3018: sub filecategoryselect {
 3019:     my ($name,$value)=@_;
 3020:     return &select_form($value,$name,
 3021: 			'' => &mt('Any category'),
 3022: 			map { $_,$_ } sort(keys(%category_extensions)));
 3023: }
 3024: 
 3025: =pod
 3026: 
 3027: =item * &filedescription() 
 3028: 
 3029: returns description for a specified file type
 3030: 
 3031: =cut
 3032: 
 3033: sub filedescription {
 3034:     my $file_description = $fd{lc(shift())};
 3035:     $file_description =~ s:([\[\]]):~$1:g;
 3036:     return &mt($file_description);
 3037: }
 3038: 
 3039: =pod
 3040: 
 3041: =item * &filedescriptionex() 
 3042: 
 3043: returns description for a specified file type with
 3044: extra formatting
 3045: 
 3046: =cut
 3047: 
 3048: sub filedescriptionex {
 3049:     my $ex=shift;
 3050:     my $file_description = $fd{lc($ex)};
 3051:     $file_description =~ s:([\[\]]):~$1:g;
 3052:     return '.'.$ex.' '.&mt($file_description);
 3053: }
 3054: 
 3055: # End of .tab access
 3056: =pod
 3057: 
 3058: =back
 3059: 
 3060: =cut
 3061: 
 3062: # ------------------------------------------------------------------ File Types
 3063: sub fileextensions {
 3064:     return sort(keys(%fe));
 3065: }
 3066: 
 3067: # ----------------------------------------------------------- Display Languages
 3068: # returns a hash with all desired display languages
 3069: #
 3070: 
 3071: sub display_languages {
 3072:     my %languages=();
 3073:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3074: 	$languages{$lang}=1;
 3075:     }
 3076:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3077:     if ($env{'form.displaylanguage'}) {
 3078: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3079: 	    $languages{$lang}=1;
 3080:         }
 3081:     }
 3082:     return %languages;
 3083: }
 3084: 
 3085: sub languages {
 3086:     my ($possible_langs) = @_;
 3087:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3088:     if (!ref($possible_langs)) {
 3089: 	if( wantarray ) {
 3090: 	    return @preferred_langs;
 3091: 	} else {
 3092: 	    return $preferred_langs[0];
 3093: 	}
 3094:     }
 3095:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3096:     my @preferred_possibilities;
 3097:     foreach my $preferred_lang (@preferred_langs) {
 3098: 	if (exists($possibilities{$preferred_lang})) {
 3099: 	    push(@preferred_possibilities, $preferred_lang);
 3100: 	}
 3101:     }
 3102:     if( wantarray ) {
 3103: 	return @preferred_possibilities;
 3104:     }
 3105:     return $preferred_possibilities[0];
 3106: }
 3107: 
 3108: sub user_lang {
 3109:     my ($touname,$toudom,$fromcid) = @_;
 3110:     my @userlangs;
 3111:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3112:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3113:                     $env{'course.'.$fromcid.'.languages'}));
 3114:     } else {
 3115:         my %langhash = &getlangs($touname,$toudom);
 3116:         if ($langhash{'languages'} ne '') {
 3117:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3118:         } else {
 3119:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3120:             if ($domdefs{'lang_def'} ne '') {
 3121:                 @userlangs = ($domdefs{'lang_def'});
 3122:             }
 3123:         }
 3124:     }
 3125:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3126:     my $user_lh = Apache::localize->get_handle(@languages);
 3127:     return $user_lh;
 3128: }
 3129: 
 3130: 
 3131: ###############################################################
 3132: ##               Student Answer Attempts                     ##
 3133: ###############################################################
 3134: 
 3135: =pod
 3136: 
 3137: =head1 Alternate Problem Views
 3138: 
 3139: =over 4
 3140: 
 3141: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3142:     $getattempt, $regexp, $gradesub)
 3143: 
 3144: Return string with previous attempt on problem. Arguments:
 3145: 
 3146: =over 4
 3147: 
 3148: =item * $symb: Problem, including path
 3149: 
 3150: =item * $username: username of the desired student
 3151: 
 3152: =item * $domain: domain of the desired student
 3153: 
 3154: =item * $course: Course ID
 3155: 
 3156: =item * $getattempt: Leave blank for all attempts, otherwise put
 3157:     something
 3158: 
 3159: =item * $regexp: if string matches this regexp, the string will be
 3160:     sent to $gradesub
 3161: 
 3162: =item * $gradesub: routine that processes the string if it matches $regexp
 3163: 
 3164: =back
 3165: 
 3166: The output string is a table containing all desired attempts, if any.
 3167: 
 3168: =cut
 3169: 
 3170: sub get_previous_attempt {
 3171:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3172:   my $prevattempts='';
 3173:   no strict 'refs';
 3174:   if ($symb) {
 3175:     my (%returnhash)=
 3176:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3177:     if ($returnhash{'version'}) {
 3178:       my %lasthash=();
 3179:       my $version;
 3180:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3181:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3182: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3183:         }
 3184:       }
 3185:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3186:       $prevattempts.='<th>'.&mt('History').'</th>';
 3187:       foreach my $key (sort(keys(%lasthash))) {
 3188: 	my ($ign,@parts) = split(/\./,$key);
 3189: 	if ($#parts > 0) {
 3190: 	  my $data=$parts[-1];
 3191: 	  pop(@parts);
 3192: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3193: 	} else {
 3194: 	  if ($#parts == 0) {
 3195: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3196: 	  } else {
 3197: 	    $prevattempts.='<th>'.$ign.'</th>';
 3198: 	  }
 3199: 	}
 3200:       }
 3201:       $prevattempts.=&end_data_table_header_row();
 3202:       if ($getattempt eq '') {
 3203: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3204: 	  $prevattempts.=&start_data_table_row().
 3205: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3206: 	    foreach my $key (sort(keys(%lasthash))) {
 3207: 		my $value = &format_previous_attempt_value($key,
 3208: 							   $returnhash{$version.':'.$key});
 3209: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3210: 	    }
 3211: 	  $prevattempts.=&end_data_table_row();
 3212: 	 }
 3213:       }
 3214:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3215:       foreach my $key (sort(keys(%lasthash))) {
 3216: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3217: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3218: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3219:       }
 3220:       $prevattempts.= &end_data_table_row().&end_data_table();
 3221:     } else {
 3222:       $prevattempts=
 3223: 	  &start_data_table().&start_data_table_row().
 3224: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3225: 	  &end_data_table_row().&end_data_table();
 3226:     }
 3227:   } else {
 3228:     $prevattempts=
 3229: 	  &start_data_table().&start_data_table_row().
 3230: 	  '<td>'.&mt('No data.').'</td>'.
 3231: 	  &end_data_table_row().&end_data_table();
 3232:   }
 3233: }
 3234: 
 3235: sub format_previous_attempt_value {
 3236:     my ($key,$value) = @_;
 3237:     if ($key =~ /timestamp/) {
 3238: 	$value = &Apache::lonlocal::locallocaltime($value);
 3239:     } elsif (ref($value) eq 'ARRAY') {
 3240: 	$value = '('.join(', ', @{ $value }).')';
 3241:     } else {
 3242: 	$value = &unescape($value);
 3243:     }
 3244:     return $value;
 3245: }
 3246: 
 3247: 
 3248: sub relative_to_absolute {
 3249:     my ($url,$output)=@_;
 3250:     my $parser=HTML::TokeParser->new(\$output);
 3251:     my $token;
 3252:     my $thisdir=$url;
 3253:     my @rlinks=();
 3254:     while ($token=$parser->get_token) {
 3255: 	if ($token->[0] eq 'S') {
 3256: 	    if ($token->[1] eq 'a') {
 3257: 		if ($token->[2]->{'href'}) {
 3258: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3259: 		}
 3260: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3261: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3262: 	    } elsif ($token->[1] eq 'base') {
 3263: 		$thisdir=$token->[2]->{'href'};
 3264: 	    }
 3265: 	}
 3266:     }
 3267:     $thisdir=~s-/[^/]*$--;
 3268:     foreach my $link (@rlinks) {
 3269: 	unless (($link=~/^https?\:\/\//i) ||
 3270: 		($link=~/^\//) ||
 3271: 		($link=~/^javascript:/i) ||
 3272: 		($link=~/^mailto:/i) ||
 3273: 		($link=~/^\#/)) {
 3274: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3275: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3276: 	}
 3277:     }
 3278: # -------------------------------------------------- Deal with Applet codebases
 3279:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3280:     return $output;
 3281: }
 3282: 
 3283: =pod
 3284: 
 3285: =item * &get_student_view()
 3286: 
 3287: show a snapshot of what student was looking at
 3288: 
 3289: =cut
 3290: 
 3291: sub get_student_view {
 3292:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3293:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3294:   my (%form);
 3295:   my @elements=('symb','courseid','domain','username');
 3296:   foreach my $element (@elements) {
 3297:       $form{'grade_'.$element}=eval '$'.$element #'
 3298:   }
 3299:   if (defined($moreenv)) {
 3300:       %form=(%form,%{$moreenv});
 3301:   }
 3302:   if (defined($target)) { $form{'grade_target'} = $target; }
 3303:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3304:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3305:   $userview=~s/\<body[^\>]*\>//gi;
 3306:   $userview=~s/\<\/body\>//gi;
 3307:   $userview=~s/\<html\>//gi;
 3308:   $userview=~s/\<\/html\>//gi;
 3309:   $userview=~s/\<head\>//gi;
 3310:   $userview=~s/\<\/head\>//gi;
 3311:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3312:   $userview=&relative_to_absolute($feedurl,$userview);
 3313:   if (wantarray) {
 3314:      return ($userview,$response);
 3315:   } else {
 3316:      return $userview;
 3317:   }
 3318: }
 3319: 
 3320: sub get_student_view_with_retries {
 3321:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3322: 
 3323:     my $ok = 0;                 # True if we got a good response.
 3324:     my $content;
 3325:     my $response;
 3326: 
 3327:     # Try to get the student_view done. within the retries count:
 3328:     
 3329:     do {
 3330:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3331:          $ok      = $response->is_success;
 3332:          if (!$ok) {
 3333:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3334:          }
 3335:          $retries--;
 3336:     } while (!$ok && ($retries > 0));
 3337:     
 3338:     if (!$ok) {
 3339:        $content = '';          # On error return an empty content.
 3340:     }
 3341:     if (wantarray) {
 3342:        return ($content, $response);
 3343:     } else {
 3344:        return $content;
 3345:     }
 3346: }
 3347: 
 3348: =pod
 3349: 
 3350: =item * &get_student_answers() 
 3351: 
 3352: show a snapshot of how student was answering problem
 3353: 
 3354: =cut
 3355: 
 3356: sub get_student_answers {
 3357:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3358:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3359:   my (%moreenv);
 3360:   my @elements=('symb','courseid','domain','username');
 3361:   foreach my $element (@elements) {
 3362:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3363:   }
 3364:   $moreenv{'grade_target'}='answer';
 3365:   %moreenv=(%form,%moreenv);
 3366:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3367:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3368:   return $userview;
 3369: }
 3370: 
 3371: =pod
 3372: 
 3373: =item * &submlink()
 3374: 
 3375: Inputs: $text $uname $udom $symb $target
 3376: 
 3377: Returns: A link to grades.pm such as to see the SUBM view of a student
 3378: 
 3379: =cut
 3380: 
 3381: ###############################################
 3382: sub submlink {
 3383:     my ($text,$uname,$udom,$symb,$target)=@_;
 3384:     if (!($uname && $udom)) {
 3385: 	(my $cursymb, my $courseid,$udom,$uname)=
 3386: 	    &Apache::lonnet::whichuser($symb);
 3387: 	if (!$symb) { $symb=$cursymb; }
 3388:     }
 3389:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3390:     $symb=&escape($symb);
 3391:     if ($target) { $target="target=\"$target\""; }
 3392:     return '<a href="/adm/grades?&command=submission&'.
 3393: 	'symb='.$symb.'&student='.$uname.
 3394: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3395: }
 3396: ##############################################
 3397: 
 3398: =pod
 3399: 
 3400: =item * &pgrdlink()
 3401: 
 3402: Inputs: $text $uname $udom $symb $target
 3403: 
 3404: Returns: A link to grades.pm such as to see the PGRD view of a student
 3405: 
 3406: =cut
 3407: 
 3408: ###############################################
 3409: sub pgrdlink {
 3410:     my $link=&submlink(@_);
 3411:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3412:     return $link;
 3413: }
 3414: ##############################################
 3415: 
 3416: =pod
 3417: 
 3418: =item * &pprmlink()
 3419: 
 3420: Inputs: $text $uname $udom $symb $target
 3421: 
 3422: Returns: A link to parmset.pm such as to see the PPRM view of a
 3423: student and a specific resource
 3424: 
 3425: =cut
 3426: 
 3427: ###############################################
 3428: sub pprmlink {
 3429:     my ($text,$uname,$udom,$symb,$target)=@_;
 3430:     if (!($uname && $udom)) {
 3431: 	(my $cursymb, my $courseid,$udom,$uname)=
 3432: 	    &Apache::lonnet::whichuser($symb);
 3433: 	if (!$symb) { $symb=$cursymb; }
 3434:     }
 3435:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3436:     $symb=&escape($symb);
 3437:     if ($target) { $target="target=\"$target\""; }
 3438:     return '<a href="/adm/parmset?command=set&amp;'.
 3439: 	'symb='.$symb.'&amp;uname='.$uname.
 3440: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3441: }
 3442: ##############################################
 3443: 
 3444: =pod
 3445: 
 3446: =back
 3447: 
 3448: =cut
 3449: 
 3450: ###############################################
 3451: 
 3452: 
 3453: sub timehash {
 3454:     my ($thistime) = @_;
 3455:     my $timezone = &Apache::lonlocal::gettimezone();
 3456:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3457:                      ->set_time_zone($timezone);
 3458:     my $wday = $dt->day_of_week();
 3459:     if ($wday == 7) { $wday = 0; }
 3460:     return ( 'second' => $dt->second(),
 3461:              'minute' => $dt->minute(),
 3462:              'hour'   => $dt->hour(),
 3463:              'day'     => $dt->day_of_month(),
 3464:              'month'   => $dt->month(),
 3465:              'year'    => $dt->year(),
 3466:              'weekday' => $wday,
 3467:              'dayyear' => $dt->day_of_year(),
 3468:              'dlsav'   => $dt->is_dst() );
 3469: }
 3470: 
 3471: sub utc_string {
 3472:     my ($date)=@_;
 3473:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3474: }
 3475: 
 3476: sub maketime {
 3477:     my %th=@_;
 3478:     my ($epoch_time,$timezone,$dt);
 3479:     $timezone = &Apache::lonlocal::gettimezone();
 3480:     eval {
 3481:         $dt = DateTime->new( year   => $th{'year'},
 3482:                              month  => $th{'month'},
 3483:                              day    => $th{'day'},
 3484:                              hour   => $th{'hour'},
 3485:                              minute => $th{'minute'},
 3486:                              second => $th{'second'},
 3487:                              time_zone => $timezone,
 3488:                          );
 3489:     };
 3490:     if (!$@) {
 3491:         $epoch_time = $dt->epoch;
 3492:         if ($epoch_time) {
 3493:             return $epoch_time;
 3494:         }
 3495:     }
 3496:     return POSIX::mktime(
 3497:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3498:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3499: }
 3500: 
 3501: #########################################
 3502: 
 3503: sub findallcourses {
 3504:     my ($roles,$uname,$udom) = @_;
 3505:     my %roles;
 3506:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3507:     my %courses;
 3508:     my $now=time;
 3509:     if (!defined($uname)) {
 3510:         $uname = $env{'user.name'};
 3511:     }
 3512:     if (!defined($udom)) {
 3513:         $udom = $env{'user.domain'};
 3514:     }
 3515:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3516:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3517:         if (!%roles) {
 3518:             %roles = (
 3519:                        cc => 1,
 3520:                        in => 1,
 3521:                        ep => 1,
 3522:                        ta => 1,
 3523:                        cr => 1,
 3524:                        st => 1,
 3525:              );
 3526:         }
 3527:         foreach my $entry (keys(%roleshash)) {
 3528:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3529:             if ($trole =~ /^cr/) { 
 3530:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3531:             } else {
 3532:                 next if (!exists($roles{$trole}));
 3533:             }
 3534:             if ($tend) {
 3535:                 next if ($tend < $now);
 3536:             }
 3537:             if ($tstart) {
 3538:                 next if ($tstart > $now);
 3539:             }
 3540:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3541:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3542:             if ($secpart eq '') {
 3543:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3544:                 $sec = 'none';
 3545:                 $realsec = '';
 3546:             } else {
 3547:                 $cnum = $cnumpart;
 3548:                 ($sec,$role) = split(/_/,$secpart);
 3549:                 $realsec = $sec;
 3550:             }
 3551:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3552:         }
 3553:     } else {
 3554:         foreach my $key (keys(%env)) {
 3555: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3556:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3557: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3558: 	        next if ($role eq 'ca' || $role eq 'aa');
 3559: 	        next if (%roles && !exists($roles{$role}));
 3560: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3561:                 my $active=1;
 3562:                 if ($starttime) {
 3563: 		    if ($now<$starttime) { $active=0; }
 3564:                 }
 3565:                 if ($endtime) {
 3566:                     if ($now>$endtime) { $active=0; }
 3567:                 }
 3568:                 if ($active) {
 3569:                     if ($sec eq '') {
 3570:                         $sec = 'none';
 3571:                     }
 3572:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3573:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3574:                 }
 3575:             }
 3576:         }
 3577:     }
 3578:     return %courses;
 3579: }
 3580: 
 3581: ###############################################
 3582: 
 3583: sub blockcheck {
 3584:     my ($setters,$activity,$uname,$udom) = @_;
 3585: 
 3586:     if (!defined($udom)) {
 3587:         $udom = $env{'user.domain'};
 3588:     }
 3589:     if (!defined($uname)) {
 3590:         $uname = $env{'user.name'};
 3591:     }
 3592: 
 3593:     # If uname and udom are for a course, check for blocks in the course.
 3594: 
 3595:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3596:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3597:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3598:         return ($startblock,$endblock);
 3599:     }
 3600: 
 3601:     my $startblock = 0;
 3602:     my $endblock = 0;
 3603:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3604: 
 3605:     # If uname is for a user, and activity is course-specific, i.e.,
 3606:     # boards, chat or groups, check for blocking in current course only.
 3607: 
 3608:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3609:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3610:         foreach my $key (keys(%live_courses)) {
 3611:             if ($key ne $env{'request.course.id'}) {
 3612:                 delete($live_courses{$key});
 3613:             }
 3614:         }
 3615:     }
 3616: 
 3617:     my $otheruser = 0;
 3618:     my %own_courses;
 3619:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3620:         # Resource belongs to user other than current user.
 3621:         $otheruser = 1;
 3622:         # Gather courses for current user
 3623:         %own_courses = 
 3624:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3625:     }
 3626: 
 3627:     # Gather active course roles - course coordinator, instructor, 
 3628:     # exam proctor, ta, student, or custom role.
 3629: 
 3630:     foreach my $course (keys(%live_courses)) {
 3631:         my ($cdom,$cnum);
 3632:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3633:             $cdom = $env{'course.'.$course.'.domain'};
 3634:             $cnum = $env{'course.'.$course.'.num'};
 3635:         } else {
 3636:             ($cdom,$cnum) = split(/_/,$course); 
 3637:         }
 3638:         my $no_ownblock = 0;
 3639:         my $no_userblock = 0;
 3640:         if ($otheruser && $activity ne 'com') {
 3641:             # Check if current user has 'evb' priv for this
 3642:             if (defined($own_courses{$course})) {
 3643:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3644:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3645:                     if ($sec ne 'none') {
 3646:                         $checkrole .= '/'.$sec;
 3647:                     }
 3648:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3649:                         $no_ownblock = 1;
 3650:                         last;
 3651:                     }
 3652:                 }
 3653:             }
 3654:             # if they have 'evb' priv and are currently not playing student
 3655:             next if (($no_ownblock) &&
 3656:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3657:         }
 3658:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3659:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3660:             if ($sec ne 'none') {
 3661:                 $checkrole .= '/'.$sec;
 3662:             }
 3663:             if ($otheruser) {
 3664:                 # Resource belongs to user other than current user.
 3665:                 # Assemble privs for that user, and check for 'evb' priv.
 3666:                 my ($trole,$tdom,$tnum,$tsec);
 3667:                 my $entry = $live_courses{$course}{$sec};
 3668:                 if ($entry =~ /^cr/) {
 3669:                     ($trole,$tdom,$tnum,$tsec) = 
 3670:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3671:                 } else {
 3672:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3673:                 }
 3674:                 my ($spec,$area,$trest,%allroles,%userroles);
 3675:                 $area = '/'.$tdom.'/'.$tnum;
 3676:                 $trest = $tnum;
 3677:                 if ($tsec ne '') {
 3678:                     $area .= '/'.$tsec;
 3679:                     $trest .= '/'.$tsec;
 3680:                 }
 3681:                 $spec = $trole.'.'.$area;
 3682:                 if ($trole =~ /^cr/) {
 3683:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3684:                                                       $tdom,$spec,$trest,$area);
 3685:                 } else {
 3686:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3687:                                                        $tdom,$spec,$trest,$area);
 3688:                 }
 3689:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3690:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3691:                     if ($1) {
 3692:                         $no_userblock = 1;
 3693:                         last;
 3694:                     }
 3695:                 }
 3696:             } else {
 3697:                 # Resource belongs to current user
 3698:                 # Check for 'evb' priv via lonnet::allowed().
 3699:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3700:                     $no_ownblock = 1;
 3701:                     last;
 3702:                 }
 3703:             }
 3704:         }
 3705:         # if they have the evb priv and are currently not playing student
 3706:         next if (($no_ownblock) &&
 3707:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3708:         next if ($no_userblock);
 3709: 
 3710:         # Retrieve blocking times and identity of blocker for course
 3711:         # of specified user, unless user has 'evb' privilege.
 3712:         
 3713:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3714:         if (($start != 0) && 
 3715:             (($startblock == 0) || ($startblock > $start))) {
 3716:             $startblock = $start;
 3717:         }
 3718:         if (($end != 0)  &&
 3719:             (($endblock == 0) || ($endblock < $end))) {
 3720:             $endblock = $end;
 3721:         }
 3722:     }
 3723:     return ($startblock,$endblock);
 3724: }
 3725: 
 3726: sub get_blocks {
 3727:     my ($setters,$activity,$cdom,$cnum) = @_;
 3728:     my $startblock = 0;
 3729:     my $endblock = 0;
 3730:     my $course = $cdom.'_'.$cnum;
 3731:     $setters->{$course} = {};
 3732:     $setters->{$course}{'staff'} = [];
 3733:     $setters->{$course}{'times'} = [];
 3734:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3735:     foreach my $record (keys(%records)) {
 3736:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3737:         if ($start <= time && $end >= time) {
 3738:             my ($staff_name,$staff_dom,$title,$blocks) =
 3739:                 &parse_block_record($records{$record});
 3740:             if ($blocks->{$activity} eq 'on') {
 3741:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3742:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3743:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3744:                     $startblock = $start;
 3745:                 }
 3746:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3747:                     $endblock = $end;
 3748:                 }
 3749:             }
 3750:         }
 3751:     }
 3752:     return ($startblock,$endblock);
 3753: }
 3754: 
 3755: sub parse_block_record {
 3756:     my ($record) = @_;
 3757:     my ($setuname,$setudom,$title,$blocks);
 3758:     if (ref($record) eq 'HASH') {
 3759:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3760:         $title = &unescape($record->{'event'});
 3761:         $blocks = $record->{'blocks'};
 3762:     } else {
 3763:         my @data = split(/:/,$record,3);
 3764:         if (scalar(@data) eq 2) {
 3765:             $title = $data[1];
 3766:             ($setuname,$setudom) = split(/@/,$data[0]);
 3767:         } else {
 3768:             ($setuname,$setudom,$title) = @data;
 3769:         }
 3770:         $blocks = { 'com' => 'on' };
 3771:     }
 3772:     return ($setuname,$setudom,$title,$blocks);
 3773: }
 3774: 
 3775: sub build_block_table {
 3776:     my ($startblock,$endblock,$setters) = @_;
 3777:     my %lt = &Apache::lonlocal::texthash(
 3778:         'cacb' => 'Currently active communication blocks',
 3779:         'cour' => 'Course',
 3780:         'dura' => 'Duration',
 3781:         'blse' => 'Block set by'
 3782:     );
 3783:     my $output;
 3784:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3785:     $output .= &start_data_table();
 3786:     $output .= '
 3787: <tr>
 3788:  <th>'.$lt{'cour'}.'</th>
 3789:  <th>'.$lt{'dura'}.'</th>
 3790:  <th>'.$lt{'blse'}.'</th>
 3791: </tr>
 3792: ';
 3793:     foreach my $course (keys(%{$setters})) {
 3794:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3795:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3796:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3797:             my $fullname = &plainname($uname,$udom);
 3798:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3799:                 && $env{'user.name'} ne 'public' 
 3800:                 && $env{'user.domain'} ne 'public') {
 3801:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3802:             }
 3803:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3804:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3805:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3806:             $output .= &Apache::loncommon::start_data_table_row().
 3807:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3808:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3809:                        '<td>'.$fullname.'</td>'.
 3810:                         &Apache::loncommon::end_data_table_row();
 3811:         }
 3812:     }
 3813:     $output .= &end_data_table();
 3814: }
 3815: 
 3816: sub blocking_status {
 3817:     my ($activity,$uname,$udom) = @_;
 3818:     my %setters;
 3819:     my ($blocked,$output,$ownitem,$is_course);
 3820:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3821:     if ($startblock && $endblock) {
 3822:         $blocked = 1;
 3823:         if (wantarray) {
 3824:             my $category;
 3825:             if ($activity eq 'boards') {
 3826:                 $category = 'Discussion posts in this course';
 3827:             } elsif ($activity eq 'blogs') {
 3828:                 $category = 'Blogs';
 3829:             } elsif ($activity eq 'port') {
 3830:                 if (defined($uname) && defined($udom)) {
 3831:                     if ($uname eq $env{'user.name'} &&
 3832:                         $udom eq $env{'user.domain'}) {
 3833:                         $ownitem = 1;
 3834:                     }
 3835:                 }
 3836:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3837:                 if ($ownitem) { 
 3838:                     $category = 'Your portfolio files';  
 3839:                 } elsif ($is_course) {
 3840:                     my $coursedesc;
 3841:                     foreach my $course (keys(%setters)) {
 3842:                         my %courseinfo =
 3843:                              &Apache::lonnet::coursedescription($course);
 3844:                         $coursedesc = $courseinfo{'description'};
 3845:                     }
 3846:                     $category = "Group portfolio in the course '$coursedesc'";
 3847:                 } else {
 3848:                     $category = 'Portfolio files belonging to ';
 3849:                     if ($env{'user.name'} eq 'public' && 
 3850:                         $env{'user.domain'} eq 'public') {
 3851:                         $category .= &plainname($uname,$udom);
 3852:                     } else {
 3853:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3854:                     }
 3855:                 }
 3856:             } elsif ($activity eq 'groups') {
 3857:                 $category = 'Groups in this course';
 3858:             }
 3859:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3860:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3861:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3862:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3863:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3864:             }
 3865:         }
 3866:     }
 3867:     if (wantarray) {
 3868:         return ($blocked,$output);
 3869:     } else {
 3870:         return $blocked;
 3871:     }
 3872: }
 3873: 
 3874: ###############################################
 3875: 
 3876: sub check_ip_acc {
 3877:     my ($acc)=@_;
 3878:     &Apache::lonxml::debug("acc is $acc");
 3879:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3880:         return 1;
 3881:     }
 3882:     my $allowed=0;
 3883:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3884: 
 3885:     my $name;
 3886:     foreach my $pattern (split(',',$acc)) {
 3887:         $pattern =~ s/^\s*//;
 3888:         $pattern =~ s/\s*$//;
 3889:         if ($pattern =~ /\*$/) {
 3890:             #35.8.*
 3891:             $pattern=~s/\*//;
 3892:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3893:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3894:             #35.8.3.[34-56]
 3895:             my $low=$2;
 3896:             my $high=$3;
 3897:             $pattern=$1;
 3898:             if ($ip =~ /^\Q$pattern\E/) {
 3899:                 my $last=(split(/\./,$ip))[3];
 3900:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3901:             }
 3902:         } elsif ($pattern =~ /^\*/) {
 3903:             #*.msu.edu
 3904:             $pattern=~s/\*//;
 3905:             if (!defined($name)) {
 3906:                 use Socket;
 3907:                 my $netaddr=inet_aton($ip);
 3908:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3909:             }
 3910:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3911:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3912:             #127.0.0.1
 3913:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3914:         } else {
 3915:             #some.name.com
 3916:             if (!defined($name)) {
 3917:                 use Socket;
 3918:                 my $netaddr=inet_aton($ip);
 3919:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3920:             }
 3921:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3922:         }
 3923:         if ($allowed) { last; }
 3924:     }
 3925:     return $allowed;
 3926: }
 3927: 
 3928: ###############################################
 3929: 
 3930: =pod
 3931: 
 3932: =head1 Domain Template Functions
 3933: 
 3934: =over 4
 3935: 
 3936: =item * &determinedomain()
 3937: 
 3938: Inputs: $domain (usually will be undef)
 3939: 
 3940: Returns: Determines which domain should be used for designs
 3941: 
 3942: =cut
 3943: 
 3944: ###############################################
 3945: sub determinedomain {
 3946:     my $domain=shift;
 3947:     if (! $domain) {
 3948:         # Determine domain if we have not been given one
 3949:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3950:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3951:         if ($env{'request.role.domain'}) { 
 3952:             $domain=$env{'request.role.domain'}; 
 3953:         }
 3954:     }
 3955:     return $domain;
 3956: }
 3957: ###############################################
 3958: 
 3959: sub devalidate_domconfig_cache {
 3960:     my ($udom)=@_;
 3961:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3962: }
 3963: 
 3964: # ---------------------- Get domain configuration for a domain
 3965: sub get_domainconf {
 3966:     my ($udom) = @_;
 3967:     my $cachetime=1800;
 3968:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3969:     if (defined($cached)) { return %{$result}; }
 3970: 
 3971:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3972: 					     ['login','rolecolors'],$udom);
 3973:     my (%designhash,%legacy);
 3974:     if (keys(%domconfig) > 0) {
 3975:         if (ref($domconfig{'login'}) eq 'HASH') {
 3976:             if (keys(%{$domconfig{'login'}})) {
 3977:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3978:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3979:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3980:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3981:                                 $domconfig{'login'}{$key}{$img};
 3982:                         }
 3983:                     } else {
 3984:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3985:                     }
 3986:                 }
 3987:             } else {
 3988:                 $legacy{'login'} = 1;
 3989:             }
 3990:         } else {
 3991:             $legacy{'login'} = 1;
 3992:         }
 3993:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3994:             if (keys(%{$domconfig{'rolecolors'}})) {
 3995:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3996:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3997:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3998:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3999:                         }
 4000:                     }
 4001:                 }
 4002:             } else {
 4003:                 $legacy{'rolecolors'} = 1;
 4004:             }
 4005:         } else {
 4006:             $legacy{'rolecolors'} = 1;
 4007:         }
 4008:         if (keys(%legacy) > 0) {
 4009:             my %legacyhash = &get_legacy_domconf($udom);
 4010:             foreach my $item (keys(%legacyhash)) {
 4011:                 if ($item =~ /^\Q$udom\E\.login/) {
 4012:                     if ($legacy{'login'}) { 
 4013:                         $designhash{$item} = $legacyhash{$item};
 4014:                     }
 4015:                 } else {
 4016:                     if ($legacy{'rolecolors'}) {
 4017:                         $designhash{$item} = $legacyhash{$item};
 4018:                     }
 4019:                 }
 4020:             }
 4021:         }
 4022:     } else {
 4023:         %designhash = &get_legacy_domconf($udom); 
 4024:     }
 4025:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4026: 				  $cachetime);
 4027:     return %designhash;
 4028: }
 4029: 
 4030: sub get_legacy_domconf {
 4031:     my ($udom) = @_;
 4032:     my %legacyhash;
 4033:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4034:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4035:     if (-e $designfile) {
 4036:         if ( open (my $fh,"<$designfile") ) {
 4037:             while (my $line = <$fh>) {
 4038:                 next if ($line =~ /^\#/);
 4039:                 chomp($line);
 4040:                 my ($key,$val)=(split(/\=/,$line));
 4041:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4042:             }
 4043:             close($fh);
 4044:         }
 4045:     }
 4046:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4047:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4048:     }
 4049:     return %legacyhash;
 4050: }
 4051: 
 4052: =pod
 4053: 
 4054: =item * &domainlogo()
 4055: 
 4056: Inputs: $domain (usually will be undef)
 4057: 
 4058: Returns: A link to a domain logo, if the domain logo exists.
 4059: If the domain logo does not exist, a description of the domain.
 4060: 
 4061: =cut
 4062: 
 4063: ###############################################
 4064: sub domainlogo {
 4065:     my $domain = &determinedomain(shift);
 4066:     my %designhash = &get_domainconf($domain);    
 4067:     # See if there is a logo
 4068:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4069:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4070:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4071: 	    if ($imgsrc =~ m{^/res/}) {
 4072: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4073: 		&Apache::lonnet::repcopy($local_name);
 4074: 	    }
 4075: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4076:         } 
 4077:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4078:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4079:         return &Apache::lonnet::domain($domain,'description');
 4080:     } else {
 4081:         return '';
 4082:     }
 4083: }
 4084: ##############################################
 4085: 
 4086: =pod
 4087: 
 4088: =item * &designparm()
 4089: 
 4090: Inputs: $which parameter; $domain (usually will be undef)
 4091: 
 4092: Returns: value of designparamter $which
 4093: 
 4094: =cut
 4095: 
 4096: 
 4097: ##############################################
 4098: sub designparm {
 4099:     my ($which,$domain)=@_;
 4100:     if ($env{'browser.blackwhite'} eq 'on') {
 4101: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4102: 	    return '#000000';
 4103: 	}
 4104: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4105: 	    return '#FFFFFF';
 4106: 	}
 4107: 	if ($which=~/\.tabbg$/) {
 4108: 	    return '#CCCCCC';
 4109: 	}
 4110:     }
 4111:     if (exists($env{'environment.color.'.$which})) {
 4112: 	return $env{'environment.color.'.$which};
 4113:     }
 4114:     $domain=&determinedomain($domain);
 4115:     my %domdesign = &get_domainconf($domain);
 4116:     my $output;
 4117:     if ($domdesign{$domain.'.'.$which} ne '') {
 4118: 	$output = $domdesign{$domain.'.'.$which};
 4119:     } else {
 4120:         $output = $defaultdesign{$which};
 4121:     }
 4122:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4123:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4124:         if ($output =~ m{^/(adm|res)/}) {
 4125: 	    if ($output =~ m{^/res/}) {
 4126: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4127: 		&Apache::lonnet::repcopy($local_name);
 4128: 	    }
 4129:             $output = &lonhttpdurl($output);
 4130:         }
 4131:     }
 4132:     return $output;
 4133: }
 4134: 
 4135: ###############################################
 4136: ###############################################
 4137: 
 4138: =pod
 4139: 
 4140: =back
 4141: 
 4142: =head1 HTML Helpers
 4143: 
 4144: =over 4
 4145: 
 4146: =item * &bodytag()
 4147: 
 4148: Returns a uniform header for LON-CAPA web pages.
 4149: 
 4150: Inputs: 
 4151: 
 4152: =over 4
 4153: 
 4154: =item * $title, A title to be displayed on the page.
 4155: 
 4156: =item * $function, the current role (can be undef).
 4157: 
 4158: =item * $addentries, extra parameters for the <body> tag.
 4159: 
 4160: =item * $bodyonly, if defined, only return the <body> tag.
 4161: 
 4162: =item * $domain, if defined, force a given domain.
 4163: 
 4164: =item * $forcereg, if page should register as content page (relevant for 
 4165:             text interface only)
 4166: 
 4167: =item * $customtitle, alternate text to use instead of $title
 4168:                       in the title box that appears, this text
 4169:                       is not auto translated like the $title is
 4170: 
 4171: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4172:                    navigational links
 4173: 
 4174: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4175: 
 4176: =item * $notitle, if true keep the nav controls, but remove the title bar
 4177: 
 4178: =item * $no_inline_link, if true and in remote mode, don't show the 
 4179:          'Switch To Inline Menu' link
 4180: 
 4181: =item * $args, optional argument valid values are
 4182:             no_auto_mt_title -> prevents &mt()ing the title arg
 4183:             inherit_jsmath -> when creating popup window in a page,
 4184:                               should it have jsmath forced on by the
 4185:                               current page
 4186: 
 4187: =back
 4188: 
 4189: Returns: A uniform header for LON-CAPA web pages.  
 4190: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4191: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4192: other decorations will be returned.
 4193: 
 4194: =cut
 4195: 
 4196: sub bodytag {
 4197:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4198: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4199: 
 4200:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4201: 
 4202:     $function = &get_users_function() if (!$function);
 4203:     my $img =    &designparm($function.'.img',$domain);
 4204:     my $font =   &designparm($function.'.font',$domain);
 4205:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4206: 
 4207:     my %design = ( 'style'   => 'margin-top: 0px',
 4208: 		   'bgcolor' => $pgbg,
 4209: 		   'text'    => $font,
 4210:                    'alink'   => &designparm($function.'.alink',$domain),
 4211: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4212: 		   'link'    => &designparm($function.'.link',$domain),);
 4213:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4214: 
 4215:  # role and realm
 4216:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4217:     if ($role  eq 'ca') {
 4218:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4219:         $realm = &plainname($rname,$rdom);
 4220:     } 
 4221: # realm
 4222:     if ($env{'request.course.id'}) {
 4223:         if ($env{'request.role'} !~ /^cr/) {
 4224:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4225:         }
 4226: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4227:     } else {
 4228:         $role = &Apache::lonnet::plaintext($role);
 4229:     }
 4230: 
 4231:     if (!$realm) { $realm='&nbsp;'; }
 4232: # Set messages
 4233:     my $messages=&domainlogo($domain);
 4234: 
 4235:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4236: 
 4237: # construct main body tag
 4238:     my $bodytag = "<body $extra_body_attr>".
 4239: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4240: 
 4241:     if ($bodyonly) {
 4242:         return $bodytag;
 4243:     } elsif ($env{'browser.interface'} eq 'textual') {
 4244: # Accessibility
 4245:           
 4246: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4247: 	if (!$notitle) {
 4248: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4249: 	}
 4250: 	return $bodytag;
 4251:     }
 4252: 
 4253:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4254:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4255: 	undef($role);
 4256:     } else {
 4257: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4258:     }
 4259:     
 4260:     my $roleinfo=(<<ENDROLE);
 4261: <td class="LC_title_bar_who">
 4262: <div class="LC_title_bar_name">
 4263:     $name
 4264:     &nbsp;
 4265: </div>
 4266: <div class="LC_title_bar_role">
 4267: $role&nbsp;
 4268: </div>
 4269: <div class="LC_title_bar_realm">
 4270: $realm&nbsp;
 4271: </div>
 4272: </td>
 4273: ENDROLE
 4274: 
 4275:     my $titleinfo = '<h1>'.$title.'</h1>';
 4276:     if ($customtitle) {
 4277:         $titleinfo = $customtitle;
 4278:     }
 4279:     #
 4280:     # Extra info if you are the DC
 4281:     my $dc_info = '';
 4282:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4283:                         $env{'course.'.$env{'request.course.id'}.
 4284:                                  '.domain'}.'/'})) {
 4285:         my $cid = $env{'request.course.id'};
 4286:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4287:         $dc_info =~ s/\s+$//;
 4288:         $dc_info = '('.$dc_info.')';
 4289:     }
 4290: 
 4291:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4292:         # No Remote
 4293: 	if ($env{'request.state'} eq 'construct') {
 4294: 	    $forcereg=1;
 4295: 	}
 4296: 
 4297: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4298: 	    # this is for resources; directories have customtitle, and crumbs
 4299:             # and select recent are created in lonpubdir.pm  
 4300: 	    my ($uname,$thisdisfn)=
 4301: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4302: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4303: 	    $formaction=~s/\/+/\//g;
 4304: 
 4305: 	    my $parentpath = '';
 4306: 	    my $lastitem = '';
 4307: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4308: 		$parentpath = $1;
 4309: 		$lastitem = $2;
 4310: 	    } else {
 4311: 		$lastitem = $thisdisfn;
 4312: 	    }
 4313: 	    $titleinfo = 
 4314: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4315: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4316: 		.'<form name="dirs" method="post" action="'.$formaction
 4317: 		.'" target="_top"><tt><b>'
 4318: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4319: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4320: 		.'</form>'
 4321: 		.&Apache::lonmenu::constspaceform();
 4322:         }
 4323: 
 4324:         my $titletable;
 4325: 	if (!$notitle) {
 4326: 	    $titletable =
 4327: 		'<table id="LC_title_bar">'.
 4328:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4329: 			 '</tr></table>';
 4330: 	}
 4331: 	if ($notopbar) {
 4332: 	    $bodytag .= $titletable;
 4333: 	} else {
 4334: 	    if ($env{'request.state'} eq 'construct') {
 4335:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4336: 							  $titletable);
 4337:             } else {
 4338:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4339: 		    $titletable;
 4340:             }
 4341:         }
 4342:         return $bodytag;
 4343:     }
 4344: 
 4345: #
 4346: # Top frame rendering, Remote is up
 4347: #
 4348: 
 4349:     my $imgsrc = $img;
 4350:     if ($img =~ /^\/adm/) {
 4351:         $imgsrc = &lonhttpdurl($img);
 4352:     }
 4353:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4354: 
 4355:     # Explicit link to get inline menu
 4356:     my $menu= ($no_inline_link?''
 4357: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4358:     #
 4359:     if ($notitle) {
 4360: 	return $bodytag;
 4361:     }
 4362:     return(<<ENDBODY);
 4363: $bodytag
 4364: <table id="LC_title_bar" class="LC_with_remote">
 4365: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4366:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4367: </tr>
 4368: <tr><td>$titleinfo $dc_info $menu</td>
 4369: $roleinfo
 4370: </tr>
 4371: </table>
 4372: ENDBODY
 4373: }
 4374: 
 4375: sub make_attr_string {
 4376:     my ($register,$attr_ref) = @_;
 4377: 
 4378:     if ($attr_ref && !ref($attr_ref)) {
 4379: 	die("addentries Must be a hash ref ".
 4380: 	    join(':',caller(1))." ".
 4381: 	    join(':',caller(0))." ");
 4382:     }
 4383: 
 4384:     if ($register) {
 4385: 	my ($on_load,$on_unload);
 4386: 	foreach my $key (keys(%{$attr_ref})) {
 4387: 	    if      (lc($key) eq 'onload') {
 4388: 		$on_load.=$attr_ref->{$key}.';';
 4389: 		delete($attr_ref->{$key});
 4390: 
 4391: 	    } elsif (lc($key) eq 'onunload') {
 4392: 		$on_unload.=$attr_ref->{$key}.';';
 4393: 		delete($attr_ref->{$key});
 4394: 	    }
 4395: 	}
 4396: 	$attr_ref->{'onload'}  =
 4397: 	    &Apache::lonmenu::loadevents().  $on_load;
 4398: 	$attr_ref->{'onunload'}=
 4399: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4400:     }
 4401: 
 4402: # Accessibility font enhance
 4403:     if ($env{'browser.fontenhance'} eq 'on') {
 4404: 	my $style;
 4405: 	foreach my $key (keys(%{$attr_ref})) {
 4406: 	    if (lc($key) eq 'style') {
 4407: 		$style.=$attr_ref->{$key}.';';
 4408: 		delete($attr_ref->{$key});
 4409: 	    }
 4410: 	}
 4411: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4412:     }
 4413: 
 4414:     if ($env{'browser.blackwhite'} eq 'on') {
 4415: 	delete($attr_ref->{'font'});
 4416: 	delete($attr_ref->{'link'});
 4417: 	delete($attr_ref->{'alink'});
 4418: 	delete($attr_ref->{'vlink'});
 4419: 	delete($attr_ref->{'bgcolor'});
 4420: 	delete($attr_ref->{'background'});
 4421:     }
 4422: 
 4423:     my $attr_string;
 4424:     foreach my $attr (keys(%$attr_ref)) {
 4425: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4426:     }
 4427:     return $attr_string;
 4428: }
 4429: 
 4430: 
 4431: ###############################################
 4432: ###############################################
 4433: 
 4434: =pod
 4435: 
 4436: =item * &endbodytag()
 4437: 
 4438: Returns a uniform footer for LON-CAPA web pages.
 4439: 
 4440: Inputs: 1 - optional reference to an args hash
 4441: If in the hash, key for noredirectlink has a value which evaluates to true,
 4442: a 'Continue' link is not displayed if the page contains an
 4443: internal redirect in the <head></head> section,
 4444: i.e., $env{'internal.head.redirect'} exists   
 4445: 
 4446: =cut
 4447: 
 4448: sub endbodytag {
 4449:     my ($args) = @_;
 4450:     my $endbodytag='</body>';
 4451:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4452:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4453:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4454: 	    $endbodytag=
 4455: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4456: 	        &mt('Continue').'</a>'.
 4457: 	        $endbodytag;
 4458:         }
 4459:     }
 4460:     return $endbodytag;
 4461: }
 4462: 
 4463: =pod
 4464: 
 4465: =item * &standard_css()
 4466: 
 4467: Returns a style sheet
 4468: 
 4469: Inputs: (all optional)
 4470:             domain         -> force to color decorate a page for a specific
 4471:                                domain
 4472:             function       -> force usage of a specific rolish color scheme
 4473:             bgcolor        -> override the default page bgcolor
 4474: 
 4475: =cut
 4476: 
 4477: sub standard_css {
 4478:     my ($function,$domain,$bgcolor) = @_;
 4479:     $function  = &get_users_function() if (!$function);
 4480:     my $img    = &designparm($function.'.img',   $domain);
 4481:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4482:     my $font   = &designparm($function.'.font',  $domain);
 4483:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4484:     my $pgbg_or_bgcolor =
 4485: 	         $bgcolor ||
 4486: 	         &designparm($function.'.pgbg',  $domain);
 4487:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4488:     my $alink  = &designparm($function.'.alink', $domain);
 4489:     my $vlink  = &designparm($function.'.vlink', $domain);
 4490:     my $link   = &designparm($function.'.link',  $domain);
 4491: 
 4492:     my $loginbg = &designparm('login.sidebg',$domain);
 4493:     my $bgcol = &designparm('login.bgcol',$domain);
 4494:     my $textcol = &designparm('login.textcol',$domain);
 4495: 
 4496:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4497:     my $mono                 = 'monospace';
 4498:     my $data_table_head      = $tabbg;
 4499:     my $data_table_light     = '#EEEEEE';
 4500:     my $data_table_dark      = '#DDDDDD';
 4501:     my $data_table_darker    = '#CCCCCC';
 4502:     my $data_table_highlight = '#FFFF00';
 4503:     my $mail_new             = '#FFBB77';
 4504:     my $mail_new_hover       = '#DD9955';
 4505:     my $mail_read            = '#BBBB77';
 4506:     my $mail_read_hover      = '#999944';
 4507:     my $mail_replied         = '#AAAA88';
 4508:     my $mail_replied_hover   = '#888855';
 4509:     my $mail_other           = '#99BBBB';
 4510:     my $mail_other_hover     = '#669999';
 4511:     my $table_header         = '#DDDDDD';
 4512:     my $feedback_link_bg     = '#BBBBBB';
 4513:     my $lg_border_color	     = '#C8C8C8';
 4514: 
 4515:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4516: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4517: 	                                                 : '0px 3px 0px 4px';
 4518: 
 4519: 
 4520:     return <<END;
 4521: body{
 4522:      font-family: $sans;
 4523:      line-height:130%;
 4524:      font-size:0.83em;
 4525:      color:$font;
 4526:   }
 4527: a:link, a:visited { font-size:100%; }
 4528: 
 4529: a:focus { color: red; background: yellow }
 4530: table.thinborder,
 4531: table.thinborder tr th {
 4532:   border-style: solid;
 4533:   border-width: 1px;
 4534:   border-color: $lg_border_color;
 4535:   background: $tabbg;
 4536: }
 4537: table.thinborder tr td {
 4538:   border-style: solid;
 4539:   border-width: 1px;
 4540:   border-color: $lg_border_color;
 4541: }
 4542: 
 4543: form, .inline { display: inline; }
 4544: 
 4545: .LC_right {text-align:right;}
 4546: .LC_middle {vertical-align:middle;}
 4547: 
 4548: /* just for tests */
 4549: .LC_400Box {width:400px; }
 4550: /* end */
 4551: 
 4552: .LC_filename {
 4553:   font-family: $mono;
 4554:   white-space:pre;
 4555: }
 4556: 
 4557: .LC_fileicon {
 4558:   border: none;
 4559:   height: 1.3em;
 4560:   vertical-align: text-bottom;
 4561:   margin-right: 0.3em;
 4562:   text-decoration:none;
 4563: }
 4564: 
 4565: .LC_error {
 4566:   color: red;
 4567:   font-size: larger;
 4568: }
 4569: .LC_warning,
 4570: .LC_diff_removed {
 4571:   color: red;
 4572: }
 4573: 
 4574: .LC_info,
 4575: .LC_success,
 4576: .LC_diff_added {
 4577:   color: green;
 4578: }
 4579: .LC_unknown {
 4580:   color: yellow;
 4581: }
 4582: 
 4583: .LC_icon {
 4584:   border: none;
 4585: }
 4586: 
 4587: .LC_indexer_icon {
 4588:   border: 0px;
 4589:   height: 22px;
 4590: }
 4591: .LC_docs_spacer {
 4592:   width: 25px;
 4593:   height: 1px;
 4594:   border: none;
 4595: }
 4596: 
 4597: .LC_internal_info {
 4598:   color: #999999;
 4599: }
 4600: 
 4601: table.LC_pastsubmission {
 4602:   border: 1px solid black;
 4603:   margin: 2px;
 4604: }
 4605: 
 4606: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4607:   width: 100%;
 4608:   background: $pgbg;
 4609:   border: 2px;
 4610:   border-collapse: separate;
 4611:   padding: 0px;
 4612: }
 4613: 
 4614: table#LC_title_bar, table.LC_breadcrumbs,
 4615: table#LC_title_bar.LC_with_remote {
 4616:   width: 100%;
 4617:   border-color: $pgbg;
 4618:   border-style: solid;
 4619:   border-width: $border;
 4620: 
 4621:   background: $pgbg;
 4622:   font-family: $sans;
 4623:   border-collapse: collapse;
 4624:   padding: 0px;
 4625: }
 4626: table.LC_docs_path {
 4627:   width: 100%;
 4628:   border: 0;
 4629:   background: $pgbg;
 4630:   font-family: $sans;
 4631:   border-collapse: collapse;
 4632:   padding: 0px;
 4633: }
 4634: 
 4635: table#LC_title_bar td {
 4636:   background: $tabbg;
 4637: }
 4638: table#LC_title_bar .LC_title_bar_who {
 4639:   background: $tabbg;
 4640:   color: $font;
 4641:   font: small $sans;
 4642:   text-align: right;
 4643:   margin: 0px;
 4644: }
 4645: table#LC_title_bar .LC_title_bar_name {
 4646:   margin: 0px;
 4647: }
 4648: table#LC_title_bar .LC_title_bar_role {
 4649:   margin: 0px;
 4650: }
 4651: table#LC_title_bar .LC_title_bar_realm {
 4652:   margin: 0px;
 4653: }
 4654: span.LC_metadata {
 4655:     font-family: $sans;
 4656: }
 4657: table#LC_title_bar td.LC_title_bar_domain_logo {
 4658:   background: $sidebg;
 4659:   text-align: right;
 4660:   padding: 0px;
 4661: }
 4662: table#LC_title_bar td.LC_title_bar_role_logo {
 4663:   background: $sidebg;
 4664:   padding: 0px;
 4665: }
 4666: 
 4667: table#LC_menubuttons img{
 4668:   border: 0px;
 4669: }
 4670: table#LC_top_nav td {
 4671:   background: $tabbg;
 4672:   border: 0px;
 4673:   font-size: small;
 4674:   vertical-align:top;
 4675:   padding:2px 5px 2px 5px;
 4676: }
 4677: table#LC_top_nav td a, div#LC_top_nav a {
 4678:   color: $font;
 4679:   font-family: $sans;
 4680: }
 4681: table#LC_top_nav td.LC_top_nav_logo {
 4682:   background: $tabbg;
 4683:   text-align: left;
 4684:   white-space: nowrap;
 4685:   width: 31px;
 4686: }
 4687: table#LC_top_nav td.LC_top_nav_logo img {
 4688:   border: 0px;
 4689:   vertical-align: bottom;
 4690: }
 4691: table#LC_top_nav td.LC_top_nav_exit,
 4692: table#LC_top_nav td.LC_top_nav_help {
 4693:   width: 2.0em;
 4694: }
 4695: table#LC_top_nav td.LC_top_nav_login {
 4696:   width: 4.0em;
 4697:   text-align: center;
 4698: }
 4699: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4700:   background: $tabbg;
 4701:   color: $font;
 4702:   font-family: $sans;
 4703:   font-size: smaller;
 4704: }
 4705: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4706: table.LC_docs_path td.LC_docs_path_component {
 4707:   background: $tabbg;
 4708:   color: $font;
 4709:   font-family: $sans;
 4710:   font-size: larger;
 4711:   text-align: right;
 4712: }
 4713: td.LC_table_cell_checkbox {
 4714:   text-align: center;
 4715: }
 4716: table#LC_mainmenu td.LC_mainmenu_column {
 4717:     vertical-align: top;
 4718: }
 4719: 
 4720: .LC_fontsize_small
 4721: {
 4722:  font-size: 70%;
 4723: }
 4724: 
 4725: .LC_fontsize_medium
 4726: {
 4727:  font-size: 85%;
 4728: }
 4729: 
 4730: .LC_fontsize_large
 4731: {
 4732:  font-size: 120%;
 4733: }
 4734: 
 4735: .LC_menubuttons_inline_text {
 4736:   color: $font;
 4737:   font-family: $sans;
 4738:   font-size: 90%;
 4739:   padding-left:3px;
 4740: }
 4741: 
 4742: .LC_menubuttons_link {
 4743:   text-decoration: none;
 4744: }
 4745: /*2008--9-5: new menu style sheet.Changed category*/
 4746: .LC_menubuttons_category {
 4747:   color: $font;
 4748:   background: $pgbg;
 4749:   font-family: $sans;
 4750:   font-size: larger;
 4751:   font-weight: bold;
 4752: }
 4753: 
 4754: td.LC_menubuttons_text {
 4755:  	color: $font;
 4756: }
 4757: 
 4758: 
 4759: 
 4760: .LC_current_location {
 4761:   font-family: $sans;
 4762:   background: $tabbg;
 4763: }
 4764: .LC_new_mail {
 4765:   font-family: $sans;
 4766:   background: $tabbg;
 4767:   font-weight: bold;
 4768: }
 4769: 
 4770: 
 4771: .LC_dropadd_labeltext {
 4772:   font-family: $sans;
 4773:   text-align: right;
 4774: }
 4775: 
 4776: .LC_preferences_labeltext {
 4777:   font-family: $sans;
 4778:   text-align: right;
 4779: }
 4780: 
 4781: .LC_roleslog_note {
 4782:   font-size: small;
 4783: }
 4784: 
 4785: .LC_mail_functions {
 4786:     font-weight: bold;
 4787: }
 4788: 
 4789: table.LC_aboutme_port {
 4790:   border: 0px;
 4791:   border-collapse: collapse;
 4792:   border-spacing: 0px;
 4793: }
 4794: table.LC_data_table, table.LC_mail_list {
 4795:   border: 1px solid #000000;
 4796:   border-collapse: separate;
 4797:   border-spacing: 1px;
 4798:   background: $pgbg;
 4799: }
 4800: .LC_data_table_dense {
 4801:   font-size: small;
 4802: }
 4803: table.LC_nested_outer {
 4804:   border: 1px solid #000000;
 4805:   border-collapse: collapse;
 4806:   border-spacing: 0px;
 4807:   width: 100%;
 4808: }
 4809: table.LC_nested {
 4810:   border: 0px;
 4811:   border-collapse: collapse;
 4812:   border-spacing: 0px;
 4813:   width: 100%;
 4814: }
 4815: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4816: table.LC_prior_tries tr th {
 4817:   font-weight: bold;
 4818:   background-color: $data_table_head;
 4819:   font-size:90%;
 4820: }
 4821: table.LC_data_table tr.LC_info_row > td {
 4822:   background-color: #CCCCCC;
 4823:   font-weight: bold;
 4824:   text-align: left;
 4825: }
 4826: table.LC_data_table tr.LC_odd_row > td,
 4827: table.LC_pick_box tr > td.LC_odd_row,
 4828: table.LC_aboutme_port tr td {
 4829:   background-color: $data_table_light;
 4830:   padding: 2px;
 4831: }
 4832: table.LC_data_table tr.LC_even_row > td,
 4833: table.LC_pick_box tr > td.LC_even_row,
 4834: table.LC_aboutme_port tr.LC_even_row td {
 4835:   background-color: $data_table_dark;
 4836:   padding: 2px;
 4837: }
 4838: table.LC_data_table tr.LC_data_table_highlight td {
 4839:   background-color: $data_table_darker;
 4840: }
 4841: table.LC_data_table tr td.LC_leftcol_header {
 4842:   background-color: $data_table_head;
 4843:   font-weight: bold;
 4844: }
 4845: table.LC_data_table tr.LC_empty_row td,
 4846: table.LC_nested tr.LC_empty_row td {
 4847:   background-color: #FFFFFF;
 4848:   font-weight: bold;
 4849:   font-style: italic;
 4850:   text-align: center;
 4851:   padding: 8px;
 4852: }
 4853: table.LC_nested tr.LC_empty_row td {
 4854:   padding: 4ex
 4855: }
 4856: table.LC_nested_outer tr th {
 4857:   font-weight: bold;
 4858:   background-color: $data_table_head;
 4859:   font-size: small;
 4860:   border-bottom: 1px solid #000000;
 4861: }
 4862: table.LC_nested_outer tr td.LC_subheader {
 4863:   background-color: $data_table_head;
 4864:   font-weight: bold;
 4865:   font-size: small;
 4866:   border-bottom: 1px solid #000000;
 4867:   text-align: right;
 4868: }
 4869: table.LC_nested tr.LC_info_row td {
 4870:   background-color: #CCCCCC;
 4871:   font-weight: bold;
 4872:   font-size: small;
 4873:   text-align: center;
 4874: }
 4875: table.LC_nested tr.LC_info_row td.LC_left_item,
 4876: table.LC_nested_outer tr th.LC_left_item {
 4877:   text-align: left;
 4878: }
 4879: table.LC_nested td {
 4880:   background-color: #FFFFFF;
 4881:   font-size: small;
 4882: }
 4883: table.LC_nested_outer tr th.LC_right_item,
 4884: table.LC_nested tr.LC_info_row td.LC_right_item,
 4885: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4886: table.LC_nested tr td.LC_right_item {
 4887:   text-align: right;
 4888: }
 4889: 
 4890: table.LC_nested tr.LC_odd_row td {
 4891:   background-color: #EEEEEE;
 4892: }
 4893: 
 4894: table.LC_createuser {
 4895: }
 4896: 
 4897: table.LC_createuser tr.LC_section_row td {
 4898:   font-size: small;
 4899: }
 4900: 
 4901: table.LC_createuser tr.LC_info_row td  {
 4902:   background-color: #CCCCCC;
 4903:   font-weight: bold;
 4904:   text-align: center;
 4905: }
 4906: 
 4907: table.LC_calendar {
 4908:   border: 1px solid #000000;
 4909:   border-collapse: collapse;
 4910: }
 4911: table.LC_calendar_pickdate {
 4912:   font-size: xx-small;
 4913: }
 4914: table.LC_calendar tr td {
 4915:   border: 1px solid #000000;
 4916:   vertical-align: top;
 4917: }
 4918: table.LC_calendar tr td.LC_calendar_day_empty {
 4919:   background-color: $data_table_dark;
 4920: }
 4921: table.LC_calendar tr td.LC_calendar_day_current {
 4922:   background-color: $data_table_highlight;
 4923: }
 4924: table.LC_mail_list tr.LC_mail_new {
 4925:   background-color: $mail_new;
 4926: }
 4927: table.LC_mail_list tr.LC_mail_new:hover {
 4928:   background-color: $mail_new_hover;
 4929: }
 4930: table.LC_mail_list tr.LC_mail_even{
 4931: }
 4932: table.LC_mail_list tr.LC_mail_odd{
 4933: }
 4934: table.LC_mail_list tr.LC_mail_read {
 4935:   background-color: $mail_read;
 4936: }
 4937: table.LC_mail_list tr.LC_mail_read:hover {
 4938:   background-color: $mail_read_hover;
 4939: }
 4940: table.LC_mail_list tr.LC_mail_replied {
 4941:   background-color: $mail_replied;
 4942: }
 4943: table.LC_mail_list tr.LC_mail_replied:hover {
 4944:   background-color: $mail_replied_hover;
 4945: }
 4946: table.LC_mail_list tr.LC_mail_other {
 4947:   background-color: $mail_other;
 4948: }
 4949: table.LC_mail_list tr.LC_mail_other:hover {
 4950:   background-color: $mail_other_hover;
 4951: }
 4952: 
 4953: table.LC_data_table tr > td.LC_browser_file,
 4954: table.LC_data_table tr > td.LC_browser_file_published {
 4955:   background: #CCFF88;
 4956: }
 4957: table.LC_data_table tr > td.LC_browser_file_locked,
 4958: table.LC_data_table tr > td.LC_browser_file_unpublished {
 4959:   background: #FFAA99;
 4960: }
 4961: table.LC_data_table tr > td.LC_browser_file_obsolete {
 4962:   background: #AAAAAA;
 4963: }
 4964: table.LC_data_table tr > td.LC_browser_file_modified,
 4965: table.LC_data_table tr > td.LC_browser_file_metamodified {
 4966:   background: #FFFF77;
 4967: }
 4968: table.LC_data_table tr.LC_browser_folder > td {
 4969:   background: #CCCCFF;
 4970: }
 4971: 
 4972: table.LC_data_table tr > td.LC_roles_is {
 4973: /*  background: #77FF77; */
 4974: }
 4975: table.LC_data_table tr > td.LC_roles_future {
 4976:   background: #FFFF77;
 4977: }
 4978: table.LC_data_table tr > td.LC_roles_will {
 4979:   background: #FFAA77;
 4980: }
 4981: table.LC_data_table tr > td.LC_roles_expired {
 4982:   background: #FF7777;
 4983: }
 4984: table.LC_data_table tr > td.LC_roles_will_not {
 4985:   background: #AAFF77;
 4986: }
 4987: table.LC_data_table tr > td.LC_roles_selected {
 4988:   background: #11CC55;
 4989: }
 4990: 
 4991: span.LC_current_location {
 4992:   font-size:larger;
 4993:   background: $pgbg;
 4994: }
 4995: 
 4996: span.LC_parm_menu_item {
 4997:   font-size: larger;
 4998:   font-family: $sans;
 4999: }
 5000: span.LC_parm_scope_all {
 5001:   color: red;
 5002: }
 5003: span.LC_parm_scope_folder {
 5004:   color: green;
 5005: }
 5006: span.LC_parm_scope_resource {
 5007:   color: orange;
 5008: }
 5009: span.LC_parm_part {
 5010:   color: blue;
 5011: }
 5012: span.LC_parm_folder, span.LC_parm_symb {
 5013:   font-size: x-small;
 5014:   font-family: $mono;
 5015:   color: #AAAAAA;
 5016: }
 5017: 
 5018: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 5019: td.LC_parm_overview_parm_selectors,td.LC_parm_overview_restrictions  {
 5020:   border: 1px solid black;
 5021:   border-collapse: collapse;
 5022: }
 5023: table.LC_parm_overview_restrictions td {
 5024:   border-width: 1px 4px 1px 4px;
 5025:   border-style: solid;
 5026:   border-color: $pgbg;
 5027:   text-align: center;
 5028: }
 5029: table.LC_parm_overview_restrictions th {
 5030:   background: $tabbg;
 5031:   border-width: 1px 4px 1px 4px;
 5032:   border-style: solid;
 5033:   border-color: $pgbg;
 5034: }
 5035: table#LC_helpmenu {
 5036:   border: 0px;
 5037:   height: 55px;
 5038:   border-spacing: 0px;
 5039: }
 5040: 
 5041: table#LC_helpmenu fieldset legend {
 5042:   font-size: larger;
 5043:   font-weight: bold;
 5044: }
 5045: table#LC_helpmenu_links {
 5046:   width: 100%;
 5047:   border: 1px solid black;
 5048:   background: $pgbg;
 5049:   padding: 0px;
 5050:   border-spacing: 1px;
 5051: }
 5052: table#LC_helpmenu_links tr td {
 5053:   padding: 1px;
 5054:   background: $tabbg;
 5055:   text-align: center;
 5056:   font-weight: bold;
 5057: }
 5058: 
 5059: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5060: table#LC_helpmenu_links a:active {
 5061:   text-decoration: none;
 5062:   color: $font;
 5063: }
 5064: table#LC_helpmenu_links a:hover {
 5065:   text-decoration: underline;
 5066:   color: $vlink;
 5067: }
 5068: 
 5069: .LC_chrt_popup_exists {
 5070:   border: 1px solid #339933;
 5071:   margin: -1px;
 5072: }
 5073: .LC_chrt_popup_up {
 5074:   border: 1px solid yellow;
 5075:   margin: -1px;
 5076: }
 5077: .LC_chrt_popup {
 5078:   border: 1px solid #8888FF;
 5079:   background: #CCCCFF;
 5080: }
 5081: table.LC_pick_box {
 5082:   border-collapse: separate;
 5083:   background: white;
 5084:   border: 1px solid black;
 5085:   border-spacing: 1px;
 5086: }
 5087: table.LC_pick_box td.LC_pick_box_title {
 5088:   background: $tabbg;
 5089:   font-weight: bold;
 5090:   text-align: right;
 5091:   vertical-align: top;
 5092:   width: 184px;
 5093:   padding: 8px;
 5094: }
 5095: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5096:   background: $tabbg;
 5097:   font-weight: bold;
 5098:   text-align: right;
 5099:   width: 350px;
 5100:   padding: 8px;
 5101: }
 5102: 
 5103: table.LC_pick_box td.LC_pick_box_value {
 5104:   text-align: left;
 5105:   padding: 8px;
 5106: }
 5107: table.LC_pick_box td.LC_pick_box_select {
 5108:   text-align: left;
 5109:   padding: 8px;
 5110: }
 5111: table.LC_pick_box td.LC_pick_box_separator {
 5112:   padding: 0px;
 5113:   height: 1px;
 5114:   background: black;
 5115: }
 5116: table.LC_pick_box td.LC_pick_box_submit {
 5117:   text-align: right;
 5118: }
 5119: table.LC_pick_box td.LC_evenrow_value {
 5120:   text-align: left;
 5121:   padding: 8px;
 5122:   background-color: $data_table_light;
 5123: }
 5124: table.LC_pick_box td.LC_oddrow_value {
 5125:   text-align: left;
 5126:   padding: 8px;
 5127:   background-color: $data_table_light;
 5128: }
 5129: table.LC_helpform_receipt {
 5130:   width: 620px;
 5131:   border-collapse: separate;
 5132:   background: white;
 5133:   border: 1px solid black;
 5134:   border-spacing: 1px;
 5135: }
 5136: table.LC_helpform_receipt td.LC_pick_box_title {
 5137:   background: $tabbg;
 5138:   font-weight: bold;
 5139:   text-align: right;
 5140:   width: 184px;
 5141:   padding: 8px;
 5142: }
 5143: table.LC_helpform_receipt td.LC_evenrow_value {
 5144:   text-align: left;
 5145:   padding: 8px;
 5146:   background-color: $data_table_light;
 5147: }
 5148: table.LC_helpform_receipt td.LC_oddrow_value {
 5149:   text-align: left;
 5150:   padding: 8px;
 5151:   background-color: $data_table_light;
 5152: }
 5153: table.LC_helpform_receipt td.LC_pick_box_separator {
 5154:   padding: 0px;
 5155:   height: 1px;
 5156:   background: black;
 5157: }
 5158: span.LC_helpform_receipt_cat {
 5159:   font-weight: bold;
 5160: }
 5161: table.LC_group_priv_box {
 5162:   background: white;
 5163:   border: 1px solid black;
 5164:   border-spacing: 1px;
 5165: }
 5166: table.LC_group_priv_box td.LC_pick_box_title {
 5167:   background: $tabbg;
 5168:   font-weight: bold;
 5169:   text-align: right;
 5170:   width: 184px;
 5171: }
 5172: table.LC_group_priv_box td.LC_groups_fixed {
 5173:   background: $data_table_light;
 5174:   text-align: center;
 5175: }
 5176: table.LC_group_priv_box td.LC_groups_optional {
 5177:   background: $data_table_dark;
 5178:   text-align: center;
 5179: }
 5180: table.LC_group_priv_box td.LC_groups_functionality {
 5181:   background: $data_table_darker;
 5182:   text-align: center;
 5183:   font-weight: bold;
 5184: }
 5185: table.LC_group_priv td {
 5186:   text-align: left;
 5187:   padding: 0px;
 5188: }
 5189: 
 5190: table.LC_notify_front_page {
 5191:   background: white;
 5192:   border: 1px solid black;
 5193:   padding: 8px;
 5194: }
 5195: table.LC_notify_front_page td {
 5196:   padding: 8px;
 5197: }
 5198: .LC_navbuttons {
 5199:   margin: 2ex 0ex 2ex 0ex;
 5200: }
 5201: .LC_topic_bar {
 5202:   font-family: $sans;
 5203:   font-weight: bold;
 5204:   width: 100%;
 5205:   background: $tabbg;
 5206:   vertical-align: middle;
 5207:   margin: 2ex 0ex 2ex 0ex;
 5208: }
 5209: .LC_topic_bar span {
 5210:   vertical-align: middle;
 5211: }
 5212: .LC_topic_bar img {
 5213:   vertical-align: bottom;
 5214: }
 5215: table.LC_course_group_status {
 5216:   margin: 20px;
 5217: }
 5218: table.LC_status_selector td {
 5219:   vertical-align: top;
 5220:   text-align: center;
 5221:   padding: 4px;
 5222: }
 5223: table.LC_descriptive_input td.LC_description {
 5224:   vertical-align: top;
 5225:   text-align: right;
 5226:   font-weight: bold;
 5227: }
 5228: div.LC_feedback_link {
 5229:   clear: both;
 5230:   background: white;
 5231:   width: 100%;
 5232: }
 5233: span.LC_feedback_link {
 5234:   background: $feedback_link_bg;
 5235:   font-size: larger;
 5236: }
 5237: span.LC_message_link {
 5238:   background: $feedback_link_bg;
 5239:   font-size: larger;
 5240:   position: absolute;
 5241:   right: 1em;
 5242: }
 5243: 
 5244: table.LC_prior_tries {
 5245:   border: 1px solid #000000;
 5246:   border-collapse: separate;
 5247:   border-spacing: 1px;
 5248: }
 5249: 
 5250: table.LC_prior_tries td {
 5251:   padding: 2px;
 5252: }
 5253: 
 5254: .LC_answer_correct {
 5255:   background: #AAFFAA;
 5256:   color: black;
 5257: }
 5258: .LC_answer_charged_try {
 5259:   background: #FFAAAA ! important;
 5260:   color: black;
 5261: }
 5262: .LC_answer_not_charged_try,
 5263: .LC_answer_no_grade,
 5264: .LC_answer_late {
 5265:   background: #FFFFAA;
 5266:   color: black;
 5267: }
 5268: .LC_answer_previous {
 5269:   background: #AAAAFF;
 5270:   color: black;
 5271: }
 5272: .LC_answer_no_message {
 5273:   background: #FFFFFF;
 5274:   color: black;
 5275: }
 5276: .LC_answer_unknown {
 5277:   background: orange;
 5278:   color: black;
 5279: }
 5280: span.LC_prior_numerical,
 5281: span.LC_prior_string,
 5282: span.LC_prior_custom,
 5283: span.LC_prior_reaction,
 5284: span.LC_prior_math {
 5285:   font-family: monospace;
 5286:   white-space: pre;
 5287: }
 5288: 
 5289: span.LC_prior_string {
 5290:   font-family: monospace;
 5291:   white-space: pre;
 5292: }
 5293: 
 5294: table.LC_prior_option {
 5295:   width: 100%;
 5296:   border-collapse: collapse;
 5297: }
 5298: table.LC_prior_rank, table.LC_prior_match {
 5299:   border-collapse: collapse;
 5300: }
 5301: table.LC_prior_option tr td,
 5302: table.LC_prior_rank tr td,
 5303: table.LC_prior_match tr td {
 5304:   border: 1px solid #000000;
 5305: }
 5306: 
 5307: td.LC_nobreak,
 5308: span.LC_nobreak {
 5309:   white-space: nowrap;
 5310: }
 5311: 
 5312: span.LC_cusr_emph {
 5313:   font-style: italic;
 5314: }
 5315: 
 5316: span.LC_cusr_subheading {
 5317:   font-weight: normal;
 5318:   font-size: 85%;
 5319: }
 5320: 
 5321: table.LC_docs_documents {
 5322:   background: #BBBBBB;
 5323:   border-width: 0px;
 5324:   border-collapse: collapse;
 5325: }
 5326: table.LC_docs_documents td.LC_docs_document {
 5327:   border: 2px solid black;
 5328:   padding: 4px;
 5329: }
 5330: .LC_docs_entry_move {
 5331:   border: 0px;
 5332:   border-collapse: collapse;
 5333: }
 5334: 
 5335: .LC_docs_entry_move td {
 5336:   border: 2px solid #BBBBBB;
 5337:   background: #DDDDDD;
 5338: }
 5339: 
 5340: .LC_docs_editor td.LC_docs_entry_commands {
 5341:   background: #DDDDDD;
 5342:   font-size: x-small;
 5343: }
 5344: .LC_docs_copy {
 5345:   color: #000099;
 5346: }
 5347: .LC_docs_cut {
 5348:   color: #550044;
 5349: }
 5350: .LC_docs_rename {
 5351:   color: #009900;
 5352: }
 5353: .LC_docs_remove {
 5354:   color: #990000;
 5355: }
 5356: 
 5357: .LC_docs_reinit_warn,
 5358: .LC_docs_ext_edit {
 5359:   font-size: x-small;
 5360: }
 5361: 
 5362: .LC_docs_editor td.LC_docs_entry_title,
 5363: .LC_docs_editor td.LC_docs_entry_icon {
 5364:   background: #FFFFBB;
 5365: }
 5366: .LC_docs_editor td.LC_docs_entry_parameter {
 5367:   background: #BBBBFF;
 5368:   font-size: x-small;
 5369:   white-space: nowrap;
 5370: }
 5371: 
 5372: table.LC_docs_adddocs td,
 5373: table.LC_docs_adddocs th {
 5374:   border: 1px solid #BBBBBB;
 5375:   padding: 4px;
 5376:   background: #DDDDDD;
 5377: }
 5378: 
 5379: table.LC_sty_begin {
 5380:   background: #BBFFBB;
 5381: }
 5382: table.LC_sty_end {
 5383:   background: #FFBBBB;
 5384: }
 5385: 
 5386: table.LC_double_column {
 5387:   border-width: 0px;
 5388:   border-collapse: collapse;
 5389:   width: 100%;
 5390:   padding: 2px;
 5391: }
 5392: 
 5393: table.LC_double_column tr td.LC_left_col {
 5394:   top: 2px;
 5395:   left: 2px;
 5396:   width: 47%;
 5397:   vertical-align: top;
 5398: }
 5399: 
 5400: table.LC_double_column tr td.LC_right_col {
 5401:   top: 2px;
 5402:   right: 2px;
 5403:   width: 47%;
 5404:   vertical-align: top;
 5405: }
 5406: 
 5407: span.LC_role_level {
 5408:   font-weight: bold;
 5409: }
 5410: 
 5411: div.LC_left_float {
 5412:   float: left;
 5413:   padding-right: 5%;
 5414:   padding-bottom: 4px;
 5415: }
 5416: 
 5417: div.LC_clear_float_header {
 5418:   padding-bottom: 2px;
 5419: }
 5420: 
 5421: div.LC_clear_float_footer {
 5422:   padding-top: 10px;
 5423:   clear: both;
 5424: }
 5425: 
 5426: 
 5427: div.LC_grade_show_user {
 5428:   margin-top: 20px;
 5429:   border: 1px solid black;
 5430: }
 5431: div.LC_grade_user_name {
 5432:   background: #DDDDEE;
 5433:   border-bottom: 1px solid black;
 5434:   font-weight: bold;
 5435:   font-size: large;
 5436: }
 5437: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5438:   background: #DDEEDD;
 5439: }
 5440: 
 5441: div.LC_grade_show_problem,
 5442: div.LC_grade_submissions,
 5443: div.LC_grade_message_center,
 5444: div.LC_grade_info_links,
 5445: div.LC_grade_assign {
 5446:   margin: 5px;
 5447:   width: 99%;
 5448:   background: #FFFFFF;
 5449: }
 5450: div.LC_grade_show_problem_header,
 5451: div.LC_grade_submissions_header,
 5452: div.LC_grade_message_center_header,
 5453: div.LC_grade_assign_header {
 5454:   font-weight: bold;
 5455:   font-size: large;
 5456: }
 5457: div.LC_grade_show_problem_problem,
 5458: div.LC_grade_submissions_body,
 5459: div.LC_grade_message_center_body,
 5460: div.LC_grade_assign_body {
 5461:   border: 1px solid black;
 5462:   width: 99%;
 5463:   background: #FFFFFF;
 5464: }
 5465: span.LC_grade_check_note {
 5466:   font-weight: normal;
 5467:   font-size: medium;
 5468:   display: inline;
 5469:   position: absolute;
 5470:   right: 1em;
 5471: }
 5472: 
 5473: table.LC_scantron_action {
 5474:   width: 100%;
 5475: }
 5476: table.LC_scantron_action tr th {
 5477:   font-weight:bold;
 5478:   font-style:normal;
 5479: }
 5480: .LC_edit_problem_header,
 5481: div.LC_edit_problem_footer {
 5482:   font-weight: normal;
 5483:   font-size:  medium;
 5484:   margin: 2px;
 5485: }
 5486: div.LC_edit_problem_header,
 5487: div.LC_edit_problem_header div,
 5488: div.LC_edit_problem_footer,
 5489: div.LC_edit_problem_footer div,
 5490: div.LC_edit_problem_editxml_header,
 5491: div.LC_edit_problem_editxml_header div {
 5492:   margin-top: 5px;
 5493: }
 5494: div.LC_edit_problem_header_edit_row {
 5495:   background: $tabbg;
 5496:   padding: 3px;
 5497:   margin-bottom: 5px;
 5498: }
 5499: div.LC_edit_problem_header_title {
 5500:   font-weight: bold;
 5501:   font-size: larger;
 5502:   background: $tabbg;
 5503:   padding: 3px;
 5504: }
 5505: table.LC_edit_problem_header_title {
 5506:   font-size: larger;
 5507:   font-weight:  bold;
 5508:   width: 100%;
 5509:   border-color: $pgbg;
 5510:   border-style: solid;
 5511:   border-width: $border;
 5512: 
 5513:   background: $tabbg;
 5514:   border-collapse: collapse;
 5515:   padding: 0px
 5516: }
 5517: 
 5518: div.LC_edit_problem_discards {
 5519:   float: left;
 5520:   padding-bottom: 5px;
 5521: }
 5522: div.LC_edit_problem_saves {
 5523:   float: right;
 5524:   padding-bottom: 5px;
 5525: }
 5526: hr.LC_edit_problem_divide {
 5527:   clear: both;
 5528:   color: $tabbg;
 5529:   background-color: $tabbg;
 5530:   height: 3px;
 5531:   border: 0px;
 5532: }
 5533: img.stift{
 5534:   border-width:0;
 5535:   vertical-align:middle;
 5536: }
 5537: 
 5538: table#LC_mainmenu{
 5539:  margin-top:10px;
 5540:  width:80%;
 5541: 
 5542: }
 5543: 
 5544: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5545:   vertical-align: top;
 5546:   width: 45%;
 5547: }
 5548: .LC_mainmenu_fieldset_category {
 5549:   color: $font;
 5550:   background: $pgbg;
 5551:   font-family: $sans;
 5552:   font-size: small;
 5553:   font-weight: bold;
 5554: }
 5555: div.LC_createcourse {
 5556:     margin: 10px 10px 10px 10px;
 5557: }
 5558: 
 5559: /* ---- Remove when done ----
 5560: # The following styles is part of the redesign of LON-CAPA and are
 5561: # subject to change during this project.
 5562: # Don't rely on their current functionality as they might be 
 5563: # changed or removed.
 5564: # --------------------------*/
 5565: 
 5566: a:hover,
 5567: ol.LC_smallMenu a:hover,
 5568: ol#LC_MenuBreadcrumbs a:hover,
 5569: ol#LC_PathBreadcrumbs a:hover,
 5570: ul#LC_TabMainMenuContent a:hover,
 5571: .LC_FormSectionClearButton input:hover
 5572: ul.LC_TabContent   li:hover a{
 5573: 	color:#BF2317;
 5574:         text-decoration:none;
 5575: }
 5576: 
 5577: h1 {
 5578: 	padding:5px 10px 5px 20px;
 5579: 	line-height:130%;
 5580: }
 5581: 
 5582: h2,h3,h4,h5,h6
 5583: {
 5584: 	margin:5px 0px 5px 0px;
 5585: 	padding:0px;
 5586: 	line-height:130%;
 5587: }
 5588: .LC_hcell{
 5589:         padding:3px 15px 3px 15px;
 5590:         margin:0px;
 5591: 	background-color:$tabbg;
 5592: 	border-bottom:solid 1px $lg_border_color;
 5593: }
 5594: .LC_noBorder {
 5595:         border:0px;
 5596: }
 5597: 
 5598: 
 5599: /* Main Header with discription of Person, Course, etc. */
 5600: 
 5601: .LC_Right {
 5602:         float: right;
 5603:         margin: 0px;
 5604:         padding: 0px;
 5605: }
 5606: 
 5607: p, .LC_ContentBox {
 5608: 	padding: 10px;
 5609: 
 5610: }
 5611: .LC_FormSectionClearButton input {
 5612:         background-color:transparent;
 5613:         border:0px;
 5614:         cursor:pointer;
 5615:         text-decoration:underline;
 5616: }
 5617: 
 5618: .LC_help_open_topic {
 5619:         color: #FFFFFF;
 5620:         background-color: #EEEEFF;
 5621:         margin: 1px;
 5622:         padding: 4px;
 5623:         border: 1px solid #000033;
 5624:         white-space: nowrap;
 5625: /*		vertical-align: middle; */
 5626: }
 5627: 
 5628: dl,ul,div,fieldset {
 5629: 	margin: 10px 10px 10px 0px;
 5630: 	overflow:hidden;
 5631: }
 5632: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5633: 	margin: 0px;
 5634: }
 5635: 
 5636: ol.LC_smallMenu li {
 5637: 	display: inline;
 5638: 	padding: 5px 5px 0px 10px;
 5639: 	vertical-align: top;
 5640: }
 5641: 
 5642: ol.LC_smallMenu li img {
 5643: 	vertical-align: bottom;
 5644: }
 5645: 
 5646: ol.LC_smallMenu a {
 5647: 	font-size: 90%;
 5648: 	color: RGB(80, 80, 80);
 5649: 	text-decoration: none;
 5650: }
 5651: ol#LC_TabMainMenuContent, ul.LC_TabContent ,
 5652: ul.LC_TabContentBigger {
 5653: 	display:block;
 5654: 	list-style:none;
 5655: 	margin: 0px;
 5656: 	padding: 0px;
 5657: }
 5658: 
 5659: ol#LC_TabMainMenuContent li, ul.LC_TabContent li,
 5660: ul.LC_TabContentBigger li{
 5661: 	display: inline;
 5662: 	border-right: solid 1px $lg_border_color;
 5663: 	float:left;
 5664: 	line-height:140%;
 5665: 	white-space:nowrap;
 5666: }
 5667: ol#LC_TabMainMenuContent li{
 5668: 	vertical-align: bottom;
 5669: 	border-bottom: solid 1px RGB(175, 175, 175);
 5670: 	padding: 5px 10px 5px 10px;
 5671: 	margin-right:5px;
 5672: 	margin-bottom:3px;
 5673: 	font-weight: bold;
 5674: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5675: }
 5676: 
 5677: ol#LC_TabMainMenuContent li a{
 5678: 	color: RGB(47, 47, 47);
 5679: 	text-decoration: none;
 5680: }
 5681: ul.LC_TabContent {
 5682: 	min-height:1.6em;
 5683: }
 5684: ul.LC_TabContent li{
 5685: 	vertical-align:middle;
 5686: 	padding:0px 10px 0px 10px;
 5687: 	background-color:$tabbg;
 5688: 	border-bottom:solid 1px $lg_border_color;
 5689: }
 5690: ul.LC_TabContent li a, ul.LC_TabContent li{
 5691: 	color:rgb(47,47,47);
 5692: 	text-decoration:none;
 5693: 	font-size:95%;
 5694: 	font-weight:bold;
 5695: 	padding-right: 16px;
 5696: }
 5697: ul.LC_TabContent li:hover, ul.LC_TabContent li.active{
 5698:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5699: 	border-bottom:solid 1px #FFFFFF;
 5700: 	padding-right: 16px;
 5701: }
 5702: ul.LC_TabContentBigger li{
 5703: 	vertical-align:bottom;
 5704: 	border-top:solid 1px $lg_border_color;
 5705: 	border-left:solid 1px $lg_border_color;
 5706: 	padding:5px 10px 5px 10px;
 5707: 	margin-left:2px;
 5708: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5709: }
 5710: ul.LC_TabContentBigger li:hover, ul.LC_TabContentBigger li.active{
 5711: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5712: }
 5713: ul.LC_TabContentBigger li, ul.LC_TabContentBigger li a{
 5714: 	font-size:110%;
 5715: 	font-weight:bold;
 5716: }
 5717: 
 5718: ol#LC_MenuBreadcrumbs, ol#LC_PathBreadcrumbs, ul.LC_CourseBreadcrumbs{
 5719: 	border-top: solid 1px RGB(255, 255, 255);
 5720: 	height: 20px;
 5721: 	line-height: 20px;
 5722: 	vertical-align: bottom;
 5723: 	margin: 0px 0px 30px 0px;
 5724: 	padding-left: 10px;
 5725: 	list-style-position: inside;
 5726: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5727: }
 5728: 
 5729: ol#LC_MenuBreadcrumbs li, ol#LC_PathBreadcrumbs li, ul.LC_CourseBreadcrumbs li {
 5730: /*
 5731: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5732: */
 5733: 	display: inline;
 5734: 	padding: 0px 0px 0px 10px;
 5735: /*	vertical-align: bottom; */
 5736: 	overflow:hidden;
 5737: }
 5738: 
 5739: ol#LC_MenuBreadcrumbs li a, ul.LC_CourseBreadcrumbs li a {
 5740: 	text-decoration: none;
 5741: 	font-size:90%;
 5742: }
 5743: ol#LC_PathBreadcrumbs li a{
 5744: 	text-decoration:none;
 5745: 	font-size:100%;
 5746: 	font-weight:bold;
 5747: }
 5748: .LC_ContentBoxSpecial
 5749: {
 5750: 	border: solid 1px $lg_border_color;
 5751: }
 5752: .LC_ContentBoxSpecialContactInfo
 5753: {
 5754: 	border: solid 1px $lg_border_color;
 5755: 	max-width:25%;
 5756: 	min-width:25%;
 5757: }
 5758: .LC_AboutMe_Image
 5759: {
 5760: 	float:left;
 5761: 	margin-right:10px;
 5762: }
 5763: .LC_Clear_AboutMe_Image
 5764: {
 5765: 	clear:left;
 5766: }
 5767: dl.LC_ListStyleClean dt {
 5768: 	padding-right: 5px;
 5769: 	display: table-header-group;
 5770: }
 5771: 
 5772: dl.LC_ListStyleClean dd {
 5773: 	display: table-row;
 5774: }
 5775: 
 5776: .LC_ListStyleClean,
 5777: .LC_ListStyleSimple,
 5778: .LC_ListStyleNormal,
 5779: .LC_ListStyle_Border,
 5780: .LC_ListStyleSpecial
 5781: 	{
 5782: 	/*display:block;	*/
 5783: 	list-style-position: inside;
 5784: 	list-style-type: none;
 5785: 	overflow: hidden;
 5786: 	padding: 0px;
 5787: }
 5788: 
 5789: .LC_ListStyleSimple li,
 5790: .LC_ListStyleSimple dd,
 5791: .LC_ListStyleNormal li,
 5792: .LC_ListStyleNormal dd,
 5793: .LC_ListStyleSpecial li,
 5794: .LC_ListStyleSpecial dd
 5795: 	{
 5796: 	margin: 0px;
 5797: 	padding: 5px 5px 5px 10px;
 5798: 	clear: both;
 5799: }
 5800: 
 5801: .LC_ListStyleClean li,
 5802: .LC_ListStyleClean dd {
 5803: 	padding-top: 0px;
 5804: 	padding-bottom: 0px;
 5805: }
 5806: 
 5807: .LC_ListStyleSimple dd,
 5808: .LC_ListStyleSimple li{
 5809: 	border-bottom: solid 1px $lg_border_color;
 5810: }
 5811: 
 5812: .LC_ListStyleSpecial li,
 5813: .LC_ListStyleSpecial dd {
 5814: 	list-style-type: none;
 5815: 	background-color: RGB(220, 220, 220);
 5816: 	margin-bottom: 4px;
 5817: }
 5818: 
 5819: table.LC_SimpleTable {
 5820: 	margin:5px;
 5821: 	border:solid 1px $lg_border_color;
 5822: 	}
 5823: 
 5824: table.LC_SimpleTable tr {
 5825: 	padding:0px;
 5826: 	border:solid 1px $lg_border_color;
 5827: }
 5828: table.LC_SimpleTable thead{
 5829: 	 background:rgb(220,220,220);
 5830: }
 5831: 
 5832: div.LC_columnSection {
 5833: 	display: block;
 5834: 	clear: both;
 5835: 	overflow: hidden;
 5836: 	margin:0px;
 5837: }
 5838: 
 5839: div.LC_columnSection>* {
 5840: 	float: left;
 5841: 	margin: 10px 20px 10px 0px;
 5842: 	overflow:hidden;
 5843: }
 5844: 
 5845: .ContentBoxSpecialTemplate
 5846: {
 5847:         border: solid 1px $lg_border_color;
 5848: }
 5849: .ContentBoxTemplate {
 5850:         padding:10px;
 5851: }
 5852: 
 5853: div.LC_columnSection > .ContentBoxTemplate,
 5854: div.LC_columnSection > .ContentBoxSpecialTemplate
 5855:         {
 5856:         width: 600px;
 5857: }
 5858: 
 5859: .clear{
 5860: 	clear: both;
 5861: 	line-height: 0px;
 5862: 	font-size: 0px;
 5863: 	height: 0px;
 5864: }
 5865: 
 5866: .LC_loginpage_container {
 5867: 	text-align:left;
 5868: 	margin : 0 auto;
 5869: 	width:65%;
 5870: 	padding: 10px;
 5871: 	height: auto;
 5872: 	background-color:#FFFFFF;
 5873: 	border:1px solid #CCCCCC;
 5874: }
 5875: 
 5876: 
 5877: .LC_loginpage_loginContainer {
 5878: 	float:left;
 5879: 	width: 182px;
 5880: 	border:1px solid #CCCCCC;
 5881: 	background-color:$loginbg;
 5882: }
 5883: 
 5884: .LC_loginpage_loginContainer h2{
 5885: 	margin-top:0;
 5886: 	display:block;
 5887: 	background:$bgcol;
 5888: 	color:$textcol;
 5889: 	padding-left:5px;
 5890: }
 5891: .LC_loginpage_loginInfo {
 5892: 	margin-left:20px;
 5893: 	float:left;
 5894: 	width:30%;
 5895: 	border:1px solid #CCCCCC;
 5896: 	padding:10px;
 5897: }
 5898: 
 5899: .LC_loginpage_loginDomain {
 5900: 	margin-right:20px;
 5901: 	width:20%;
 5902: 	float:left;
 5903: 	padding:10px;
 5904: }
 5905: 
 5906: .LC_loginpage_space {
 5907: 	clear: both;
 5908: 	margin-bottom: 20px;
 5909: 	border-bottom: 1px solid #CCCCCC;
 5910: }
 5911: 
 5912: table em{
 5913: 	font-weight: bold;
 5914: 	font-style: normal;
 5915: }
 5916: table.LC_tableBrowseRes,
 5917: table.LC_tableOfContent{
 5918:         border:none;
 5919: 	border-spacing: 1;
 5920: 	padding: 3px;
 5921: 	background-color: #FFFFFF;
 5922: 	font-size: 90%;
 5923: }
 5924: table.LC_tableBrowseRes a,
 5925: table.LC_tableOfContent a {
 5926:         background-color: transparent;
 5927: 	text-decoration: none;
 5928: }
 5929: 
 5930: table.LC_tableBrowseRes tr.LC_trOdd,
 5931: table.LC_tableOfContent tr.LC_trOdd{
 5932: 	background-color: #EEEEEE;
 5933: }
 5934: 
 5935: table.LC_tableOfContent img{
 5936: 	border: none;
 5937: 	height: 1.3em;
 5938: 	vertical-align: text-bottom;
 5939: 	margin-right: 0.3em;
 5940: }
 5941: 
 5942: a#LC_content_toolbar_firsthomework{
 5943: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 5944: }
 5945: 
 5946: a#LC_content_toolbar_launchnav{
 5947: 	background-image:url(/res/adm/pages/start-navigation.gif);
 5948: }
 5949: 
 5950: a#LC_content_toolbar_closenav{
 5951: 	background-image:url(/res/adm/pages/close-navigation.gif);
 5952: }
 5953: 
 5954: a#LC_content_toolbar_everything{
 5955: 	background-image:url(/res/adm/pages/show-all.gif);
 5956: }
 5957: 
 5958: a#LC_content_toolbar_uncompleted{
 5959: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 5960: }
 5961: 
 5962: #LC_content_toolbar_clearbubbles{
 5963: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 5964: }
 5965: 
 5966: a#LC_content_toolbar_changefolder{
 5967: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 5968: }
 5969: 
 5970: a#LC_content_toolbar_changefolder_toggled{
 5971: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 5972: }
 5973: 
 5974: ul#LC_toolbar li a:hover{
 5975: 	background-position: bottom center;
 5976: }
 5977: 
 5978: ul#LC_toolbar{
 5979: 	padding:0;
 5980: 	margin: 2px;
 5981: 	list-style:none;
 5982: 	position:relative;
 5983: 	background-color:white;
 5984: }
 5985: 
 5986: ul#LC_toolbar li{
 5987: 	border:1px solid white;
 5988: 	padding:0;
 5989: 	margin: 0;
 5990:     float: left;
 5991: 	display:inline;
 5992: 	vertical-align:middle;
 5993: }
 5994: 
 5995: /*
 5996:  This style is used for standard function lists, e.g. functions of Personal Information Page.
 5997:  It produces a horizontally aligned list with a bullet at the beginning of each function item.
 5998:  */
 5999: .LC_fieldset_functions li {
 6000: 	float: right;
 6001: 	height: 35px;
 6002: 	background-color: blue; 
 6003: 	white-space: nowrap;
 6004: 	margin-left: 10px;	
 6005: }
 6006: 
 6007: a.LC_toolbarItem{
 6008: 	display:block;
 6009: 	padding:0;
 6010: 	margin:0;
 6011: 	height: 32px;
 6012: 	width: 32px;
 6013: 	color:white;
 6014: 	border:0 none;
 6015: 	background-repeat:no-repeat;
 6016: 	background-color:transparent;
 6017: }
 6018: 
 6019: ul.LC_functionslist li {
 6020:   float: left;
 6021:   white-space: nowrap;
 6022:   height: 35px; /* at least as high as heighest list item */
 6023:   margin: 0px 15px 15px 10px;
 6024: }
 6025: 
 6026: 
 6027: END
 6028: }
 6029: 
 6030: =pod
 6031: 
 6032: =item * &headtag()
 6033: 
 6034: Returns a uniform footer for LON-CAPA web pages.
 6035: 
 6036: Inputs: $title - optional title for the head
 6037:         $head_extra - optional extra HTML to put inside the <head>
 6038:         $args - optional arguments
 6039:             force_register - if is true call registerurl so the remote is 
 6040:                              informed
 6041:             redirect       -> array ref of
 6042:                                    1- seconds before redirect occurs
 6043:                                    2- url to redirect to
 6044:                                    3- whether the side effect should occur
 6045:                            (side effect of setting 
 6046:                                $env{'internal.head.redirect'} to the url 
 6047:                                redirected too)
 6048:             domain         -> force to color decorate a page for a specific
 6049:                                domain
 6050:             function       -> force usage of a specific rolish color scheme
 6051:             bgcolor        -> override the default page bgcolor
 6052:             no_auto_mt_title
 6053:                            -> prevent &mt()ing the title arg
 6054: 
 6055: =cut
 6056: 
 6057: sub headtag {
 6058:     my ($title,$head_extra,$args) = @_;
 6059:     
 6060:     my $function = $args->{'function'} || &get_users_function();
 6061:     my $domain   = $args->{'domain'}   || &determinedomain();
 6062:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6063:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6064: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6065: 		   #time(),
 6066: 		   $env{'environment.color.timestamp'},
 6067: 		   $function,$domain,$bgcolor);
 6068: 
 6069:     $url = '/adm/css/'.&escape($url).'.css';
 6070: 
 6071:     my $result =
 6072: 	'<head>'.
 6073: 	&font_settings();
 6074: 
 6075:     if (!$args->{'frameset'}) {
 6076: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6077:     }
 6078:     if ($args->{'force_register'}) {
 6079: 	$result .= &Apache::lonmenu::registerurl(1);
 6080:     }
 6081:     if (!$args->{'no_nav_bar'} 
 6082: 	&& !$args->{'only_body'}
 6083: 	&& !$args->{'frameset'}) {
 6084: 	$result .= &help_menu_js();
 6085:     }
 6086: 
 6087:     if (ref($args->{'redirect'})) {
 6088: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6089: 	$url = &Apache::lonenc::check_encrypt($url);
 6090: 	if (!$inhibit_continue) {
 6091: 	    $env{'internal.head.redirect'} = $url;
 6092: 	}
 6093: 	$result.=<<ADDMETA
 6094: <meta http-equiv="pragma" content="no-cache" />
 6095: <meta http-equiv="Refresh" content="$time; url=$url" />
 6096: ADDMETA
 6097:     }
 6098:     if (!defined($title)) {
 6099: 	$title = 'The LearningOnline Network with CAPA';
 6100:     }
 6101:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6102:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6103: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6104: 	.$head_extra;
 6105:     return $result;
 6106: }
 6107: 
 6108: =pod
 6109: 
 6110: =item * &font_settings()
 6111: 
 6112: Returns neccessary <meta> to set the proper encoding
 6113: 
 6114: Inputs: none
 6115: 
 6116: =cut
 6117: 
 6118: sub font_settings {
 6119:     my $headerstring='';
 6120:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6121: 	$headerstring.=
 6122: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6123:     }
 6124:     return $headerstring;
 6125: }
 6126: 
 6127: =pod
 6128: 
 6129: =item * &xml_begin()
 6130: 
 6131: Returns the needed doctype and <html>
 6132: 
 6133: Inputs: none
 6134: 
 6135: =cut
 6136: 
 6137: sub xml_begin {
 6138:     my $output='';
 6139: 
 6140:     if ($env{'internal.start_page'}==1) {
 6141: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6142:     }
 6143: 
 6144:     if ($env{'browser.mathml'}) {
 6145: 	$output='<?xml version="1.0"?>'
 6146:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6147: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6148:             
 6149: #	    .'<!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">] >'
 6150: 	    .'<!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">'
 6151:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6152: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6153:     } else {
 6154: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6155:     }
 6156:     return $output;
 6157: }
 6158: 
 6159: =pod
 6160: 
 6161: =item * &endheadtag()
 6162: 
 6163: Returns a uniform </head> for LON-CAPA web pages.
 6164: 
 6165: Inputs: none
 6166: 
 6167: =cut
 6168: 
 6169: sub endheadtag {
 6170:     return '</head>';
 6171: }
 6172: 
 6173: =pod
 6174: 
 6175: =item * &head()
 6176: 
 6177: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6178: 
 6179: Inputs:
 6180: 
 6181: =over 4
 6182: 
 6183: $title - optional title for the page
 6184: 
 6185: $head_extra - optional extra HTML to put inside the <head>
 6186: 
 6187: =back
 6188: 
 6189: =cut
 6190: 
 6191: sub head {
 6192:     my ($title,$head_extra,$args) = @_;
 6193:     return &headtag($title,$head_extra,$args).&endheadtag();
 6194: }
 6195: 
 6196: =pod
 6197: 
 6198: =item * &start_page()
 6199: 
 6200: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6201: 
 6202: Inputs:
 6203: 
 6204: =over 4
 6205: 
 6206: $title - optional title for the page
 6207: 
 6208: $head_extra - optional extra HTML to incude inside the <head>
 6209: 
 6210: $args - additional optional args supported are:
 6211: 
 6212: =over 8
 6213: 
 6214:              only_body      -> is true will set &bodytag() onlybodytag
 6215:                                     arg on
 6216:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6217:              add_entries    -> additional attributes to add to the  <body>
 6218:              domain         -> force to color decorate a page for a 
 6219:                                     specific domain
 6220:              function       -> force usage of a specific rolish color
 6221:                                     scheme
 6222:              redirect       -> see &headtag()
 6223:              bgcolor        -> override the default page bg color
 6224:              js_ready       -> return a string ready for being used in 
 6225:                                     a javascript writeln
 6226:              html_encode    -> return a string ready for being used in 
 6227:                                     a html attribute
 6228:              force_register -> if is true will turn on the &bodytag()
 6229:                                     $forcereg arg
 6230:              body_title     -> alternate text to use instead of $title
 6231:                                     in the title box that appears, this text
 6232:                                     is not auto translated like the $title is
 6233:              frameset       -> if true will start with a <frameset>
 6234:                                     rather than <body>
 6235:              no_title       -> if true the title bar won't be shown
 6236:              skip_phases    -> hash ref of 
 6237:                                     head -> skip the <html><head> generation
 6238:                                     body -> skip all <body> generation
 6239:              no_inline_link -> if true and in remote mode, don't show the 
 6240:                                     'Switch To Inline Menu' link
 6241:              no_auto_mt_title -> prevent &mt()ing the title arg
 6242:              inherit_jsmath -> when creating popup window in a page,
 6243:                                     should it have jsmath forced on by the
 6244:                                     current page
 6245: 
 6246: =back
 6247: 
 6248: =back
 6249: 
 6250: =cut
 6251: 
 6252: sub start_page {
 6253:     my ($title,$head_extra,$args) = @_;
 6254:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6255:     my %head_args;
 6256:     foreach my $arg ('redirect','force_register','domain','function',
 6257: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6258: 		     'no_auto_mt_title') {
 6259: 	if (defined($args->{$arg})) {
 6260: 	    $head_args{$arg} = $args->{$arg};
 6261: 	}
 6262:     }
 6263: 
 6264:     $env{'internal.start_page'}++;
 6265:     my $result;
 6266:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6267: 	$result.=
 6268: 	    &xml_begin().
 6269: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6270:     }
 6271:     
 6272:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6273: 	if ($args->{'frameset'}) {
 6274: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6275: 						$args->{'add_entries'});
 6276: 	    $result .= "\n<frameset $attr_string>\n";
 6277: 	} else {
 6278: 	    $result .=
 6279: 		&bodytag($title, 
 6280: 			 $args->{'function'},       $args->{'add_entries'},
 6281: 			 $args->{'only_body'},      $args->{'domain'},
 6282: 			 $args->{'force_register'}, $args->{'body_title'},
 6283: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6284: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6285: 			 $args);
 6286: 	}
 6287:     }
 6288: 
 6289:     if ($args->{'js_ready'}) {
 6290: 		$result = &js_ready($result);
 6291:     }
 6292:     if ($args->{'html_encode'}) {
 6293: 		$result = &html_encode($result);
 6294:     }
 6295: 
 6296: 	#Breadcrumbs
 6297:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6298: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6299: 		#if any br links exists, add them to the breadcrumbs
 6300: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6301: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6302: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6303: 			}
 6304: 		}
 6305: 
 6306: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6307: 		if(exists($args->{'bread_crumbs_component'})){
 6308: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6309: 		}else{
 6310: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6311: 		}
 6312:     }
 6313:     return $result;
 6314: }
 6315: 
 6316: 
 6317: =pod
 6318: 
 6319: =item * &head()
 6320: 
 6321: Returns a complete </body></html> section for LON-CAPA web pages.
 6322: 
 6323: Inputs:         $args - additional optional args supported are:
 6324:                  js_ready     -> return a string ready for being used in 
 6325:                                  a javascript writeln
 6326:                  html_encode  -> return a string ready for being used in 
 6327:                                  a html attribute
 6328:                  frameset     -> if true will start with a <frameset>
 6329:                                  rather than <body>
 6330:                  dicsussion   -> if true will get discussion from
 6331:                                   lonxml::xmlend
 6332:                                  (you can pass the target and parser arguments
 6333:                                   through optional 'target' and 'parser' args
 6334:                                   to this routine)
 6335: 
 6336: =cut
 6337: 
 6338: sub end_page {
 6339:     my ($args) = @_;
 6340:     $env{'internal.end_page'}++;
 6341:     my $result;
 6342:     if ($args->{'discussion'}) {
 6343: 	my ($target,$parser);
 6344: 	if (ref($args->{'discussion'})) {
 6345: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6346: 				$args->{'discussion'}{'parser'});
 6347: 	}
 6348: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6349:     }
 6350: 
 6351:     if ($args->{'frameset'}) {
 6352: 	$result .= '</frameset>';
 6353:     } else {
 6354: 	$result .= &endbodytag($args);
 6355:     }
 6356:     $result .= "\n</html>";
 6357: 
 6358:     if ($args->{'js_ready'}) {
 6359: 	$result = &js_ready($result);
 6360:     }
 6361: 
 6362:     if ($args->{'html_encode'}) {
 6363: 	$result = &html_encode($result);
 6364:     }
 6365: 
 6366:     return $result;
 6367: }
 6368: 
 6369: sub html_encode {
 6370:     my ($result) = @_;
 6371: 
 6372:     $result = &HTML::Entities::encode($result,'<>&"');
 6373:     
 6374:     return $result;
 6375: }
 6376: sub js_ready {
 6377:     my ($result) = @_;
 6378: 
 6379:     $result =~ s/[\n\r]/ /xmsg;
 6380:     $result =~ s/\\/\\\\/xmsg;
 6381:     $result =~ s/'/\\'/xmsg;
 6382:     $result =~ s{</}{<\\/}xmsg;
 6383:     
 6384:     return $result;
 6385: }
 6386: 
 6387: sub validate_page {
 6388:     if (  exists($env{'internal.start_page'})
 6389: 	  &&     $env{'internal.start_page'} > 1) {
 6390: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6391: 				 $env{'internal.start_page'}.' '.
 6392: 				 $ENV{'request.filename'});
 6393:     }
 6394:     if (  exists($env{'internal.end_page'})
 6395: 	  &&     $env{'internal.end_page'} > 1) {
 6396: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6397: 				 $env{'internal.end_page'}.' '.
 6398: 				 $env{'request.filename'});
 6399:     }
 6400:     if (     exists($env{'internal.start_page'})
 6401: 	&& ! exists($env{'internal.end_page'})) {
 6402: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6403: 				 $env{'request.filename'});
 6404:     }
 6405:     if (   ! exists($env{'internal.start_page'})
 6406: 	&&   exists($env{'internal.end_page'})) {
 6407: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6408: 				 $env{'request.filename'});
 6409:     }
 6410: }
 6411: 
 6412: sub simple_error_page {
 6413:     my ($r,$title,$msg) = @_;
 6414:     my $page =
 6415: 	&Apache::loncommon::start_page($title).
 6416: 	&mt($msg).
 6417: 	&Apache::loncommon::end_page();
 6418:     if (ref($r)) {
 6419: 	$r->print($page);
 6420: 	return;
 6421:     }
 6422:     return $page;
 6423: }
 6424: 
 6425: {
 6426:     my @row_count;
 6427:     sub start_data_table {
 6428: 	my ($add_class) = @_;
 6429: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6430: 	unshift(@row_count,0);
 6431: 	return '<table class="'.$css_class.'">'."\n";
 6432:     }
 6433: 
 6434:     sub end_data_table {
 6435: 	shift(@row_count);
 6436: 	return '</table>'."\n";;
 6437:     }
 6438: 
 6439:     sub start_data_table_row {
 6440: 	my ($add_class) = @_;
 6441: 	$row_count[0]++;
 6442: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6443: 	$css_class = (join(' ',$css_class,$add_class));
 6444: 	return  '<tr class="'.$css_class.'">'."\n";;
 6445:     }
 6446:     
 6447:     sub continue_data_table_row {
 6448: 	my ($add_class) = @_;
 6449: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6450: 	$css_class = (join(' ',$css_class,$add_class));
 6451: 	return  '<tr class="'.$css_class.'">'."\n";;
 6452:     }
 6453: 
 6454:     sub end_data_table_row {
 6455: 	return '</tr>'."\n";;
 6456:     }
 6457: 
 6458:     sub start_data_table_empty_row {
 6459: #	$row_count[0]++;
 6460: 	return  '<tr class="LC_empty_row" >'."\n";;
 6461:     }
 6462: 
 6463:     sub end_data_table_empty_row {
 6464: 	return '</tr>'."\n";;
 6465:     }
 6466: 
 6467:     sub start_data_table_header_row {
 6468: 	return  '<tr class="LC_header_row">'."\n";;
 6469:     }
 6470: 
 6471:     sub end_data_table_header_row {
 6472: 	return '</tr>'."\n";;
 6473:     }
 6474: }
 6475: 
 6476: =pod
 6477: 
 6478: =item * &inhibit_menu_check($arg)
 6479: 
 6480: Checks for a inhibitmenu state and generates output to preserve it
 6481: 
 6482: Inputs:         $arg - can be any of
 6483:                      - undef - in which case the return value is a string 
 6484:                                to add  into arguments list of a uri
 6485:                      - 'input' - in which case the return value is a HTML
 6486:                                  <form> <input> field of type hidden to
 6487:                                  preserve the value
 6488:                      - a url - in which case the return value is the url with
 6489:                                the neccesary cgi args added to preserve the
 6490:                                inhibitmenu state
 6491:                      - a ref to a url - no return value, but the string is
 6492:                                         updated to include the neccessary cgi
 6493:                                         args to preserve the inhibitmenu state
 6494: 
 6495: =cut
 6496: 
 6497: sub inhibit_menu_check {
 6498:     my ($arg) = @_;
 6499:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6500:     if ($arg eq 'input') {
 6501: 	if ($env{'form.inhibitmenu'}) {
 6502: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6503: 	} else {
 6504: 	    return
 6505: 	}
 6506:     }
 6507:     if ($env{'form.inhibitmenu'}) {
 6508: 	if (ref($arg)) {
 6509: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6510: 	} elsif ($arg eq '') {
 6511: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6512: 	} else {
 6513: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6514: 	}
 6515:     }
 6516:     if (!ref($arg)) {
 6517: 	return $arg;
 6518:     }
 6519: }
 6520: 
 6521: ###############################################
 6522: 
 6523: =pod
 6524: 
 6525: =back
 6526: 
 6527: =head1 User Information Routines
 6528: 
 6529: =over 4
 6530: 
 6531: =item * &get_users_function()
 6532: 
 6533: Used by &bodytag to determine the current users primary role.
 6534: Returns either 'student','coordinator','admin', or 'author'.
 6535: 
 6536: =cut
 6537: 
 6538: ###############################################
 6539: sub get_users_function {
 6540:     my $function = 'student';
 6541:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6542:         $function='coordinator';
 6543:     }
 6544:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6545:         $function='admin';
 6546:     }
 6547:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6548:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6549:         $function='author';
 6550:     }
 6551:     return $function;
 6552: }
 6553: 
 6554: ###############################################
 6555: 
 6556: =pod
 6557: 
 6558: =item * &check_user_status()
 6559: 
 6560: Determines current status of supplied role for a
 6561: specific user. Roles can be active, previous or future.
 6562: 
 6563: Inputs: 
 6564: user's domain, user's username, course's domain,
 6565: course's number, optional section ID.
 6566: 
 6567: Outputs:
 6568: role status: active, previous or future. 
 6569: 
 6570: =cut
 6571: 
 6572: sub check_user_status {
 6573:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6574:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6575:     my @uroles = keys %userinfo;
 6576:     my $srchstr;
 6577:     my $active_chk = 'none';
 6578:     my $now = time;
 6579:     if (@uroles > 0) {
 6580:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6581:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6582:         } else {
 6583:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6584:         }
 6585:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6586:             my $role_end = 0;
 6587:             my $role_start = 0;
 6588:             $active_chk = 'active';
 6589:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6590:                 $role_end = $1;
 6591:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6592:                     $role_start = $1;
 6593:                 }
 6594:             }
 6595:             if ($role_start > 0) {
 6596:                 if ($now < $role_start) {
 6597:                     $active_chk = 'future';
 6598:                 }
 6599:             }
 6600:             if ($role_end > 0) {
 6601:                 if ($now > $role_end) {
 6602:                     $active_chk = 'previous';
 6603:                 }
 6604:             }
 6605:         }
 6606:     }
 6607:     return $active_chk;
 6608: }
 6609: 
 6610: ###############################################
 6611: 
 6612: =pod
 6613: 
 6614: =item * &get_sections()
 6615: 
 6616: Determines all the sections for a course including
 6617: sections with students and sections containing other roles.
 6618: Incoming parameters: 
 6619: 
 6620: 1. domain
 6621: 2. course number 
 6622: 3. reference to array containing roles for which sections should 
 6623: be gathered (optional).
 6624: 4. reference to array containing status types for which sections 
 6625: should be gathered (optional).
 6626: 
 6627: If the third argument is undefined, sections are gathered for any role. 
 6628: If the fourth argument is undefined, sections are gathered for any status.
 6629: Permissible values are 'active' or 'future' or 'previous'.
 6630:  
 6631: Returns section hash (keys are section IDs, values are
 6632: number of users in each section), subject to the
 6633: optional roles filter, optional status filter 
 6634: 
 6635: =cut
 6636: 
 6637: ###############################################
 6638: sub get_sections {
 6639:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6640:     if (!defined($cdom) || !defined($cnum)) {
 6641:         my $cid =  $env{'request.course.id'};
 6642: 
 6643: 	return if (!defined($cid));
 6644: 
 6645:         $cdom = $env{'course.'.$cid.'.domain'};
 6646:         $cnum = $env{'course.'.$cid.'.num'};
 6647:     }
 6648: 
 6649:     my %sectioncount;
 6650:     my $now = time;
 6651: 
 6652:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6653: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6654: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6655: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6656:         my $start_index = &Apache::loncoursedata::CL_START();
 6657:         my $end_index = &Apache::loncoursedata::CL_END();
 6658:         my $status;
 6659: 	while (my ($student,$data) = each(%$classlist)) {
 6660: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6661: 				                     $data->[$status_index],
 6662:                                                      $data->[$start_index],
 6663:                                                      $data->[$end_index]);
 6664:             if ($stu_status eq 'Active') {
 6665:                 $status = 'active';
 6666:             } elsif ($end < $now) {
 6667:                 $status = 'previous';
 6668:             } elsif ($start > $now) {
 6669:                 $status = 'future';
 6670:             } 
 6671: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6672:                 if ((!defined($possible_status)) || (($status ne '') && 
 6673:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6674: 		    $sectioncount{$section}++;
 6675:                 }
 6676: 	    }
 6677: 	}
 6678:     }
 6679:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6680:     foreach my $user (sort(keys(%courseroles))) {
 6681: 	if ($user !~ /^(\w{2})/) { next; }
 6682: 	my ($role) = ($user =~ /^(\w{2})/);
 6683: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6684: 	my ($section,$status);
 6685: 	if ($role eq 'cr' &&
 6686: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6687: 	    $section=$1;
 6688: 	}
 6689: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6690: 	if (!defined($section) || $section eq '-1') { next; }
 6691:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6692:         if ($end == -1 && $start == -1) {
 6693:             next; #deleted role
 6694:         }
 6695:         if (!defined($possible_status)) { 
 6696:             $sectioncount{$section}++;
 6697:         } else {
 6698:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6699:                 $status = 'active';
 6700:             } elsif ($end < $now) {
 6701:                 $status = 'future';
 6702:             } elsif ($start > $now) {
 6703:                 $status = 'previous';
 6704:             }
 6705:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6706:                 $sectioncount{$section}++;
 6707:             }
 6708:         }
 6709:     }
 6710:     return %sectioncount;
 6711: }
 6712: 
 6713: ###############################################
 6714: 
 6715: =pod
 6716: 
 6717: =item * &get_course_users()
 6718: 
 6719: Retrieves usernames:domains for users in the specified course
 6720: with specific role(s), and access status. 
 6721: 
 6722: Incoming parameters:
 6723: 1. course domain
 6724: 2. course number
 6725: 3. access status: users must have - either active, 
 6726: previous, future, or all.
 6727: 4. reference to array of permissible roles
 6728: 5. reference to array of section restrictions (optional)
 6729: 6. reference to results object (hash of hashes).
 6730: 7. reference to optional userdata hash
 6731: 8. reference to optional statushash
 6732: 9. flag if privileged users (except those set to unhide in
 6733:    course settings) should be excluded    
 6734: Keys of top level results hash are roles.
 6735: Keys of inner hashes are username:domain, with 
 6736: values set to access type.
 6737: Optional userdata hash returns an array with arguments in the 
 6738: same order as loncoursedata::get_classlist() for student data.
 6739: 
 6740: Optional statushash returns
 6741: 
 6742: Entries for end, start, section and status are blank because
 6743: of the possibility of multiple values for non-student roles.
 6744: 
 6745: =cut
 6746: 
 6747: ###############################################
 6748: 
 6749: sub get_course_users {
 6750:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6751:     my %idx = ();
 6752:     my %seclists;
 6753: 
 6754:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6755:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6756:     $idx{end} = &Apache::loncoursedata::CL_END();
 6757:     $idx{start} = &Apache::loncoursedata::CL_START();
 6758:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6759:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6760:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6761:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6762: 
 6763:     if (grep(/^st$/,@{$roles})) {
 6764:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6765:         my $now = time;
 6766:         foreach my $student (keys(%{$classlist})) {
 6767:             my $match = 0;
 6768:             my $secmatch = 0;
 6769:             my $section = $$classlist{$student}[$idx{section}];
 6770:             my $status = $$classlist{$student}[$idx{status}];
 6771:             if ($section eq '') {
 6772:                 $section = 'none';
 6773:             }
 6774:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6775:                 if (grep(/^all$/,@{$sections})) {
 6776:                     $secmatch = 1;
 6777:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6778:                     if (grep(/^none$/,@{$sections})) {
 6779:                         $secmatch = 1;
 6780:                     }
 6781:                 } else {  
 6782: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6783: 		        $secmatch = 1;
 6784:                     }
 6785: 		}
 6786:                 if (!$secmatch) {
 6787:                     next;
 6788:                 }
 6789:             }
 6790:             if (defined($$types{'active'})) {
 6791:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6792:                     push(@{$$users{st}{$student}},'active');
 6793:                     $match = 1;
 6794:                 }
 6795:             }
 6796:             if (defined($$types{'previous'})) {
 6797:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6798:                     push(@{$$users{st}{$student}},'previous');
 6799:                     $match = 1;
 6800:                 }
 6801:             }
 6802:             if (defined($$types{'future'})) {
 6803:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6804:                     push(@{$$users{st}{$student}},'future');
 6805:                     $match = 1;
 6806:                 }
 6807:             }
 6808:             if ($match) {
 6809:                 push(@{$seclists{$student}},$section);
 6810:                 if (ref($userdata) eq 'HASH') {
 6811:                     $$userdata{$student} = $$classlist{$student};
 6812:                 }
 6813:                 if (ref($statushash) eq 'HASH') {
 6814:                     $statushash->{$student}{'st'}{$section} = $status;
 6815:                 }
 6816:             }
 6817:         }
 6818:     }
 6819:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6820:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6821:         my $now = time;
 6822:         my %displaystatus = ( previous => 'Expired',
 6823:                               active   => 'Active',
 6824:                               future   => 'Future',
 6825:                             );
 6826:         my %nothide;
 6827:         if ($hidepriv) {
 6828:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6829:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6830:                 if ($user !~ /:/) {
 6831:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6832:                 } else {
 6833:                     $nothide{$user} = 1;
 6834:                 }
 6835:             }
 6836:         }
 6837:         foreach my $person (sort(keys(%coursepersonnel))) {
 6838:             my $match = 0;
 6839:             my $secmatch = 0;
 6840:             my $status;
 6841:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6842:             $user =~ s/:$//;
 6843:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6844:             if ($end == -1 || $start == -1) {
 6845:                 next;
 6846:             }
 6847:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6848:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6849:                 my ($uname,$udom) = split(/:/,$user);
 6850:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6851:                     if (grep(/^all$/,@{$sections})) {
 6852:                         $secmatch = 1;
 6853:                     } elsif ($usec eq '') {
 6854:                         if (grep(/^none$/,@{$sections})) {
 6855:                             $secmatch = 1;
 6856:                         }
 6857:                     } else {
 6858:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6859:                             $secmatch = 1;
 6860:                         }
 6861:                     }
 6862:                     if (!$secmatch) {
 6863:                         next;
 6864:                     }
 6865:                 }
 6866:                 if ($usec eq '') {
 6867:                     $usec = 'none';
 6868:                 }
 6869:                 if ($uname ne '' && $udom ne '') {
 6870:                     if ($hidepriv) {
 6871:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6872:                             (!$nothide{$uname.':'.$udom})) {
 6873:                             next;
 6874:                         }
 6875:                     }
 6876:                     if ($end > 0 && $end < $now) {
 6877:                         $status = 'previous';
 6878:                     } elsif ($start > $now) {
 6879:                         $status = 'future';
 6880:                     } else {
 6881:                         $status = 'active';
 6882:                     }
 6883:                     foreach my $type (keys(%{$types})) { 
 6884:                         if ($status eq $type) {
 6885:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6886:                                 push(@{$$users{$role}{$user}},$type);
 6887:                             }
 6888:                             $match = 1;
 6889:                         }
 6890:                     }
 6891:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6892:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6893: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6894:                         }
 6895:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6896:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6897:                         }
 6898:                         if (ref($statushash) eq 'HASH') {
 6899:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6900:                         }
 6901:                     }
 6902:                 }
 6903:             }
 6904:         }
 6905:         if (grep(/^ow$/,@{$roles})) {
 6906:             if ((defined($cdom)) && (defined($cnum))) {
 6907:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6908:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6909:                     my $owner = $csettings{'internal.courseowner'};
 6910:                     next if ($owner eq '');
 6911:                     my ($ownername,$ownerdom);
 6912:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6913:                         $ownername = $1;
 6914:                         $ownerdom = $2;
 6915:                     } else {
 6916:                         $ownername = $owner;
 6917:                         $ownerdom = $cdom;
 6918:                         $owner = $ownername.':'.$ownerdom;
 6919:                     }
 6920:                     @{$$users{'ow'}{$owner}} = 'any';
 6921:                     if (defined($userdata) && 
 6922: 			!exists($$userdata{$owner})) {
 6923: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6924:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6925:                             push(@{$seclists{$owner}},'none');
 6926:                         }
 6927:                         if (ref($statushash) eq 'HASH') {
 6928:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6929:                         }
 6930: 		    }
 6931:                 }
 6932:             }
 6933:         }
 6934:         foreach my $user (keys(%seclists)) {
 6935:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6936:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6937:         }
 6938:     }
 6939:     return;
 6940: }
 6941: 
 6942: sub get_user_info {
 6943:     my ($udom,$uname,$idx,$userdata) = @_;
 6944:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6945: 	&plainname($uname,$udom,'lastname');
 6946:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6947:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6948:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6949:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6950:     return;
 6951: }
 6952: 
 6953: ###############################################
 6954: 
 6955: =pod
 6956: 
 6957: =item * &get_user_quota()
 6958: 
 6959: Retrieves quota assigned for storage of portfolio files for a user  
 6960: 
 6961: Incoming parameters:
 6962: 1. user's username
 6963: 2. user's domain
 6964: 
 6965: Returns:
 6966: 1. Disk quota (in Mb) assigned to student.
 6967: 2. (Optional) Type of setting: custom or default
 6968:    (individually assigned or default for user's 
 6969:    institutional status).
 6970: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6971:    or student - types as defined in localenroll::inst_usertypes 
 6972:    for user's domain, which determines default quota for user.
 6973: 4. (Optional) - Default quota which would apply to the user.
 6974: 
 6975: If a value has been stored in the user's environment, 
 6976: it will return that, otherwise it returns the maximal default
 6977: defined for the user's instituional status(es) in the domain.
 6978: 
 6979: =cut
 6980: 
 6981: ###############################################
 6982: 
 6983: 
 6984: sub get_user_quota {
 6985:     my ($uname,$udom) = @_;
 6986:     my ($quota,$quotatype,$settingstatus,$defquota);
 6987:     if (!defined($udom)) {
 6988:         $udom = $env{'user.domain'};
 6989:     }
 6990:     if (!defined($uname)) {
 6991:         $uname = $env{'user.name'};
 6992:     }
 6993:     if (($udom eq '' || $uname eq '') ||
 6994:         ($udom eq 'public') && ($uname eq 'public')) {
 6995:         $quota = 0;
 6996:         $quotatype = 'default';
 6997:         $defquota = 0; 
 6998:     } else {
 6999:         my $inststatus;
 7000:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7001:             $quota = $env{'environment.portfolioquota'};
 7002:             $inststatus = $env{'environment.inststatus'};
 7003:         } else {
 7004:             my %userenv = 
 7005:                 &Apache::lonnet::get('environment',['portfolioquota',
 7006:                                      'inststatus'],$udom,$uname);
 7007:             my ($tmp) = keys(%userenv);
 7008:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7009:                 $quota = $userenv{'portfolioquota'};
 7010:                 $inststatus = $userenv{'inststatus'};
 7011:             } else {
 7012:                 undef(%userenv);
 7013:             }
 7014:         }
 7015:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7016:         if ($quota eq '') {
 7017:             $quota = $defquota;
 7018:             $quotatype = 'default';
 7019:         } else {
 7020:             $quotatype = 'custom';
 7021:         }
 7022:     }
 7023:     if (wantarray) {
 7024:         return ($quota,$quotatype,$settingstatus,$defquota);
 7025:     } else {
 7026:         return $quota;
 7027:     }
 7028: }
 7029: 
 7030: ###############################################
 7031: 
 7032: =pod
 7033: 
 7034: =item * &default_quota()
 7035: 
 7036: Retrieves default quota assigned for storage of user portfolio files,
 7037: given an (optional) user's institutional status.
 7038: 
 7039: Incoming parameters:
 7040: 1. domain
 7041: 2. (Optional) institutional status(es).  This is a : separated list of 
 7042:    status types (e.g., faculty, staff, student etc.)
 7043:    which apply to the user for whom the default is being retrieved.
 7044:    If the institutional status string in undefined, the domain
 7045:    default quota will be returned. 
 7046: 
 7047: Returns:
 7048: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7049: 2. (Optional) institutional type which determined the value of the
 7050:    default quota.
 7051: 
 7052: If a value has been stored in the domain's configuration db,
 7053: it will return that, otherwise it returns 20 (for backwards 
 7054: compatibility with domains which have not set up a configuration
 7055: db file; the original statically defined portfolio quota was 20 Mb). 
 7056: 
 7057: If the user's status includes multiple types (e.g., staff and student),
 7058: the largest default quota which applies to the user determines the
 7059: default quota returned.
 7060: 
 7061: =back
 7062: 
 7063: =cut
 7064: 
 7065: ###############################################
 7066: 
 7067: 
 7068: sub default_quota {
 7069:     my ($udom,$inststatus) = @_;
 7070:     my ($defquota,$settingstatus);
 7071:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7072:                                             ['quotas'],$udom);
 7073:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7074:         if ($inststatus ne '') {
 7075:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7076:             foreach my $item (@statuses) {
 7077:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7078:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7079:                         if ($defquota eq '') {
 7080:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7081:                             $settingstatus = $item;
 7082:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7083:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7084:                             $settingstatus = $item;
 7085:                         }
 7086:                     }
 7087:                 } else {
 7088:                     if ($quotahash{'quotas'}{$item} ne '') {
 7089:                         if ($defquota eq '') {
 7090:                             $defquota = $quotahash{'quotas'}{$item};
 7091:                             $settingstatus = $item;
 7092:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7093:                             $defquota = $quotahash{'quotas'}{$item};
 7094:                             $settingstatus = $item;
 7095:                         }
 7096:                     }
 7097:                 }
 7098:             }
 7099:         }
 7100:         if ($defquota eq '') {
 7101:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7102:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7103:             } else {
 7104:                 $defquota = $quotahash{'quotas'}{'default'};
 7105:             }
 7106:             $settingstatus = 'default';
 7107:         }
 7108:     } else {
 7109:         $settingstatus = 'default';
 7110:         $defquota = 20;
 7111:     }
 7112:     if (wantarray) {
 7113:         return ($defquota,$settingstatus);
 7114:     } else {
 7115:         return $defquota;
 7116:     }
 7117: }
 7118: 
 7119: sub get_secgrprole_info {
 7120:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7121:     my %sections_count = &get_sections($cdom,$cnum);
 7122:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7123:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7124:     my @groups = sort(keys(%curr_groups));
 7125:     my $allroles = [];
 7126:     my $rolehash;
 7127:     my $accesshash = {
 7128:                      active => 'Currently has access',
 7129:                      future => 'Will have future access',
 7130:                      previous => 'Previously had access',
 7131:                   };
 7132:     if ($needroles) {
 7133:         $rolehash = {'all' => 'all'};
 7134:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7135: 	if (&Apache::lonnet::error(%user_roles)) {
 7136: 	    undef(%user_roles);
 7137: 	}
 7138:         foreach my $item (keys(%user_roles)) {
 7139:             my ($role)=split(/\:/,$item,2);
 7140:             if ($role eq 'cr') { next; }
 7141:             if ($role =~ /^cr/) {
 7142:                 $$rolehash{$role} = (split('/',$role))[3];
 7143:             } else {
 7144:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7145:             }
 7146:         }
 7147:         foreach my $key (sort(keys(%{$rolehash}))) {
 7148:             push(@{$allroles},$key);
 7149:         }
 7150:         push (@{$allroles},'st');
 7151:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7152:     }
 7153:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7154: }
 7155: 
 7156: sub user_picker {
 7157:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7158:     my $currdom = $dom;
 7159:     my %curr_selected = (
 7160:                         srchin => 'dom',
 7161:                         srchby => 'lastname',
 7162:                       );
 7163:     my $srchterm;
 7164:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7165:         if ($srch->{'srchby'} ne '') {
 7166:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7167:         }
 7168:         if ($srch->{'srchin'} ne '') {
 7169:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7170:         }
 7171:         if ($srch->{'srchtype'} ne '') {
 7172:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7173:         }
 7174:         if ($srch->{'srchdomain'} ne '') {
 7175:             $currdom = $srch->{'srchdomain'};
 7176:         }
 7177:         $srchterm = $srch->{'srchterm'};
 7178:     }
 7179:     my %lt=&Apache::lonlocal::texthash(
 7180:                     'usr'       => 'Search criteria',
 7181:                     'doma'      => 'Domain/institution to search',
 7182:                     'uname'     => 'username',
 7183:                     'lastname'  => 'last name',
 7184:                     'lastfirst' => 'last name, first name',
 7185:                     'crs'       => 'in this course',
 7186:                     'dom'       => 'in selected LON-CAPA domain', 
 7187:                     'alc'       => 'all LON-CAPA',
 7188:                     'instd'     => 'in institutional directory for selected domain',
 7189:                     'exact'     => 'is',
 7190:                     'contains'  => 'contains',
 7191:                     'begins'    => 'begins with',
 7192:                     'youm'      => "You must include some text to search for.",
 7193:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7194:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7195:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7196:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7197:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7198:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7199:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7200:                                        );
 7201:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7202:     my $srchinsel = ' <select name="srchin">';
 7203: 
 7204:     my @srchins = ('crs','dom','alc','instd');
 7205: 
 7206:     foreach my $option (@srchins) {
 7207:         # FIXME 'alc' option unavailable until 
 7208:         #       loncreateuser::print_user_query_page()
 7209:         #       has been completed.
 7210:         next if ($option eq 'alc');
 7211:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7212:         if ($curr_selected{'srchin'} eq $option) {
 7213:             $srchinsel .= ' 
 7214:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7215:         } else {
 7216:             $srchinsel .= '
 7217:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7218:         }
 7219:     }
 7220:     $srchinsel .= "\n  </select>\n";
 7221: 
 7222:     my $srchbysel =  ' <select name="srchby">';
 7223:     foreach my $option ('lastname','lastfirst','uname') {
 7224:         if ($curr_selected{'srchby'} eq $option) {
 7225:             $srchbysel .= '
 7226:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7227:         } else {
 7228:             $srchbysel .= '
 7229:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7230:          }
 7231:     }
 7232:     $srchbysel .= "\n  </select>\n";
 7233: 
 7234:     my $srchtypesel = ' <select name="srchtype">';
 7235:     foreach my $option ('begins','contains','exact') {
 7236:         if ($curr_selected{'srchtype'} eq $option) {
 7237:             $srchtypesel .= '
 7238:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7239:         } else {
 7240:             $srchtypesel .= '
 7241:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7242:         }
 7243:     }
 7244:     $srchtypesel .= "\n  </select>\n";
 7245: 
 7246:     my ($newuserscript,$new_user_create);
 7247: 
 7248:     if ($forcenewuser) {
 7249:         if (ref($srch) eq 'HASH') {
 7250:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7251:                 if ($cancreate) {
 7252:                     $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>';
 7253:                 } else {
 7254:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 7255:                     my %usertypetext = (
 7256:                         official   => 'institutional',
 7257:                         unofficial => 'non-institutional',
 7258:                     );
 7259:                     $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 />';
 7260:                 }
 7261:             }
 7262:         }
 7263: 
 7264:         $newuserscript = <<"ENDSCRIPT";
 7265: 
 7266: function setSearch(createnew,callingForm) {
 7267:     if (createnew == 1) {
 7268:         for (var i=0; i<callingForm.srchby.length; i++) {
 7269:             if (callingForm.srchby.options[i].value == 'uname') {
 7270:                 callingForm.srchby.selectedIndex = i;
 7271:             }
 7272:         }
 7273:         for (var i=0; i<callingForm.srchin.length; i++) {
 7274:             if ( callingForm.srchin.options[i].value == 'dom') {
 7275: 		callingForm.srchin.selectedIndex = i;
 7276:             }
 7277:         }
 7278:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7279:             if (callingForm.srchtype.options[i].value == 'exact') {
 7280:                 callingForm.srchtype.selectedIndex = i;
 7281:             }
 7282:         }
 7283:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7284:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7285:                 callingForm.srchdomain.selectedIndex = i;
 7286:             }
 7287:         }
 7288:     }
 7289: }
 7290: ENDSCRIPT
 7291: 
 7292:     }
 7293: 
 7294:     my $output = <<"END_BLOCK";
 7295: <script type="text/javascript">
 7296: function validateEntry(callingForm) {
 7297: 
 7298:     var checkok = 1;
 7299:     var srchin;
 7300:     for (var i=0; i<callingForm.srchin.length; i++) {
 7301: 	if ( callingForm.srchin[i].checked ) {
 7302: 	    srchin = callingForm.srchin[i].value;
 7303: 	}
 7304:     }
 7305: 
 7306:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7307:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7308:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7309:     var srchterm =  callingForm.srchterm.value;
 7310:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7311:     var msg = "";
 7312: 
 7313:     if (srchterm == "") {
 7314:         checkok = 0;
 7315:         msg += "$lt{'youm'}\\n";
 7316:     }
 7317: 
 7318:     if (srchtype== 'begins') {
 7319:         if (srchterm.length < 2) {
 7320:             checkok = 0;
 7321:             msg += "$lt{'thte'}\\n";
 7322:         }
 7323:     }
 7324: 
 7325:     if (srchtype== 'contains') {
 7326:         if (srchterm.length < 3) {
 7327:             checkok = 0;
 7328:             msg += "$lt{'thet'}\\n";
 7329:         }
 7330:     }
 7331:     if (srchin == 'instd') {
 7332:         if (srchdomain == '') {
 7333:             checkok = 0;
 7334:             msg += "$lt{'yomc'}\\n";
 7335:         }
 7336:     }
 7337:     if (srchin == 'dom') {
 7338:         if (srchdomain == '') {
 7339:             checkok = 0;
 7340:             msg += "$lt{'ymcd'}\\n";
 7341:         }
 7342:     }
 7343:     if (srchby == 'lastfirst') {
 7344:         if (srchterm.indexOf(",") == -1) {
 7345:             checkok = 0;
 7346:             msg += "$lt{'whus'}\\n";
 7347:         }
 7348:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7349:             checkok = 0;
 7350:             msg += "$lt{'whse'}\\n";
 7351:         }
 7352:     }
 7353:     if (checkok == 0) {
 7354:         alert("$lt{'thfo'}\\n"+msg);
 7355:         return;
 7356:     }
 7357:     if (checkok == 1) {
 7358:         callingForm.submit();
 7359:     }
 7360: }
 7361: 
 7362: $newuserscript
 7363: 
 7364: </script>
 7365: 
 7366: $new_user_create
 7367: 
 7368: <table>
 7369:  <tr>
 7370:   <td>$lt{'doma'}:</td>
 7371:   <td>$domform</td>
 7372:   </td>
 7373:  </tr>
 7374:  <tr>
 7375:   <td>$lt{'usr'}:</td>
 7376:   <td>$srchbysel
 7377:       $srchtypesel 
 7378:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7379:       $srchinsel 
 7380:   </td>
 7381:  </tr>
 7382: </table>
 7383: <br />
 7384: END_BLOCK
 7385: 
 7386:     return $output;
 7387: }
 7388: 
 7389: sub user_rule_check {
 7390:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7391:     my $response;
 7392:     if (ref($usershash) eq 'HASH') {
 7393:         foreach my $user (keys(%{$usershash})) {
 7394:             my ($uname,$udom) = split(/:/,$user);
 7395:             next if ($udom eq '' || $uname eq '');
 7396:             my ($id,$newuser);
 7397:             if (ref($usershash->{$user}) eq 'HASH') {
 7398:                 $newuser = $usershash->{$user}->{'newuser'};
 7399:                 $id = $usershash->{$user}->{'id'};
 7400:             }
 7401:             my $inst_response;
 7402:             if (ref($checks) eq 'HASH') {
 7403:                 if (defined($checks->{'username'})) {
 7404:                     ($inst_response,%{$inst_results->{$user}}) = 
 7405:                         &Apache::lonnet::get_instuser($udom,$uname);
 7406:                 } elsif (defined($checks->{'id'})) {
 7407:                     ($inst_response,%{$inst_results->{$user}}) =
 7408:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7409:                 }
 7410:             } else {
 7411:                 ($inst_response,%{$inst_results->{$user}}) =
 7412:                     &Apache::lonnet::get_instuser($udom,$uname);
 7413:                 return;
 7414:             }
 7415:             if (!$got_rules->{$udom}) {
 7416:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7417:                                                   ['usercreation'],$udom);
 7418:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7419:                     foreach my $item ('username','id') {
 7420:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7421:                             $$curr_rules{$udom}{$item} = 
 7422:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7423:                         }
 7424:                     }
 7425:                 }
 7426:                 $got_rules->{$udom} = 1;  
 7427:             }
 7428:             foreach my $item (keys(%{$checks})) {
 7429:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7430:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7431:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7432:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7433:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7434:                                 if ($rule_check{$rule}) {
 7435:                                     $$rulematch{$user}{$item} = $rule;
 7436:                                     if ($inst_response eq 'ok') {
 7437:                                         if (ref($inst_results) eq 'HASH') {
 7438:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7439:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7440:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7441:                                                 }
 7442:                                             }
 7443:                                         }
 7444:                                     }
 7445:                                     last;
 7446:                                 }
 7447:                             }
 7448:                         }
 7449:                     }
 7450:                 }
 7451:             }
 7452:         }
 7453:     }
 7454:     return;
 7455: }
 7456: 
 7457: sub user_rule_formats {
 7458:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7459:     my %text = ( 
 7460:                  'username' => 'Usernames',
 7461:                  'id'       => 'IDs',
 7462:                );
 7463:     my $output;
 7464:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7465:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7466:         if (@{$ruleorder} > 0) {
 7467:             $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>';
 7468:             foreach my $rule (@{$ruleorder}) {
 7469:                 if (ref($curr_rules) eq 'ARRAY') {
 7470:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7471:                         if (ref($rules->{$rule}) eq 'HASH') {
 7472:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7473:                                         $rules->{$rule}{'desc'}.'</li>';
 7474:                         }
 7475:                     }
 7476:                 }
 7477:             }
 7478:             $output .= '</ul>';
 7479:         }
 7480:     }
 7481:     return $output;
 7482: }
 7483: 
 7484: sub instrule_disallow_msg {
 7485:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7486:     my $response;
 7487:     my %text = (
 7488:                   item   => 'username',
 7489:                   items  => 'usernames',
 7490:                   match  => 'matches',
 7491:                   do     => 'does',
 7492:                   action => 'a username',
 7493:                   one    => 'one',
 7494:                );
 7495:     if ($count > 1) {
 7496:         $text{'item'} = 'usernames';
 7497:         $text{'match'} ='match';
 7498:         $text{'do'} = 'do';
 7499:         $text{'action'} = 'usernames',
 7500:         $text{'one'} = 'ones';
 7501:     }
 7502:     if ($checkitem eq 'id') {
 7503:         $text{'items'} = 'IDs';
 7504:         $text{'item'} = 'ID';
 7505:         $text{'action'} = 'an ID';
 7506:         if ($count > 1) {
 7507:             $text{'item'} = 'IDs';
 7508:             $text{'action'} = 'IDs';
 7509:         }
 7510:     }
 7511:     $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 />';
 7512:     if ($mode eq 'upload') {
 7513:         if ($checkitem eq 'username') {
 7514:             $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'}.");
 7515:         } elsif ($checkitem eq 'id') {
 7516:             $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.");
 7517:         }
 7518:     } elsif ($mode eq 'selfcreate') {
 7519:         if ($checkitem eq 'id') {
 7520:             $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.");
 7521:         }
 7522:     } else {
 7523:         if ($checkitem eq 'username') {
 7524:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7525:         } elsif ($checkitem eq 'id') {
 7526:             $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.");
 7527:         }
 7528:     }
 7529:     return $response;
 7530: }
 7531: 
 7532: sub personal_data_fieldtitles {
 7533:     my %fieldtitles = &Apache::lonlocal::texthash (
 7534:                         id => 'Student/Employee ID',
 7535:                         permanentemail => 'E-mail address',
 7536:                         lastname => 'Last Name',
 7537:                         firstname => 'First Name',
 7538:                         middlename => 'Middle Name',
 7539:                         generation => 'Generation',
 7540:                         gen => 'Generation',
 7541:                         inststatus => 'Affiliation',
 7542:                    );
 7543:     return %fieldtitles;
 7544: }
 7545: 
 7546: sub sorted_inst_types {
 7547:     my ($dom) = @_;
 7548:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7549:     my $othertitle = &mt('All users');
 7550:     if ($env{'request.course.id'}) {
 7551:         $othertitle  = &mt('Any users');
 7552:     }
 7553:     my @types;
 7554:     if (ref($order) eq 'ARRAY') {
 7555:         @types = @{$order};
 7556:     }
 7557:     if (@types == 0) {
 7558:         if (ref($usertypes) eq 'HASH') {
 7559:             @types = sort(keys(%{$usertypes}));
 7560:         }
 7561:     }
 7562:     if (keys(%{$usertypes}) > 0) {
 7563:         $othertitle = &mt('Other users');
 7564:     }
 7565:     return ($othertitle,$usertypes,\@types);
 7566: }
 7567: 
 7568: sub get_institutional_codes {
 7569:     my ($settings,$allcourses,$LC_code) = @_;
 7570: # Get complete list of course sections to update
 7571:     my @currsections = ();
 7572:     my @currxlists = ();
 7573:     my $coursecode = $$settings{'internal.coursecode'};
 7574: 
 7575:     if ($$settings{'internal.sectionnums'} ne '') {
 7576:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7577:     }
 7578: 
 7579:     if ($$settings{'internal.crosslistings'} ne '') {
 7580:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7581:     }
 7582: 
 7583:     if (@currxlists > 0) {
 7584:         foreach (@currxlists) {
 7585:             if (m/^([^:]+):(\w*)$/) {
 7586:                 unless (grep/^$1$/,@{$allcourses}) {
 7587:                     push @{$allcourses},$1;
 7588:                     $$LC_code{$1} = $2;
 7589:                 }
 7590:             }
 7591:         }
 7592:     }
 7593:  
 7594:     if (@currsections > 0) {
 7595:         foreach (@currsections) {
 7596:             if (m/^(\w+):(\w*)$/) {
 7597:                 my $sec = $coursecode.$1;
 7598:                 my $lc_sec = $2;
 7599:                 unless (grep/^$sec$/,@{$allcourses}) {
 7600:                     push @{$allcourses},$sec;
 7601:                     $$LC_code{$sec} = $lc_sec;
 7602:                 }
 7603:             }
 7604:         }
 7605:     }
 7606:     return;
 7607: }
 7608: 
 7609: =pod
 7610: 
 7611: =head1 Slot Helpers
 7612: 
 7613: =over 4
 7614: 
 7615: =item * sorted_slots()
 7616: 
 7617: Sorts an array of slot names in order of slot start time (earliest first). 
 7618: 
 7619: Inputs:
 7620: 
 7621: =over 4
 7622: 
 7623: slotsarr  - Reference to array of unsorted slot names.
 7624: 
 7625: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7626: 
 7627: =back
 7628: 
 7629: Returns:
 7630: 
 7631: =over 4
 7632: 
 7633: sorted   - An array of slot names sorted by the start time of the slot.
 7634: 
 7635: =back
 7636: 
 7637: =back
 7638: 
 7639: =cut
 7640: 
 7641: 
 7642: sub sorted_slots {
 7643:     my ($slotsarr,$slots) = @_;
 7644:     my @sorted;
 7645:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7646:         @sorted =
 7647:             sort {
 7648:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7649:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7650:                      }
 7651:                      if (ref($slots->{$a})) { return -1;}
 7652:                      if (ref($slots->{$b})) { return 1;}
 7653:                      return 0;
 7654:                  } @{$slotsarr};
 7655:     }
 7656:     return @sorted;
 7657: }
 7658: 
 7659: 
 7660: =pod
 7661: 
 7662: =head1 HTTP Helpers
 7663: 
 7664: =over 4
 7665: 
 7666: =item * &get_unprocessed_cgi($query,$possible_names)
 7667: 
 7668: Modify the %env hash to contain unprocessed CGI form parameters held in
 7669: $query.  The parameters listed in $possible_names (an array reference),
 7670: will be set in $env{'form.name'} if they do not already exist.
 7671: 
 7672: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7673: $possible_names is an ref to an array of form element names.  As an example:
 7674: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7675: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7676: 
 7677: =cut
 7678: 
 7679: sub get_unprocessed_cgi {
 7680:   my ($query,$possible_names)= @_;
 7681:   # $Apache::lonxml::debug=1;
 7682:   foreach my $pair (split(/&/,$query)) {
 7683:     my ($name, $value) = split(/=/,$pair);
 7684:     $name = &unescape($name);
 7685:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7686:       $value =~ tr/+/ /;
 7687:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7688:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7689:     }
 7690:   }
 7691: }
 7692: 
 7693: =pod
 7694: 
 7695: =item * &cacheheader() 
 7696: 
 7697: returns cache-controlling header code
 7698: 
 7699: =cut
 7700: 
 7701: sub cacheheader {
 7702:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7703:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7704:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7705:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7706:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7707:     return $output;
 7708: }
 7709: 
 7710: =pod
 7711: 
 7712: =item * &no_cache($r) 
 7713: 
 7714: specifies header code to not have cache
 7715: 
 7716: =cut
 7717: 
 7718: sub no_cache {
 7719:     my ($r) = @_;
 7720:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7721: 	$env{'request.method'} ne 'GET') { return ''; }
 7722:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7723:     $r->no_cache(1);
 7724:     $r->header_out("Expires" => $date);
 7725:     $r->header_out("Pragma" => "no-cache");
 7726: }
 7727: 
 7728: sub content_type {
 7729:     my ($r,$type,$charset) = @_;
 7730:     if ($r) {
 7731: 	#  Note that printout.pl calls this with undef for $r.
 7732: 	&no_cache($r);
 7733:     }
 7734:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7735:     unless ($charset) {
 7736: 	$charset=&Apache::lonlocal::current_encoding;
 7737:     }
 7738:     if ($charset) { $type.='; charset='.$charset; }
 7739:     if ($r) {
 7740: 	$r->content_type($type);
 7741:     } else {
 7742: 	print("Content-type: $type\n\n");
 7743:     }
 7744: }
 7745: 
 7746: =pod
 7747: 
 7748: =item * &add_to_env($name,$value) 
 7749: 
 7750: adds $name to the %env hash with value
 7751: $value, if $name already exists, the entry is converted to an array
 7752: reference and $value is added to the array.
 7753: 
 7754: =cut
 7755: 
 7756: sub add_to_env {
 7757:   my ($name,$value)=@_;
 7758:   if (defined($env{$name})) {
 7759:     if (ref($env{$name})) {
 7760:       #already have multiple values
 7761:       push(@{ $env{$name} },$value);
 7762:     } else {
 7763:       #first time seeing multiple values, convert hash entry to an arrayref
 7764:       my $first=$env{$name};
 7765:       undef($env{$name});
 7766:       push(@{ $env{$name} },$first,$value);
 7767:     }
 7768:   } else {
 7769:     $env{$name}=$value;
 7770:   }
 7771: }
 7772: 
 7773: =pod
 7774: 
 7775: =item * &get_env_multiple($name) 
 7776: 
 7777: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7778: values may be defined and end up as an array ref.
 7779: 
 7780: returns an array of values
 7781: 
 7782: =cut
 7783: 
 7784: sub get_env_multiple {
 7785:     my ($name) = @_;
 7786:     my @values;
 7787:     if (defined($env{$name})) {
 7788:         # exists is it an array
 7789:         if (ref($env{$name})) {
 7790:             @values=@{ $env{$name} };
 7791:         } else {
 7792:             $values[0]=$env{$name};
 7793:         }
 7794:     }
 7795:     return(@values);
 7796: }
 7797: 
 7798: sub ask_for_embedded_content {
 7799:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7800:     my $upload_output = '
 7801:    <form name="upload_embedded" action="'.$actionurl.'"
 7802:                   method="post" enctype="multipart/form-data">';
 7803:     $upload_output .= $state;
 7804:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7805: 
 7806:     my $num = 0;
 7807:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7808:         $upload_output .= &start_data_table_row().
 7809:             '<td>'.$embed_file.'</td><td>';
 7810:         if ($args->{'ignore_remote_references'}
 7811:             && $embed_file =~ m{^\w+://}) {
 7812:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7813:         } elsif ($args->{'error_on_invalid_names'}
 7814:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7815: 
 7816:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7817: 
 7818:         } else {
 7819:             $upload_output .='
 7820:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7821:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7822:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7823:             $upload_output .=
 7824:                 "\n\t\t".
 7825:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7826:                 $attrib.'" />';
 7827:             if (exists($$codebase{$embed_file})) {
 7828:                 $upload_output .=
 7829:                     "\n\t\t".
 7830:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7831:                     &escape($$codebase{$embed_file}).'" />';
 7832:             }
 7833:         }
 7834:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7835:         $num++;
 7836:     }
 7837:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7838:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7839:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7840:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7841:    </form>';
 7842:     return $upload_output;
 7843: }
 7844: 
 7845: sub upload_embedded {
 7846:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7847:         $current_disk_usage) = @_;
 7848:     my $output;
 7849:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7850:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7851:         my $orig_uploaded_filename =
 7852:             $env{'form.embedded_item_'.$i.'.filename'};
 7853: 
 7854:         $env{'form.embedded_orig_'.$i} =
 7855:             &unescape($env{'form.embedded_orig_'.$i});
 7856:         my ($path,$fname) =
 7857:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7858:         # no path, whole string is fname
 7859:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7860: 
 7861:         $path = $env{'form.currentpath'}.$path;
 7862:         $fname = &Apache::lonnet::clean_filename($fname);
 7863:         # See if there is anything left
 7864:         next if ($fname eq '');
 7865: 
 7866:         # Check if file already exists as a file or directory.
 7867:         my ($state,$msg);
 7868:         if ($context eq 'portfolio') {
 7869:             my $port_path = $dirpath;
 7870:             if ($group ne '') {
 7871:                 $port_path = "groups/$group/$port_path";
 7872:             }
 7873:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7874:                                               $dir_root,$port_path,$disk_quota,
 7875:                                               $current_disk_usage,$uname,$udom);
 7876:             if ($state eq 'will_exceed_quota'
 7877:                 || $state eq 'file_locked'
 7878:                 || $state eq 'file_exists' ) {
 7879:                 $output .= $msg;
 7880:                 next;
 7881:             }
 7882:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7883:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7884:             if ($state eq 'exists') {
 7885:                 $output .= $msg;
 7886:                 next;
 7887:             }
 7888:         }
 7889:         # Check if extension is valid
 7890:         if (($fname =~ /\.(\w+)$/) &&
 7891:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7892:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7893:             next;
 7894:         } elsif (($fname =~ /\.(\w+)$/) &&
 7895:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7896:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7897:             next;
 7898:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7899:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7900:             next;
 7901:         }
 7902: 
 7903:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7904:         if ($context eq 'portfolio') {
 7905:             my $result=
 7906:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7907:                                                 $dirpath.$path);
 7908:             if ($result !~ m|^/uploaded/|) {
 7909:                 $output .= '<span class="LC_error">'
 7910:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7911:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7912:                       .'</span><br />';
 7913:                 next;
 7914:             } else {
 7915:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7916:                            $path.$fname.'</span>').'</p>';     
 7917:             }
 7918:         } else {
 7919: # Save the file
 7920:             my $target = $env{'form.embedded_item_'.$i};
 7921:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7922:             my $dest = $fullpath.$fname;
 7923:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7924:             my @parts=split(/\//,$fullpath);
 7925:             my $count;
 7926:             my $filepath = $dir_root;
 7927:             for ($count=4;$count<=$#parts;$count++) {
 7928:                 $filepath .= "/$parts[$count]";
 7929:                 if ((-e $filepath)!=1) {
 7930:                     mkdir($filepath,0770);
 7931:                 }
 7932:             }
 7933:             my $fh;
 7934:             if (!open($fh,'>'.$dest)) {
 7935:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7936:                 $output .= '<span class="LC_error">'.
 7937:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7938:                            '</span><br />';
 7939:             } else {
 7940:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7941:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7942:                     $output .= '<span class="LC_error">'.
 7943:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7944:                               '</span><br />';
 7945:                 } else {
 7946:                     if ($context eq 'testbank') {
 7947:                         $output .= &mt('Embedded file uploaded successfully:').
 7948:                                    '&nbsp;<a href="'.$url.'">'.
 7949:                                    $orig_uploaded_filename.'</a><br />';
 7950:                     } else {
 7951:                         $output .= '<span class=\"LC_fontsize_large\">'.
 7952:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7953:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 7954:                     }
 7955:                 }
 7956:                 close($fh);
 7957:             }
 7958:         }
 7959:     }
 7960:     return $output;
 7961: }
 7962: 
 7963: sub check_for_existing {
 7964:     my ($path,$fname,$element) = @_;
 7965:     my ($state,$msg);
 7966:     if (-d $path.'/'.$fname) {
 7967:         $state = 'exists';
 7968:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7969:     } elsif (-e $path.'/'.$fname) {
 7970:         $state = 'exists';
 7971:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7972:     }
 7973:     if ($state eq 'exists') {
 7974:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7975:     }
 7976:     return ($state,$msg);
 7977: }
 7978: 
 7979: sub check_for_upload {
 7980:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7981:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7982:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7983:     my $getpropath = 1;
 7984:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7985:                                             $getpropath);
 7986:     my $found_file = 0;
 7987:     my $locked_file = 0;
 7988:     foreach my $line (@dir_list) {
 7989:         my ($file_name)=split(/\&/,$line,2);
 7990:         if ($file_name eq $fname){
 7991:             $file_name = $path.$file_name;
 7992:             if ($group ne '') {
 7993:                 $file_name = $group.$file_name;
 7994:             }
 7995:             $found_file = 1;
 7996:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7997:                 $locked_file = 1;
 7998:             }
 7999:         }
 8000:     }
 8001:     if (($current_disk_usage + $filesize) > $disk_quota){
 8002:         my $msg = '<span class="LC_error">'.
 8003:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8004:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8005:         return ('will_exceed_quota',$msg);
 8006:     } elsif ($found_file) {
 8007:         if ($locked_file) {
 8008:             my $msg = '<span class="LC_error">';
 8009:             $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>');
 8010:             $msg .= '</span><br />';
 8011:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8012:             return ('file_locked',$msg);
 8013:         } else {
 8014:             my $msg = '<span class="LC_error">';
 8015:             $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'});
 8016:             $msg .= '</span>';
 8017:             $msg .= '<br />';
 8018:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8019:             return ('file_exists',$msg);
 8020:         }
 8021:     }
 8022: }
 8023: 
 8024: 
 8025: =pod
 8026: 
 8027: =back
 8028: 
 8029: =head1 CSV Upload/Handling functions
 8030: 
 8031: =over 4
 8032: 
 8033: =item * &upfile_store($r)
 8034: 
 8035: Store uploaded file, $r should be the HTTP Request object,
 8036: needs $env{'form.upfile'}
 8037: returns $datatoken to be put into hidden field
 8038: 
 8039: =cut
 8040: 
 8041: sub upfile_store {
 8042:     my $r=shift;
 8043:     $env{'form.upfile'}=~s/\r/\n/gs;
 8044:     $env{'form.upfile'}=~s/\f/\n/gs;
 8045:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8046:     $env{'form.upfile'}=~s/\n+$//gs;
 8047: 
 8048:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8049: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8050:     {
 8051:         my $datafile = $r->dir_config('lonDaemons').
 8052:                            '/tmp/'.$datatoken.'.tmp';
 8053:         if ( open(my $fh,">$datafile") ) {
 8054:             print $fh $env{'form.upfile'};
 8055:             close($fh);
 8056:         }
 8057:     }
 8058:     return $datatoken;
 8059: }
 8060: 
 8061: =pod
 8062: 
 8063: =item * &load_tmp_file($r)
 8064: 
 8065: Load uploaded file from tmp, $r should be the HTTP Request object,
 8066: needs $env{'form.datatoken'},
 8067: sets $env{'form.upfile'} to the contents of the file
 8068: 
 8069: =cut
 8070: 
 8071: sub load_tmp_file {
 8072:     my $r=shift;
 8073:     my @studentdata=();
 8074:     {
 8075:         my $studentfile = $r->dir_config('lonDaemons').
 8076:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8077:         if ( open(my $fh,"<$studentfile") ) {
 8078:             @studentdata=<$fh>;
 8079:             close($fh);
 8080:         }
 8081:     }
 8082:     $env{'form.upfile'}=join('',@studentdata);
 8083: }
 8084: 
 8085: =pod
 8086: 
 8087: =item * &upfile_record_sep()
 8088: 
 8089: Separate uploaded file into records
 8090: returns array of records,
 8091: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8092: 
 8093: =cut
 8094: 
 8095: sub upfile_record_sep {
 8096:     if ($env{'form.upfiletype'} eq 'xml') {
 8097:     } else {
 8098: 	my @records;
 8099: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8100: 	    if ($line=~/^\s*$/) { next; }
 8101: 	    push(@records,$line);
 8102: 	}
 8103: 	return @records;
 8104:     }
 8105: }
 8106: 
 8107: =pod
 8108: 
 8109: =item * &record_sep($record)
 8110: 
 8111: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8112: 
 8113: =cut
 8114: 
 8115: sub takeleft {
 8116:     my $index=shift;
 8117:     return substr('0000'.$index,-4,4);
 8118: }
 8119: 
 8120: sub record_sep {
 8121:     my $record=shift;
 8122:     my %components=();
 8123:     if ($env{'form.upfiletype'} eq 'xml') {
 8124:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8125:         my $i=0;
 8126:         foreach my $field (split(/\s+/,$record)) {
 8127:             $field=~s/^(\"|\')//;
 8128:             $field=~s/(\"|\')$//;
 8129:             $components{&takeleft($i)}=$field;
 8130:             $i++;
 8131:         }
 8132:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8133:         my $i=0;
 8134:         foreach my $field (split(/\t/,$record)) {
 8135:             $field=~s/^(\"|\')//;
 8136:             $field=~s/(\"|\')$//;
 8137:             $components{&takeleft($i)}=$field;
 8138:             $i++;
 8139:         }
 8140:     } else {
 8141:         my $separator=',';
 8142:         if ($env{'form.upfiletype'} eq 'semisv') {
 8143:             $separator=';';
 8144:         }
 8145:         my $i=0;
 8146: # the character we are looking for to indicate the end of a quote or a record 
 8147:         my $looking_for=$separator;
 8148: # do not add the characters to the fields
 8149:         my $ignore=0;
 8150: # we just encountered a separator (or the beginning of the record)
 8151:         my $just_found_separator=1;
 8152: # store the field we are working on here
 8153:         my $field='';
 8154: # work our way through all characters in record
 8155:         foreach my $character ($record=~/(.)/g) {
 8156:             if ($character eq $looking_for) {
 8157:                if ($character ne $separator) {
 8158: # Found the end of a quote, again looking for separator
 8159:                   $looking_for=$separator;
 8160:                   $ignore=1;
 8161:                } else {
 8162: # Found a separator, store away what we got
 8163:                   $components{&takeleft($i)}=$field;
 8164: 	          $i++;
 8165:                   $just_found_separator=1;
 8166:                   $ignore=0;
 8167:                   $field='';
 8168:                }
 8169:                next;
 8170:             }
 8171: # single or double quotation marks after a separator indicate beginning of a quote
 8172: # we are now looking for the end of the quote and need to ignore separators
 8173:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8174:                $looking_for=$character;
 8175:                next;
 8176:             }
 8177: # ignore would be true after we reached the end of a quote
 8178:             if ($ignore) { next; }
 8179:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8180:             $field.=$character;
 8181:             $just_found_separator=0; 
 8182:         }
 8183: # catch the very last entry, since we never encountered the separator
 8184:         $components{&takeleft($i)}=$field;
 8185:     }
 8186:     return %components;
 8187: }
 8188: 
 8189: ######################################################
 8190: ######################################################
 8191: 
 8192: =pod
 8193: 
 8194: =item * &upfile_select_html()
 8195: 
 8196: Return HTML code to select a file from the users machine and specify 
 8197: the file type.
 8198: 
 8199: =cut
 8200: 
 8201: ######################################################
 8202: ######################################################
 8203: sub upfile_select_html {
 8204:     my %Types = (
 8205:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8206:                  semisv => &mt('Semicolon separated values'),
 8207:                  space => &mt('Space separated'),
 8208:                  tab   => &mt('Tabulator separated'),
 8209: #                 xml   => &mt('HTML/XML'),
 8210:                  );
 8211:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8212:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8213:     foreach my $type (sort(keys(%Types))) {
 8214:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8215:     }
 8216:     $Str .= "</select>\n";
 8217:     return $Str;
 8218: }
 8219: 
 8220: sub get_samples {
 8221:     my ($records,$toget) = @_;
 8222:     my @samples=({});
 8223:     my $got=0;
 8224:     foreach my $rec (@$records) {
 8225: 	my %temp = &record_sep($rec);
 8226: 	if (! grep(/\S/, values(%temp))) { next; }
 8227: 	if (%temp) {
 8228: 	    $samples[$got]=\%temp;
 8229: 	    $got++;
 8230: 	    if ($got == $toget) { last; }
 8231: 	}
 8232:     }
 8233:     return \@samples;
 8234: }
 8235: 
 8236: ######################################################
 8237: ######################################################
 8238: 
 8239: =pod
 8240: 
 8241: =item * &csv_print_samples($r,$records)
 8242: 
 8243: Prints a table of sample values from each column uploaded $r is an
 8244: Apache Request ref, $records is an arrayref from
 8245: &Apache::loncommon::upfile_record_sep
 8246: 
 8247: =cut
 8248: 
 8249: ######################################################
 8250: ######################################################
 8251: sub csv_print_samples {
 8252:     my ($r,$records) = @_;
 8253:     my $samples = &get_samples($records,5);
 8254: 
 8255:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8256:               &start_data_table_header_row());
 8257:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8258:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8259:     $r->print(&end_data_table_header_row());
 8260:     foreach my $hash (@$samples) {
 8261: 	$r->print(&start_data_table_row());
 8262: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8263: 	    $r->print('<td>');
 8264: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8265: 	    $r->print('</td>');
 8266: 	}
 8267: 	$r->print(&end_data_table_row());
 8268:     }
 8269:     $r->print(&end_data_table().'<br />'."\n");
 8270: }
 8271: 
 8272: ######################################################
 8273: ######################################################
 8274: 
 8275: =pod
 8276: 
 8277: =item * &csv_print_select_table($r,$records,$d)
 8278: 
 8279: Prints a table to create associations between values and table columns.
 8280: 
 8281: $r is an Apache Request ref,
 8282: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8283: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8284: 
 8285: =cut
 8286: 
 8287: ######################################################
 8288: ######################################################
 8289: sub csv_print_select_table {
 8290:     my ($r,$records,$d) = @_;
 8291:     my $i=0;
 8292:     my $samples = &get_samples($records,1);
 8293:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8294: 	      &start_data_table().&start_data_table_header_row().
 8295:               '<th>'.&mt('Attribute').'</th>'.
 8296:               '<th>'.&mt('Column').'</th>'.
 8297:               &end_data_table_header_row()."\n");
 8298:     foreach my $array_ref (@$d) {
 8299: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8300: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8301: 
 8302: 	$r->print('<td><select name=f'.$i.
 8303: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8304: 	$r->print('<option value="none"></option>');
 8305: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8306: 	    $r->print('<option value="'.$sample.'"'.
 8307:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8308:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8309: 	}
 8310: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8311: 	$i++;
 8312:     }
 8313:     $r->print(&end_data_table());
 8314:     $i--;
 8315:     return $i;
 8316: }
 8317: 
 8318: ######################################################
 8319: ######################################################
 8320: 
 8321: =pod
 8322: 
 8323: =item * &csv_samples_select_table($r,$records,$d)
 8324: 
 8325: Prints a table of sample values from the upload and can make associate samples to internal names.
 8326: 
 8327: $r is an Apache Request ref,
 8328: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8329: $d is an array of 2 element arrays (internal name, displayed name)
 8330: 
 8331: =cut
 8332: 
 8333: ######################################################
 8334: ######################################################
 8335: sub csv_samples_select_table {
 8336:     my ($r,$records,$d) = @_;
 8337:     my $i=0;
 8338:     #
 8339:     my $max_samples = 5;
 8340:     my $samples = &get_samples($records,$max_samples);
 8341:     $r->print(&start_data_table().
 8342:               &start_data_table_header_row().'<th>'.
 8343:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8344:               &end_data_table_header_row());
 8345: 
 8346:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8347: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8348: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8349: 	foreach my $option (@$d) {
 8350: 	    my ($value,$display,$defaultcol)=@{ $option };
 8351: 	    $r->print('<option value="'.$value.'"'.
 8352:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8353:                       $display.'</option>');
 8354: 	}
 8355: 	$r->print('</select></td><td>');
 8356: 	foreach my $line (0..($max_samples-1)) {
 8357: 	    if (defined($samples->[$line]{$key})) { 
 8358: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8359: 	    }
 8360: 	}
 8361: 	$r->print('</td>'.&end_data_table_row());
 8362: 	$i++;
 8363:     }
 8364:     $r->print(&end_data_table());
 8365:     $i--;
 8366:     return($i);
 8367: }
 8368: 
 8369: ######################################################
 8370: ######################################################
 8371: 
 8372: =pod
 8373: 
 8374: =item * &clean_excel_name($name)
 8375: 
 8376: Returns a replacement for $name which does not contain any illegal characters.
 8377: 
 8378: =cut
 8379: 
 8380: ######################################################
 8381: ######################################################
 8382: sub clean_excel_name {
 8383:     my ($name) = @_;
 8384:     $name =~ s/[:\*\?\/\\]//g;
 8385:     if (length($name) > 31) {
 8386:         $name = substr($name,0,31);
 8387:     }
 8388:     return $name;
 8389: }
 8390: 
 8391: =pod
 8392: 
 8393: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8394: 
 8395: Returns either 1 or undef
 8396: 
 8397: 1 if the part is to be hidden, undef if it is to be shown
 8398: 
 8399: Arguments are:
 8400: 
 8401: $id the id of the part to be checked
 8402: $symb, optional the symb of the resource to check
 8403: $udom, optional the domain of the user to check for
 8404: $uname, optional the username of the user to check for
 8405: 
 8406: =cut
 8407: 
 8408: sub check_if_partid_hidden {
 8409:     my ($id,$symb,$udom,$uname) = @_;
 8410:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8411: 					 $symb,$udom,$uname);
 8412:     my $truth=1;
 8413:     #if the string starts with !, then the list is the list to show not hide
 8414:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8415:     my @hiddenlist=split(/,/,$hiddenparts);
 8416:     foreach my $checkid (@hiddenlist) {
 8417: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8418:     }
 8419:     return !$truth;
 8420: }
 8421: 
 8422: 
 8423: ############################################################
 8424: ############################################################
 8425: 
 8426: =pod
 8427: 
 8428: =back 
 8429: 
 8430: =head1 cgi-bin script and graphing routines
 8431: 
 8432: =over 4
 8433: 
 8434: =item * &get_cgi_id()
 8435: 
 8436: Inputs: none
 8437: 
 8438: Returns an id which can be used to pass environment variables
 8439: to various cgi-bin scripts.  These environment variables will
 8440: be removed from the users environment after a given time by
 8441: the routine &Apache::lonnet::transfer_profile_to_env.
 8442: 
 8443: =cut
 8444: 
 8445: ############################################################
 8446: ############################################################
 8447: my $uniq=0;
 8448: sub get_cgi_id {
 8449:     $uniq=($uniq+1)%100000;
 8450:     return (time.'_'.$$.'_'.$uniq);
 8451: }
 8452: 
 8453: ############################################################
 8454: ############################################################
 8455: 
 8456: =pod
 8457: 
 8458: =item * &DrawBarGraph()
 8459: 
 8460: Facilitates the plotting of data in a (stacked) bar graph.
 8461: Puts plot definition data into the users environment in order for 
 8462: graph.png to plot it.  Returns an <img> tag for the plot.
 8463: The bars on the plot are labeled '1','2',...,'n'.
 8464: 
 8465: Inputs:
 8466: 
 8467: =over 4
 8468: 
 8469: =item $Title: string, the title of the plot
 8470: 
 8471: =item $xlabel: string, text describing the X-axis of the plot
 8472: 
 8473: =item $ylabel: string, text describing the Y-axis of the plot
 8474: 
 8475: =item $Max: scalar, the maximum Y value to use in the plot
 8476: If $Max is < any data point, the graph will not be rendered.
 8477: 
 8478: =item $colors: array ref holding the colors to be used for the data sets when
 8479: they are plotted.  If undefined, default values will be used.
 8480: 
 8481: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8482: 
 8483: =item @Values: An array of array references.  Each array reference holds data
 8484: to be plotted in a stacked bar chart.
 8485: 
 8486: =item If the final element of @Values is a hash reference the key/value
 8487: pairs will be added to the graph definition.
 8488: 
 8489: =back
 8490: 
 8491: Returns:
 8492: 
 8493: An <img> tag which references graph.png and the appropriate identifying
 8494: information for the plot.
 8495: 
 8496: =cut
 8497: 
 8498: ############################################################
 8499: ############################################################
 8500: sub DrawBarGraph {
 8501:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8502:     #
 8503:     if (! defined($colors)) {
 8504:         $colors = ['#33ff00', 
 8505:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8506:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8507:                   ]; 
 8508:     }
 8509:     my $extra_settings = {};
 8510:     if (ref($Values[-1]) eq 'HASH') {
 8511:         $extra_settings = pop(@Values);
 8512:     }
 8513:     #
 8514:     my $identifier = &get_cgi_id();
 8515:     my $id = 'cgi.'.$identifier;        
 8516:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8517:         return '';
 8518:     }
 8519:     #
 8520:     my @Labels;
 8521:     if (defined($labels)) {
 8522:         @Labels = @$labels;
 8523:     } else {
 8524:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8525:             push (@Labels,$i+1);
 8526:         }
 8527:     }
 8528:     #
 8529:     my $NumBars = scalar(@{$Values[0]});
 8530:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8531:     my %ValuesHash;
 8532:     my $NumSets=1;
 8533:     foreach my $array (@Values) {
 8534:         next if (! ref($array));
 8535:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8536:             join(',',@$array);
 8537:     }
 8538:     #
 8539:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8540:     if ($NumBars < 3) {
 8541:         $width = 120+$NumBars*32;
 8542:         $xskip = 1;
 8543:         $bar_width = 30;
 8544:     } elsif ($NumBars < 5) {
 8545:         $width = 120+$NumBars*20;
 8546:         $xskip = 1;
 8547:         $bar_width = 20;
 8548:     } elsif ($NumBars < 10) {
 8549:         $width = 120+$NumBars*15;
 8550:         $xskip = 1;
 8551:         $bar_width = 15;
 8552:     } elsif ($NumBars <= 25) {
 8553:         $width = 120+$NumBars*11;
 8554:         $xskip = 5;
 8555:         $bar_width = 8;
 8556:     } elsif ($NumBars <= 50) {
 8557:         $width = 120+$NumBars*8;
 8558:         $xskip = 5;
 8559:         $bar_width = 4;
 8560:     } else {
 8561:         $width = 120+$NumBars*8;
 8562:         $xskip = 5;
 8563:         $bar_width = 4;
 8564:     }
 8565:     #
 8566:     $Max = 1 if ($Max < 1);
 8567:     if ( int($Max) < $Max ) {
 8568:         $Max++;
 8569:         $Max = int($Max);
 8570:     }
 8571:     $Title  = '' if (! defined($Title));
 8572:     $xlabel = '' if (! defined($xlabel));
 8573:     $ylabel = '' if (! defined($ylabel));
 8574:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8575:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8576:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8577:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8578:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8579:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8580:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8581:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8582:     $ValuesHash{$id.'.height'}   = $height;
 8583:     $ValuesHash{$id.'.width'}    = $width;
 8584:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8585:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8586:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8587:     #
 8588:     # Deal with other parameters
 8589:     while (my ($key,$value) = each(%$extra_settings)) {
 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: =item * &DrawXYGraph()
 8603: 
 8604: Facilitates the plotting of data in an XY graph.
 8605: Puts plot definition data into the users environment in order for 
 8606: graph.png to plot it.  Returns an <img> tag for the plot.
 8607: 
 8608: Inputs:
 8609: 
 8610: =over 4
 8611: 
 8612: =item $Title: string, the title of the plot
 8613: 
 8614: =item $xlabel: string, text describing the X-axis of the plot
 8615: 
 8616: =item $ylabel: string, text describing the Y-axis of the plot
 8617: 
 8618: =item $Max: scalar, the maximum Y value to use in the plot
 8619: If $Max is < any data point, the graph will not be rendered.
 8620: 
 8621: =item $colors: Array ref containing the hex color codes for the data to be 
 8622: plotted in.  If undefined, default values will be used.
 8623: 
 8624: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8625: 
 8626: =item $Ydata: Array ref containing Array refs.  
 8627: Each of the contained arrays will be plotted as a separate curve.
 8628: 
 8629: =item %Values: hash indicating or overriding any default values which are 
 8630: passed to graph.png.  
 8631: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8632: 
 8633: =back
 8634: 
 8635: Returns:
 8636: 
 8637: An <img> tag which references graph.png and the appropriate identifying
 8638: information for the plot.
 8639: 
 8640: =cut
 8641: 
 8642: ############################################################
 8643: ############################################################
 8644: sub DrawXYGraph {
 8645:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8646:     #
 8647:     # Create the identifier for the graph
 8648:     my $identifier = &get_cgi_id();
 8649:     my $id = 'cgi.'.$identifier;
 8650:     #
 8651:     $Title  = '' if (! defined($Title));
 8652:     $xlabel = '' if (! defined($xlabel));
 8653:     $ylabel = '' if (! defined($ylabel));
 8654:     my %ValuesHash = 
 8655:         (
 8656:          $id.'.title'  => &escape($Title),
 8657:          $id.'.xlabel' => &escape($xlabel),
 8658:          $id.'.ylabel' => &escape($ylabel),
 8659:          $id.'.y_max_value'=> $Max,
 8660:          $id.'.labels'     => join(',',@$Xlabels),
 8661:          $id.'.PlotType'   => 'XY',
 8662:          );
 8663:     #
 8664:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8665:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8666:     }
 8667:     #
 8668:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8669:         return '';
 8670:     }
 8671:     my $NumSets=1;
 8672:     foreach my $array (@{$Ydata}){
 8673:         next if (! ref($array));
 8674:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8675:     }
 8676:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8677:     #
 8678:     # Deal with other parameters
 8679:     while (my ($key,$value) = each(%Values)) {
 8680:         $ValuesHash{$id.'.'.$key} = $value;
 8681:     }
 8682:     #
 8683:     &Apache::lonnet::appenv(\%ValuesHash);
 8684:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8685: }
 8686: 
 8687: ############################################################
 8688: ############################################################
 8689: 
 8690: =pod
 8691: 
 8692: =item * &DrawXYYGraph()
 8693: 
 8694: Facilitates the plotting of data in an XY graph with two Y axes.
 8695: Puts plot definition data into the users environment in order for 
 8696: graph.png to plot it.  Returns an <img> tag for the plot.
 8697: 
 8698: Inputs:
 8699: 
 8700: =over 4
 8701: 
 8702: =item $Title: string, the title of the plot
 8703: 
 8704: =item $xlabel: string, text describing the X-axis of the plot
 8705: 
 8706: =item $ylabel: string, text describing the Y-axis of the plot
 8707: 
 8708: =item $colors: Array ref containing the hex color codes for the data to be 
 8709: plotted in.  If undefined, default values will be used.
 8710: 
 8711: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8712: 
 8713: =item $Ydata1: The first data set
 8714: 
 8715: =item $Min1: The minimum value of the left Y-axis
 8716: 
 8717: =item $Max1: The maximum value of the left Y-axis
 8718: 
 8719: =item $Ydata2: The second data set
 8720: 
 8721: =item $Min2: The minimum value of the right Y-axis
 8722: 
 8723: =item $Max2: The maximum value of the left Y-axis
 8724: 
 8725: =item %Values: hash indicating or overriding any default values which are 
 8726: passed to graph.png.  
 8727: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8728: 
 8729: =back
 8730: 
 8731: Returns:
 8732: 
 8733: An <img> tag which references graph.png and the appropriate identifying
 8734: information for the plot.
 8735: 
 8736: =cut
 8737: 
 8738: ############################################################
 8739: ############################################################
 8740: sub DrawXYYGraph {
 8741:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8742:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8743:     #
 8744:     # Create the identifier for the graph
 8745:     my $identifier = &get_cgi_id();
 8746:     my $id = 'cgi.'.$identifier;
 8747:     #
 8748:     $Title  = '' if (! defined($Title));
 8749:     $xlabel = '' if (! defined($xlabel));
 8750:     $ylabel = '' if (! defined($ylabel));
 8751:     my %ValuesHash = 
 8752:         (
 8753:          $id.'.title'  => &escape($Title),
 8754:          $id.'.xlabel' => &escape($xlabel),
 8755:          $id.'.ylabel' => &escape($ylabel),
 8756:          $id.'.labels' => join(',',@$Xlabels),
 8757:          $id.'.PlotType' => 'XY',
 8758:          $id.'.NumSets' => 2,
 8759:          $id.'.two_axes' => 1,
 8760:          $id.'.y1_max_value' => $Max1,
 8761:          $id.'.y1_min_value' => $Min1,
 8762:          $id.'.y2_max_value' => $Max2,
 8763:          $id.'.y2_min_value' => $Min2,
 8764:          );
 8765:     #
 8766:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8767:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8768:     }
 8769:     #
 8770:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8771:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8772:         return '';
 8773:     }
 8774:     my $NumSets=1;
 8775:     foreach my $array ($Ydata1,$Ydata2){
 8776:         next if (! ref($array));
 8777:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8778:     }
 8779:     #
 8780:     # Deal with other parameters
 8781:     while (my ($key,$value) = each(%Values)) {
 8782:         $ValuesHash{$id.'.'.$key} = $value;
 8783:     }
 8784:     #
 8785:     &Apache::lonnet::appenv(\%ValuesHash);
 8786:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8787: }
 8788: 
 8789: ############################################################
 8790: ############################################################
 8791: 
 8792: =pod
 8793: 
 8794: =back 
 8795: 
 8796: =head1 Statistics helper routines?  
 8797: 
 8798: Bad place for them but what the hell.
 8799: 
 8800: =over 4
 8801: 
 8802: =item * &chartlink()
 8803: 
 8804: Returns a link to the chart for a specific student.  
 8805: 
 8806: Inputs:
 8807: 
 8808: =over 4
 8809: 
 8810: =item $linktext: The text of the link
 8811: 
 8812: =item $sname: The students username
 8813: 
 8814: =item $sdomain: The students domain
 8815: 
 8816: =back
 8817: 
 8818: =back
 8819: 
 8820: =cut
 8821: 
 8822: ############################################################
 8823: ############################################################
 8824: sub chartlink {
 8825:     my ($linktext, $sname, $sdomain) = @_;
 8826:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8827:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8828:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8829:        '">'.$linktext.'</a>';
 8830: }
 8831: 
 8832: #######################################################
 8833: #######################################################
 8834: 
 8835: =pod
 8836: 
 8837: =head1 Course Environment Routines
 8838: 
 8839: =over 4
 8840: 
 8841: =item * &restore_course_settings()
 8842: 
 8843: =item * &store_course_settings()
 8844: 
 8845: Restores/Store indicated form parameters from the course environment.
 8846: Will not overwrite existing values of the form parameters.
 8847: 
 8848: Inputs: 
 8849: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8850: 
 8851: a hash ref describing the data to be stored.  For example:
 8852:    
 8853: %Save_Parameters = ('Status' => 'scalar',
 8854:     'chartoutputmode' => 'scalar',
 8855:     'chartoutputdata' => 'scalar',
 8856:     'Section' => 'array',
 8857:     'Group' => 'array',
 8858:     'StudentData' => 'array',
 8859:     'Maps' => 'array');
 8860: 
 8861: Returns: both routines return nothing
 8862: 
 8863: =back
 8864: 
 8865: =cut
 8866: 
 8867: #######################################################
 8868: #######################################################
 8869: sub store_course_settings {
 8870:     return &store_settings($env{'request.course.id'},@_);
 8871: }
 8872: 
 8873: sub store_settings {
 8874:     # save to the environment
 8875:     # appenv the same items, just to be safe
 8876:     my $udom  = $env{'user.domain'};
 8877:     my $uname = $env{'user.name'};
 8878:     my ($context,$prefix,$Settings) = @_;
 8879:     my %SaveHash;
 8880:     my %AppHash;
 8881:     while (my ($setting,$type) = each(%$Settings)) {
 8882:         my $basename = join('.','internal',$context,$prefix,$setting);
 8883:         my $envname = 'environment.'.$basename;
 8884:         if (exists($env{'form.'.$setting})) {
 8885:             # Save this value away
 8886:             if ($type eq 'scalar' &&
 8887:                 (! exists($env{$envname}) || 
 8888:                  $env{$envname} ne $env{'form.'.$setting})) {
 8889:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8890:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8891:             } elsif ($type eq 'array') {
 8892:                 my $stored_form;
 8893:                 if (ref($env{'form.'.$setting})) {
 8894:                     $stored_form = join(',',
 8895:                                         map {
 8896:                                             &escape($_);
 8897:                                         } sort(@{$env{'form.'.$setting}}));
 8898:                 } else {
 8899:                     $stored_form = 
 8900:                         &escape($env{'form.'.$setting});
 8901:                 }
 8902:                 # Determine if the array contents are the same.
 8903:                 if ($stored_form ne $env{$envname}) {
 8904:                     $SaveHash{$basename} = $stored_form;
 8905:                     $AppHash{$envname}   = $stored_form;
 8906:                 }
 8907:             }
 8908:         }
 8909:     }
 8910:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8911:                                           $udom,$uname);
 8912:     if ($put_result !~ /^(ok|delayed)/) {
 8913:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8914:                                  'got error:'.$put_result);
 8915:     }
 8916:     # Make sure these settings stick around in this session, too
 8917:     &Apache::lonnet::appenv(\%AppHash);
 8918:     return;
 8919: }
 8920: 
 8921: sub restore_course_settings {
 8922:     return &restore_settings($env{'request.course.id'},@_);
 8923: }
 8924: 
 8925: sub restore_settings {
 8926:     my ($context,$prefix,$Settings) = @_;
 8927:     while (my ($setting,$type) = each(%$Settings)) {
 8928:         next if (exists($env{'form.'.$setting}));
 8929:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8930:             '.'.$setting;
 8931:         if (exists($env{$envname})) {
 8932:             if ($type eq 'scalar') {
 8933:                 $env{'form.'.$setting} = $env{$envname};
 8934:             } elsif ($type eq 'array') {
 8935:                 $env{'form.'.$setting} = [ 
 8936:                                            map { 
 8937:                                                &unescape($_); 
 8938:                                            } split(',',$env{$envname})
 8939:                                            ];
 8940:             }
 8941:         }
 8942:     }
 8943: }
 8944: 
 8945: #######################################################
 8946: #######################################################
 8947: 
 8948: =pod
 8949: 
 8950: =head1 Domain E-mail Routines  
 8951: 
 8952: =over 4
 8953: 
 8954: =item * &build_recipient_list()
 8955: 
 8956: Build recipient lists for four types of e-mail:
 8957: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8958: (d) Help requests, generated by
 8959: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 8960: 
 8961: Inputs:
 8962: defmail (scalar - email address of default recipient), 
 8963: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8964: defdom (domain for which to retrieve configuration settings),
 8965: origmail (scalar - email address of recipient from loncapa.conf, 
 8966: i.e., predates configuration by DC via domainprefs.pm 
 8967: 
 8968: Returns: comma separated list of addresses to which to send e-mail.
 8969: 
 8970: =back
 8971: 
 8972: =cut
 8973: 
 8974: ############################################################
 8975: ############################################################
 8976: sub build_recipient_list {
 8977:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8978:     my @recipients;
 8979:     my $otheremails;
 8980:     my %domconfig =
 8981:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8982:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8983:         if (exists($domconfig{'contacts'}{$mailing})) {
 8984:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8985:                 my @contacts = ('adminemail','supportemail');
 8986:                 foreach my $item (@contacts) {
 8987:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8988:                         my $addr = $domconfig{'contacts'}{$item}; 
 8989:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8990:                             push(@recipients,$addr);
 8991:                         }
 8992:                     }
 8993:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8994:                 }
 8995:             }
 8996:         } elsif ($origmail ne '') {
 8997:             push(@recipients,$origmail);
 8998:         }
 8999:     } elsif ($origmail ne '') {
 9000:         push(@recipients,$origmail);
 9001:     }
 9002:     if (defined($defmail)) {
 9003:         if ($defmail ne '') {
 9004:             push(@recipients,$defmail);
 9005:         }
 9006:     }
 9007:     if ($otheremails) {
 9008:         my @others;
 9009:         if ($otheremails =~ /,/) {
 9010:             @others = split(/,/,$otheremails);
 9011:         } else {
 9012:             push(@others,$otheremails);
 9013:         }
 9014:         foreach my $addr (@others) {
 9015:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9016:                 push(@recipients,$addr);
 9017:             }
 9018:         }
 9019:     }
 9020:     my $recipientlist = join(',',@recipients); 
 9021:     return $recipientlist;
 9022: }
 9023: 
 9024: ############################################################
 9025: ############################################################
 9026: 
 9027: =pod
 9028: 
 9029: =head1 Course Catalog Routines
 9030: 
 9031: =over 4
 9032: 
 9033: =item * &gather_categories()
 9034: 
 9035: Converts category definitions - keys of categories hash stored in  
 9036: coursecategories in configuration.db on the primary library server in a 
 9037: domain - to an array.  Also generates javascript and idx hash used to 
 9038: generate Domain Coordinator interface for editing Course Categories.
 9039: 
 9040: Inputs:
 9041: 
 9042: categories (reference to hash of category definitions).
 9043: 
 9044: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9045:       categories and subcategories).
 9046: 
 9047: idx (reference to hash of counters used in Domain Coordinator interface for 
 9048:       editing Course Categories).
 9049: 
 9050: jsarray (reference to array of categories used to create Javascript arrays for
 9051:          Domain Coordinator interface for editing Course Categories).
 9052: 
 9053: Returns: nothing
 9054: 
 9055: Side effects: populates cats, idx and jsarray. 
 9056: 
 9057: =cut
 9058: 
 9059: sub gather_categories {
 9060:     my ($categories,$cats,$idx,$jsarray) = @_;
 9061:     my %counters;
 9062:     my $num = 0;
 9063:     foreach my $item (keys(%{$categories})) {
 9064:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9065:         if ($container eq '' && $depth == 0) {
 9066:             $cats->[$depth][$categories->{$item}] = $cat;
 9067:         } else {
 9068:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9069:         }
 9070:         my ($escitem,$tail) = split(/:/,$item,2);
 9071:         if ($counters{$tail} eq '') {
 9072:             $counters{$tail} = $num;
 9073:             $num ++;
 9074:         }
 9075:         if (ref($idx) eq 'HASH') {
 9076:             $idx->{$item} = $counters{$tail};
 9077:         }
 9078:         if (ref($jsarray) eq 'ARRAY') {
 9079:             push(@{$jsarray->[$counters{$tail}]},$item);
 9080:         }
 9081:     }
 9082:     return;
 9083: }
 9084: 
 9085: =pod
 9086: 
 9087: =item * &extract_categories()
 9088: 
 9089: Used to generate breadcrumb trails for course categories.
 9090: 
 9091: Inputs:
 9092: 
 9093: categories (reference to hash of category definitions).
 9094: 
 9095: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9096:       categories and subcategories).
 9097: 
 9098: trails (reference to array of breacrumb trails for each category).
 9099: 
 9100: allitems (reference to hash - key is category key 
 9101:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9102: 
 9103: idx (reference to hash of counters used in Domain Coordinator interface for
 9104:       editing Course Categories).
 9105: 
 9106: jsarray (reference to array of categories used to create Javascript arrays for
 9107:          Domain Coordinator interface for editing Course Categories).
 9108: 
 9109: subcats (reference to hash of arrays containing all subcategories within each 
 9110:          category, -recursive)
 9111: 
 9112: Returns: nothing
 9113: 
 9114: Side effects: populates trails and allitems hash references.
 9115: 
 9116: =cut
 9117: 
 9118: sub extract_categories {
 9119:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9120:     if (ref($categories) eq 'HASH') {
 9121:         &gather_categories($categories,$cats,$idx,$jsarray);
 9122:         if (ref($cats->[0]) eq 'ARRAY') {
 9123:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9124:                 my $name = $cats->[0][$i];
 9125:                 my $item = &escape($name).'::0';
 9126:                 my $trailstr;
 9127:                 if ($name eq 'instcode') {
 9128:                     $trailstr = &mt('Official courses (with institutional codes)');
 9129:                 } else {
 9130:                     $trailstr = $name;
 9131:                 }
 9132:                 if ($allitems->{$item} eq '') {
 9133:                     push(@{$trails},$trailstr);
 9134:                     $allitems->{$item} = scalar(@{$trails})-1;
 9135:                 }
 9136:                 my @parents = ($name);
 9137:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9138:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9139:                         my $category = $cats->[1]{$name}[$j];
 9140:                         if (ref($subcats) eq 'HASH') {
 9141:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9142:                         }
 9143:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9144:                     }
 9145:                 } else {
 9146:                     if (ref($subcats) eq 'HASH') {
 9147:                         $subcats->{$item} = [];
 9148:                     }
 9149:                 }
 9150:             }
 9151:         }
 9152:     }
 9153:     return;
 9154: }
 9155: 
 9156: =pod
 9157: 
 9158: =item *&recurse_categories()
 9159: 
 9160: Recursively used to generate breadcrumb trails for course categories.
 9161: 
 9162: Inputs:
 9163: 
 9164: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9165:       categories and subcategories).
 9166: 
 9167: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9168: 
 9169: category (current course category, for which breadcrumb trail is being generated).
 9170: 
 9171: trails (reference to array of breadcrumb trails for each category).
 9172: 
 9173: allitems (reference to hash - key is category key
 9174:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9175: 
 9176: parents (array containing containers directories for current category, 
 9177:          back to top level). 
 9178: 
 9179: Returns: nothing
 9180: 
 9181: Side effects: populates trails and allitems hash references
 9182: 
 9183: =cut
 9184: 
 9185: sub recurse_categories {
 9186:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9187:     my $shallower = $depth - 1;
 9188:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9189:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9190:             my $name = $cats->[$depth]{$category}[$k];
 9191:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9192:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9193:             if ($allitems->{$item} eq '') {
 9194:                 push(@{$trails},$trailstr);
 9195:                 $allitems->{$item} = scalar(@{$trails})-1;
 9196:             }
 9197:             my $deeper = $depth+1;
 9198:             push(@{$parents},$category);
 9199:             if (ref($subcats) eq 'HASH') {
 9200:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9201:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9202:                     my $higher;
 9203:                     if ($j > 0) {
 9204:                         $higher = &escape($parents->[$j]).':'.
 9205:                                   &escape($parents->[$j-1]).':'.$j;
 9206:                     } else {
 9207:                         $higher = &escape($parents->[$j]).'::'.$j;
 9208:                     }
 9209:                     push(@{$subcats->{$higher}},$subcat);
 9210:                 }
 9211:             }
 9212:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9213:                                 $subcats);
 9214:             pop(@{$parents});
 9215:         }
 9216:     } else {
 9217:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9218:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9219:         if ($allitems->{$item} eq '') {
 9220:             push(@{$trails},$trailstr);
 9221:             $allitems->{$item} = scalar(@{$trails})-1;
 9222:         }
 9223:     }
 9224:     return;
 9225: }
 9226: 
 9227: =pod
 9228: 
 9229: =item *&assign_categories_table()
 9230: 
 9231: Create a datatable for display of hierarchical categories in a domain,
 9232: with checkboxes to allow a course to be categorized. 
 9233: 
 9234: Inputs:
 9235: 
 9236: cathash - reference to hash of categories defined for the domain (from
 9237:           configuration.db)
 9238: 
 9239: currcat - scalar with an & separated list of categories assigned to a course. 
 9240: 
 9241: Returns: $output (markup to be displayed) 
 9242: 
 9243: =cut
 9244: 
 9245: sub assign_categories_table {
 9246:     my ($cathash,$currcat) = @_;
 9247:     my $output;
 9248:     if (ref($cathash) eq 'HASH') {
 9249:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9250:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9251:         $maxdepth = scalar(@cats);
 9252:         if (@cats > 0) {
 9253:             my $itemcount = 0;
 9254:             if (ref($cats[0]) eq 'ARRAY') {
 9255:                 $output = &Apache::loncommon::start_data_table();
 9256:                 my @currcategories;
 9257:                 if ($currcat ne '') {
 9258:                     @currcategories = split('&',$currcat);
 9259:                 }
 9260:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9261:                     my $parent = $cats[0][$i];
 9262:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9263:                     next if ($parent eq 'instcode');
 9264:                     my $item = &escape($parent).'::0';
 9265:                     my $checked = '';
 9266:                     if (@currcategories > 0) {
 9267:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9268:                             $checked = ' checked="checked"';
 9269:                         }
 9270:                     }
 9271:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9272:                                '<input type="checkbox" name="usecategory" value="'.
 9273:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9274:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9275:                     my $depth = 1;
 9276:                     push(@path,$parent);
 9277:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9278:                     pop(@path);
 9279:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9280:                     $itemcount ++;
 9281:                 }
 9282:                 $output .= &Apache::loncommon::end_data_table();
 9283:             }
 9284:         }
 9285:     }
 9286:     return $output;
 9287: }
 9288: 
 9289: =pod
 9290: 
 9291: =item *&assign_category_rows()
 9292: 
 9293: Create a datatable row for display of nested categories in a domain,
 9294: with checkboxes to allow a course to be categorized,called recursively.
 9295: 
 9296: Inputs:
 9297: 
 9298: itemcount - track row number for alternating colors
 9299: 
 9300: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9301:       categories and subcategories.
 9302: 
 9303: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9304: 
 9305: parent - parent of current category item
 9306: 
 9307: path - Array containing all categories back up through the hierarchy from the
 9308:        current category to the top level.
 9309: 
 9310: currcategories - reference to array of current categories assigned to the course
 9311: 
 9312: Returns: $output (markup to be displayed).
 9313: 
 9314: =cut
 9315: 
 9316: sub assign_category_rows {
 9317:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9318:     my ($text,$name,$item,$chgstr);
 9319:     if (ref($cats) eq 'ARRAY') {
 9320:         my $maxdepth = scalar(@{$cats});
 9321:         if (ref($cats->[$depth]) eq 'HASH') {
 9322:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9323:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9324:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9325:                 $text .= '<td><table class="LC_datatable">';
 9326:                 for (my $j=0; $j<$numchildren; $j++) {
 9327:                     $name = $cats->[$depth]{$parent}[$j];
 9328:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9329:                     my $deeper = $depth+1;
 9330:                     my $checked = '';
 9331:                     if (ref($currcategories) eq 'ARRAY') {
 9332:                         if (@{$currcategories} > 0) {
 9333:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9334:                                 $checked = ' checked="checked"';
 9335:                             }
 9336:                         }
 9337:                     }
 9338:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9339:                              '<input type="checkbox" name="usecategory" value="'.
 9340:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9341:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9342:                              '</td><td>';
 9343:                     if (ref($path) eq 'ARRAY') {
 9344:                         push(@{$path},$name);
 9345:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9346:                         pop(@{$path});
 9347:                     }
 9348:                     $text .= '</td></tr>';
 9349:                 }
 9350:                 $text .= '</table></td>';
 9351:             }
 9352:         }
 9353:     }
 9354:     return $text;
 9355: }
 9356: 
 9357: ############################################################
 9358: ############################################################
 9359: 
 9360: 
 9361: sub commit_customrole {
 9362:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9363:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9364:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9365:                          ($end?', ending '.localtime($end):'').': <b>'.
 9366:               &Apache::lonnet::assigncustomrole(
 9367:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9368:                  '</b><br />';
 9369:     return $output;
 9370: }
 9371: 
 9372: sub commit_standardrole {
 9373:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9374:     my ($output,$logmsg,$linefeed);
 9375:     if ($context eq 'auto') {
 9376:         $linefeed = "\n";
 9377:     } else {
 9378:         $linefeed = "<br />\n";
 9379:     }  
 9380:     if ($three eq 'st') {
 9381:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9382:                                          $one,$two,$sec,$context);
 9383:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9384:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9385:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9386:         } else {
 9387:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9388:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9389:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9390:             if ($context eq 'auto') {
 9391:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9392:             } else {
 9393:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9394:                &mt('Add to classlist').': <b>ok</b>';
 9395:             }
 9396:             $output .= $linefeed;
 9397:         }
 9398:     } else {
 9399:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9400:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9401:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9402:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9403:         if ($context eq 'auto') {
 9404:             $output .= $result.$linefeed;
 9405:         } else {
 9406:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9407:         }
 9408:     }
 9409:     return $output;
 9410: }
 9411: 
 9412: sub commit_studentrole {
 9413:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9414:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9415:     if ($context eq 'auto') {
 9416:         $linefeed = "\n";
 9417:     } else {
 9418:         $linefeed = '<br />'."\n";
 9419:     }
 9420:     if (defined($one) && defined($two)) {
 9421:         my $cid=$one.'_'.$two;
 9422:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9423:         my $secchange = 0;
 9424:         my $expire_role_result;
 9425:         my $modify_section_result;
 9426:         if ($oldsec ne '-1') { 
 9427:             if ($oldsec ne $sec) {
 9428:                 $secchange = 1;
 9429:                 my $now = time;
 9430:                 my $uurl='/'.$cid;
 9431:                 $uurl=~s/\_/\//g;
 9432:                 if ($oldsec) {
 9433:                     $uurl.='/'.$oldsec;
 9434:                 }
 9435:                 $oldsecurl = $uurl;
 9436:                 $expire_role_result = 
 9437:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9438:                 if ($env{'request.course.sec'} ne '') { 
 9439:                     if ($expire_role_result eq 'refused') {
 9440:                         my @roles = ('st');
 9441:                         my @statuses = ('previous');
 9442:                         my @roledoms = ($one);
 9443:                         my $withsec = 1;
 9444:                         my %roleshash = 
 9445:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9446:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9447:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9448:                             my ($oldstart,$oldend) = 
 9449:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9450:                             if ($oldend > 0 && $oldend <= $now) {
 9451:                                 $expire_role_result = 'ok';
 9452:                             }
 9453:                         }
 9454:                     }
 9455:                 }
 9456:                 $result = $expire_role_result;
 9457:             }
 9458:         }
 9459:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9460:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9461:             if ($modify_section_result =~ /^ok/) {
 9462:                 if ($secchange == 1) {
 9463:                     if ($sec eq '') {
 9464:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9465:                     } else {
 9466:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9467:                     }
 9468:                 } elsif ($oldsec eq '-1') {
 9469:                     if ($sec eq '') {
 9470:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9471:                     } else {
 9472:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9473:                     }
 9474:                 } else {
 9475:                     if ($sec eq '') {
 9476:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9477:                     } else {
 9478:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9479:                     }
 9480:                 }
 9481:             } else {
 9482:                 if ($secchange) {       
 9483:                     $$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;
 9484:                 } else {
 9485:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9486:                 }
 9487:             }
 9488:             $result = $modify_section_result;
 9489:         } elsif ($secchange == 1) {
 9490:             if ($oldsec eq '') {
 9491:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9492:             } else {
 9493:                 $$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;
 9494:             }
 9495:             if ($expire_role_result eq 'refused') {
 9496:                 my $newsecurl = '/'.$cid;
 9497:                 $newsecurl =~ s/\_/\//g;
 9498:                 if ($sec ne '') {
 9499:                     $newsecurl.='/'.$sec;
 9500:                 }
 9501:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9502:                     if ($sec eq '') {
 9503:                         $$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;
 9504:                     } else {
 9505:                         $$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;
 9506:                     }
 9507:                 }
 9508:             }
 9509:         }
 9510:     } else {
 9511:         $$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;
 9512:         $result = "error: incomplete course id\n";
 9513:     }
 9514:     return $result;
 9515: }
 9516: 
 9517: ############################################################
 9518: ############################################################
 9519: 
 9520: sub check_clone {
 9521:     my ($args,$linefeed) = @_;
 9522:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9523:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9524:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9525:     my $clonemsg;
 9526:     my $can_clone = 0;
 9527: 
 9528:     if ($clonehome eq 'no_host') {
 9529:         $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'});     
 9530:     } else {
 9531: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9532: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9533: 	    $can_clone = 1;
 9534: 	} else {
 9535: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9536: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9537: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9538:             if (grep(/^\*$/,@cloners)) {
 9539:                 $can_clone = 1;
 9540:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9541:                 $can_clone = 1;
 9542:             } else {
 9543: 	        my %roleshash =
 9544: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9545: 					 $args->{'ccdomain'},
 9546:                                          'userroles',['active'],['cc'],
 9547: 					 [$args->{'clonedomain'}]);
 9548: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9549: 		    $can_clone = 1;
 9550: 	        } else {
 9551:                     $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'});
 9552: 	        }
 9553: 	    }
 9554:         }
 9555:     }
 9556:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9557: }
 9558: 
 9559: sub construct_course {
 9560:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9561:     my $outcome;
 9562:     my $linefeed =  '<br />'."\n";
 9563:     if ($context eq 'auto') {
 9564:         $linefeed = "\n";
 9565:     }
 9566: 
 9567: #
 9568: # Are we cloning?
 9569: #
 9570:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9571:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9572: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9573: 	if ($context ne 'auto') {
 9574:             if ($clonemsg ne '') {
 9575: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9576:             }
 9577: 	}
 9578: 	$outcome .= $clonemsg.$linefeed;
 9579: 
 9580:         if (!$can_clone) {
 9581: 	    return (0,$outcome);
 9582: 	}
 9583:     }
 9584: 
 9585: #
 9586: # Open course
 9587: #
 9588:     my $crstype = lc($args->{'crstype'});
 9589:     my %cenv=();
 9590:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9591:                                              $args->{'cdescr'},
 9592:                                              $args->{'curl'},
 9593:                                              $args->{'course_home'},
 9594:                                              $args->{'nonstandard'},
 9595:                                              $args->{'crscode'},
 9596:                                              $args->{'ccuname'}.':'.
 9597:                                              $args->{'ccdomain'},
 9598:                                              $args->{'crstype'});
 9599: 
 9600:     # Note: The testing routines depend on this being output; see 
 9601:     # Utils::Course. This needs to at least be output as a comment
 9602:     # if anyone ever decides to not show this, and Utils::Course::new
 9603:     # will need to be suitably modified.
 9604:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9605: #
 9606: # Check if created correctly
 9607: #
 9608:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9609:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9610:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9611: 
 9612: #
 9613: # Do the cloning
 9614: #   
 9615:     if ($can_clone && $cloneid) {
 9616: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9617: 	if ($context ne 'auto') {
 9618: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9619: 	}
 9620: 	$outcome .= $clonemsg.$linefeed;
 9621: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9622: # Copy all files
 9623: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9624: # Restore URL
 9625: 	$cenv{'url'}=$oldcenv{'url'};
 9626: # Restore title
 9627: 	$cenv{'description'}=$oldcenv{'description'};
 9628: # Mark as cloned
 9629: 	$cenv{'clonedfrom'}=$cloneid;
 9630: # Need to clone grading mode
 9631:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9632:         $cenv{'grading'}=$newenv{'grading'};
 9633: # Do not clone these environment entries
 9634:         &Apache::lonnet::del('environment',
 9635:                   ['default_enrollment_start_date',
 9636:                    'default_enrollment_end_date',
 9637:                    'question.email',
 9638:                    'policy.email',
 9639:                    'comment.email',
 9640:                    'pch.users.denied',
 9641:                    'plc.users.denied',
 9642:                    'hidefromcat',
 9643:                    'categories'],
 9644:                    $$crsudom,$$crsunum);
 9645:     }
 9646: 
 9647: #
 9648: # Set environment (will override cloned, if existing)
 9649: #
 9650:     my @sections = ();
 9651:     my @xlists = ();
 9652:     if ($args->{'crstype'}) {
 9653:         $cenv{'type'}=$args->{'crstype'};
 9654:     }
 9655:     if ($args->{'crsid'}) {
 9656:         $cenv{'courseid'}=$args->{'crsid'};
 9657:     }
 9658:     if ($args->{'crscode'}) {
 9659:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9660:     }
 9661:     if ($args->{'crsquota'} ne '') {
 9662:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9663:     } else {
 9664:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9665:     }
 9666:     if ($args->{'ccuname'}) {
 9667:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9668:                                         ':'.$args->{'ccdomain'};
 9669:     } else {
 9670:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9671:     }
 9672:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9673:     if ($args->{'crssections'}) {
 9674:         $cenv{'internal.sectionnums'} = '';
 9675:         if ($args->{'crssections'} =~ m/,/) {
 9676:             @sections = split/,/,$args->{'crssections'};
 9677:         } else {
 9678:             $sections[0] = $args->{'crssections'};
 9679:         }
 9680:         if (@sections > 0) {
 9681:             foreach my $item (@sections) {
 9682:                 my ($sec,$gp) = split/:/,$item;
 9683:                 my $class = $args->{'crscode'}.$sec;
 9684:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9685:                 $cenv{'internal.sectionnums'} .= $item.',';
 9686:                 unless ($addcheck eq 'ok') {
 9687:                     push @badclasses, $class;
 9688:                 }
 9689:             }
 9690:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9691:         }
 9692:     }
 9693: # do not hide course coordinator from staff listing, 
 9694: # even if privileged
 9695:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9696: # add crosslistings
 9697:     if ($args->{'crsxlist'}) {
 9698:         $cenv{'internal.crosslistings'}='';
 9699:         if ($args->{'crsxlist'} =~ m/,/) {
 9700:             @xlists = split/,/,$args->{'crsxlist'};
 9701:         } else {
 9702:             $xlists[0] = $args->{'crsxlist'};
 9703:         }
 9704:         if (@xlists > 0) {
 9705:             foreach my $item (@xlists) {
 9706:                 my ($xl,$gp) = split/:/,$item;
 9707:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9708:                 $cenv{'internal.crosslistings'} .= $item.',';
 9709:                 unless ($addcheck eq 'ok') {
 9710:                     push @badclasses, $xl;
 9711:                 }
 9712:             }
 9713:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9714:         }
 9715:     }
 9716:     if ($args->{'autoadds'}) {
 9717:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9718:     }
 9719:     if ($args->{'autodrops'}) {
 9720:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9721:     }
 9722: # check for notification of enrollment changes
 9723:     my @notified = ();
 9724:     if ($args->{'notify_owner'}) {
 9725:         if ($args->{'ccuname'} ne '') {
 9726:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9727:         }
 9728:     }
 9729:     if ($args->{'notify_dc'}) {
 9730:         if ($uname ne '') { 
 9731:             push(@notified,$uname.':'.$udom);
 9732:         }
 9733:     }
 9734:     if (@notified > 0) {
 9735:         my $notifylist;
 9736:         if (@notified > 1) {
 9737:             $notifylist = join(',',@notified);
 9738:         } else {
 9739:             $notifylist = $notified[0];
 9740:         }
 9741:         $cenv{'internal.notifylist'} = $notifylist;
 9742:     }
 9743:     if (@badclasses > 0) {
 9744:         my %lt=&Apache::lonlocal::texthash(
 9745:                 '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',
 9746:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9747:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9748:         );
 9749:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9750:                            ' ('.$lt{'adby'}.')';
 9751:         if ($context eq 'auto') {
 9752:             $outcome .= $badclass_msg.$linefeed;
 9753:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9754:             foreach my $item (@badclasses) {
 9755:                 if ($context eq 'auto') {
 9756:                     $outcome .= " - $item\n";
 9757:                 } else {
 9758:                     $outcome .= "<li>$item</li>\n";
 9759:                 }
 9760:             }
 9761:             if ($context eq 'auto') {
 9762:                 $outcome .= $linefeed;
 9763:             } else {
 9764:                 $outcome .= "</ul><br /><br /></div>\n";
 9765:             }
 9766:         } 
 9767:     }
 9768:     if ($args->{'no_end_date'}) {
 9769:         $args->{'endaccess'} = 0;
 9770:     }
 9771:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9772:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9773:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9774:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9775:     if ($args->{'showphotos'}) {
 9776:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9777:     }
 9778:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9779:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9780:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9781:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9782:             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'); 
 9783:             if ($context eq 'auto') {
 9784:                 $outcome .= $krb_msg;
 9785:             } else {
 9786:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9787:             }
 9788:             $outcome .= $linefeed;
 9789:         }
 9790:     }
 9791:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9792:        if ($args->{'setpolicy'}) {
 9793:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9794:        }
 9795:        if ($args->{'setcontent'}) {
 9796:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9797:        }
 9798:     }
 9799:     if ($args->{'reshome'}) {
 9800: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9801: 	$cenv{'reshome'}=~s/\/+$/\//;
 9802:     }
 9803: #
 9804: # course has keyed access
 9805: #
 9806:     if ($args->{'setkeys'}) {
 9807:        $cenv{'keyaccess'}='yes';
 9808:     }
 9809: # if specified, key authority is not course, but user
 9810: # only active if keyaccess is yes
 9811:     if ($args->{'keyauth'}) {
 9812: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9813: 	$user = &LONCAPA::clean_username($user);
 9814: 	$domain = &LONCAPA::clean_username($domain);
 9815: 	if ($user ne '' && $domain ne '') {
 9816: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9817: 	}
 9818:     }
 9819: 
 9820:     if ($args->{'disresdis'}) {
 9821:         $cenv{'pch.roles.denied'}='st';
 9822:     }
 9823:     if ($args->{'disablechat'}) {
 9824:         $cenv{'plc.roles.denied'}='st';
 9825:     }
 9826: 
 9827:     # Record we've not yet viewed the Course Initialization Helper for this 
 9828:     # course
 9829:     $cenv{'course.helper.not.run'} = 1;
 9830:     #
 9831:     # Use new Randomseed
 9832:     #
 9833:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9834:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9835:     #
 9836:     # The encryption code and receipt prefix for this course
 9837:     #
 9838:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9839:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9840:     #
 9841:     # By default, use standard grading
 9842:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9843: 
 9844:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9845:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9846: #
 9847: # Open all assignments
 9848: #
 9849:     if ($args->{'openall'}) {
 9850:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9851:        my %storecontent = ($storeunder         => time,
 9852:                            $storeunder.'.type' => 'date_start');
 9853:        
 9854:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9855:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9856:    }
 9857: #
 9858: # Set first page
 9859: #
 9860:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9861: 	    || ($cloneid)) {
 9862: 	use LONCAPA::map;
 9863: 	$outcome .= &mt('Setting first resource').': ';
 9864: 
 9865: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9866:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9867: 
 9868:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9869:         my $title; my $url;
 9870:         if ($args->{'firstres'} eq 'syl') {
 9871: 	    $title=&mt('Syllabus');
 9872:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9873:         } else {
 9874:             $title=&mt('Navigate Contents');
 9875:             $url='/adm/navmaps';
 9876:         }
 9877: 
 9878:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9879: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9880: 
 9881: 	if ($errtext) { $fatal=2; }
 9882:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9883:     }
 9884: 
 9885:     return (1,$outcome);
 9886: }
 9887: 
 9888: ############################################################
 9889: ############################################################
 9890: 
 9891: sub course_type {
 9892:     my ($cid) = @_;
 9893:     if (!defined($cid)) {
 9894:         $cid = $env{'request.course.id'};
 9895:     }
 9896:     if (defined($env{'course.'.$cid.'.type'})) {
 9897:         return $env{'course.'.$cid.'.type'};
 9898:     } else {
 9899:         return 'Course';
 9900:     }
 9901: }
 9902: 
 9903: sub group_term {
 9904:     my $crstype = &course_type();
 9905:     my %names = (
 9906:                   'Course' => 'group',
 9907:                   'Group' => 'team',
 9908:                 );
 9909:     return $names{$crstype};
 9910: }
 9911: 
 9912: sub icon {
 9913:     my ($file)=@_;
 9914:     my $curfext = lc((split(/\./,$file))[-1]);
 9915:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9916:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9917:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9918: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9919: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9920: 	            $curfext.".gif") {
 9921: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9922: 		$curfext.".gif";
 9923: 	}
 9924:     }
 9925:     return &lonhttpdurl($iconname);
 9926: } 
 9927: 
 9928: sub lonhttpdurl {
 9929: #
 9930: # Had been used for "small fry" static images on separate port 8080.
 9931: # Modify here if lightweight http functionality desired again.
 9932: # Currently eliminated due to increasing firewall issues.
 9933: #
 9934:     my ($url)=@_;
 9935:     return $url;
 9936: }
 9937: 
 9938: sub connection_aborted {
 9939:     my ($r)=@_;
 9940:     $r->print(" ");$r->rflush();
 9941:     my $c = $r->connection;
 9942:     return $c->aborted();
 9943: }
 9944: 
 9945: #    Escapes strings that may have embedded 's that will be put into
 9946: #    strings as 'strings'.
 9947: sub escape_single {
 9948:     my ($input) = @_;
 9949:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9950:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9951:     return $input;
 9952: }
 9953: 
 9954: #  Same as escape_single, but escape's "'s  This 
 9955: #  can be used for  "strings"
 9956: sub escape_double {
 9957:     my ($input) = @_;
 9958:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9959:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9960:     return $input;
 9961: }
 9962:  
 9963: #   Escapes the last element of a full URL.
 9964: sub escape_url {
 9965:     my ($url)   = @_;
 9966:     my @urlslices = split(/\//, $url,-1);
 9967:     my $lastitem = &escape(pop(@urlslices));
 9968:     return join('/',@urlslices).'/'.$lastitem;
 9969: }
 9970: 
 9971: # -------------------------------------------------------- Initliaze user login
 9972: sub init_user_environment {
 9973:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9974:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9975: 
 9976:     my $public=($username eq 'public' && $domain eq 'public');
 9977: 
 9978: # See if old ID present, if so, remove
 9979: 
 9980:     my ($filename,$cookie,$userroles);
 9981:     my $now=time;
 9982: 
 9983:     if ($public) {
 9984: 	my $max_public=100;
 9985: 	my $oldest;
 9986: 	my $oldest_time=0;
 9987: 	for(my $next=1;$next<=$max_public;$next++) {
 9988: 	    if (-e $lonids."/publicuser_$next.id") {
 9989: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9990: 		if ($mtime<$oldest_time || !$oldest_time) {
 9991: 		    $oldest_time=$mtime;
 9992: 		    $oldest=$next;
 9993: 		}
 9994: 	    } else {
 9995: 		$cookie="publicuser_$next";
 9996: 		last;
 9997: 	    }
 9998: 	}
 9999: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10000:     } else {
10001: 	# if this isn't a robot, kill any existing non-robot sessions
10002: 	if (!$args->{'robot'}) {
10003: 	    opendir(DIR,$lonids);
10004: 	    while ($filename=readdir(DIR)) {
10005: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10006: 		    unlink($lonids.'/'.$filename);
10007: 		}
10008: 	    }
10009: 	    closedir(DIR);
10010: 	}
10011: # Give them a new cookie
10012: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10013: 		                   : $now.$$.int(rand(10000)));
10014: 	$cookie="$username\_$id\_$domain\_$authhost";
10015:     
10016: # Initialize roles
10017: 
10018: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10019:     }
10020: # ------------------------------------ Check browser type and MathML capability
10021: 
10022:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10023:         $clientunicode,$clientos) = &decode_user_agent($r);
10024: 
10025: # -------------------------------------- Any accessibility options to remember?
10026:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
10027: 	foreach my $option ('imagesuppress','appletsuppress',
10028: 			    'embedsuppress','fontenhance','blackwhite') {
10029: 	    if ($form->{$option} eq 'true') {
10030: 		&Apache::lonnet::put('environment',{$option => 'on'},
10031: 				     $domain,$username);
10032: 	    } else {
10033: 		&Apache::lonnet::del('environment',[$option],
10034: 				     $domain,$username);
10035: 	    }
10036: 	}
10037:     }
10038: # ------------------------------------------------------------- Get environment
10039: 
10040:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10041:     my ($tmp) = keys(%userenv);
10042:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10043: 	# default remote control to off
10044: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10045:     } else {
10046: 	undef(%userenv);
10047:     }
10048:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10049: 	$form->{'interface'}=$userenv{'interface'};
10050:     }
10051:     $env{'environment.remote'}=$userenv{'remote'};
10052:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10053: 
10054: # --------------- Do not trust query string to be put directly into environment
10055:     foreach my $option ('imagesuppress','appletsuppress',
10056: 			'embedsuppress','fontenhance','blackwhite',
10057: 			'interface','localpath','localres') {
10058: 	$form->{$option}=~s/[\n\r\=]//gs;
10059:     }
10060: # --------------------------------------------------------- Write first profile
10061: 
10062:     {
10063: 	my %initial_env = 
10064: 	    ("user.name"          => $username,
10065: 	     "user.domain"        => $domain,
10066: 	     "user.home"          => $authhost,
10067: 	     "browser.type"       => $clientbrowser,
10068: 	     "browser.version"    => $clientversion,
10069: 	     "browser.mathml"     => $clientmathml,
10070: 	     "browser.unicode"    => $clientunicode,
10071: 	     "browser.os"         => $clientos,
10072: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10073: 	     "request.course.fn"  => '',
10074: 	     "request.course.uri" => '',
10075: 	     "request.course.sec" => '',
10076: 	     "request.role"       => 'cm',
10077: 	     "request.role.adv"   => $env{'user.adv'},
10078: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10079: 
10080:         if ($form->{'localpath'}) {
10081: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10082: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10083:         }
10084: 	
10085: 	if ($public) {
10086: 	    $initial_env{"environment.remote"} = "off";
10087: 	}
10088: 	if ($form->{'interface'}) {
10089: 	    $form->{'interface'}=~s/\W//gs;
10090: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10091: 	    $env{'browser.interface'}=$form->{'interface'};
10092: 	    foreach my $option ('imagesuppress','appletsuppress',
10093: 				'embedsuppress','fontenhance','blackwhite') {
10094: 		if (($form->{$option} eq 'true') ||
10095: 		    ($userenv{$option} eq 'on')) {
10096: 		    $initial_env{"browser.$option"} = "on";
10097: 		}
10098: 	    }
10099: 	}
10100: 
10101:         foreach my $tool ('aboutme','blog','portfolio') {
10102:             $userenv{'availabletools.'.$tool} = 
10103:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10104:         }
10105: 
10106:         foreach my $crstype ('official','unofficial') {
10107:             $userenv{'canrequest.'.$crstype} =
10108:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10109:                                                   'reload','requestcourses');
10110:         }
10111: 
10112: 	$env{'user.environment'} = "$lonids/$cookie.id";
10113: 	
10114: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10115: 		 &GDBM_WRCREAT(),0640)) {
10116: 	    &_add_to_env(\%disk_env,\%initial_env);
10117: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10118: 	    &_add_to_env(\%disk_env,$userroles);
10119: 	    if (ref($args->{'extra_env'})) {
10120: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10121: 	    }
10122: 	    untie(%disk_env);
10123: 	} else {
10124: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10125: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10126: 	    return 'error: '.$!;
10127: 	}
10128:     }
10129:     $env{'request.role'}='cm';
10130:     $env{'request.role.adv'}=$env{'user.adv'};
10131:     $env{'browser.type'}=$clientbrowser;
10132: 
10133:     return $cookie;
10134: 
10135: }
10136: 
10137: sub _add_to_env {
10138:     my ($idf,$env_data,$prefix) = @_;
10139:     if (ref($env_data) eq 'HASH') {
10140:         while (my ($key,$value) = each(%$env_data)) {
10141: 	    $idf->{$prefix.$key} = $value;
10142: 	    $env{$prefix.$key}   = $value;
10143:         }
10144:     }
10145: }
10146: 
10147: # --- Get the symbolic name of a problem and the url
10148: sub get_symb {
10149:     my ($request,$silent) = @_;
10150:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10151:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10152:     if ($symb eq '') {
10153:         if (!$silent) {
10154:             $request->print("Unable to handle ambiguous references:$url:.");
10155:             return ();
10156:         }
10157:     }
10158:     &Apache::lonenc::check_decrypt(\$symb);
10159:     return ($symb);
10160: }
10161: 
10162: # --------------------------------------------------------------Get annotation
10163: 
10164: sub get_annotation {
10165:     my ($symb,$enc) = @_;
10166: 
10167:     my $key = $symb;
10168:     if (!$enc) {
10169:         $key =
10170:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10171:     }
10172:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10173:     return $annotation{$key};
10174: }
10175: 
10176: sub clean_symb {
10177:     my ($symb,$delete_enc) = @_;
10178: 
10179:     &Apache::lonenc::check_decrypt(\$symb);
10180:     my $enc = $env{'request.enc'};
10181:     if ($delete_enc) {
10182:         delete($env{'request.enc'});
10183:     }
10184: 
10185:     return ($symb,$enc);
10186: }
10187: 
10188: =pod
10189: 
10190: =back
10191: 
10192: =cut
10193: 
10194: 1;
10195: __END__;
10196: 

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