File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.872: download - view: text, annotated - select for diffs
Fri Jul 31 02:13:05 2009 UTC (14 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
loncommon.pm
- Rename fifth arg to &select_dom_form() from $autosubmit to $onchange;
- More flexibility - $onchange arg now includes the javascript call executed following an
  onchange event.

coursecatalog.pm
- Replace $nochange arg in loncommon::select_dom_form() with function to execute.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.872 2009/07/31 02:13:05 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use 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: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom;
  425: 	if (roleflag) { url+="&roles=1"; }
  426:         if (courseadvonly) { url+="&courseadvonly=1"; }
  427:         var title = 'Student_Browser';
  428:         var options = 'scrollbars=1,resizable=1,menubar=0';
  429:         options += ',width=700,height=600';
  430:         stdeditbrowser = open(url,title,options,'1');
  431:         stdeditbrowser.focus();
  432:     }
  433: // ]]>
  434: </script>
  435: ENDSTDBRW
  436: }
  437: 
  438: sub selectstudent_link {
  439:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  440:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  441:    if ($env{'request.course.id'}) {  
  442:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  443: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  444: 					'/'.$env{'request.course.sec'})) {
  445: 	   return '';
  446:        }
  447:        if ($courseadvonly)  {
  448:            $callargs .= ",'',1,1";
  449:        }
  450:        return '<span class="LC_nobreak">'.
  451:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  452:               &mt('Select User').'</a></span>';
  453:    }
  454:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  455:        $callargs .= ",1"; 
  456:        return '<span class="LC_nobreak">'.
  457:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  458:               &mt('Select User').'</a></span>';
  459:    }
  460:    return '';
  461: }
  462: 
  463: sub authorbrowser_javascript {
  464:     return <<"ENDAUTHORBRW";
  465: <script type="text/javascript" language="JavaScript">
  466: // <![CDATA[
  467: var stdeditbrowser;
  468: 
  469: function openauthorbrowser(formname,udom) {
  470:     var url = '/adm/pickauthor?';
  471:     url += 'form='+formname+'&roledom='+udom;
  472:     var title = 'Author_Browser';
  473:     var options = 'scrollbars=1,resizable=1,menubar=0';
  474:     options += ',width=700,height=600';
  475:     stdeditbrowser = open(url,title,options,'1');
  476:     stdeditbrowser.focus();
  477: }
  478: 
  479: // ]]>
  480: </script>
  481: ENDAUTHORBRW
  482: }
  483: 
  484: sub coursebrowser_javascript {
  485:     my ($domainfilter,$sec_element,$formname)=@_;
  486:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Community - for which you wish to add/modify a user role');
  487:    my $output = '
  488: <script type="text/javascript" language="JavaScript">
  489: // <![CDATA[
  490:     var stdeditbrowser;'."\n";
  491:    $output .= <<"ENDSTDBRW";
  492:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  493:         var url = '/adm/pickcourse?';
  494:         var domainfilter = '';
  495:         var formid = getFormIdByName(formname);
  496:         if (formid > -1) {
  497:             var domid = getIndexByName(formid,udom);
  498:             if (domid > -1) {
  499:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  500:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  501:                 }
  502:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  503:                     domainfilter=document.forms[formid].elements[domid].value;
  504:                 }
  505:             }
  506:         }
  507:         if (domainfilter != null) {
  508:            if (domainfilter != '') {
  509:                url += 'domainfilter='+domainfilter+'&';
  510: 	   }
  511:         }
  512:         url += 'form=' + formname + '&cnumelement='+uname+
  513: 	                            '&cdomelement='+udom+
  514:                                     '&cnameelement='+desc;
  515:         if (extra_element !=null && extra_element != '') {
  516:             if (formname == 'rolechoice' || formname == 'studentform') {
  517:                 url += '&roleelement='+extra_element;
  518:                 if (domainfilter == null || domainfilter == '') {
  519:                     url += '&domainfilter='+extra_element;
  520:                 }
  521:             }
  522:             else {
  523:                 if (formname == 'portform') {
  524:                     url += '&setroles='+extra_element;
  525:                 } else {
  526:                     if (formname == 'rules') {
  527:                         url += '&fixeddom='+extra_element; 
  528:                     }
  529:                 }
  530:             }     
  531:         }
  532:         if (formname == 'ccrs') {
  533:             var ownername = document.forms[formid].ccuname.value;
  534:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  535:             url += '&cloner='+ownername+':'+ownerdom;
  536:         }
  537:         if (multflag !=null && multflag != '') {
  538:             url += '&multiple='+multflag;
  539:         }
  540:         if (crstype == 'Course/Community') {
  541:             if (formname == 'cu') {
  542:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  543:                 if (crstype == "") {
  544:                     alert("$crs_or_grp_alert");
  545:                     return;
  546:                 }
  547:             }
  548:         }
  549:         if (crstype !=null && crstype != '') {
  550:             url += '&type='+crstype;
  551:         }
  552:         var title = 'Course_Browser';
  553:         var options = 'scrollbars=1,resizable=1,menubar=0';
  554:         options += ',width=700,height=600';
  555:         stdeditbrowser = open(url,title,options,'1');
  556:         stdeditbrowser.focus();
  557:     }
  558: 
  559:     function getFormIdByName(formname) {
  560:         for (var i=0;i<document.forms.length;i++) {
  561:             if (document.forms[i].name == formname) {
  562:                 return i;
  563:             }
  564:         }
  565:         return -1; 
  566:     }
  567: 
  568:     function getIndexByName(formid,item) {
  569:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  570:             if (document.forms[formid].elements[i].name == item) {
  571:                 return i;
  572:             }
  573:         }
  574:         return -1;
  575:     }
  576: ENDSTDBRW
  577:     if ($sec_element ne '') {
  578:         $output .= &setsec_javascript($sec_element,$formname);
  579:     }
  580:     $output .= '
  581: // ]]>
  582: </script>';
  583:     return $output;
  584: }
  585: 
  586: sub setsec_javascript {
  587:     my ($sec_element,$formname) = @_;
  588:     my $setsections = qq|
  589: function setSect(sectionlist) {
  590:     var sectionsArray = new Array();
  591:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  592:         sectionsArray = sectionlist.split(",");
  593:     }
  594:     var numSections = sectionsArray.length;
  595:     document.$formname.$sec_element.length = 0;
  596:     if (numSections == 0) {
  597:         document.$formname.$sec_element.multiple=false;
  598:         document.$formname.$sec_element.size=1;
  599:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  600:     } else {
  601:         if (numSections == 1) {
  602:             document.$formname.$sec_element.multiple=false;
  603:             document.$formname.$sec_element.size=1;
  604:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  605:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  606:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  607:         } else {
  608:             for (var i=0; i<numSections; i++) {
  609:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  610:             }
  611:             document.$formname.$sec_element.multiple=true
  612:             if (numSections < 3) {
  613:                 document.$formname.$sec_element.size=numSections;
  614:             } else {
  615:                 document.$formname.$sec_element.size=3;
  616:             }
  617:             document.$formname.$sec_element.options[0].selected = false
  618:         }
  619:     }
  620: }
  621: |;
  622:     return $setsections;
  623: }
  624: 
  625: 
  626: sub selectcourse_link {
  627:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  628:    my $linktext = &mt('Select Course');
  629:    if ($selecttype eq 'Community') {
  630:        $linktext = &mt('Select Community'); 
  631:    }
  632:    return '<span class="LC_nobreak">'
  633:          ."<a href='"
  634:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  635:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  636:          .'","'.$multflag.'","'.$selecttype.'");'
  637:          ."'>".$linktext.'</a>'
  638:          .'</span>';
  639: }
  640: 
  641: sub selectauthor_link {
  642:    my ($form,$udom)=@_;
  643:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  644:           &mt('Select Author').'</a>';
  645: }
  646: 
  647: sub check_uncheck_jscript {
  648:     my $jscript = <<"ENDSCRT";
  649: function checkAll(field) {
  650:     if (field.length > 0) {
  651:         for (i = 0; i < field.length; i++) {
  652:             field[i].checked = true ;
  653:         }
  654:     } else {
  655:         field.checked = true
  656:     }
  657: }
  658:  
  659: function uncheckAll(field) {
  660:     if (field.length > 0) {
  661:         for (i = 0; i < field.length; i++) {
  662:             field[i].checked = false ;
  663:         }
  664:     } else {
  665:         field.checked = false ;
  666:     }
  667: }
  668: ENDSCRT
  669:     return $jscript;
  670: }
  671: 
  672: sub select_timezone {
  673:    my ($name,$selected,$onchange,$includeempty)=@_;
  674:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  675:    if ($includeempty) {
  676:        $output .= '<option value=""';
  677:        if (($selected eq '') || ($selected eq 'local')) {
  678:            $output .= ' selected="selected" ';
  679:        }
  680:        $output .= '> </option>';
  681:    }
  682:    my @timezones = DateTime::TimeZone->all_names;
  683:    foreach my $tzone (@timezones) {
  684:        $output.= '<option value="'.$tzone.'"';
  685:        if ($tzone eq $selected) {
  686:            $output.=' selected="selected"';
  687:        }
  688:        $output.=">$tzone</option>\n";
  689:    }
  690:    $output.="</select>";
  691:    return $output;
  692: }
  693: 
  694: sub select_datelocale {
  695:     my ($name,$selected,$onchange,$includeempty)=@_;
  696:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  697:     if ($includeempty) {
  698:         $output .= '<option value=""';
  699:         if ($selected eq '') {
  700:             $output .= ' selected="selected" ';
  701:         }
  702:         $output .= '> </option>';
  703:     }
  704:     my (@possibles,%locale_names);
  705:     my @locales = DateTime::Locale::Catalog::Locales;
  706:     foreach my $locale (@locales) {
  707:         if (ref($locale) eq 'HASH') {
  708:             my $id = $locale->{'id'};
  709:             if ($id ne '') {
  710:                 my $en_terr = $locale->{'en_territory'};
  711:                 my $native_terr = $locale->{'native_territory'};
  712:                 my @languages = &Apache::lonlocal::preferred_languages();
  713:                 if (grep(/^en$/,@languages) || !@languages) {
  714:                     if ($en_terr ne '') {
  715:                         $locale_names{$id} = '('.$en_terr.')';
  716:                     } elsif ($native_terr ne '') {
  717:                         $locale_names{$id} = $native_terr;
  718:                     }
  719:                 } else {
  720:                     if ($native_terr ne '') {
  721:                         $locale_names{$id} = $native_terr.' ';
  722:                     } elsif ($en_terr ne '') {
  723:                         $locale_names{$id} = '('.$en_terr.')';
  724:                     }
  725:                 }
  726:                 push (@possibles,$id);
  727:             }
  728:         }
  729:     }
  730:     foreach my $item (sort(@possibles)) {
  731:         $output.= '<option value="'.$item.'"';
  732:         if ($item eq $selected) {
  733:             $output.=' selected="selected"';
  734:         }
  735:         $output.=">$item";
  736:         if ($locale_names{$item} ne '') {
  737:             $output.="  $locale_names{$item}</option>\n";
  738:         }
  739:         $output.="</option>\n";
  740:     }
  741:     $output.="</select>";
  742:     return $output;
  743: }
  744: 
  745: sub select_language {
  746:     my ($name,$selected,$includeempty) = @_;
  747:     my %langchoices;
  748:     if ($includeempty) {
  749:         %langchoices = ('' => 'No language preference');
  750:     }
  751:     foreach my $id (&languageids()) {
  752:         my $code = &supportedlanguagecode($id);
  753:         if ($code) {
  754:             $langchoices{$code} = &plainlanguagedescription($id);
  755:         }
  756:     }
  757:     return &select_form($selected,$name,%langchoices);
  758: }
  759: 
  760: =pod
  761: 
  762: =item * &linked_select_forms(...)
  763: 
  764: linked_select_forms returns a string containing a <script></script> block
  765: and html for two <select> menus.  The select menus will be linked in that
  766: changing the value of the first menu will result in new values being placed
  767: in the second menu.  The values in the select menu will appear in alphabetical
  768: order unless a defined order is provided.
  769: 
  770: linked_select_forms takes the following ordered inputs:
  771: 
  772: =over 4
  773: 
  774: =item * $formname, the name of the <form> tag
  775: 
  776: =item * $middletext, the text which appears between the <select> tags
  777: 
  778: =item * $firstdefault, the default value for the first menu
  779: 
  780: =item * $firstselectname, the name of the first <select> tag
  781: 
  782: =item * $secondselectname, the name of the second <select> tag
  783: 
  784: =item * $hashref, a reference to a hash containing the data for the menus.
  785: 
  786: =item * $menuorder, the order of values in the first menu
  787: 
  788: =back 
  789: 
  790: Below is an example of such a hash.  Only the 'text', 'default', and 
  791: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  792: values for the first select menu.  The text that coincides with the 
  793: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  794: and text for the second menu are given in the hash pointed to by 
  795: $menu{$choice1}->{'select2'}.  
  796: 
  797:  my %menu = ( A1 => { text =>"Choice A1" ,
  798:                        default => "B3",
  799:                        select2 => { 
  800:                            B1 => "Choice B1",
  801:                            B2 => "Choice B2",
  802:                            B3 => "Choice B3",
  803:                            B4 => "Choice B4"
  804:                            },
  805:                        order => ['B4','B3','B1','B2'],
  806:                    },
  807:                A2 => { text =>"Choice A2" ,
  808:                        default => "C2",
  809:                        select2 => { 
  810:                            C1 => "Choice C1",
  811:                            C2 => "Choice C2",
  812:                            C3 => "Choice C3"
  813:                            },
  814:                        order => ['C2','C1','C3'],
  815:                    },
  816:                A3 => { text =>"Choice A3" ,
  817:                        default => "D6",
  818:                        select2 => { 
  819:                            D1 => "Choice D1",
  820:                            D2 => "Choice D2",
  821:                            D3 => "Choice D3",
  822:                            D4 => "Choice D4",
  823:                            D5 => "Choice D5",
  824:                            D6 => "Choice D6",
  825:                            D7 => "Choice D7"
  826:                            },
  827:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  828:                    }
  829:                );
  830: 
  831: =cut
  832: 
  833: sub linked_select_forms {
  834:     my ($formname,
  835:         $middletext,
  836:         $firstdefault,
  837:         $firstselectname,
  838:         $secondselectname, 
  839:         $hashref,
  840:         $menuorder,
  841:         ) = @_;
  842:     my $second = "document.$formname.$secondselectname";
  843:     my $first = "document.$formname.$firstselectname";
  844:     # output the javascript to do the changing
  845:     my $result = '';
  846:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  847:     $result.="// <![CDATA[\n";
  848:     $result.="var select2data = new Object();\n";
  849:     $" = '","';
  850:     my $debug = '';
  851:     foreach my $s1 (sort(keys(%$hashref))) {
  852:         $result.="select2data.d_$s1 = new Object();\n";        
  853:         $result.="select2data.d_$s1.def = new String('".
  854:             $hashref->{$s1}->{'default'}."');\n";
  855:         $result.="select2data.d_$s1.values = new Array(";
  856:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  857:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  858:             @s2values = @{$hashref->{$s1}->{'order'}};
  859:         }
  860:         $result.="\"@s2values\");\n";
  861:         $result.="select2data.d_$s1.texts = new Array(";        
  862:         my @s2texts;
  863:         foreach my $value (@s2values) {
  864:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  865:         }
  866:         $result.="\"@s2texts\");\n";
  867:     }
  868:     $"=' ';
  869:     $result.= <<"END";
  870: 
  871: function select1_changed() {
  872:     // Determine new choice
  873:     var newvalue = "d_" + $first.value;
  874:     // update select2
  875:     var values     = select2data[newvalue].values;
  876:     var texts      = select2data[newvalue].texts;
  877:     var select2def = select2data[newvalue].def;
  878:     var i;
  879:     // out with the old
  880:     for (i = 0; i < $second.options.length; i++) {
  881:         $second.options[i] = null;
  882:     }
  883:     // in with the nuclear
  884:     for (i=0;i<values.length; i++) {
  885:         $second.options[i] = new Option(values[i]);
  886:         $second.options[i].value = values[i];
  887:         $second.options[i].text = texts[i];
  888:         if (values[i] == select2def) {
  889:             $second.options[i].selected = true;
  890:         }
  891:     }
  892: }
  893: // ]]>
  894: </script>
  895: END
  896:     # output the initial values for the selection lists
  897:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  898:     my @order = sort(keys(%{$hashref}));
  899:     if (ref($menuorder) eq 'ARRAY') {
  900:         @order = @{$menuorder};
  901:     }
  902:     foreach my $value (@order) {
  903:         $result.="    <option value=\"$value\" ";
  904:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  905:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  906:     }
  907:     $result .= "</select>\n";
  908:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  909:     $result .= $middletext;
  910:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  911:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  912:     
  913:     my @secondorder = sort(keys(%select2));
  914:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  915:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  916:     }
  917:     foreach my $value (@secondorder) {
  918:         $result.="    <option value=\"$value\" ";        
  919:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  920:         $result.=">".&mt($select2{$value})."</option>\n";
  921:     }
  922:     $result .= "</select>\n";
  923:     #    return $debug;
  924:     return $result;
  925: }   #  end of sub linked_select_forms {
  926: 
  927: =pod
  928: 
  929: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  930: 
  931: Returns a string corresponding to an HTML link to the given help
  932: $topic, where $topic corresponds to the name of a .tex file in
  933: /home/httpd/html/adm/help/tex, with underscores replaced by
  934: spaces. 
  935: 
  936: $text will optionally be linked to the same topic, allowing you to
  937: link text in addition to the graphic. If you do not want to link
  938: text, but wish to specify one of the later parameters, pass an
  939: empty string. 
  940: 
  941: $stayOnPage is a value that will be interpreted as a boolean. If true,
  942: the link will not open a new window. If false, the link will open
  943: a new window using Javascript. (Default is false.) 
  944: 
  945: $width and $height are optional numerical parameters that will
  946: override the width and height of the popped up window, which may
  947: be useful for certain help topics with big pictures included. 
  948: 
  949: =cut
  950: 
  951: sub help_open_topic {
  952:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  953:     $text = "" if (not defined $text);
  954:     $stayOnPage = 0 if (not defined $stayOnPage);
  955:     $width = 350 if (not defined $width);
  956:     $height = 400 if (not defined $height);
  957:     my $filename = $topic;
  958:     $filename =~ s/ /_/g;
  959: 
  960:     my $template = "";
  961:     my $link;
  962:     
  963:     $topic=~s/\W/\_/g;
  964: 
  965:     if (!$stayOnPage) {
  966: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  967:     } else {
  968: 	$link = "/adm/help/${filename}.hlp";
  969:     }
  970: 
  971:     # Add the text
  972:     if ($text ne "") {	
  973: 	$template.='<span class="LC_help_open_topic">'
  974:                   .'<a target="_top" href="'.$link.'">'
  975:                   .$text.'</a>';
  976:     }
  977: 
  978:     # (Always) Add the graphic
  979:     my $title = &mt('Online Help');
  980:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  981:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  982:               .'<img src="'.$helpicon.'" border="0"'
  983:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  984:               .' title="'.$title.'"' 
  985:               .' /></a>';
  986:     if ($text ne "") {	
  987:         $template.='</span>';
  988:     }
  989:     return $template;
  990: 
  991: }
  992: 
  993: # This is a quicky function for Latex cheatsheet editing, since it 
  994: # appears in at least four places
  995: sub helpLatexCheatsheet {
  996:     my ($topic,$text,$not_author) = @_;
  997:     my $out;
  998:     my $addOther = '';
  999:     if ($topic) {
 1000: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1001: 							       undef, undef, 600).
 1002: 								   '</span> ';
 1003:     }
 1004:     $out = '<span>' # Start cheatsheet
 1005: 	  .$addOther
 1006:           .'<span>'
 1007: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1008: 					       undef,undef,600)
 1009: 	  .'</span> <span>'
 1010: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1011: 					       undef,undef,600)
 1012: 	  .'</span>';
 1013:     unless ($not_author) {
 1014:         $out .= ' <span>'
 1015: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1016: 	                                            undef,undef,600)
 1017: 	       .'</span>';
 1018:     }
 1019:     $out .= '</span>'; # End cheatsheet
 1020:     return $out;
 1021: }
 1022: 
 1023: sub general_help {
 1024:     my $helptopic='Student_Intro';
 1025:     if ($env{'request.role'}=~/^(ca|au)/) {
 1026: 	$helptopic='Authoring_Intro';
 1027:     } elsif ($env{'request.role'}=~/^cc/) {
 1028: 	$helptopic='Course_Coordination_Intro';
 1029:     } elsif ($env{'request.role'}=~/^dc/) {
 1030:         $helptopic='Domain_Coordination_Intro';
 1031:     }
 1032:     return $helptopic;
 1033: }
 1034: 
 1035: sub update_help_link {
 1036:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1037:     my $origurl = $ENV{'REQUEST_URI'};
 1038:     $origurl=~s|^/~|/priv/|;
 1039:     my $timestamp = time;
 1040:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1041:         $$datum = &escape($$datum);
 1042:     }
 1043: 
 1044:     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";
 1045:     my $output .= <<"ENDOUTPUT";
 1046: <script type="text/javascript">
 1047: // <![CDATA[
 1048: banner_link = '$banner_link';
 1049: // ]]>
 1050: </script>
 1051: ENDOUTPUT
 1052:     return $output;
 1053: }
 1054: 
 1055: # now just updates the help link and generates a blue icon
 1056: sub help_open_menu {
 1057:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1058: 	= @_;    
 1059:     $stayOnPage = 0 if (not defined $stayOnPage);
 1060:     # only use pop-up help (stayOnPage == 0)
 1061:     # if environment.remote is on (using remote control UI)
 1062:     if ($env{'environment.remote'} eq 'off' ) {
 1063:         $stayOnPage=1;
 1064:     }
 1065:     my $output;
 1066:     if ($component_help) {
 1067: 	if (!$text) {
 1068: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1069: 				       $width,$height);
 1070: 	} else {
 1071: 	    my $help_text;
 1072: 	    $help_text=&unescape($topic);
 1073: 	    $output='<table><tr><td>'.
 1074: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1075: 				 $width,$height).'</td></tr></table>';
 1076: 	}
 1077:     }
 1078:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1079:     return $output.$banner_link;
 1080: }
 1081: 
 1082: sub top_nav_help {
 1083:     my ($text) = @_;
 1084:     $text = &mt($text);
 1085:     my $stay_on_page = 
 1086: 	($env{'environment.remote'} eq 'off' );
 1087:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1088: 	                     : "javascript:helpMenu('open')";
 1089:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1090: 
 1091:     my $title = &mt('Get help');
 1092: 
 1093:     return <<"END";
 1094: $banner_link
 1095:  <a href="$link" title="$title">$text</a>
 1096: END
 1097: }
 1098: 
 1099: sub help_menu_js {
 1100:     my ($text) = @_;
 1101: 
 1102:     my $stayOnPage = 
 1103: 	($env{'environment.remote'} eq 'off' );
 1104: 
 1105:     my $width = 620;
 1106:     my $height = 600;
 1107:     my $helptopic=&general_help();
 1108:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1109:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1110:     my $start_page =
 1111:         &Apache::loncommon::start_page('Help Menu', undef,
 1112: 				       {'frameset'    => 1,
 1113: 					'js_ready'    => 1,
 1114: 					'add_entries' => {
 1115: 					    'border' => '0',
 1116: 					    'rows'   => "110,*",},});
 1117:     my $end_page =
 1118:         &Apache::loncommon::end_page({'frameset' => 1,
 1119: 				      'js_ready' => 1,});
 1120: 
 1121:     my $template .= <<"ENDTEMPLATE";
 1122: <script type="text/javascript">
 1123: // <!-- BEGIN LON-CAPA Internal
 1124: // <![CDATA[
 1125: var banner_link = '';
 1126: function helpMenu(target) {
 1127:     var caller = this;
 1128:     if (target == 'open') {
 1129:         var newWindow = null;
 1130:         try {
 1131:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1132:         }
 1133:         catch(error) {
 1134:             writeHelp(caller);
 1135:             return;
 1136:         }
 1137:         if (newWindow) {
 1138:             caller = newWindow;
 1139:         }
 1140:     }
 1141:     writeHelp(caller);
 1142:     return;
 1143: }
 1144: function writeHelp(caller) {
 1145:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1146:     caller.document.close()
 1147:     caller.focus()
 1148: }
 1149: // ]]>
 1150: // END LON-CAPA Internal -->
 1151: </script>
 1152: ENDTEMPLATE
 1153:     return $template;
 1154: }
 1155: 
 1156: sub help_open_bug {
 1157:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1158:     unless ($env{'user.adv'}) { return ''; }
 1159:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1160:     $text = "" if (not defined $text);
 1161:     $stayOnPage = 0 if (not defined $stayOnPage);
 1162:     if ($env{'environment.remote'} eq 'off' ) {
 1163: 	$stayOnPage=1;
 1164:     }
 1165:     $width = 600 if (not defined $width);
 1166:     $height = 600 if (not defined $height);
 1167: 
 1168:     $topic=~s/\W+/\+/g;
 1169:     my $link='';
 1170:     my $template='';
 1171:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1172: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1173:     if (!$stayOnPage)
 1174:     {
 1175: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1176:     }
 1177:     else
 1178:     {
 1179: 	$link = $url;
 1180:     }
 1181:     # Add the text
 1182:     if ($text ne "")
 1183:     {
 1184: 	$template .= 
 1185:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1186:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1187:     }
 1188: 
 1189:     # Add the graphic
 1190:     my $title = &mt('Report a Bug');
 1191:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1192:     $template .= <<"ENDTEMPLATE";
 1193:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1194: ENDTEMPLATE
 1195:     if ($text ne '') { $template.='</td></tr></table>' };
 1196:     return $template;
 1197: 
 1198: }
 1199: 
 1200: sub help_open_faq {
 1201:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1202:     unless ($env{'user.adv'}) { return ''; }
 1203:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1204:     $text = "" if (not defined $text);
 1205:     $stayOnPage = 0 if (not defined $stayOnPage);
 1206:     if ($env{'environment.remote'} eq 'off' ) {
 1207: 	$stayOnPage=1;
 1208:     }
 1209:     $width = 350 if (not defined $width);
 1210:     $height = 400 if (not defined $height);
 1211: 
 1212:     $topic=~s/\W+/\+/g;
 1213:     my $link='';
 1214:     my $template='';
 1215:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1216:     if (!$stayOnPage)
 1217:     {
 1218: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1219:     }
 1220:     else
 1221:     {
 1222: 	$link = $url;
 1223:     }
 1224: 
 1225:     # Add the text
 1226:     if ($text ne "")
 1227:     {
 1228: 	$template .= 
 1229:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1230:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1231:     }
 1232: 
 1233:     # Add the graphic
 1234:     my $title = &mt('View the FAQ');
 1235:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1236:     $template .= <<"ENDTEMPLATE";
 1237:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1238: ENDTEMPLATE
 1239:     if ($text ne '') { $template.='</td></tr></table>' };
 1240:     return $template;
 1241: 
 1242: }
 1243: 
 1244: ###############################################################
 1245: ###############################################################
 1246: 
 1247: =pod
 1248: 
 1249: =item * &change_content_javascript():
 1250: 
 1251: This and the next function allow you to create small sections of an
 1252: otherwise static HTML page that you can update on the fly with
 1253: Javascript, even in Netscape 4.
 1254: 
 1255: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1256: must be written to the HTML page once. It will prove the Javascript
 1257: function "change(name, content)". Calling the change function with the
 1258: name of the section 
 1259: you want to update, matching the name passed to C<changable_area>, and
 1260: the new content you want to put in there, will put the content into
 1261: that area.
 1262: 
 1263: B<Note>: Netscape 4 only reserves enough space for the changable area
 1264: to contain room for the original contents. You need to "make space"
 1265: for whatever changes you wish to make, and be B<sure> to check your
 1266: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1267: it's adequate for updating a one-line status display, but little more.
 1268: This script will set the space to 100% width, so you only need to
 1269: worry about height in Netscape 4.
 1270: 
 1271: Modern browsers are much less limiting, and if you can commit to the
 1272: user not using Netscape 4, this feature may be used freely with
 1273: pretty much any HTML.
 1274: 
 1275: =cut
 1276: 
 1277: sub change_content_javascript {
 1278:     # If we're on Netscape 4, we need to use Layer-based code
 1279:     if ($env{'browser.type'} eq 'netscape' &&
 1280: 	$env{'browser.version'} =~ /^4\./) {
 1281: 	return (<<NETSCAPE4);
 1282: 	function change(name, content) {
 1283: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1284: 	    doc.open();
 1285: 	    doc.write(content);
 1286: 	    doc.close();
 1287: 	}
 1288: NETSCAPE4
 1289:     } else {
 1290: 	# Otherwise, we need to use semi-standards-compliant code
 1291: 	# (technically, "innerHTML" isn't standard but the equivalent
 1292: 	# is really scary, and every useful browser supports it
 1293: 	return (<<DOMBASED);
 1294: 	function change(name, content) {
 1295: 	    element = document.getElementById(name);
 1296: 	    element.innerHTML = content;
 1297: 	}
 1298: DOMBASED
 1299:     }
 1300: }
 1301: 
 1302: =pod
 1303: 
 1304: =item * &changable_area($name,$origContent):
 1305: 
 1306: This provides a "changable area" that can be modified on the fly via
 1307: the Javascript code provided in C<change_content_javascript>. $name is
 1308: the name you will use to reference the area later; do not repeat the
 1309: same name on a given HTML page more then once. $origContent is what
 1310: the area will originally contain, which can be left blank.
 1311: 
 1312: =cut
 1313: 
 1314: sub changable_area {
 1315:     my ($name, $origContent) = @_;
 1316: 
 1317:     if ($env{'browser.type'} eq 'netscape' &&
 1318: 	$env{'browser.version'} =~ /^4\./) {
 1319: 	# If this is netscape 4, we need to use the Layer tag
 1320: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1321:     } else {
 1322: 	return "<span id='$name'>$origContent</span>";
 1323:     }
 1324: }
 1325: 
 1326: =pod
 1327: 
 1328: =item * &viewport_geometry_js 
 1329: 
 1330: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1331: 
 1332: =cut
 1333: 
 1334: 
 1335: sub viewport_geometry_js { 
 1336:     return <<"GEOMETRY";
 1337: var Geometry = {};
 1338: function init_geometry() {
 1339:     if (Geometry.init) { return };
 1340:     Geometry.init=1;
 1341:     if (window.innerHeight) {
 1342:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1343:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1344:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1345:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1346:     }
 1347:     else if (document.documentElement && document.documentElement.clientHeight) {
 1348:         Geometry.getViewportHeight =
 1349:             function() { return document.documentElement.clientHeight; };
 1350:         Geometry.getViewportWidth =
 1351:             function() { return document.documentElement.clientWidth; };
 1352: 
 1353:         Geometry.getHorizontalScroll =
 1354:             function() { return document.documentElement.scrollLeft; };
 1355:         Geometry.getVerticalScroll =
 1356:             function() { return document.documentElement.scrollTop; };
 1357:     }
 1358:     else if (document.body.clientHeight) {
 1359:         Geometry.getViewportHeight =
 1360:             function() { return document.body.clientHeight; };
 1361:         Geometry.getViewportWidth =
 1362:             function() { return document.body.clientWidth; };
 1363:         Geometry.getHorizontalScroll =
 1364:             function() { return document.body.scrollLeft; };
 1365:         Geometry.getVerticalScroll =
 1366:             function() { return document.body.scrollTop; };
 1367:     }
 1368: }
 1369: 
 1370: GEOMETRY
 1371: }
 1372: 
 1373: =pod
 1374: 
 1375: =item * &viewport_size_js()
 1376: 
 1377: 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. 
 1378: 
 1379: =cut
 1380: 
 1381: sub viewport_size_js {
 1382:     my $geometry = &viewport_geometry_js();
 1383:     return <<"DIMS";
 1384: 
 1385: $geometry
 1386: 
 1387: function getViewportDims(width,height) {
 1388:     init_geometry();
 1389:     width.value = Geometry.getViewportWidth();
 1390:     height.value = Geometry.getViewportHeight();
 1391:     return;
 1392: }
 1393: 
 1394: DIMS
 1395: }
 1396: 
 1397: =pod
 1398: 
 1399: =item * &resize_textarea_js()
 1400: 
 1401: emits the needed javascript to resize a textarea to be as big as possible
 1402: 
 1403: creates a function resize_textrea that takes two IDs first should be
 1404: the id of the element to resize, second should be the id of a div that
 1405: surrounds everything that comes after the textarea, this routine needs
 1406: to be attached to the <body> for the onload and onresize events.
 1407: 
 1408: =back
 1409: 
 1410: =cut
 1411: 
 1412: sub resize_textarea_js {
 1413:     my $geometry = &viewport_geometry_js();
 1414:     return <<"RESIZE";
 1415:     <script type="text/javascript">
 1416: // <![CDATA[
 1417: $geometry
 1418: 
 1419: function getX(element) {
 1420:     var x = 0;
 1421:     while (element) {
 1422: 	x += element.offsetLeft;
 1423: 	element = element.offsetParent;
 1424:     }
 1425:     return x;
 1426: }
 1427: function getY(element) {
 1428:     var y = 0;
 1429:     while (element) {
 1430: 	y += element.offsetTop;
 1431: 	element = element.offsetParent;
 1432:     }
 1433:     return y;
 1434: }
 1435: 
 1436: 
 1437: function resize_textarea(textarea_id,bottom_id) {
 1438:     init_geometry();
 1439:     var textarea        = document.getElementById(textarea_id);
 1440:     //alert(textarea);
 1441: 
 1442:     var textarea_top    = getY(textarea);
 1443:     var textarea_height = textarea.offsetHeight;
 1444:     var bottom          = document.getElementById(bottom_id);
 1445:     var bottom_top      = getY(bottom);
 1446:     var bottom_height   = bottom.offsetHeight;
 1447:     var window_height   = Geometry.getViewportHeight();
 1448:     var fudge           = 23;
 1449:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1450:     if (new_height < 300) {
 1451: 	new_height = 300;
 1452:     }
 1453:     textarea.style.height=new_height+'px';
 1454: }
 1455: // ]]>
 1456: </script>
 1457: RESIZE
 1458: 
 1459: }
 1460: 
 1461: =pod
 1462: 
 1463: =head1 Excel and CSV file utility routines
 1464: 
 1465: =over 4
 1466: 
 1467: =cut
 1468: 
 1469: ###############################################################
 1470: ###############################################################
 1471: 
 1472: =pod
 1473: 
 1474: =item * &csv_translate($text) 
 1475: 
 1476: Translate $text to allow it to be output as a 'comma separated values' 
 1477: format.
 1478: 
 1479: =cut
 1480: 
 1481: ###############################################################
 1482: ###############################################################
 1483: sub csv_translate {
 1484:     my $text = shift;
 1485:     $text =~ s/\"/\"\"/g;
 1486:     $text =~ s/\n/ /g;
 1487:     return $text;
 1488: }
 1489: 
 1490: ###############################################################
 1491: ###############################################################
 1492: 
 1493: =pod
 1494: 
 1495: =item * &define_excel_formats()
 1496: 
 1497: Define some commonly used Excel cell formats.
 1498: 
 1499: Currently supported formats:
 1500: 
 1501: =over 4
 1502: 
 1503: =item header
 1504: 
 1505: =item bold
 1506: 
 1507: =item h1
 1508: 
 1509: =item h2
 1510: 
 1511: =item h3
 1512: 
 1513: =item h4
 1514: 
 1515: =item i
 1516: 
 1517: =item date
 1518: 
 1519: =back
 1520: 
 1521: Inputs: $workbook
 1522: 
 1523: Returns: $format, a hash reference.
 1524: 
 1525: =cut
 1526: 
 1527: ###############################################################
 1528: ###############################################################
 1529: sub define_excel_formats {
 1530:     my ($workbook) = @_;
 1531:     my $format;
 1532:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1533:                                                 bottom    => 1,
 1534:                                                 align     => 'center');
 1535:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1536:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1537:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1538:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1539:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1540:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1541:     $format->{'date'} = $workbook->add_format(num_format=>
 1542:                                             'mm/dd/yyyy hh:mm:ss');
 1543:     return $format;
 1544: }
 1545: 
 1546: ###############################################################
 1547: ###############################################################
 1548: 
 1549: =pod
 1550: 
 1551: =item * &create_workbook()
 1552: 
 1553: Create an Excel worksheet.  If it fails, output message on the
 1554: request object and return undefs.
 1555: 
 1556: Inputs: Apache request object
 1557: 
 1558: Returns (undef) on failure, 
 1559:     Excel worksheet object, scalar with filename, and formats 
 1560:     from &Apache::loncommon::define_excel_formats on success
 1561: 
 1562: =cut
 1563: 
 1564: ###############################################################
 1565: ###############################################################
 1566: sub create_workbook {
 1567:     my ($r) = @_;
 1568:         #
 1569:     # Create the excel spreadsheet
 1570:     my $filename = '/prtspool/'.
 1571:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1572:         time.'_'.rand(1000000000).'.xls';
 1573:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1574:     if (! defined($workbook)) {
 1575:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1576:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1577:                             "This error has been logged.  ".
 1578:                             "Please alert your LON-CAPA administrator").
 1579:                   '</p>');
 1580:         return (undef);
 1581:     }
 1582:     #
 1583:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1584:     #
 1585:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1586:     return ($workbook,$filename,$format);
 1587: }
 1588: 
 1589: ###############################################################
 1590: ###############################################################
 1591: 
 1592: =pod
 1593: 
 1594: =item * &create_text_file()
 1595: 
 1596: Create a file to write to and eventually make available to the user.
 1597: If file creation fails, outputs an error message on the request object and 
 1598: return undefs.
 1599: 
 1600: Inputs: Apache request object, and file suffix
 1601: 
 1602: Returns (undef) on failure, 
 1603:     Filehandle and filename on success.
 1604: 
 1605: =cut
 1606: 
 1607: ###############################################################
 1608: ###############################################################
 1609: sub create_text_file {
 1610:     my ($r,$suffix) = @_;
 1611:     if (! defined($suffix)) { $suffix = 'txt'; };
 1612:     my $fh;
 1613:     my $filename = '/prtspool/'.
 1614:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1615:         time.'_'.rand(1000000000).'.'.$suffix;
 1616:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1617:     if (! defined($fh)) {
 1618:         $r->log_error("Couldn't open $filename for output $!");
 1619:         $r->print(&mt('Problems occurred in creating the output file. '
 1620:                      .'This error has been logged. '
 1621:                      .'Please alert your LON-CAPA administrator.'));
 1622:     }
 1623:     return ($fh,$filename)
 1624: }
 1625: 
 1626: 
 1627: =pod 
 1628: 
 1629: =back
 1630: 
 1631: =cut
 1632: 
 1633: ###############################################################
 1634: ##        Home server <option> list generating code          ##
 1635: ###############################################################
 1636: 
 1637: # ------------------------------------------
 1638: 
 1639: sub domain_select {
 1640:     my ($name,$value,$multiple)=@_;
 1641:     my %domains=map { 
 1642: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1643:     } &Apache::lonnet::all_domains();
 1644:     if ($multiple) {
 1645: 	$domains{''}=&mt('Any domain');
 1646: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1647: 	return &multiple_select_form($name,$value,4,\%domains);
 1648:     } else {
 1649: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1650: 	return &select_form($name,$value,%domains);
 1651:     }
 1652: }
 1653: 
 1654: #-------------------------------------------
 1655: 
 1656: =pod
 1657: 
 1658: =head1 Routines for form select boxes
 1659: 
 1660: =over 4
 1661: 
 1662: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1663: 
 1664: Returns a string containing a <select> element int multiple mode
 1665: 
 1666: 
 1667: Args:
 1668:   $name - name of the <select> element
 1669:   $value - scalar or array ref of values that should already be selected
 1670:   $size - number of rows long the select element is
 1671:   $hash - the elements should be 'option' => 'shown text'
 1672:           (shown text should already have been &mt())
 1673:   $order - (optional) array ref of the order to show the elements in
 1674: 
 1675: =cut
 1676: 
 1677: #-------------------------------------------
 1678: sub multiple_select_form {
 1679:     my ($name,$value,$size,$hash,$order)=@_;
 1680:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1681:     my $output='';
 1682:     if (! defined($size)) {
 1683:         $size = 4;
 1684:         if (scalar(keys(%$hash))<4) {
 1685:             $size = scalar(keys(%$hash));
 1686:         }
 1687:     }
 1688:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1689:     my @order;
 1690:     if (ref($order) eq 'ARRAY')  {
 1691:         @order = @{$order};
 1692:     } else {
 1693:         @order = sort(keys(%$hash));
 1694:     }
 1695:     if (exists($$hash{'select_form_order'})) {
 1696:         @order = @{$$hash{'select_form_order'}};
 1697:     }
 1698:         
 1699:     foreach my $key (@order) {
 1700:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1701:         $output.='selected="selected" ' if ($selected{$key});
 1702:         $output.='>'.$hash->{$key}."</option>\n";
 1703:     }
 1704:     $output.="</select>\n";
 1705:     return $output;
 1706: }
 1707: 
 1708: #-------------------------------------------
 1709: 
 1710: =pod
 1711: 
 1712: =item * &select_form($defdom,$name,%hash)
 1713: 
 1714: Returns a string containing a <select name='$name' size='1'> form to 
 1715: allow a user to select options from a hash option_name => displayed text.  
 1716: See lonrights.pm for an example invocation and use.
 1717: 
 1718: =cut
 1719: 
 1720: #-------------------------------------------
 1721: sub select_form {
 1722:     my ($def,$name,%hash) = @_;
 1723:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1724:     my @keys;
 1725:     if (exists($hash{'select_form_order'})) {
 1726: 	@keys=@{$hash{'select_form_order'}};
 1727:     } else {
 1728: 	@keys=sort(keys(%hash));
 1729:     }
 1730:     foreach my $key (@keys) {
 1731:         $selectform.=
 1732: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1733:             ($key eq $def ? 'selected="selected" ' : '').
 1734:                 ">".&mt($hash{$key})."</option>\n";
 1735:     }
 1736:     $selectform.="</select>";
 1737:     return $selectform;
 1738: }
 1739: 
 1740: # For display filters
 1741: 
 1742: sub display_filter {
 1743:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1744:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1745:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1746: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1747: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1748: 	   '</label></span> <span class="LC_nobreak">'.
 1749:            &mt('Filter [_1]',
 1750: 	   &select_form($env{'form.displayfilter'},
 1751: 			'displayfilter',
 1752: 			('currentfolder' => 'Current folder/page',
 1753: 			 'containing' => 'Containing phrase',
 1754: 			 'none' => 'None'))).
 1755: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1756: }
 1757: 
 1758: sub gradeleveldescription {
 1759:     my $gradelevel=shift;
 1760:     my %gradelevels=(0 => 'Not specified',
 1761: 		     1 => 'Grade 1',
 1762: 		     2 => 'Grade 2',
 1763: 		     3 => 'Grade 3',
 1764: 		     4 => 'Grade 4',
 1765: 		     5 => 'Grade 5',
 1766: 		     6 => 'Grade 6',
 1767: 		     7 => 'Grade 7',
 1768: 		     8 => 'Grade 8',
 1769: 		     9 => 'Grade 9',
 1770: 		     10 => 'Grade 10',
 1771: 		     11 => 'Grade 11',
 1772: 		     12 => 'Grade 12',
 1773: 		     13 => 'Grade 13',
 1774: 		     14 => '100 Level',
 1775: 		     15 => '200 Level',
 1776: 		     16 => '300 Level',
 1777: 		     17 => '400 Level',
 1778: 		     18 => 'Graduate Level');
 1779:     return &mt($gradelevels{$gradelevel});
 1780: }
 1781: 
 1782: sub select_level_form {
 1783:     my ($deflevel,$name)=@_;
 1784:     unless ($deflevel) { $deflevel=0; }
 1785:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1786:     for (my $i=0; $i<=18; $i++) {
 1787:         $selectform.="<option value=\"$i\" ".
 1788:             ($i==$deflevel ? 'selected="selected" ' : '').
 1789:                 ">".&gradeleveldescription($i)."</option>\n";
 1790:     }
 1791:     $selectform.="</select>";
 1792:     return $selectform;
 1793: }
 1794: 
 1795: #-------------------------------------------
 1796: 
 1797: =pod
 1798: 
 1799: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1800: 
 1801: Returns a string containing a <select name='$name' size='1'> form to 
 1802: allow a user to select the domain to preform an operation in.  
 1803: See loncreateuser.pm for an example invocation and use.
 1804: 
 1805: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1806: selected");
 1807: 
 1808: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1809: 
 1810: The optional $onchange argumnet specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.  
 1811: 
 1812: =cut
 1813: 
 1814: #-------------------------------------------
 1815: sub select_dom_form {
 1816:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
 1817:     if ($onchange) {
 1818:         ' onchange="'.$onchange.'";
 1819:     }
 1820:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1821:     if ($includeempty) { @domains=('',@domains); }
 1822:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1823:     foreach my $dom (@domains) {
 1824:         $selectdomain.="<option value=\"$dom\" ".
 1825:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1826:         if ($showdomdesc) {
 1827:             if ($dom ne '') {
 1828:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1829:                 if ($domdesc ne '') {
 1830:                     $selectdomain .= ' ('.$domdesc.')';
 1831:                 }
 1832:             } 
 1833:         }
 1834:         $selectdomain .= "</option>\n";
 1835:     }
 1836:     $selectdomain.="</select>";
 1837:     return $selectdomain;
 1838: }
 1839: 
 1840: #-------------------------------------------
 1841: 
 1842: =pod
 1843: 
 1844: =item * &home_server_form_item($domain,$name,$defaultflag)
 1845: 
 1846: input: 4 arguments (two required, two optional) - 
 1847:     $domain - domain of new user
 1848:     $name - name of form element
 1849:     $default - Value of 'default' causes a default item to be first 
 1850:                             option, and selected by default. 
 1851:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1852:                             if 1 server found, or default, if 0 found.
 1853: output: returns 2 items: 
 1854: (a) form element which contains either:
 1855:    (i) <select name="$name">
 1856:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1857:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1858:        </select>
 1859:        form item if there are multiple library servers in $domain, or
 1860:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1861:        if there is only one library server in $domain.
 1862: 
 1863: (b) number of library servers found.
 1864: 
 1865: See loncreateuser.pm for example of use.
 1866: 
 1867: =cut
 1868: 
 1869: #-------------------------------------------
 1870: sub home_server_form_item {
 1871:     my ($domain,$name,$default,$hide) = @_;
 1872:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1873:     my $result;
 1874:     my $numlib = keys(%servers);
 1875:     if ($numlib > 1) {
 1876:         $result .= '<select name="'.$name.'" />'."\n";
 1877:         if ($default) {
 1878:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1879:                        '</option>'."\n";
 1880:         }
 1881:         foreach my $hostid (sort(keys(%servers))) {
 1882:             $result.= '<option value="'.$hostid.'">'.
 1883: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1884:         }
 1885:         $result .= '</select>'."\n";
 1886:     } elsif ($numlib == 1) {
 1887:         my $hostid;
 1888:         foreach my $item (keys(%servers)) {
 1889:             $hostid = $item;
 1890:         }
 1891:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1892:                    $hostid.'" />';
 1893:                    if (!$hide) {
 1894:                        $result .= $hostid.' '.$servers{$hostid};
 1895:                    }
 1896:                    $result .= "\n";
 1897:     } elsif ($default) {
 1898:         $result .= '<input type="hidden" name="'.$name.
 1899:                    '" value="default" />';
 1900:                    if (!$hide) {
 1901:                        $result .= &mt('default');
 1902:                    }
 1903:                    $result .= "\n";
 1904:     }
 1905:     return ($result,$numlib);
 1906: }
 1907: 
 1908: =pod
 1909: 
 1910: =back 
 1911: 
 1912: =cut
 1913: 
 1914: ###############################################################
 1915: ##                  Decoding User Agent                      ##
 1916: ###############################################################
 1917: 
 1918: =pod
 1919: 
 1920: =head1 Decoding the User Agent
 1921: 
 1922: =over 4
 1923: 
 1924: =item * &decode_user_agent()
 1925: 
 1926: Inputs: $r
 1927: 
 1928: Outputs:
 1929: 
 1930: =over 4
 1931: 
 1932: =item * $httpbrowser
 1933: 
 1934: =item * $clientbrowser
 1935: 
 1936: =item * $clientversion
 1937: 
 1938: =item * $clientmathml
 1939: 
 1940: =item * $clientunicode
 1941: 
 1942: =item * $clientos
 1943: 
 1944: =back
 1945: 
 1946: =back 
 1947: 
 1948: =cut
 1949: 
 1950: ###############################################################
 1951: ###############################################################
 1952: sub decode_user_agent {
 1953:     my ($r)=@_;
 1954:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1955:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1956:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1957:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1958:     my $clientbrowser='unknown';
 1959:     my $clientversion='0';
 1960:     my $clientmathml='';
 1961:     my $clientunicode='0';
 1962:     for (my $i=0;$i<=$#browsertype;$i++) {
 1963:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1964: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1965: 	    $clientbrowser=$bname;
 1966:             $httpbrowser=~/$vreg/i;
 1967: 	    $clientversion=$1;
 1968:             $clientmathml=($clientversion>=$minv);
 1969:             $clientunicode=($clientversion>=$univ);
 1970: 	}
 1971:     }
 1972:     my $clientos='unknown';
 1973:     if (($httpbrowser=~/linux/i) ||
 1974:         ($httpbrowser=~/unix/i) ||
 1975:         ($httpbrowser=~/ux/i) ||
 1976:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1977:     if (($httpbrowser=~/vax/i) ||
 1978:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1979:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1980:     if (($httpbrowser=~/mac/i) ||
 1981:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1982:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1983:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1984:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1985:             $clientunicode,$clientos,);
 1986: }
 1987: 
 1988: ###############################################################
 1989: ##    Authentication changing form generation subroutines    ##
 1990: ###############################################################
 1991: ##
 1992: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1993: ## hash, and have reasonable default values.
 1994: ##
 1995: ##    formname = the name given in the <form> tag.
 1996: #-------------------------------------------
 1997: 
 1998: =pod
 1999: 
 2000: =head1 Authentication Routines
 2001: 
 2002: =over 4
 2003: 
 2004: =item * &authform_xxxxxx()
 2005: 
 2006: The authform_xxxxxx subroutines provide javascript and html forms which 
 2007: handle some of the conveniences required for authentication forms.  
 2008: This is not an optimal method, but it works.  
 2009: 
 2010: =over 4
 2011: 
 2012: =item * authform_header
 2013: 
 2014: =item * authform_authorwarning
 2015: 
 2016: =item * authform_nochange
 2017: 
 2018: =item * authform_kerberos
 2019: 
 2020: =item * authform_internal
 2021: 
 2022: =item * authform_filesystem
 2023: 
 2024: =back
 2025: 
 2026: See loncreateuser.pm for invocation and use examples.
 2027: 
 2028: =cut
 2029: 
 2030: #-------------------------------------------
 2031: sub authform_header{  
 2032:     my %in = (
 2033:         formname => 'cu',
 2034:         kerb_def_dom => '',
 2035:         @_,
 2036:     );
 2037:     $in{'formname'} = 'document.' . $in{'formname'};
 2038:     my $result='';
 2039: 
 2040: #---------------------------------------------- Code for upper case translation
 2041:     my $Javascript_toUpperCase;
 2042:     unless ($in{kerb_def_dom}) {
 2043:         $Javascript_toUpperCase =<<"END";
 2044:         switch (choice) {
 2045:            case 'krb': currentform.elements[choicearg].value =
 2046:                currentform.elements[choicearg].value.toUpperCase();
 2047:                break;
 2048:            default:
 2049:         }
 2050: END
 2051:     } else {
 2052:         $Javascript_toUpperCase = "";
 2053:     }
 2054: 
 2055:     my $radioval = "'nochange'";
 2056:     if (defined($in{'curr_authtype'})) {
 2057:         if ($in{'curr_authtype'} ne '') {
 2058:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2059:         }
 2060:     }
 2061:     my $argfield = 'null';
 2062:     if (defined($in{'mode'})) {
 2063:         if ($in{'mode'} eq 'modifycourse')  {
 2064:             if (defined($in{'curr_autharg'})) {
 2065:                 if ($in{'curr_autharg'} ne '') {
 2066:                     $argfield = "'$in{'curr_autharg'}'";
 2067:                 }
 2068:             }
 2069:         }
 2070:     }
 2071: 
 2072:     $result.=<<"END";
 2073: var current = new Object();
 2074: current.radiovalue = $radioval;
 2075: current.argfield = $argfield;
 2076: 
 2077: function changed_radio(choice,currentform) {
 2078:     var choicearg = choice + 'arg';
 2079:     // If a radio button in changed, we need to change the argfield
 2080:     if (current.radiovalue != choice) {
 2081:         current.radiovalue = choice;
 2082:         if (current.argfield != null) {
 2083:             currentform.elements[current.argfield].value = '';
 2084:         }
 2085:         if (choice == 'nochange') {
 2086:             current.argfield = null;
 2087:         } else {
 2088:             current.argfield = choicearg;
 2089:             switch(choice) {
 2090:                 case 'krb': 
 2091:                     currentform.elements[current.argfield].value = 
 2092:                         "$in{'kerb_def_dom'}";
 2093:                 break;
 2094:               default:
 2095:                 break;
 2096:             }
 2097:         }
 2098:     }
 2099:     return;
 2100: }
 2101: 
 2102: function changed_text(choice,currentform) {
 2103:     var choicearg = choice + 'arg';
 2104:     if (currentform.elements[choicearg].value !='') {
 2105:         $Javascript_toUpperCase
 2106:         // clear old field
 2107:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2108:             currentform.elements[current.argfield].value = '';
 2109:         }
 2110:         current.argfield = choicearg;
 2111:     }
 2112:     set_auth_radio_buttons(choice,currentform);
 2113:     return;
 2114: }
 2115: 
 2116: function set_auth_radio_buttons(newvalue,currentform) {
 2117:     var i=0;
 2118:     while (i < currentform.login.length) {
 2119:         if (currentform.login[i].value == newvalue) { break; }
 2120:         i++;
 2121:     }
 2122:     if (i == currentform.login.length) {
 2123:         return;
 2124:     }
 2125:     current.radiovalue = newvalue;
 2126:     currentform.login[i].checked = true;
 2127:     return;
 2128: }
 2129: END
 2130:     return $result;
 2131: }
 2132: 
 2133: sub authform_authorwarning{
 2134:     my $result='';
 2135:     $result='<i>'.
 2136:         &mt('As a general rule, only authors or co-authors should be '.
 2137:             'filesystem authenticated '.
 2138:             '(which allows access to the server filesystem).')."</i>\n";
 2139:     return $result;
 2140: }
 2141: 
 2142: sub authform_nochange{  
 2143:     my %in = (
 2144:               formname => 'document.cu',
 2145:               kerb_def_dom => 'MSU.EDU',
 2146:               @_,
 2147:           );
 2148:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2149:     my $result;
 2150:     if (keys(%can_assign) == 0) {
 2151:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2152:     } else {
 2153:         $result = '<label>'.&mt('[_1] Do not change login data',
 2154:                   '<input type="radio" name="login" value="nochange" '.
 2155:                   'checked="checked" onclick="'.
 2156:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2157: 	    '</label>';
 2158:     }
 2159:     return $result;
 2160: }
 2161: 
 2162: sub authform_kerberos {
 2163:     my %in = (
 2164:               formname => 'document.cu',
 2165:               kerb_def_dom => 'MSU.EDU',
 2166:               kerb_def_auth => 'krb4',
 2167:               @_,
 2168:               );
 2169:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2170:         $autharg,$jscall);
 2171:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2172:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2173:        $check5 = ' checked="checked"';
 2174:     } else {
 2175:        $check4 = ' checked="checked"';
 2176:     }
 2177:     $krbarg = $in{'kerb_def_dom'};
 2178:     if (defined($in{'curr_authtype'})) {
 2179:         if ($in{'curr_authtype'} eq 'krb') {
 2180:             $krbcheck = ' checked="checked"';
 2181:             if (defined($in{'mode'})) {
 2182:                 if ($in{'mode'} eq 'modifyuser') {
 2183:                     $krbcheck = '';
 2184:                 }
 2185:             }
 2186:             if (defined($in{'curr_kerb_ver'})) {
 2187:                 if ($in{'curr_krb_ver'} eq '5') {
 2188:                     $check5 = ' checked="checked"';
 2189:                     $check4 = '';
 2190:                 } else {
 2191:                     $check4 = ' checked="checked"';
 2192:                     $check5 = '';
 2193:                 }
 2194:             }
 2195:             if (defined($in{'curr_autharg'})) {
 2196:                 $krbarg = $in{'curr_autharg'};
 2197:             }
 2198:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2199:                 if (defined($in{'curr_autharg'})) {
 2200:                     $result = 
 2201:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2202:         $in{'curr_autharg'},$krbver);
 2203:                 } else {
 2204:                     $result =
 2205:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2206:                 }
 2207:                 return $result; 
 2208:             }
 2209:         }
 2210:     } else {
 2211:         if ($authnum == 1) {
 2212:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2213:         }
 2214:     }
 2215:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2216:         return;
 2217:     } elsif ($authtype eq '') {
 2218:         if (defined($in{'mode'})) {
 2219:             if ($in{'mode'} eq 'modifycourse') {
 2220:                 if ($authnum == 1) {
 2221:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2222:                 }
 2223:             }
 2224:         }
 2225:     }
 2226:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2227:     if ($authtype eq '') {
 2228:         $authtype = '<input type="radio" name="login" value="krb" '.
 2229:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2230:                     $krbcheck.' />';
 2231:     }
 2232:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2233:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2234:          $in{'curr_authtype'} eq 'krb5') ||
 2235:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2236:          $in{'curr_authtype'} eq 'krb4')) {
 2237:         $result .= &mt
 2238:         ('[_1] Kerberos authenticated with domain [_2] '.
 2239:          '[_3] Version 4 [_4] Version 5 [_5]',
 2240:          '<label>'.$authtype,
 2241:          '</label><input type="text" size="10" name="krbarg" '.
 2242:              'value="'.$krbarg.'" '.
 2243:              'onchange="'.$jscall.'" />',
 2244:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2245:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2246: 	 '</label>');
 2247:     } elsif ($can_assign{'krb4'}) {
 2248:         $result .= &mt
 2249:         ('[_1] Kerberos authenticated with domain [_2] '.
 2250:          '[_3] Version 4 [_4]',
 2251:          '<label>'.$authtype,
 2252:          '</label><input type="text" size="10" name="krbarg" '.
 2253:              'value="'.$krbarg.'" '.
 2254:              'onchange="'.$jscall.'" />',
 2255:          '<label><input type="hidden" name="krbver" value="4" />',
 2256:          '</label>');
 2257:     } elsif ($can_assign{'krb5'}) {
 2258:         $result .= &mt
 2259:         ('[_1] Kerberos authenticated with domain [_2] '.
 2260:          '[_3] Version 5 [_4]',
 2261:          '<label>'.$authtype,
 2262:          '</label><input type="text" size="10" name="krbarg" '.
 2263:              'value="'.$krbarg.'" '.
 2264:              'onchange="'.$jscall.'" />',
 2265:          '<label><input type="hidden" name="krbver" value="5" />',
 2266:          '</label>');
 2267:     }
 2268:     return $result;
 2269: }
 2270: 
 2271: sub authform_internal{  
 2272:     my %in = (
 2273:                 formname => 'document.cu',
 2274:                 kerb_def_dom => 'MSU.EDU',
 2275:                 @_,
 2276:                 );
 2277:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2278:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2279:     if (defined($in{'curr_authtype'})) {
 2280:         if ($in{'curr_authtype'} eq 'int') {
 2281:             if ($can_assign{'int'}) {
 2282:                 $intcheck = 'checked="checked" ';
 2283:                 if (defined($in{'mode'})) {
 2284:                     if ($in{'mode'} eq 'modifyuser') {
 2285:                         $intcheck = '';
 2286:                     }
 2287:                 }
 2288:                 if (defined($in{'curr_autharg'})) {
 2289:                     $intarg = $in{'curr_autharg'};
 2290:                 }
 2291:             } else {
 2292:                 $result = &mt('Currently internally authenticated.');
 2293:                 return $result;
 2294:             }
 2295:         }
 2296:     } else {
 2297:         if ($authnum == 1) {
 2298:             $authtype = '<input type="hidden" name="login" value="int" />';
 2299:         }
 2300:     }
 2301:     if (!$can_assign{'int'}) {
 2302:         return;
 2303:     } elsif ($authtype eq '') {
 2304:         if (defined($in{'mode'})) {
 2305:             if ($in{'mode'} eq 'modifycourse') {
 2306:                 if ($authnum == 1) {
 2307:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2308:                 }
 2309:             }
 2310:         }
 2311:     }
 2312:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2313:     if ($authtype eq '') {
 2314:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2315:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2316:     }
 2317:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2318:                $intarg.'" onchange="'.$jscall.'" />';
 2319:     $result = &mt
 2320:         ('[_1] Internally authenticated (with initial password [_2])',
 2321:          '<label>'.$authtype,'</label>'.$autharg);
 2322:     $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>';
 2323:     return $result;
 2324: }
 2325: 
 2326: sub authform_local{  
 2327:     my %in = (
 2328:               formname => 'document.cu',
 2329:               kerb_def_dom => 'MSU.EDU',
 2330:               @_,
 2331:               );
 2332:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2333:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2334:     if (defined($in{'curr_authtype'})) {
 2335:         if ($in{'curr_authtype'} eq 'loc') {
 2336:             if ($can_assign{'loc'}) {
 2337:                 $loccheck = 'checked="checked" ';
 2338:                 if (defined($in{'mode'})) {
 2339:                     if ($in{'mode'} eq 'modifyuser') {
 2340:                         $loccheck = '';
 2341:                     }
 2342:                 }
 2343:                 if (defined($in{'curr_autharg'})) {
 2344:                     $locarg = $in{'curr_autharg'};
 2345:                 }
 2346:             } else {
 2347:                 $result = &mt('Currently using local (institutional) authentication.');
 2348:                 return $result;
 2349:             }
 2350:         }
 2351:     } else {
 2352:         if ($authnum == 1) {
 2353:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2354:         }
 2355:     }
 2356:     if (!$can_assign{'loc'}) {
 2357:         return;
 2358:     } elsif ($authtype eq '') {
 2359:         if (defined($in{'mode'})) {
 2360:             if ($in{'mode'} eq 'modifycourse') {
 2361:                 if ($authnum == 1) {
 2362:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2363:                 }
 2364:             }
 2365:         }
 2366:     }
 2367:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2368:     if ($authtype eq '') {
 2369:         $authtype = '<input type="radio" name="login" value="loc" '.
 2370:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2371:                     $jscall.'" />';
 2372:     }
 2373:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2374:                $locarg.'" onchange="'.$jscall.'" />';
 2375:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2376:                   '<label>'.$authtype,'</label>'.$autharg);
 2377:     return $result;
 2378: }
 2379: 
 2380: sub authform_filesystem{  
 2381:     my %in = (
 2382:               formname => 'document.cu',
 2383:               kerb_def_dom => 'MSU.EDU',
 2384:               @_,
 2385:               );
 2386:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2387:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2388:     if (defined($in{'curr_authtype'})) {
 2389:         if ($in{'curr_authtype'} eq 'fsys') {
 2390:             if ($can_assign{'fsys'}) {
 2391:                 $fsyscheck = 'checked="checked" ';
 2392:                 if (defined($in{'mode'})) {
 2393:                     if ($in{'mode'} eq 'modifyuser') {
 2394:                         $fsyscheck = '';
 2395:                     }
 2396:                 }
 2397:             } else {
 2398:                 $result = &mt('Currently Filesystem Authenticated.');
 2399:                 return $result;
 2400:             }           
 2401:         }
 2402:     } else {
 2403:         if ($authnum == 1) {
 2404:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2405:         }
 2406:     }
 2407:     if (!$can_assign{'fsys'}) {
 2408:         return;
 2409:     } elsif ($authtype eq '') {
 2410:         if (defined($in{'mode'})) {
 2411:             if ($in{'mode'} eq 'modifycourse') {
 2412:                 if ($authnum == 1) {
 2413:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2414:                 }
 2415:             }
 2416:         }
 2417:     }
 2418:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2419:     if ($authtype eq '') {
 2420:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2421:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2422:                     $jscall.'" />';
 2423:     }
 2424:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2425:                ' onchange="'.$jscall.'" />';
 2426:     $result = &mt
 2427:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2428:          '<label><input type="radio" name="login" value="fsys" '.
 2429:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2430:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2431:                   'onchange="'.$jscall.'" />');
 2432:     return $result;
 2433: }
 2434: 
 2435: sub get_assignable_auth {
 2436:     my ($dom) = @_;
 2437:     if ($dom eq '') {
 2438:         $dom = $env{'request.role.domain'};
 2439:     }
 2440:     my %can_assign = (
 2441:                           krb4 => 1,
 2442:                           krb5 => 1,
 2443:                           int  => 1,
 2444:                           loc  => 1,
 2445:                      );
 2446:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2447:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2448:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2449:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2450:             my $context;
 2451:             if ($env{'request.role'} =~ /^au/) {
 2452:                 $context = 'author';
 2453:             } elsif ($env{'request.role'} =~ /^dc/) {
 2454:                 $context = 'domain';
 2455:             } elsif ($env{'request.course.id'}) {
 2456:                 $context = 'course';
 2457:             }
 2458:             if ($context) {
 2459:                 if (ref($authhash->{$context}) eq 'HASH') {
 2460:                    %can_assign = %{$authhash->{$context}}; 
 2461:                 }
 2462:             }
 2463:         }
 2464:     }
 2465:     my $authnum = 0;
 2466:     foreach my $key (keys(%can_assign)) {
 2467:         if ($can_assign{$key}) {
 2468:             $authnum ++;
 2469:         }
 2470:     }
 2471:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2472:         $authnum --;
 2473:     }
 2474:     return ($authnum,%can_assign);
 2475: }
 2476: 
 2477: ###############################################################
 2478: ##    Get Kerberos Defaults for Domain                 ##
 2479: ###############################################################
 2480: ##
 2481: ## Returns default kerberos version and an associated argument
 2482: ## as listed in file domain.tab. If not listed, provides
 2483: ## appropriate default domain and kerberos version.
 2484: ##
 2485: #-------------------------------------------
 2486: 
 2487: =pod
 2488: 
 2489: =item * &get_kerberos_defaults()
 2490: 
 2491: get_kerberos_defaults($target_domain) returns the default kerberos
 2492: version and domain. If not found, it defaults to version 4 and the 
 2493: domain of the server.
 2494: 
 2495: =over 4
 2496: 
 2497: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2498: 
 2499: =back
 2500: 
 2501: =back
 2502: 
 2503: =cut
 2504: 
 2505: #-------------------------------------------
 2506: sub get_kerberos_defaults {
 2507:     my $domain=shift;
 2508:     my ($krbdef,$krbdefdom);
 2509:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2510:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2511:         $krbdef = $domdefaults{'auth_def'};
 2512:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2513:     } else {
 2514:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2515:         my $krbdefdom=$1;
 2516:         $krbdefdom=~tr/a-z/A-Z/;
 2517:         $krbdef = "krb4";
 2518:     }
 2519:     return ($krbdef,$krbdefdom);
 2520: }
 2521: 
 2522: 
 2523: ###############################################################
 2524: ##                Thesaurus Functions                        ##
 2525: ###############################################################
 2526: 
 2527: =pod
 2528: 
 2529: =head1 Thesaurus Functions
 2530: 
 2531: =over 4
 2532: 
 2533: =item * &initialize_keywords()
 2534: 
 2535: Initializes the package variable %Keywords if it is empty.  Uses the
 2536: package variable $thesaurus_db_file.
 2537: 
 2538: =cut
 2539: 
 2540: ###################################################
 2541: 
 2542: sub initialize_keywords {
 2543:     return 1 if (scalar keys(%Keywords));
 2544:     # If we are here, %Keywords is empty, so fill it up
 2545:     #   Make sure the file we need exists...
 2546:     if (! -e $thesaurus_db_file) {
 2547:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2548:                                  " failed because it does not exist");
 2549:         return 0;
 2550:     }
 2551:     #   Set up the hash as a database
 2552:     my %thesaurus_db;
 2553:     if (! tie(%thesaurus_db,'GDBM_File',
 2554:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2555:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2556:                                  $thesaurus_db_file);
 2557:         return 0;
 2558:     } 
 2559:     #  Get the average number of appearances of a word.
 2560:     my $avecount = $thesaurus_db{'average.count'};
 2561:     #  Put keywords (those that appear > average) into %Keywords
 2562:     while (my ($word,$data)=each (%thesaurus_db)) {
 2563:         my ($count,undef) = split /:/,$data;
 2564:         $Keywords{$word}++ if ($count > $avecount);
 2565:     }
 2566:     untie %thesaurus_db;
 2567:     # Remove special values from %Keywords.
 2568:     foreach my $value ('total.count','average.count') {
 2569:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2570:   }
 2571:     return 1;
 2572: }
 2573: 
 2574: ###################################################
 2575: 
 2576: =pod
 2577: 
 2578: =item * &keyword($word)
 2579: 
 2580: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2581: than the average number of times in the thesaurus database.  Calls 
 2582: &initialize_keywords
 2583: 
 2584: =cut
 2585: 
 2586: ###################################################
 2587: 
 2588: sub keyword {
 2589:     return if (!&initialize_keywords());
 2590:     my $word=lc(shift());
 2591:     $word=~s/\W//g;
 2592:     return exists($Keywords{$word});
 2593: }
 2594: 
 2595: ###############################################################
 2596: 
 2597: =pod 
 2598: 
 2599: =item * &get_related_words()
 2600: 
 2601: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2602: an array of words.  If the keyword is not in the thesaurus, an empty array
 2603: will be returned.  The order of the words returned is determined by the
 2604: database which holds them.
 2605: 
 2606: Uses global $thesaurus_db_file.
 2607: 
 2608: =cut
 2609: 
 2610: ###############################################################
 2611: sub get_related_words {
 2612:     my $keyword = shift;
 2613:     my %thesaurus_db;
 2614:     if (! -e $thesaurus_db_file) {
 2615:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2616:                                  "failed because the file does not exist");
 2617:         return ();
 2618:     }
 2619:     if (! tie(%thesaurus_db,'GDBM_File',
 2620:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2621:         return ();
 2622:     } 
 2623:     my @Words=();
 2624:     my $count=0;
 2625:     if (exists($thesaurus_db{$keyword})) {
 2626: 	# The first element is the number of times
 2627: 	# the word appears.  We do not need it now.
 2628: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2629: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2630: 	my $threshold=$mostfrequentcount/10;
 2631:         foreach my $possibleword (@RelatedWords) {
 2632:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2633:             if ($wordcount>$threshold) {
 2634: 		push(@Words,$word);
 2635:                 $count++;
 2636:                 if ($count>10) { last; }
 2637: 	    }
 2638:         }
 2639:     }
 2640:     untie %thesaurus_db;
 2641:     return @Words;
 2642: }
 2643: 
 2644: =pod
 2645: 
 2646: =back
 2647: 
 2648: =cut
 2649: 
 2650: # -------------------------------------------------------------- Plaintext name
 2651: =pod
 2652: 
 2653: =head1 User Name Functions
 2654: 
 2655: =over 4
 2656: 
 2657: =item * &plainname($uname,$udom,$first)
 2658: 
 2659: Takes a users logon name and returns it as a string in
 2660: "first middle last generation" form 
 2661: if $first is set to 'lastname' then it returns it as
 2662: 'lastname generation, firstname middlename' if their is a lastname
 2663: 
 2664: =cut
 2665: 
 2666: 
 2667: ###############################################################
 2668: sub plainname {
 2669:     my ($uname,$udom,$first)=@_;
 2670:     return if (!defined($uname) || !defined($udom));
 2671:     my %names=&getnames($uname,$udom);
 2672:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2673: 					  $names{'middlename'},
 2674: 					  $names{'lastname'},
 2675: 					  $names{'generation'},$first);
 2676:     $name=~s/^\s+//;
 2677:     $name=~s/\s+$//;
 2678:     $name=~s/\s+/ /g;
 2679:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2680:     return $name;
 2681: }
 2682: 
 2683: # -------------------------------------------------------------------- Nickname
 2684: =pod
 2685: 
 2686: =item * &nickname($uname,$udom)
 2687: 
 2688: Gets a users name and returns it as a string as
 2689: 
 2690: "&quot;nickname&quot;"
 2691: 
 2692: if the user has a nickname or
 2693: 
 2694: "first middle last generation"
 2695: 
 2696: if the user does not
 2697: 
 2698: =cut
 2699: 
 2700: sub nickname {
 2701:     my ($uname,$udom)=@_;
 2702:     return if (!defined($uname) || !defined($udom));
 2703:     my %names=&getnames($uname,$udom);
 2704:     my $name=$names{'nickname'};
 2705:     if ($name) {
 2706:        $name='&quot;'.$name.'&quot;'; 
 2707:     } else {
 2708:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2709: 	     $names{'lastname'}.' '.$names{'generation'};
 2710:        $name=~s/\s+$//;
 2711:        $name=~s/\s+/ /g;
 2712:     }
 2713:     return $name;
 2714: }
 2715: 
 2716: sub getnames {
 2717:     my ($uname,$udom)=@_;
 2718:     return if (!defined($uname) || !defined($udom));
 2719:     if ($udom eq 'public' && $uname eq 'public') {
 2720: 	return ('lastname' => &mt('Public'));
 2721:     }
 2722:     my $id=$uname.':'.$udom;
 2723:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2724:     if ($cached) {
 2725: 	return %{$names};
 2726:     } else {
 2727: 	my %loadnames=&Apache::lonnet::get('environment',
 2728:                     ['firstname','middlename','lastname','generation','nickname'],
 2729: 					 $udom,$uname);
 2730: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2731: 	return %loadnames;
 2732:     }
 2733: }
 2734: 
 2735: # -------------------------------------------------------------------- getemails
 2736: 
 2737: =pod
 2738: 
 2739: =item * &getemails($uname,$udom)
 2740: 
 2741: Gets a user's email information and returns it as a hash with keys:
 2742: notification, critnotification, permanentemail
 2743: 
 2744: For notification and critnotification, values are comma-separated lists 
 2745: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2746:  
 2747: 
 2748: =cut
 2749: 
 2750: 
 2751: sub getemails {
 2752:     my ($uname,$udom)=@_;
 2753:     if ($udom eq 'public' && $uname eq 'public') {
 2754: 	return;
 2755:     }
 2756:     if (!$udom) { $udom=$env{'user.domain'}; }
 2757:     if (!$uname) { $uname=$env{'user.name'}; }
 2758:     my $id=$uname.':'.$udom;
 2759:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2760:     if ($cached) {
 2761: 	return %{$names};
 2762:     } else {
 2763: 	my %loadnames=&Apache::lonnet::get('environment',
 2764:                     			   ['notification','critnotification',
 2765: 					    'permanentemail'],
 2766: 					   $udom,$uname);
 2767: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2768: 	return %loadnames;
 2769:     }
 2770: }
 2771: 
 2772: sub flush_email_cache {
 2773:     my ($uname,$udom)=@_;
 2774:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2775:     if (!$uname) { $uname=$env{'user.name'};   }
 2776:     return if ($udom eq 'public' && $uname eq 'public');
 2777:     my $id=$uname.':'.$udom;
 2778:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2779: }
 2780: 
 2781: # -------------------------------------------------------------------- getlangs
 2782: 
 2783: =pod
 2784: 
 2785: =item * &getlangs($uname,$udom)
 2786: 
 2787: Gets a user's language preference and returns it as a hash with key:
 2788: language.
 2789: 
 2790: =cut
 2791: 
 2792: 
 2793: sub getlangs {
 2794:     my ($uname,$udom) = @_;
 2795:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2796:     if (!$uname) { $uname=$env{'user.name'};   }
 2797:     my $id=$uname.':'.$udom;
 2798:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2799:     if ($cached) {
 2800:         return %{$langs};
 2801:     } else {
 2802:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2803:                                            $udom,$uname);
 2804:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2805:         return %loadlangs;
 2806:     }
 2807: }
 2808: 
 2809: sub flush_langs_cache {
 2810:     my ($uname,$udom)=@_;
 2811:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2812:     if (!$uname) { $uname=$env{'user.name'};   }
 2813:     return if ($udom eq 'public' && $uname eq 'public');
 2814:     my $id=$uname.':'.$udom;
 2815:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2816: }
 2817: 
 2818: # ------------------------------------------------------------------ Screenname
 2819: 
 2820: =pod
 2821: 
 2822: =item * &screenname($uname,$udom)
 2823: 
 2824: Gets a users screenname and returns it as a string
 2825: 
 2826: =cut
 2827: 
 2828: sub screenname {
 2829:     my ($uname,$udom)=@_;
 2830:     if ($uname eq $env{'user.name'} &&
 2831: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2832:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2833:     return $names{'screenname'};
 2834: }
 2835: 
 2836: 
 2837: # ------------------------------------------------------------- Confirm Wrapper
 2838: =pod
 2839: 
 2840: =item confirmwrapper
 2841: 
 2842: Wrap messages about completion of operation in box
 2843: 
 2844: =cut
 2845: 
 2846: sub confirmwrapper {
 2847:     my ($message)=@_;
 2848:     if ($message) {
 2849:         return "\n".'<div class="LC_confirm_box">'."\n"
 2850:                .$message."\n"
 2851:                .'</div>'."\n";
 2852:     } else {
 2853:         return $message;
 2854:     }
 2855: }
 2856: 
 2857: # ------------------------------------------------------------- Message Wrapper
 2858: 
 2859: sub messagewrapper {
 2860:     my ($link,$username,$domain,$subject,$text)=@_;
 2861:     return 
 2862:         '<a href="/adm/email?compose=individual&amp;'.
 2863:         'recname='.$username.'&amp;recdom='.$domain.
 2864: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2865:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2866: }
 2867: 
 2868: # --------------------------------------------------------------- Notes Wrapper
 2869: 
 2870: sub noteswrapper {
 2871:     my ($link,$un,$do)=@_;
 2872:     return 
 2873: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2874: }
 2875: 
 2876: # ------------------------------------------------------------- Aboutme Wrapper
 2877: 
 2878: sub aboutmewrapper {
 2879:     my ($link,$username,$domain,$target)=@_;
 2880:     if (!defined($username)  && !defined($domain)) {
 2881:         return;
 2882:     }
 2883:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2884: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2885: }
 2886: 
 2887: # ------------------------------------------------------------ Syllabus Wrapper
 2888: 
 2889: sub syllabuswrapper {
 2890:     my ($linktext,$coursedir,$domain)=@_;
 2891:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2892: }
 2893: 
 2894: # -----------------------------------------------------------------------------
 2895: 
 2896: sub track_student_link {
 2897:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2898:     my $link ="/adm/trackstudent?";
 2899:     my $title = 'View recent activity';
 2900:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2901:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2902:         $link .= "selected_student=$sname:$sdom";
 2903:         $title .= ' of this student';
 2904:     } 
 2905:     if (defined($target) && $target !~ /^\s*$/) {
 2906:         $target = qq{target="$target"};
 2907:     } else {
 2908:         $target = '';
 2909:     }
 2910:     if ($start) { $link.='&amp;start='.$start; }
 2911:     $title = &mt($title);
 2912:     $linktext = &mt($linktext);
 2913:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2914: 	&help_open_topic('View_recent_activity');
 2915: }
 2916: 
 2917: sub slot_reservations_link {
 2918:     my ($linktext,$sname,$sdom,$target) = @_;
 2919:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2920:     my $title = 'View slot reservation history';
 2921:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2922:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2923:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2924:         $title .= ' of this student';
 2925:     }
 2926:     if (defined($target) && $target !~ /^\s*$/) {
 2927:         $target = qq{target="$target"};
 2928:     } else {
 2929:         $target = '';
 2930:     }
 2931:     $title = &mt($title);
 2932:     $linktext = &mt($linktext);
 2933:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2934: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2935: 
 2936: }
 2937: 
 2938: # ===================================================== Display a student photo
 2939: 
 2940: 
 2941: sub student_image_tag {
 2942:     my ($domain,$user)=@_;
 2943:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2944:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2945: 	return '<img src="'.$imgsrc.'" align="right" />';
 2946:     } else {
 2947: 	return '';
 2948:     }
 2949: }
 2950: 
 2951: =pod
 2952: 
 2953: =back
 2954: 
 2955: =head1 Access .tab File Data
 2956: 
 2957: =over 4
 2958: 
 2959: =item * &languageids() 
 2960: 
 2961: returns list of all language ids
 2962: 
 2963: =cut
 2964: 
 2965: sub languageids {
 2966:     return sort(keys(%language));
 2967: }
 2968: 
 2969: =pod
 2970: 
 2971: =item * &languagedescription() 
 2972: 
 2973: returns description of a specified language id
 2974: 
 2975: =cut
 2976: 
 2977: sub languagedescription {
 2978:     my $code=shift;
 2979:     return  ($supported_language{$code}?'* ':'').
 2980:             $language{$code}.
 2981: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2982: }
 2983: 
 2984: sub plainlanguagedescription {
 2985:     my $code=shift;
 2986:     return $language{$code};
 2987: }
 2988: 
 2989: sub supportedlanguagecode {
 2990:     my $code=shift;
 2991:     return $supported_language{$code};
 2992: }
 2993: 
 2994: =pod
 2995: 
 2996: =item * &copyrightids() 
 2997: 
 2998: returns list of all copyrights
 2999: 
 3000: =cut
 3001: 
 3002: sub copyrightids {
 3003:     return sort(keys(%cprtag));
 3004: }
 3005: 
 3006: =pod
 3007: 
 3008: =item * &copyrightdescription() 
 3009: 
 3010: returns description of a specified copyright id
 3011: 
 3012: =cut
 3013: 
 3014: sub copyrightdescription {
 3015:     return &mt($cprtag{shift(@_)});
 3016: }
 3017: 
 3018: =pod
 3019: 
 3020: =item * &source_copyrightids() 
 3021: 
 3022: returns list of all source copyrights
 3023: 
 3024: =cut
 3025: 
 3026: sub source_copyrightids {
 3027:     return sort(keys(%scprtag));
 3028: }
 3029: 
 3030: =pod
 3031: 
 3032: =item * &source_copyrightdescription() 
 3033: 
 3034: returns description of a specified source copyright id
 3035: 
 3036: =cut
 3037: 
 3038: sub source_copyrightdescription {
 3039:     return &mt($scprtag{shift(@_)});
 3040: }
 3041: 
 3042: =pod
 3043: 
 3044: =item * &filecategories() 
 3045: 
 3046: returns list of all file categories
 3047: 
 3048: =cut
 3049: 
 3050: sub filecategories {
 3051:     return sort(keys(%category_extensions));
 3052: }
 3053: 
 3054: =pod
 3055: 
 3056: =item * &filecategorytypes() 
 3057: 
 3058: returns list of file types belonging to a given file
 3059: category
 3060: 
 3061: =cut
 3062: 
 3063: sub filecategorytypes {
 3064:     my ($cat) = @_;
 3065:     return @{$category_extensions{lc($cat)}};
 3066: }
 3067: 
 3068: =pod
 3069: 
 3070: =item * &fileembstyle() 
 3071: 
 3072: returns embedding style for a specified file type
 3073: 
 3074: =cut
 3075: 
 3076: sub fileembstyle {
 3077:     return $fe{lc(shift(@_))};
 3078: }
 3079: 
 3080: sub filemimetype {
 3081:     return $fm{lc(shift(@_))};
 3082: }
 3083: 
 3084: 
 3085: sub filecategoryselect {
 3086:     my ($name,$value)=@_;
 3087:     return &select_form($value,$name,
 3088: 			'' => &mt('Any category'),
 3089: 			map { $_,$_ } sort(keys(%category_extensions)));
 3090: }
 3091: 
 3092: =pod
 3093: 
 3094: =item * &filedescription() 
 3095: 
 3096: returns description for a specified file type
 3097: 
 3098: =cut
 3099: 
 3100: sub filedescription {
 3101:     my $file_description = $fd{lc(shift())};
 3102:     $file_description =~ s:([\[\]]):~$1:g;
 3103:     return &mt($file_description);
 3104: }
 3105: 
 3106: =pod
 3107: 
 3108: =item * &filedescriptionex() 
 3109: 
 3110: returns description for a specified file type with
 3111: extra formatting
 3112: 
 3113: =cut
 3114: 
 3115: sub filedescriptionex {
 3116:     my $ex=shift;
 3117:     my $file_description = $fd{lc($ex)};
 3118:     $file_description =~ s:([\[\]]):~$1:g;
 3119:     return '.'.$ex.' '.&mt($file_description);
 3120: }
 3121: 
 3122: # End of .tab access
 3123: =pod
 3124: 
 3125: =back
 3126: 
 3127: =cut
 3128: 
 3129: # ------------------------------------------------------------------ File Types
 3130: sub fileextensions {
 3131:     return sort(keys(%fe));
 3132: }
 3133: 
 3134: # ----------------------------------------------------------- Display Languages
 3135: # returns a hash with all desired display languages
 3136: #
 3137: 
 3138: sub display_languages {
 3139:     my %languages=();
 3140:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3141: 	$languages{$lang}=1;
 3142:     }
 3143:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3144:     if ($env{'form.displaylanguage'}) {
 3145: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3146: 	    $languages{$lang}=1;
 3147:         }
 3148:     }
 3149:     return %languages;
 3150: }
 3151: 
 3152: sub languages {
 3153:     my ($possible_langs) = @_;
 3154:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3155:     if (!ref($possible_langs)) {
 3156: 	if( wantarray ) {
 3157: 	    return @preferred_langs;
 3158: 	} else {
 3159: 	    return $preferred_langs[0];
 3160: 	}
 3161:     }
 3162:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3163:     my @preferred_possibilities;
 3164:     foreach my $preferred_lang (@preferred_langs) {
 3165: 	if (exists($possibilities{$preferred_lang})) {
 3166: 	    push(@preferred_possibilities, $preferred_lang);
 3167: 	}
 3168:     }
 3169:     if( wantarray ) {
 3170: 	return @preferred_possibilities;
 3171:     }
 3172:     return $preferred_possibilities[0];
 3173: }
 3174: 
 3175: sub user_lang {
 3176:     my ($touname,$toudom,$fromcid) = @_;
 3177:     my @userlangs;
 3178:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3179:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3180:                     $env{'course.'.$fromcid.'.languages'}));
 3181:     } else {
 3182:         my %langhash = &getlangs($touname,$toudom);
 3183:         if ($langhash{'languages'} ne '') {
 3184:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3185:         } else {
 3186:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3187:             if ($domdefs{'lang_def'} ne '') {
 3188:                 @userlangs = ($domdefs{'lang_def'});
 3189:             }
 3190:         }
 3191:     }
 3192:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3193:     my $user_lh = Apache::localize->get_handle(@languages);
 3194:     return $user_lh;
 3195: }
 3196: 
 3197: 
 3198: ###############################################################
 3199: ##               Student Answer Attempts                     ##
 3200: ###############################################################
 3201: 
 3202: =pod
 3203: 
 3204: =head1 Alternate Problem Views
 3205: 
 3206: =over 4
 3207: 
 3208: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3209:     $getattempt, $regexp, $gradesub)
 3210: 
 3211: Return string with previous attempt on problem. Arguments:
 3212: 
 3213: =over 4
 3214: 
 3215: =item * $symb: Problem, including path
 3216: 
 3217: =item * $username: username of the desired student
 3218: 
 3219: =item * $domain: domain of the desired student
 3220: 
 3221: =item * $course: Course ID
 3222: 
 3223: =item * $getattempt: Leave blank for all attempts, otherwise put
 3224:     something
 3225: 
 3226: =item * $regexp: if string matches this regexp, the string will be
 3227:     sent to $gradesub
 3228: 
 3229: =item * $gradesub: routine that processes the string if it matches $regexp
 3230: 
 3231: =back
 3232: 
 3233: The output string is a table containing all desired attempts, if any.
 3234: 
 3235: =cut
 3236: 
 3237: sub get_previous_attempt {
 3238:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3239:   my $prevattempts='';
 3240:   no strict 'refs';
 3241:   if ($symb) {
 3242:     my (%returnhash)=
 3243:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3244:     if ($returnhash{'version'}) {
 3245:       my %lasthash=();
 3246:       my $version;
 3247:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3248:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3249: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3250:         }
 3251:       }
 3252:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3253:       $prevattempts.='<th>'.&mt('History').'</th>';
 3254:       foreach my $key (sort(keys(%lasthash))) {
 3255: 	my ($ign,@parts) = split(/\./,$key);
 3256: 	if ($#parts > 0) {
 3257: 	  my $data=$parts[-1];
 3258: 	  pop(@parts);
 3259: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3260: 	} else {
 3261: 	  if ($#parts == 0) {
 3262: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3263: 	  } else {
 3264: 	    $prevattempts.='<th>'.$ign.'</th>';
 3265: 	  }
 3266: 	}
 3267:       }
 3268:       $prevattempts.=&end_data_table_header_row();
 3269:       if ($getattempt eq '') {
 3270: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3271: 	  $prevattempts.=&start_data_table_row().
 3272: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3273: 	    foreach my $key (sort(keys(%lasthash))) {
 3274: 		my $value = &format_previous_attempt_value($key,
 3275: 							   $returnhash{$version.':'.$key});
 3276: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3277: 	    }
 3278: 	  $prevattempts.=&end_data_table_row();
 3279: 	 }
 3280:       }
 3281:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3282:       foreach my $key (sort(keys(%lasthash))) {
 3283: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3284: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3285: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3286:       }
 3287:       $prevattempts.= &end_data_table_row().&end_data_table();
 3288:     } else {
 3289:       $prevattempts=
 3290: 	  &start_data_table().&start_data_table_row().
 3291: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3292: 	  &end_data_table_row().&end_data_table();
 3293:     }
 3294:   } else {
 3295:     $prevattempts=
 3296: 	  &start_data_table().&start_data_table_row().
 3297: 	  '<td>'.&mt('No data.').'</td>'.
 3298: 	  &end_data_table_row().&end_data_table();
 3299:   }
 3300: }
 3301: 
 3302: sub format_previous_attempt_value {
 3303:     my ($key,$value) = @_;
 3304:     if ($key =~ /timestamp/) {
 3305: 	$value = &Apache::lonlocal::locallocaltime($value);
 3306:     } elsif (ref($value) eq 'ARRAY') {
 3307: 	$value = '('.join(', ', @{ $value }).')';
 3308:     } else {
 3309: 	$value = &unescape($value);
 3310:     }
 3311:     return $value;
 3312: }
 3313: 
 3314: 
 3315: sub relative_to_absolute {
 3316:     my ($url,$output)=@_;
 3317:     my $parser=HTML::TokeParser->new(\$output);
 3318:     my $token;
 3319:     my $thisdir=$url;
 3320:     my @rlinks=();
 3321:     while ($token=$parser->get_token) {
 3322: 	if ($token->[0] eq 'S') {
 3323: 	    if ($token->[1] eq 'a') {
 3324: 		if ($token->[2]->{'href'}) {
 3325: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3326: 		}
 3327: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3328: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3329: 	    } elsif ($token->[1] eq 'base') {
 3330: 		$thisdir=$token->[2]->{'href'};
 3331: 	    }
 3332: 	}
 3333:     }
 3334:     $thisdir=~s-/[^/]*$--;
 3335:     foreach my $link (@rlinks) {
 3336: 	unless (($link=~/^https?\:\/\//i) ||
 3337: 		($link=~/^\//) ||
 3338: 		($link=~/^javascript:/i) ||
 3339: 		($link=~/^mailto:/i) ||
 3340: 		($link=~/^\#/)) {
 3341: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3342: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3343: 	}
 3344:     }
 3345: # -------------------------------------------------- Deal with Applet codebases
 3346:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3347:     return $output;
 3348: }
 3349: 
 3350: =pod
 3351: 
 3352: =item * &get_student_view()
 3353: 
 3354: show a snapshot of what student was looking at
 3355: 
 3356: =cut
 3357: 
 3358: sub get_student_view {
 3359:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3360:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3361:   my (%form);
 3362:   my @elements=('symb','courseid','domain','username');
 3363:   foreach my $element (@elements) {
 3364:       $form{'grade_'.$element}=eval '$'.$element #'
 3365:   }
 3366:   if (defined($moreenv)) {
 3367:       %form=(%form,%{$moreenv});
 3368:   }
 3369:   if (defined($target)) { $form{'grade_target'} = $target; }
 3370:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3371:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3372:   $userview=~s/\<body[^\>]*\>//gi;
 3373:   $userview=~s/\<\/body\>//gi;
 3374:   $userview=~s/\<html\>//gi;
 3375:   $userview=~s/\<\/html\>//gi;
 3376:   $userview=~s/\<head\>//gi;
 3377:   $userview=~s/\<\/head\>//gi;
 3378:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3379:   $userview=&relative_to_absolute($feedurl,$userview);
 3380:   if (wantarray) {
 3381:      return ($userview,$response);
 3382:   } else {
 3383:      return $userview;
 3384:   }
 3385: }
 3386: 
 3387: sub get_student_view_with_retries {
 3388:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3389: 
 3390:     my $ok = 0;                 # True if we got a good response.
 3391:     my $content;
 3392:     my $response;
 3393: 
 3394:     # Try to get the student_view done. within the retries count:
 3395:     
 3396:     do {
 3397:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3398:          $ok      = $response->is_success;
 3399:          if (!$ok) {
 3400:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3401:          }
 3402:          $retries--;
 3403:     } while (!$ok && ($retries > 0));
 3404:     
 3405:     if (!$ok) {
 3406:        $content = '';          # On error return an empty content.
 3407:     }
 3408:     if (wantarray) {
 3409:        return ($content, $response);
 3410:     } else {
 3411:        return $content;
 3412:     }
 3413: }
 3414: 
 3415: =pod
 3416: 
 3417: =item * &get_student_answers() 
 3418: 
 3419: show a snapshot of how student was answering problem
 3420: 
 3421: =cut
 3422: 
 3423: sub get_student_answers {
 3424:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3425:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3426:   my (%moreenv);
 3427:   my @elements=('symb','courseid','domain','username');
 3428:   foreach my $element (@elements) {
 3429:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3430:   }
 3431:   $moreenv{'grade_target'}='answer';
 3432:   %moreenv=(%form,%moreenv);
 3433:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3434:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3435:   return $userview;
 3436: }
 3437: 
 3438: =pod
 3439: 
 3440: =item * &submlink()
 3441: 
 3442: Inputs: $text $uname $udom $symb $target
 3443: 
 3444: Returns: A link to grades.pm such as to see the SUBM view of a student
 3445: 
 3446: =cut
 3447: 
 3448: ###############################################
 3449: sub submlink {
 3450:     my ($text,$uname,$udom,$symb,$target)=@_;
 3451:     if (!($uname && $udom)) {
 3452: 	(my $cursymb, my $courseid,$udom,$uname)=
 3453: 	    &Apache::lonnet::whichuser($symb);
 3454: 	if (!$symb) { $symb=$cursymb; }
 3455:     }
 3456:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3457:     $symb=&escape($symb);
 3458:     if ($target) { $target="target=\"$target\""; }
 3459:     return '<a href="/adm/grades?&command=submission&'.
 3460: 	'symb='.$symb.'&student='.$uname.
 3461: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3462: }
 3463: ##############################################
 3464: 
 3465: =pod
 3466: 
 3467: =item * &pgrdlink()
 3468: 
 3469: Inputs: $text $uname $udom $symb $target
 3470: 
 3471: Returns: A link to grades.pm such as to see the PGRD view of a student
 3472: 
 3473: =cut
 3474: 
 3475: ###############################################
 3476: sub pgrdlink {
 3477:     my $link=&submlink(@_);
 3478:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3479:     return $link;
 3480: }
 3481: ##############################################
 3482: 
 3483: =pod
 3484: 
 3485: =item * &pprmlink()
 3486: 
 3487: Inputs: $text $uname $udom $symb $target
 3488: 
 3489: Returns: A link to parmset.pm such as to see the PPRM view of a
 3490: student and a specific resource
 3491: 
 3492: =cut
 3493: 
 3494: ###############################################
 3495: sub pprmlink {
 3496:     my ($text,$uname,$udom,$symb,$target)=@_;
 3497:     if (!($uname && $udom)) {
 3498: 	(my $cursymb, my $courseid,$udom,$uname)=
 3499: 	    &Apache::lonnet::whichuser($symb);
 3500: 	if (!$symb) { $symb=$cursymb; }
 3501:     }
 3502:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3503:     $symb=&escape($symb);
 3504:     if ($target) { $target="target=\"$target\""; }
 3505:     return '<a href="/adm/parmset?command=set&amp;'.
 3506: 	'symb='.$symb.'&amp;uname='.$uname.
 3507: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3508: }
 3509: ##############################################
 3510: 
 3511: =pod
 3512: 
 3513: =back
 3514: 
 3515: =cut
 3516: 
 3517: ###############################################
 3518: 
 3519: 
 3520: sub timehash {
 3521:     my ($thistime) = @_;
 3522:     my $timezone = &Apache::lonlocal::gettimezone();
 3523:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3524:                      ->set_time_zone($timezone);
 3525:     my $wday = $dt->day_of_week();
 3526:     if ($wday == 7) { $wday = 0; }
 3527:     return ( 'second' => $dt->second(),
 3528:              'minute' => $dt->minute(),
 3529:              'hour'   => $dt->hour(),
 3530:              'day'     => $dt->day_of_month(),
 3531:              'month'   => $dt->month(),
 3532:              'year'    => $dt->year(),
 3533:              'weekday' => $wday,
 3534:              'dayyear' => $dt->day_of_year(),
 3535:              'dlsav'   => $dt->is_dst() );
 3536: }
 3537: 
 3538: sub utc_string {
 3539:     my ($date)=@_;
 3540:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3541: }
 3542: 
 3543: sub maketime {
 3544:     my %th=@_;
 3545:     my ($epoch_time,$timezone,$dt);
 3546:     $timezone = &Apache::lonlocal::gettimezone();
 3547:     eval {
 3548:         $dt = DateTime->new( year   => $th{'year'},
 3549:                              month  => $th{'month'},
 3550:                              day    => $th{'day'},
 3551:                              hour   => $th{'hour'},
 3552:                              minute => $th{'minute'},
 3553:                              second => $th{'second'},
 3554:                              time_zone => $timezone,
 3555:                          );
 3556:     };
 3557:     if (!$@) {
 3558:         $epoch_time = $dt->epoch;
 3559:         if ($epoch_time) {
 3560:             return $epoch_time;
 3561:         }
 3562:     }
 3563:     return POSIX::mktime(
 3564:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3565:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3566: }
 3567: 
 3568: #########################################
 3569: 
 3570: sub findallcourses {
 3571:     my ($roles,$uname,$udom) = @_;
 3572:     my %roles;
 3573:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3574:     my %courses;
 3575:     my $now=time;
 3576:     if (!defined($uname)) {
 3577:         $uname = $env{'user.name'};
 3578:     }
 3579:     if (!defined($udom)) {
 3580:         $udom = $env{'user.domain'};
 3581:     }
 3582:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3583:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3584:         if (!%roles) {
 3585:             %roles = (
 3586:                        cc => 1,
 3587:                        in => 1,
 3588:                        ep => 1,
 3589:                        ta => 1,
 3590:                        cr => 1,
 3591:                        st => 1,
 3592:              );
 3593:         }
 3594:         foreach my $entry (keys(%roleshash)) {
 3595:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3596:             if ($trole =~ /^cr/) { 
 3597:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3598:             } else {
 3599:                 next if (!exists($roles{$trole}));
 3600:             }
 3601:             if ($tend) {
 3602:                 next if ($tend < $now);
 3603:             }
 3604:             if ($tstart) {
 3605:                 next if ($tstart > $now);
 3606:             }
 3607:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3608:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3609:             if ($secpart eq '') {
 3610:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3611:                 $sec = 'none';
 3612:                 $realsec = '';
 3613:             } else {
 3614:                 $cnum = $cnumpart;
 3615:                 ($sec,$role) = split(/_/,$secpart);
 3616:                 $realsec = $sec;
 3617:             }
 3618:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3619:         }
 3620:     } else {
 3621:         foreach my $key (keys(%env)) {
 3622: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3623:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3624: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3625: 	        next if ($role eq 'ca' || $role eq 'aa');
 3626: 	        next if (%roles && !exists($roles{$role}));
 3627: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3628:                 my $active=1;
 3629:                 if ($starttime) {
 3630: 		    if ($now<$starttime) { $active=0; }
 3631:                 }
 3632:                 if ($endtime) {
 3633:                     if ($now>$endtime) { $active=0; }
 3634:                 }
 3635:                 if ($active) {
 3636:                     if ($sec eq '') {
 3637:                         $sec = 'none';
 3638:                     }
 3639:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3640:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3641:                 }
 3642:             }
 3643:         }
 3644:     }
 3645:     return %courses;
 3646: }
 3647: 
 3648: ###############################################
 3649: 
 3650: sub blockcheck {
 3651:     my ($setters,$activity,$uname,$udom) = @_;
 3652: 
 3653:     if (!defined($udom)) {
 3654:         $udom = $env{'user.domain'};
 3655:     }
 3656:     if (!defined($uname)) {
 3657:         $uname = $env{'user.name'};
 3658:     }
 3659: 
 3660:     # If uname and udom are for a course, check for blocks in the course.
 3661: 
 3662:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3663:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3664:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3665:         return ($startblock,$endblock);
 3666:     }
 3667: 
 3668:     my $startblock = 0;
 3669:     my $endblock = 0;
 3670:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3671: 
 3672:     # If uname is for a user, and activity is course-specific, i.e.,
 3673:     # boards, chat or groups, check for blocking in current course only.
 3674: 
 3675:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3676:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3677:         foreach my $key (keys(%live_courses)) {
 3678:             if ($key ne $env{'request.course.id'}) {
 3679:                 delete($live_courses{$key});
 3680:             }
 3681:         }
 3682:     }
 3683: 
 3684:     my $otheruser = 0;
 3685:     my %own_courses;
 3686:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3687:         # Resource belongs to user other than current user.
 3688:         $otheruser = 1;
 3689:         # Gather courses for current user
 3690:         %own_courses = 
 3691:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3692:     }
 3693: 
 3694:     # Gather active course roles - course coordinator, instructor, 
 3695:     # exam proctor, ta, student, or custom role.
 3696: 
 3697:     foreach my $course (keys(%live_courses)) {
 3698:         my ($cdom,$cnum);
 3699:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3700:             $cdom = $env{'course.'.$course.'.domain'};
 3701:             $cnum = $env{'course.'.$course.'.num'};
 3702:         } else {
 3703:             ($cdom,$cnum) = split(/_/,$course); 
 3704:         }
 3705:         my $no_ownblock = 0;
 3706:         my $no_userblock = 0;
 3707:         if ($otheruser && $activity ne 'com') {
 3708:             # Check if current user has 'evb' priv for this
 3709:             if (defined($own_courses{$course})) {
 3710:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3711:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3712:                     if ($sec ne 'none') {
 3713:                         $checkrole .= '/'.$sec;
 3714:                     }
 3715:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3716:                         $no_ownblock = 1;
 3717:                         last;
 3718:                     }
 3719:                 }
 3720:             }
 3721:             # if they have 'evb' priv and are currently not playing student
 3722:             next if (($no_ownblock) &&
 3723:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3724:         }
 3725:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3726:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3727:             if ($sec ne 'none') {
 3728:                 $checkrole .= '/'.$sec;
 3729:             }
 3730:             if ($otheruser) {
 3731:                 # Resource belongs to user other than current user.
 3732:                 # Assemble privs for that user, and check for 'evb' priv.
 3733:                 my ($trole,$tdom,$tnum,$tsec);
 3734:                 my $entry = $live_courses{$course}{$sec};
 3735:                 if ($entry =~ /^cr/) {
 3736:                     ($trole,$tdom,$tnum,$tsec) = 
 3737:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3738:                 } else {
 3739:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3740:                 }
 3741:                 my ($spec,$area,$trest,%allroles,%userroles);
 3742:                 $area = '/'.$tdom.'/'.$tnum;
 3743:                 $trest = $tnum;
 3744:                 if ($tsec ne '') {
 3745:                     $area .= '/'.$tsec;
 3746:                     $trest .= '/'.$tsec;
 3747:                 }
 3748:                 $spec = $trole.'.'.$area;
 3749:                 if ($trole =~ /^cr/) {
 3750:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3751:                                                       $tdom,$spec,$trest,$area);
 3752:                 } else {
 3753:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3754:                                                        $tdom,$spec,$trest,$area);
 3755:                 }
 3756:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3757:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3758:                     if ($1) {
 3759:                         $no_userblock = 1;
 3760:                         last;
 3761:                     }
 3762:                 }
 3763:             } else {
 3764:                 # Resource belongs to current user
 3765:                 # Check for 'evb' priv via lonnet::allowed().
 3766:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3767:                     $no_ownblock = 1;
 3768:                     last;
 3769:                 }
 3770:             }
 3771:         }
 3772:         # if they have the evb priv and are currently not playing student
 3773:         next if (($no_ownblock) &&
 3774:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3775:         next if ($no_userblock);
 3776: 
 3777:         # Retrieve blocking times and identity of locker for course
 3778:         # of specified user, unless user has 'evb' privilege.
 3779:         
 3780:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3781:         if (($start != 0) && 
 3782:             (($startblock == 0) || ($startblock > $start))) {
 3783:             $startblock = $start;
 3784:         }
 3785:         if (($end != 0)  &&
 3786:             (($endblock == 0) || ($endblock < $end))) {
 3787:             $endblock = $end;
 3788:         }
 3789:     }
 3790:     return ($startblock,$endblock);
 3791: }
 3792: 
 3793: sub get_blocks {
 3794:     my ($setters,$activity,$cdom,$cnum) = @_;
 3795:     my $startblock = 0;
 3796:     my $endblock = 0;
 3797:     my $course = $cdom.'_'.$cnum;
 3798:     $setters->{$course} = {};
 3799:     $setters->{$course}{'staff'} = [];
 3800:     $setters->{$course}{'times'} = [];
 3801:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3802:     foreach my $record (keys(%records)) {
 3803:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3804:         if ($start <= time && $end >= time) {
 3805:             my ($staff_name,$staff_dom,$title,$blocks) =
 3806:                 &parse_block_record($records{$record});
 3807:             if ($blocks->{$activity} eq 'on') {
 3808:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3809:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3810:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3811:                     $startblock = $start;
 3812:                 }
 3813:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3814:                     $endblock = $end;
 3815:                 }
 3816:             }
 3817:         }
 3818:     }
 3819:     return ($startblock,$endblock);
 3820: }
 3821: 
 3822: sub parse_block_record {
 3823:     my ($record) = @_;
 3824:     my ($setuname,$setudom,$title,$blocks);
 3825:     if (ref($record) eq 'HASH') {
 3826:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3827:         $title = &unescape($record->{'event'});
 3828:         $blocks = $record->{'blocks'};
 3829:     } else {
 3830:         my @data = split(/:/,$record,3);
 3831:         if (scalar(@data) eq 2) {
 3832:             $title = $data[1];
 3833:             ($setuname,$setudom) = split(/@/,$data[0]);
 3834:         } else {
 3835:             ($setuname,$setudom,$title) = @data;
 3836:         }
 3837:         $blocks = { 'com' => 'on' };
 3838:     }
 3839:     return ($setuname,$setudom,$title,$blocks);
 3840: }
 3841: 
 3842: sub blocking_status {
 3843:   my $blocked;
 3844:   my ($activity,$uname,$udom) = @_;
 3845:   my %setters;
 3846:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3847:   if ($startblock && $endblock) {
 3848:     $blocked = 1;
 3849:   }
 3850:   if(!wantarray) {
 3851:     return $blocked;
 3852:   }
 3853:   my $output;
 3854:   my $querystring;
 3855:   $querystring = "?activity=$activity";
 3856: 
 3857:       $output .= <<"END_MYBLOCK";
 3858: <script type="text/javascript">
 3859: // <![CDATA[
 3860:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 3861:         var options = "width=" + w + ",height=" + h + ",";
 3862:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 3863:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 3864:         var newWin = window.open(url, wdwName, options);
 3865:         newWin.focus();
 3866:     }
 3867: 
 3868: // ]]>
 3869: </script>
 3870: END_MYBLOCK
 3871:   my $popupUrl = "/adm/blockingstatus/$querystring";
 3872:   $output .= <<"END_BLOCK";
 3873: <div class='LC_comblock'>
 3874:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 3875:   title='Communication Blocked'>
 3876:   <img class='LC_noBorder LC_middle' title='Communication Blocked' src='/res/adm/pages/comblock.png' alt='Communication Blocked'/></a>
 3877:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 3878:   title='Communication Blocked'>Communication Blocked</a>
 3879: </div>
 3880: 
 3881: END_BLOCK
 3882: 
 3883:   return ($blocked, $output);
 3884: }
 3885: 
 3886: ###############################################
 3887: 
 3888: sub check_ip_acc {
 3889:     my ($acc)=@_;
 3890:     &Apache::lonxml::debug("acc is $acc");
 3891:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3892:         return 1;
 3893:     }
 3894:     my $allowed=0;
 3895:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3896: 
 3897:     my $name;
 3898:     foreach my $pattern (split(',',$acc)) {
 3899:         $pattern =~ s/^\s*//;
 3900:         $pattern =~ s/\s*$//;
 3901:         if ($pattern =~ /\*$/) {
 3902:             #35.8.*
 3903:             $pattern=~s/\*//;
 3904:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3905:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3906:             #35.8.3.[34-56]
 3907:             my $low=$2;
 3908:             my $high=$3;
 3909:             $pattern=$1;
 3910:             if ($ip =~ /^\Q$pattern\E/) {
 3911:                 my $last=(split(/\./,$ip))[3];
 3912:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3913:             }
 3914:         } elsif ($pattern =~ /^\*/) {
 3915:             #*.msu.edu
 3916:             $pattern=~s/\*//;
 3917:             if (!defined($name)) {
 3918:                 use Socket;
 3919:                 my $netaddr=inet_aton($ip);
 3920:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3921:             }
 3922:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3923:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3924:             #127.0.0.1
 3925:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3926:         } else {
 3927:             #some.name.com
 3928:             if (!defined($name)) {
 3929:                 use Socket;
 3930:                 my $netaddr=inet_aton($ip);
 3931:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3932:             }
 3933:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3934:         }
 3935:         if ($allowed) { last; }
 3936:     }
 3937:     return $allowed;
 3938: }
 3939: 
 3940: ###############################################
 3941: 
 3942: =pod
 3943: 
 3944: =head1 Domain Template Functions
 3945: 
 3946: =over 4
 3947: 
 3948: =item * &determinedomain()
 3949: 
 3950: Inputs: $domain (usually will be undef)
 3951: 
 3952: Returns: Determines which domain should be used for designs
 3953: 
 3954: =cut
 3955: 
 3956: ###############################################
 3957: sub determinedomain {
 3958:     my $domain=shift;
 3959:     if (! $domain) {
 3960:         # Determine domain if we have not been given one
 3961:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3962:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3963:         if ($env{'request.role.domain'}) { 
 3964:             $domain=$env{'request.role.domain'}; 
 3965:         }
 3966:     }
 3967:     return $domain;
 3968: }
 3969: ###############################################
 3970: 
 3971: sub devalidate_domconfig_cache {
 3972:     my ($udom)=@_;
 3973:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3974: }
 3975: 
 3976: # ---------------------- Get domain configuration for a domain
 3977: sub get_domainconf {
 3978:     my ($udom) = @_;
 3979:     my $cachetime=1800;
 3980:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3981:     if (defined($cached)) { return %{$result}; }
 3982: 
 3983:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3984: 					     ['login','rolecolors'],$udom);
 3985:     my (%designhash,%legacy);
 3986:     if (keys(%domconfig) > 0) {
 3987:         if (ref($domconfig{'login'}) eq 'HASH') {
 3988:             if (keys(%{$domconfig{'login'}})) {
 3989:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3990:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3991:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 3992:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 3993:                                 $domconfig{'login'}{$key}{$img};
 3994:                         }
 3995:                     } else {
 3996:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3997:                     }
 3998:                 }
 3999:             } else {
 4000:                 $legacy{'login'} = 1;
 4001:             }
 4002:         } else {
 4003:             $legacy{'login'} = 1;
 4004:         }
 4005:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4006:             if (keys(%{$domconfig{'rolecolors'}})) {
 4007:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4008:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4009:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4010:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4011:                         }
 4012:                     }
 4013:                 }
 4014:             } else {
 4015:                 $legacy{'rolecolors'} = 1;
 4016:             }
 4017:         } else {
 4018:             $legacy{'rolecolors'} = 1;
 4019:         }
 4020:         if (keys(%legacy) > 0) {
 4021:             my %legacyhash = &get_legacy_domconf($udom);
 4022:             foreach my $item (keys(%legacyhash)) {
 4023:                 if ($item =~ /^\Q$udom\E\.login/) {
 4024:                     if ($legacy{'login'}) { 
 4025:                         $designhash{$item} = $legacyhash{$item};
 4026:                     }
 4027:                 } else {
 4028:                     if ($legacy{'rolecolors'}) {
 4029:                         $designhash{$item} = $legacyhash{$item};
 4030:                     }
 4031:                 }
 4032:             }
 4033:         }
 4034:     } else {
 4035:         %designhash = &get_legacy_domconf($udom); 
 4036:     }
 4037:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4038: 				  $cachetime);
 4039:     return %designhash;
 4040: }
 4041: 
 4042: sub get_legacy_domconf {
 4043:     my ($udom) = @_;
 4044:     my %legacyhash;
 4045:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4046:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4047:     if (-e $designfile) {
 4048:         if ( open (my $fh,"<$designfile") ) {
 4049:             while (my $line = <$fh>) {
 4050:                 next if ($line =~ /^\#/);
 4051:                 chomp($line);
 4052:                 my ($key,$val)=(split(/\=/,$line));
 4053:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4054:             }
 4055:             close($fh);
 4056:         }
 4057:     }
 4058:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4059:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4060:     }
 4061:     return %legacyhash;
 4062: }
 4063: 
 4064: =pod
 4065: 
 4066: =item * &domainlogo()
 4067: 
 4068: Inputs: $domain (usually will be undef)
 4069: 
 4070: Returns: A link to a domain logo, if the domain logo exists.
 4071: If the domain logo does not exist, a description of the domain.
 4072: 
 4073: =cut
 4074: 
 4075: ###############################################
 4076: sub domainlogo {
 4077:     my $domain = &determinedomain(shift);
 4078:     my %designhash = &get_domainconf($domain);    
 4079:     # See if there is a logo
 4080:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4081:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4082:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4083: 	    if ($imgsrc =~ m{^/res/}) {
 4084: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4085: 		&Apache::lonnet::repcopy($local_name);
 4086: 	    }
 4087: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4088:         } 
 4089:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4090:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4091:         return &Apache::lonnet::domain($domain,'description');
 4092:     } else {
 4093:         return '';
 4094:     }
 4095: }
 4096: ##############################################
 4097: 
 4098: =pod
 4099: 
 4100: =item * &designparm()
 4101: 
 4102: Inputs: $which parameter; $domain (usually will be undef)
 4103: 
 4104: Returns: value of designparamter $which
 4105: 
 4106: =cut
 4107: 
 4108: 
 4109: ##############################################
 4110: sub designparm {
 4111:     my ($which,$domain)=@_;
 4112:     if (exists($env{'environment.color.'.$which})) {
 4113:         return $env{'environment.color.'.$which};
 4114:     }
 4115:     $domain=&determinedomain($domain);
 4116:     my %domdesign = &get_domainconf($domain);
 4117:     my $output;
 4118:     if ($domdesign{$domain.'.'.$which} ne '') {
 4119:         $output = $domdesign{$domain.'.'.$which};
 4120:     } else {
 4121:         $output = $defaultdesign{$which};
 4122:     }
 4123:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4124:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4125:         if ($output =~ m{^/(adm|res)/}) {
 4126:             if ($output =~ m{^/res/}) {
 4127:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4128:                 &Apache::lonnet::repcopy($local_name);
 4129:             }
 4130:             $output = &lonhttpdurl($output);
 4131:         }
 4132:     }
 4133:     return $output;
 4134: }
 4135: 
 4136: ##############################################
 4137: =pod
 4138: 
 4139: =item * &authorspace()
 4140: 
 4141: Inputs: ./.
 4142: 
 4143: Returns: Path to the Construction Space of the current user's
 4144:          accessed author space
 4145:          The author space will be that of the current user
 4146:          when accessing the own author space
 4147:          and that of the co-author/assistent co-author
 4148:          when accessing the co-author's/assistent co-author's
 4149:          space
 4150: 
 4151: =cut
 4152: 
 4153: sub authorspace {
 4154:     my $caname = '';
 4155:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4156:         (undef,$caname) =
 4157:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4158:     } else {
 4159:         $caname = $env{'user.name'};
 4160:     }
 4161:     return '/priv/'.$caname.'/';
 4162: }
 4163: 
 4164: ##############################################
 4165: =pod
 4166: 
 4167: =item * &head_subbox()
 4168: 
 4169: Inputs: $content (contains HTML code with page functions, etc.)
 4170: 
 4171: Returns: HTML div with $content
 4172:          To be included in page header
 4173: 
 4174: =cut
 4175: 
 4176: sub head_subbox {
 4177:     my ($content)=@_;
 4178:     my $output =
 4179:         '<div id="LC_head_subbox">'
 4180:        .$content
 4181:        .'</div>'
 4182: }
 4183: 
 4184: ##############################################
 4185: =pod
 4186: 
 4187: =item * &CSTR_pageheader()
 4188: 
 4189: Inputs: ./.
 4190: 
 4191: Returns: HTML div with CSTR path and recent box
 4192:          To be included on Construction Space pages
 4193: 
 4194: =cut
 4195: 
 4196: sub CSTR_pageheader {
 4197:     # this is for resources; directories have customtitle, and crumbs
 4198:             # and select recent are created in lonpubdir.pm  
 4199:     my ($uname,$thisdisfn)=
 4200:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4201:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4202:     $formaction=~s/\/+/\//g;
 4203: 
 4204:     my $parentpath = '';
 4205:     my $lastitem = '';
 4206:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4207:         $parentpath = $1;
 4208:         $lastitem = $2;
 4209:     } else {
 4210:         $lastitem = $thisdisfn;
 4211:     }
 4212:     return
 4213:          '<div>'
 4214:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4215:         .'<b>'.&mt('Construction Space:').'</b> '
 4216:         .'<form name="dirs" method="post" action="'.$formaction
 4217:         .'" target="_top"><tt><b>' #FIXME lonpubdir: target="_parent"
 4218:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."$lastitem</b></tt><br />"
 4219:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4220:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4221:         .'</form>'
 4222:         .&Apache::lonmenu::constspaceform()
 4223:         .'</div>';
 4224: }
 4225: 
 4226: ###############################################
 4227: ###############################################
 4228: 
 4229: =pod
 4230: 
 4231: =back
 4232: 
 4233: =head1 HTML Helpers
 4234: 
 4235: =over 4
 4236: 
 4237: =item * &bodytag()
 4238: 
 4239: Returns a uniform header for LON-CAPA web pages.
 4240: 
 4241: Inputs: 
 4242: 
 4243: =over 4
 4244: 
 4245: =item * $title, A title to be displayed on the page.
 4246: 
 4247: =item * $function, the current role (can be undef).
 4248: 
 4249: =item * $addentries, extra parameters for the <body> tag.
 4250: 
 4251: =item * $bodyonly, if defined, only return the <body> tag.
 4252: 
 4253: =item * $domain, if defined, force a given domain.
 4254: 
 4255: =item * $forcereg, if page should register as content page (relevant for 
 4256:             text interface only)
 4257: 
 4258: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4259:                      navigational links
 4260: 
 4261: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4262: 
 4263: =item * $no_inline_link, if true and in remote mode, don't show the 
 4264:          'Switch To Inline Menu' link
 4265: 
 4266: =item * $args, optional argument valid values are
 4267:             no_auto_mt_title -> prevents &mt()ing the title arg
 4268:             inherit_jsmath -> when creating popup window in a page,
 4269:                               should it have jsmath forced on by the
 4270:                               current page
 4271: 
 4272: =back
 4273: 
 4274: Returns: A uniform header for LON-CAPA web pages.  
 4275: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4276: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4277: other decorations will be returned.
 4278: 
 4279: =cut
 4280: 
 4281: sub bodytag {
 4282:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4283:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4284: 
 4285:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4286: 
 4287:     $function = &get_users_function() if (!$function);
 4288:     my $img =    &designparm($function.'.img',$domain);
 4289:     my $font =   &designparm($function.'.font',$domain);
 4290:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4291: 
 4292:     my %design = ( 'style'   => 'margin-top: 0',
 4293: 		   'bgcolor' => $pgbg,
 4294: 		   'text'    => $font,
 4295:                    'alink'   => &designparm($function.'.alink',$domain),
 4296: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4297: 		   'link'    => &designparm($function.'.link',$domain),);
 4298:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4299: 
 4300:  # role and realm
 4301:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4302:     if ($role  eq 'ca') {
 4303:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4304:         $realm = &plainname($rname,$rdom);
 4305:     } 
 4306: # realm
 4307:     if ($env{'request.course.id'}) {
 4308:         if ($env{'request.role'} !~ /^cr/) {
 4309:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4310:         }
 4311: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4312:     } else {
 4313:         $role = &Apache::lonnet::plaintext($role);
 4314:     }
 4315: 
 4316:     if (!$realm) { $realm='&nbsp;'; }
 4317: # Set messages
 4318:     my $messages=&domainlogo($domain);
 4319: 
 4320:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4321: 
 4322: # construct main body tag
 4323:     my $bodytag = "<body $extra_body_attr>".
 4324: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4325: 
 4326:     if ($bodyonly) {
 4327:         return $bodytag;
 4328:     } 
 4329: 
 4330:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4331:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4332: 	undef($role);
 4333:     } else {
 4334: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4335:     }
 4336:     
 4337:     my $titleinfo = '<h1>'.$title.'</h1>';
 4338:     #
 4339:     # Extra info if you are the DC
 4340:     my $dc_info = '';
 4341:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4342:                         $env{'course.'.$env{'request.course.id'}.
 4343:                                  '.domain'}.'/'})) {
 4344:         my $cid = $env{'request.course.id'};
 4345:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4346:         $dc_info =~ s/\s+$//;
 4347:         $dc_info = '('.$dc_info.')';
 4348:     }
 4349: 
 4350:     $role = "($role)" if $role;
 4351:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4352: 
 4353:     if ($env{'environment.remote'} eq 'off') {
 4354:         # No Remote
 4355: 	if ($env{'request.state'} eq 'construct') {
 4356: 	    $forcereg=1;
 4357: 	}
 4358: 
 4359: #    if ($env{'request.state'} eq 'construct') {
 4360: #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4361: #    }
 4362: 
 4363:         my $titletable = '<table id="LC_title_bar">'
 4364:                         ."<tr><td> $titleinfo $dc_info</td>"
 4365:                         .'</tr></table>';
 4366: 
 4367: 	if ($no_nav_bar) {
 4368: 	    $bodytag .= $titletable;
 4369: 	} else {
 4370:         $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4371:             <em>$realm</em> $dc_info</div>| unless $env{'form.inhibitmenu'};
 4372: 
 4373: 	    if ($env{'request.state'} eq 'construct') {
 4374:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$titletable);
 4375:             } else {
 4376:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg).$titletable;
 4377:             }
 4378:         }
 4379:         return $bodytag;
 4380:     }
 4381: 
 4382: #
 4383: # Top frame rendering, Remote is up
 4384: #
 4385: 
 4386:     my $imgsrc = $img;
 4387:     if ($img =~ /^\/adm/) {
 4388:         $imgsrc = &lonhttpdurl($img);
 4389:     }
 4390:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4391: 
 4392:     # Explicit link to get inline menu
 4393:     my $menu= ($no_inline_link?''
 4394: 	       :'<a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4395:     $bodytag .= qq|<div id="LC_nav_bar">$name $role
 4396:             <em>$realm</em> $dc_info </div>
 4397:             <ol class="LC_smallMenu LC_right">
 4398:                 <li>$menu</li>
 4399:             </ol>| unless $env{'form.inhibitmenu'};
 4400:     #
 4401:     return(<<ENDBODY);
 4402: $bodytag
 4403: <table id="LC_title_bar" class="LC_with_remote">
 4404: <tr><td>$upperleft</td>
 4405:     <td>$messages&nbsp;</td>
 4406: </tr>
 4407: <tr><td>$titleinfo $dc_info $menu</td>
 4408: </tr>
 4409: </table>
 4410: ENDBODY
 4411: }
 4412: 
 4413: sub make_attr_string {
 4414:     my ($register,$attr_ref) = @_;
 4415: 
 4416:     if ($attr_ref && !ref($attr_ref)) {
 4417: 	die("addentries Must be a hash ref ".
 4418: 	    join(':',caller(1))." ".
 4419: 	    join(':',caller(0))." ");
 4420:     }
 4421: 
 4422:     if ($register) {
 4423: 	my ($on_load,$on_unload);
 4424: 	foreach my $key (keys(%{$attr_ref})) {
 4425: 	    if      (lc($key) eq 'onload') {
 4426: 		$on_load.=$attr_ref->{$key}.';';
 4427: 		delete($attr_ref->{$key});
 4428: 
 4429: 	    } elsif (lc($key) eq 'onunload') {
 4430: 		$on_unload.=$attr_ref->{$key}.';';
 4431: 		delete($attr_ref->{$key});
 4432: 	    }
 4433: 	}
 4434: 	$attr_ref->{'onload'}  =
 4435: 	    &Apache::lonmenu::loadevents().  $on_load;
 4436: 	$attr_ref->{'onunload'}=
 4437: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4438:     }
 4439: 
 4440: # Accessibility font enhance
 4441:     if ($env{'browser.fontenhance'} eq 'on') {
 4442: 	my $style;
 4443: 	foreach my $key (keys(%{$attr_ref})) {
 4444: 	    if (lc($key) eq 'style') {
 4445: 		$style.=$attr_ref->{$key}.';';
 4446: 		delete($attr_ref->{$key});
 4447: 	    }
 4448: 	}
 4449: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4450:     }
 4451: 
 4452:     my $attr_string;
 4453:     foreach my $attr (keys(%$attr_ref)) {
 4454: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4455:     }
 4456:     return $attr_string;
 4457: }
 4458: 
 4459: 
 4460: ###############################################
 4461: ###############################################
 4462: 
 4463: =pod
 4464: 
 4465: =item * &endbodytag()
 4466: 
 4467: Returns a uniform footer for LON-CAPA web pages.
 4468: 
 4469: Inputs: 1 - optional reference to an args hash
 4470: If in the hash, key for noredirectlink has a value which evaluates to true,
 4471: a 'Continue' link is not displayed if the page contains an
 4472: internal redirect in the <head></head> section,
 4473: i.e., $env{'internal.head.redirect'} exists   
 4474: 
 4475: =cut
 4476: 
 4477: sub endbodytag {
 4478:     my ($args) = @_;
 4479:     my $endbodytag='</body>';
 4480:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4481:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4482:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4483: 	    $endbodytag=
 4484: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4485: 	        &mt('Continue').'</a>'.
 4486: 	        $endbodytag;
 4487:         }
 4488:     }
 4489:     return $endbodytag;
 4490: }
 4491: 
 4492: =pod
 4493: 
 4494: =item * &standard_css()
 4495: 
 4496: Returns a style sheet
 4497: 
 4498: Inputs: (all optional)
 4499:             domain         -> force to color decorate a page for a specific
 4500:                                domain
 4501:             function       -> force usage of a specific rolish color scheme
 4502:             bgcolor        -> override the default page bgcolor
 4503: 
 4504: =cut
 4505: 
 4506: sub standard_css {
 4507:     my ($function,$domain,$bgcolor) = @_;
 4508:     $function  = &get_users_function() if (!$function);
 4509:     my $img    = &designparm($function.'.img',   $domain);
 4510:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4511:     my $font   = &designparm($function.'.font',  $domain);
 4512:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4513: #second colour for later usage
 4514:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4515:     my $pgbg_or_bgcolor =
 4516: 	         $bgcolor ||
 4517: 	         &designparm($function.'.pgbg',  $domain);
 4518:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4519:     my $alink  = &designparm($function.'.alink', $domain);
 4520:     my $vlink  = &designparm($function.'.vlink', $domain);
 4521:     my $link   = &designparm($function.'.link',  $domain);
 4522: 
 4523:     my $loginbg = &designparm('login.sidebg',$domain);
 4524:     my $bgcol = &designparm('login.bgcol',$domain);
 4525:     my $textcol = &designparm('login.textcol',$domain);
 4526: 
 4527:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4528:     my $mono                 = 'monospace';
 4529:     my $data_table_head      = $sidebg;
 4530:     my $data_table_light     = '#FAFAFA';
 4531:     my $data_table_dark      = '#F0F0F0';
 4532:     my $data_table_darker    = '#CCCCCC';
 4533:     my $data_table_highlight = '#FFFF00';
 4534:     my $mail_new             = '#FFBB77';
 4535:     my $mail_new_hover       = '#DD9955';
 4536:     my $mail_read            = '#BBBB77';
 4537:     my $mail_read_hover      = '#999944';
 4538:     my $mail_replied         = '#AAAA88';
 4539:     my $mail_replied_hover   = '#888855';
 4540:     my $mail_other           = '#99BBBB';
 4541:     my $mail_other_hover     = '#669999';
 4542:     my $table_header         = '#DDDDDD';
 4543:     my $feedback_link_bg     = '#BBBBBB';
 4544:     my $lg_border_color	     = '#C8C8C8';
 4545: 
 4546:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4547: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4548: 	                                                 : '0 3px 0 4px';
 4549: 
 4550: 
 4551:     return <<END;
 4552: body {
 4553:    font-family: $sans;
 4554:    line-height:130%;
 4555:    font-size:0.83em;
 4556:    color:$font;
 4557: }
 4558: 
 4559: a:link, a:visited { 
 4560:   font-size:100%; 
 4561: }
 4562: 
 4563: a:focus { 
 4564:   color: red;
 4565:   background: yellow 
 4566: }
 4567: 
 4568: hr {
 4569:   clear: both;
 4570:   color: $tabbg;
 4571:   background-color: $tabbg;
 4572:   height: 3px;
 4573:   border: none;
 4574: }
 4575: 
 4576: form, .inline { 
 4577:    display: inline; 
 4578: }
 4579: 
 4580: .LC_right {
 4581:    text-align:right;
 4582: }
 4583: 
 4584: .LC_middle {
 4585:    vertical-align:middle;
 4586: }
 4587: 
 4588: /* just for tests */
 4589: .LC_400Box {width:400px; }
 4590: /* end */
 4591: 
 4592: .LC_filename {
 4593:   font-family: $mono;
 4594:   white-space:pre;
 4595: }
 4596: 
 4597: .LC_fileicon {
 4598:   border: none;
 4599:   height: 1.3em;
 4600:   vertical-align: text-bottom;
 4601:   margin-right: 0.3em;
 4602:   text-decoration:none;
 4603: }
 4604: 
 4605: .LC_error {
 4606:   color: red;
 4607:   font-size: larger;
 4608: }
 4609: 
 4610: .LC_warning,
 4611: .LC_diff_removed {
 4612:   color: red;
 4613: }
 4614: 
 4615: .LC_info,
 4616: .LC_success,
 4617: .LC_diff_added {
 4618:   color: green;
 4619: }
 4620: 
 4621: div.LC_confirm_box {
 4622:   background-color: #FAFAFA;
 4623:   border: 1px solid $lg_border_color;
 4624:   margin-right: 0;
 4625:   padding: 5px;
 4626: }
 4627: 
 4628: div.LC_confirm_box .LC_error img,
 4629: div.LC_confirm_box .LC_success img {
 4630:   vertical-align: middle;
 4631: }
 4632: 
 4633: .LC_icon {
 4634:   border: none;
 4635:   vertical-align: middle;
 4636: }
 4637: 
 4638: .LC_docs_spacer {
 4639:   width: 25px;
 4640:   height: 1px;
 4641:   border: none;
 4642: }
 4643: 
 4644: .LC_internal_info {
 4645:   color: #999999;
 4646: }
 4647: 
 4648: .LC_discussion {
 4649:    background: $tabbg;
 4650:    border: 1px solid black;
 4651:    margin: 2px;
 4652: }
 4653: 
 4654: .LC_disc_action_links_bar {
 4655:    background: $tabbg;
 4656:    border: none;
 4657:    margin: 4px;
 4658: }
 4659: 
 4660: .LC_disc_action_left {
 4661:    text-align: left;
 4662: }
 4663: 
 4664: .LC_disc_action_right {
 4665:    text-align: right;
 4666: }
 4667: 
 4668: .LC_disc_new_item {
 4669:    background: white;
 4670:    border: 2px solid red;
 4671:    margin: 2px;
 4672: }
 4673: 
 4674: .LC_disc_old_item {
 4675:    background: white;
 4676:    border: 1px solid black;
 4677:    margin: 2px;
 4678: }
 4679: 
 4680: table.LC_pastsubmission {
 4681:   border: 1px solid black;
 4682:   margin: 2px;
 4683: }
 4684: 
 4685: table#LC_top_nav,
 4686: table#LC_menubuttons,
 4687: table#LC_nav_location {
 4688:   width: 100%;
 4689:   background: $pgbg;
 4690:   border: 2px;
 4691:   border-collapse: separate;
 4692:   padding: 0;
 4693: }
 4694: 
 4695: table#LC_title_bar a {
 4696:   color: $fontmenu;
 4697: }
 4698: 
 4699: table#LC_title_bar {
 4700:   clear: both;
 4701:   display: none;
 4702: }
 4703: 
 4704: table#LC_title_bar,
 4705: table.LC_breadcrumbs,
 4706: table#LC_title_bar.LC_with_remote {
 4707:   width: 100%;
 4708:   border-color: $pgbg;
 4709:   border-style: solid;
 4710:   border-width: $border;
 4711:   background: $pgbg;
 4712:   color: $fontmenu;
 4713:   border-collapse: collapse;
 4714:   padding: 0;
 4715:   margin: 0;
 4716: }
 4717: 
 4718: table#LC_title_bar td {
 4719:   background: $tabbg;
 4720: }
 4721: 
 4722: table#LC_menubuttons img{
 4723:   border: none;
 4724: }
 4725: 
 4726: table#LC_top_nav td {
 4727:   background: $tabbg;
 4728:   border: none;
 4729:   font-size: small;
 4730:   vertical-align:top;
 4731:   padding:2px 5px 2px 5px;
 4732: }
 4733: 
 4734: table#LC_top_nav td a,
 4735: div#LC_top_nav a {
 4736:   color: $font;
 4737: }
 4738: 
 4739: table#LC_top_nav td.LC_top_nav_logo {
 4740:   background: $tabbg;
 4741:   text-align: left;
 4742:   white-space: nowrap;
 4743:   width: 31px;
 4744: }
 4745: 
 4746: table#LC_top_nav td.LC_top_nav_logo img {
 4747:   border: none;
 4748:   vertical-align: bottom;
 4749: }
 4750: 
 4751: table#LC_top_nav td.LC_top_nav_exit,
 4752: table#LC_top_nav td.LC_top_nav_help {
 4753:   width: 2.0em;
 4754: }
 4755: 
 4756: table#LC_top_nav td.LC_top_nav_login {
 4757:   width: 4.0em;
 4758:   text-align: center;
 4759: }
 4760: 
 4761: .LC_breadcrumbs_component {
 4762:     float: right;
 4763:     margin: 0 1em;
 4764: }
 4765: .LC_breadcrumbs_component img {
 4766:     vertical-align: middle;
 4767: }
 4768: 
 4769: td.LC_table_cell_checkbox {
 4770:   text-align: center;
 4771: }
 4772: 
 4773: table#LC_mainmenu td.LC_mainmenu_column {
 4774:     vertical-align: top;
 4775: }
 4776: 
 4777: .LC_fontsize_small {
 4778:  font-size: 70%;
 4779: }
 4780: 
 4781: #LC_breadcrumbs {
 4782:  clear:both;
 4783:  background: $sidebg;
 4784:  border-bottom: 1px solid $lg_border_color;
 4785:  line-height: 32px; 
 4786:  margin: 0;
 4787:  padding: 0;
 4788: }
 4789: 
 4790: /* Preliminary fix to hide breadcrumbs inside remote control window */
 4791: #LC_remote #LC_breadcrumbs {
 4792:     display:none;
 4793: }
 4794: 
 4795: #LC_head_subbox {
 4796:  clear:both;
 4797:  background: #F8F8F8; /* $sidebg; */
 4798:  border-bottom: 1px solid $lg_border_color;
 4799:  margin: 0 0 10px 0;
 4800:  padding: 5px;
 4801: }
 4802: 
 4803: .LC_fontsize_medium {
 4804:  font-size: 85%;
 4805: }
 4806: 
 4807: .LC_fontsize_large {
 4808:  font-size: 120%;
 4809: }
 4810: 
 4811: .LC_menubuttons_inline_text {
 4812:   color: $font;
 4813:   font-size: 90%;
 4814:   padding-left:3px;
 4815: }
 4816: 
 4817: .LC_menubuttons_link {
 4818:   text-decoration: none;
 4819: }
 4820: 
 4821: .LC_menubuttons_category {
 4822:   color: $font;
 4823:   background: $pgbg;
 4824:   font-size: larger;
 4825:   font-weight: bold;
 4826: }
 4827: 
 4828: td.LC_menubuttons_text {
 4829:  	color: $font;
 4830: }
 4831: 
 4832: .LC_current_location {
 4833:   background: $tabbg;
 4834: }
 4835: 
 4836: .LC_new_mail {
 4837:   background: $tabbg;
 4838:   font-weight: bold;
 4839: }
 4840: 
 4841: .LC_roleslog_note {
 4842:   font-size: small;
 4843: }
 4844: 
 4845: table.LC_data_table,
 4846: table.LC_mail_list {
 4847:   border: 1px solid #000000;
 4848:   border-collapse: separate;
 4849:   border-spacing: 1px;
 4850:   background: $pgbg;
 4851: }
 4852: 
 4853: .LC_data_table_dense {
 4854:   font-size: small;
 4855: }
 4856: 
 4857: table.LC_nested_outer {
 4858:   border: 1px solid #000000;
 4859:   border-collapse: collapse;
 4860:   border-spacing: 0;
 4861:   width: 100%;
 4862: }
 4863: 
 4864: table.LC_nested {
 4865:   border: none;
 4866:   border-collapse: collapse;
 4867:   border-spacing: 0;
 4868:   width: 100%;
 4869: }
 4870: 
 4871: table.LC_data_table tr th, 
 4872: table.LC_calendar tr th, 
 4873: table.LC_mail_list tr th,
 4874: table.LC_prior_tries tr th {
 4875:   font-weight: bold;
 4876:   background-color: $data_table_head;
 4877:   color:$fontmenu;
 4878:   font-size:90%;
 4879: }
 4880: 
 4881: table.LC_data_table tr.LC_info_row > td {
 4882:   background-color: #CCCCCC;
 4883:   font-weight: bold;
 4884:   text-align: left;
 4885: }
 4886: 
 4887: table.LC_data_table tr.LC_odd_row > td,
 4888: table.LC_pick_box tr > td.LC_odd_row {
 4889:   background-color: $data_table_light;
 4890:   padding: 2px;
 4891: }
 4892: 
 4893: table.LC_data_table tr.LC_even_row > td,
 4894: table.LC_pick_box tr > td.LC_even_row {
 4895:   background-color: $data_table_dark;
 4896:   padding: 2px;
 4897: }
 4898: 
 4899: table.LC_data_table tr.LC_data_table_highlight td {
 4900:   background-color: $data_table_darker;
 4901: }
 4902: 
 4903: table.LC_data_table tr td.LC_leftcol_header {
 4904:   background-color: $data_table_head;
 4905:   font-weight: bold;
 4906: }
 4907: 
 4908: table.LC_data_table tr.LC_empty_row td,
 4909: table.LC_nested tr.LC_empty_row td {
 4910:   background-color: #FFFFFF;
 4911:   font-weight: bold;
 4912:   font-style: italic;
 4913:   text-align: center;
 4914:   padding: 8px;
 4915: }
 4916: 
 4917: table.LC_nested tr.LC_empty_row td {
 4918:   padding: 4ex
 4919: }
 4920: 
 4921: table.LC_nested_outer tr th {
 4922:   font-weight: bold;
 4923:   color:$fontmenu;
 4924:   background-color: $data_table_head;
 4925:   font-size: small;
 4926:   border-bottom: 1px solid #000000;
 4927: }
 4928: 
 4929: table.LC_nested_outer tr td.LC_subheader {
 4930:   background-color: $data_table_head;
 4931:   font-weight: bold;
 4932:   font-size: small;
 4933:   border-bottom: 1px solid #000000;
 4934:   text-align: right;
 4935: }
 4936: 
 4937: table.LC_nested tr.LC_info_row td {
 4938:   background-color: #CCCCCC;
 4939:   font-weight: bold;
 4940:   font-size: small;
 4941:   text-align: center;
 4942: }
 4943: 
 4944: table.LC_nested tr.LC_info_row td.LC_left_item,
 4945: table.LC_nested_outer tr th.LC_left_item {
 4946:   text-align: left;
 4947: }
 4948: 
 4949: table.LC_nested td {
 4950:   background-color: #FFFFFF;
 4951:   font-size: small;
 4952: }
 4953: 
 4954: table.LC_nested_outer tr th.LC_right_item,
 4955: table.LC_nested tr.LC_info_row td.LC_right_item,
 4956: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4957: table.LC_nested tr td.LC_right_item {
 4958:   text-align: right;
 4959: }
 4960: 
 4961: table.LC_nested tr.LC_odd_row td {
 4962:   background-color: #EEEEEE;
 4963: }
 4964: 
 4965: table.LC_createuser {
 4966: }
 4967: 
 4968: table.LC_createuser tr.LC_section_row td {
 4969:   font-size: small;
 4970: }
 4971: 
 4972: table.LC_createuser tr.LC_info_row td  {
 4973:   background-color: #CCCCCC;
 4974:   font-weight: bold;
 4975:   text-align: center;
 4976: }
 4977: 
 4978: table.LC_calendar {
 4979:   border: 1px solid #000000;
 4980:   border-collapse: collapse;
 4981: }
 4982: 
 4983: table.LC_calendar_pickdate {
 4984:   font-size: xx-small;
 4985: }
 4986: 
 4987: table.LC_calendar tr td {
 4988:   border: 1px solid #000000;
 4989:   vertical-align: top;
 4990: }
 4991: 
 4992: table.LC_calendar tr td.LC_calendar_day_empty {
 4993:   background-color: $data_table_dark;
 4994: }
 4995: 
 4996: table.LC_calendar tr td.LC_calendar_day_current {
 4997:   background-color: $data_table_highlight;
 4998: }
 4999: 
 5000: table.LC_mail_list tr.LC_mail_new {
 5001:   background-color: $mail_new;
 5002: }
 5003: 
 5004: table.LC_mail_list tr.LC_mail_new:hover {
 5005:   background-color: $mail_new_hover;
 5006: }
 5007: 
 5008: table.LC_mail_list tr.LC_mail_even {
 5009: }
 5010: 
 5011: table.LC_mail_list tr.LC_mail_odd {
 5012: }
 5013: 
 5014: table.LC_mail_list tr.LC_mail_read {
 5015:   background-color: $mail_read;
 5016: }
 5017: 
 5018: table.LC_mail_list tr.LC_mail_read:hover {
 5019:   background-color: $mail_read_hover;
 5020: }
 5021: 
 5022: table.LC_mail_list tr.LC_mail_replied {
 5023:   background-color: $mail_replied;
 5024: }
 5025: 
 5026: table.LC_mail_list tr.LC_mail_replied:hover {
 5027:   background-color: $mail_replied_hover;
 5028: }
 5029: 
 5030: table.LC_mail_list tr.LC_mail_other {
 5031:   background-color: $mail_other;
 5032: }
 5033: 
 5034: table.LC_mail_list tr.LC_mail_other:hover {
 5035:   background-color: $mail_other_hover;
 5036: }
 5037: 
 5038: table.LC_data_table tr > td.LC_browser_file,
 5039: table.LC_data_table tr > td.LC_browser_file_published {
 5040:   background: #CCFF88;
 5041: }
 5042: 
 5043: table.LC_data_table tr > td.LC_browser_file_locked,
 5044: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5045:   background: #FFAA99;
 5046: }
 5047: 
 5048: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5049:   background: #AAAAAA;
 5050: }
 5051: 
 5052: table.LC_data_table tr > td.LC_browser_file_modified,
 5053: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5054:   background: #FFFF77;
 5055: }
 5056: 
 5057: table.LC_data_table tr.LC_browser_folder > td {
 5058:   background: #CCCCFF;
 5059: }
 5060: 
 5061: table.LC_data_table tr > td.LC_roles_is {
 5062: /*  background: #77FF77; */
 5063: }
 5064: 
 5065: table.LC_data_table tr > td.LC_roles_future {
 5066:   background: #FFFF77;
 5067: }
 5068: 
 5069: table.LC_data_table tr > td.LC_roles_will {
 5070:   background: #FFAA77;
 5071: }
 5072: 
 5073: table.LC_data_table tr > td.LC_roles_expired {
 5074:   background: #FF7777;
 5075: }
 5076: 
 5077: table.LC_data_table tr > td.LC_roles_will_not {
 5078:   background: #AAFF77;
 5079: }
 5080: 
 5081: table.LC_data_table tr > td.LC_roles_selected {
 5082:   background: #11CC55;
 5083: }
 5084: 
 5085: span.LC_current_location {
 5086:   font-size:larger;
 5087:   background: $pgbg;
 5088: }
 5089: 
 5090: span.LC_parm_menu_item {
 5091:   font-size: larger;
 5092: }
 5093: 
 5094: span.LC_parm_scope_all {
 5095:   color: red;
 5096: }
 5097: 
 5098: span.LC_parm_scope_folder {
 5099:   color: green;
 5100: }
 5101: 
 5102: span.LC_parm_scope_resource {
 5103:   color: orange;
 5104: }
 5105: 
 5106: span.LC_parm_part {
 5107:   color: blue;
 5108: }
 5109: 
 5110: span.LC_parm_folder, span.LC_parm_symb {
 5111:   font-size: x-small;
 5112:   font-family: $mono;
 5113:   color: #AAAAAA;
 5114: }
 5115: 
 5116: td.LC_parm_overview_level_menu,
 5117: td.LC_parm_overview_map_menu,
 5118: td.LC_parm_overview_parm_selectors,
 5119: td.LC_parm_overview_restrictions  {
 5120:   border: 1px solid black;
 5121:   border-collapse: collapse;
 5122: }
 5123: 
 5124: table.LC_parm_overview_restrictions td {
 5125:   border-width: 1px 4px 1px 4px;
 5126:   border-style: solid;
 5127:   border-color: $pgbg;
 5128:   text-align: center;
 5129: }
 5130: 
 5131: table.LC_parm_overview_restrictions th {
 5132:   background: $tabbg;
 5133:   border-width: 1px 4px 1px 4px;
 5134:   border-style: solid;
 5135:   border-color: $pgbg;
 5136: }
 5137: 
 5138: table#LC_helpmenu {
 5139:   border: none;
 5140:   height: 55px;
 5141:   border-spacing: 0;
 5142: }
 5143: 
 5144: table#LC_helpmenu fieldset legend {
 5145:   font-size: larger;
 5146: }
 5147: 
 5148: table#LC_helpmenu_links {
 5149:   width: 100%;
 5150:   border: 1px solid black;
 5151:   background: $pgbg;
 5152:   padding: 0;
 5153:   border-spacing: 1px;
 5154: }
 5155: 
 5156: table#LC_helpmenu_links tr td {
 5157:   padding: 1px;
 5158:   background: $tabbg;
 5159:   text-align: center;
 5160:   font-weight: bold;
 5161: }
 5162: 
 5163: table#LC_helpmenu_links a:link,
 5164: table#LC_helpmenu_links a:visited,
 5165: table#LC_helpmenu_links a:active {
 5166:   text-decoration: none;
 5167:   color: $font;
 5168: }
 5169: 
 5170: table#LC_helpmenu_links a:hover {
 5171:   text-decoration: underline;
 5172:   color: $vlink;
 5173: }
 5174: 
 5175: .LC_chrt_popup_exists {
 5176:   border: 1px solid #339933;
 5177:   margin: -1px;
 5178: }
 5179: 
 5180: .LC_chrt_popup_up {
 5181:   border: 1px solid yellow;
 5182:   margin: -1px;
 5183: }
 5184: 
 5185: .LC_chrt_popup {
 5186:   border: 1px solid #8888FF;
 5187:   background: #CCCCFF;
 5188: }
 5189: 
 5190: table.LC_pick_box {
 5191:   border-collapse: separate;
 5192:   background: white;
 5193:   border: 1px solid black;
 5194:   border-spacing: 1px;
 5195: }
 5196: 
 5197: table.LC_pick_box td.LC_pick_box_title {
 5198:   background: $sidebg;
 5199:   font-weight: bold;
 5200:   text-align: right;
 5201:   vertical-align: top;
 5202:   width: 184px;
 5203:   padding: 8px;
 5204: }
 5205: 
 5206: table.LC_pick_box td.LC_pick_box_value {
 5207:   text-align: left;
 5208:   padding: 8px;
 5209: }
 5210: 
 5211: table.LC_pick_box td.LC_pick_box_select {
 5212:   text-align: left;
 5213:   padding: 8px;
 5214: }
 5215: 
 5216: table.LC_pick_box td.LC_pick_box_separator {
 5217:   padding: 0;
 5218:   height: 1px;
 5219:   background: black;
 5220: }
 5221: 
 5222: table.LC_pick_box td.LC_pick_box_submit {
 5223:   text-align: right;
 5224: }
 5225: 
 5226: table.LC_pick_box td.LC_evenrow_value {
 5227:   text-align: left;
 5228:   padding: 8px;
 5229:   background-color: $data_table_light;
 5230: }
 5231: 
 5232: table.LC_pick_box td.LC_oddrow_value {
 5233:   text-align: left;
 5234:   padding: 8px;
 5235:   background-color: $data_table_light;
 5236: }
 5237: 
 5238: table.LC_helpform_receipt {
 5239:   width: 620px;
 5240:   border-collapse: separate;
 5241:   background: white;
 5242:   border: 1px solid black;
 5243:   border-spacing: 1px;
 5244: }
 5245: 
 5246: table.LC_helpform_receipt td.LC_pick_box_title {
 5247:   background: $tabbg;
 5248:   font-weight: bold;
 5249:   text-align: right;
 5250:   width: 184px;
 5251:   padding: 8px;
 5252: }
 5253: 
 5254: table.LC_helpform_receipt td.LC_evenrow_value {
 5255:   text-align: left;
 5256:   padding: 8px;
 5257:   background-color: $data_table_light;
 5258: }
 5259: 
 5260: table.LC_helpform_receipt td.LC_oddrow_value {
 5261:   text-align: left;
 5262:   padding: 8px;
 5263:   background-color: $data_table_light;
 5264: }
 5265: 
 5266: table.LC_helpform_receipt td.LC_pick_box_separator {
 5267:   padding: 0;
 5268:   height: 1px;
 5269:   background: black;
 5270: }
 5271: 
 5272: span.LC_helpform_receipt_cat {
 5273:   font-weight: bold;
 5274: }
 5275: 
 5276: table.LC_group_priv_box {
 5277:   background: white;
 5278:   border: 1px solid black;
 5279:   border-spacing: 1px;
 5280: }
 5281: 
 5282: table.LC_group_priv_box td.LC_pick_box_title {
 5283:   background: $tabbg;
 5284:   font-weight: bold;
 5285:   text-align: right;
 5286:   width: 184px;
 5287: }
 5288: 
 5289: table.LC_group_priv_box td.LC_groups_fixed {
 5290:   background: $data_table_light;
 5291:   text-align: center;
 5292: }
 5293: 
 5294: table.LC_group_priv_box td.LC_groups_optional {
 5295:   background: $data_table_dark;
 5296:   text-align: center;
 5297: }
 5298: 
 5299: table.LC_group_priv_box td.LC_groups_functionality {
 5300:   background: $data_table_darker;
 5301:   text-align: center;
 5302:   font-weight: bold;
 5303: }
 5304: 
 5305: table.LC_group_priv td {
 5306:   text-align: left;
 5307:   padding: 0;
 5308: }
 5309: 
 5310: table.LC_notify_front_page {
 5311:   background: white;
 5312:   border: 1px solid black;
 5313:   padding: 8px;
 5314: }
 5315: 
 5316: table.LC_notify_front_page td {
 5317:   padding: 8px;
 5318: }
 5319: 
 5320: .LC_navbuttons {
 5321:   margin: 2ex 0ex 2ex 0ex;
 5322: }
 5323: 
 5324: .LC_topic_bar {
 5325:   font-weight: bold;
 5326:   width: 100%;
 5327:   background: $tabbg;
 5328:   vertical-align: middle;
 5329:   margin: 2ex 0ex 2ex 0ex;
 5330:   padding: 3px;
 5331: }
 5332: 
 5333: .LC_topic_bar span {
 5334:   vertical-align: middle;
 5335: }
 5336: 
 5337: .LC_topic_bar img {
 5338:   vertical-align: bottom;
 5339: }
 5340: 
 5341: table.LC_course_group_status {
 5342:   margin: 20px;
 5343: }
 5344: 
 5345: table.LC_status_selector td {
 5346:   vertical-align: top;
 5347:   text-align: center;
 5348:   padding: 4px;
 5349: }
 5350: 
 5351: div.LC_feedback_link {
 5352:   clear: both;
 5353:   background: $sidebg;
 5354:   width: 100%;
 5355:   padding-bottom: 10px;
 5356:   border: 1px $tabbg solid;
 5357:   height: 22px;
 5358:   line-height: 22px;
 5359:   padding-top: 5px;
 5360: }
 5361: 
 5362: div.LC_feedback_link img {
 5363:   height: 22px;
 5364:   vertical-align:middle;
 5365: }
 5366: 
 5367: div.LC_feedback_link a{
 5368:   text-decoration: none;
 5369: }
 5370: 
 5371: div.LC_comblock {
 5372:   display:inline; 
 5373:   color:$font;
 5374:   font-size:90%;
 5375: }
 5376: 
 5377: div.LC_feedback_link div.LC_comblock {
 5378:   padding-left:5px;
 5379: }
 5380: 
 5381: div.LC_feedback_link div.LC_comblock a {
 5382:   color:$font;
 5383: }
 5384: 
 5385: span.LC_feedback_link {
 5386:   /* background: $feedback_link_bg; */
 5387:   font-size: larger;
 5388: }
 5389: 
 5390: span.LC_message_link {
 5391:   /* background: $feedback_link_bg; */
 5392:   font-size: larger;
 5393:   position: absolute;
 5394:   right: 1em;
 5395: }
 5396: 
 5397: table.LC_prior_tries {
 5398:   border: 1px solid #000000;
 5399:   border-collapse: separate;
 5400:   border-spacing: 1px;
 5401: }
 5402: 
 5403: table.LC_prior_tries td {
 5404:   padding: 2px;
 5405: }
 5406: 
 5407: .LC_answer_correct {
 5408:   background: lightgreen;
 5409:   color: darkgreen;
 5410:   padding: 6px;
 5411: }
 5412: 
 5413: .LC_answer_charged_try {
 5414:   background: #FFAAAA;
 5415:   color: darkred;
 5416:   padding: 6px;
 5417: }
 5418: 
 5419: .LC_answer_not_charged_try,
 5420: .LC_answer_no_grade,
 5421: .LC_answer_late {
 5422:   background: lightyellow;
 5423:   color: black;
 5424:   padding: 6px;
 5425: }
 5426: 
 5427: .LC_answer_previous {
 5428:   background: lightblue;
 5429:   color: darkblue;
 5430:   padding: 6px;
 5431: }
 5432: 
 5433: .LC_answer_no_message {
 5434:   background: #FFFFFF;
 5435:   color: black;
 5436:   padding: 6px;
 5437: }
 5438: 
 5439: .LC_answer_unknown {
 5440:   background: orange;
 5441:   color: black;
 5442:   padding: 6px;
 5443: }
 5444: 
 5445: span.LC_prior_numerical,
 5446: span.LC_prior_string,
 5447: span.LC_prior_custom,
 5448: span.LC_prior_reaction,
 5449: span.LC_prior_math {
 5450:   font-family: monospace;
 5451:   white-space: pre;
 5452: }
 5453: 
 5454: span.LC_prior_string {
 5455:   font-family: monospace;
 5456:   white-space: pre;
 5457: }
 5458: 
 5459: table.LC_prior_option {
 5460:   width: 100%;
 5461:   border-collapse: collapse;
 5462: }
 5463: 
 5464: table.LC_prior_rank, 
 5465: table.LC_prior_match {
 5466:   border-collapse: collapse;
 5467: }
 5468: 
 5469: table.LC_prior_option tr td,
 5470: table.LC_prior_rank tr td,
 5471: table.LC_prior_match tr td {
 5472:   border: 1px solid #000000;
 5473: }
 5474: 
 5475: .LC_nobreak {
 5476:   white-space: nowrap;
 5477: }
 5478: 
 5479: span.LC_cusr_emph {
 5480:   font-style: italic;
 5481: }
 5482: 
 5483: span.LC_cusr_subheading {
 5484:   font-weight: normal;
 5485:   font-size: 85%;
 5486: }
 5487: 
 5488: table.LC_docs_documents {
 5489:   background: #BBBBBB;
 5490:   border-width: 0;
 5491:   border-collapse: collapse;
 5492: }
 5493: 
 5494: table.LC_docs_documents td.LC_docs_document {
 5495:   border: 2px solid black;
 5496:   padding: 4px;
 5497: }
 5498: 
 5499: div.LC_docs_entry_move {
 5500:   border: 1px solid #BBBBBB;
 5501:   background: #DDDDDD;
 5502:   width: 22px;
 5503:   padding: 1px;
 5504:   margin: 0;
 5505: }
 5506: 
 5507: table.LC_data_table tr > td.LC_docs_entry_commands,
 5508: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5509:   background: #DDDDDD;
 5510:   font-size: x-small;
 5511: }
 5512: 
 5513: .LC_docs_entry_parameter {
 5514:   white-space: nowrap;
 5515: }
 5516: 
 5517: .LC_docs_copy {
 5518:   color: #000099;
 5519: }
 5520: 
 5521: .LC_docs_cut {
 5522:   color: #550044;
 5523: }
 5524: 
 5525: .LC_docs_rename {
 5526:   color: #009900;
 5527: }
 5528: 
 5529: .LC_docs_remove {
 5530:   color: #990000;
 5531: }
 5532: 
 5533: .LC_docs_reinit_warn,
 5534: .LC_docs_ext_edit {
 5535:   font-size: x-small;
 5536: }
 5537: 
 5538: table.LC_docs_adddocs td,
 5539: table.LC_docs_adddocs th {
 5540:   border: 1px solid #BBBBBB;
 5541:   padding: 4px;
 5542:   background: #DDDDDD;
 5543: }
 5544: 
 5545: table.LC_sty_begin {
 5546:   background: #BBFFBB;
 5547: }
 5548: 
 5549: table.LC_sty_end {
 5550:   background: #FFBBBB;
 5551: }
 5552: 
 5553: table.LC_double_column {
 5554:   border-width: 0;
 5555:   border-collapse: collapse;
 5556:   width: 100%;
 5557:   padding: 2px;
 5558: }
 5559: 
 5560: table.LC_double_column tr td.LC_left_col {
 5561:   top: 2px;
 5562:   left: 2px;
 5563:   width: 47%;
 5564:   vertical-align: top;
 5565: }
 5566: 
 5567: table.LC_double_column tr td.LC_right_col {
 5568:   top: 2px;
 5569:   right: 2px;
 5570:   width: 47%;
 5571:   vertical-align: top;
 5572: }
 5573: 
 5574: span.LC_role_level {
 5575:   font-weight: bold;
 5576: }
 5577: 
 5578: div.LC_left_float {
 5579:   float: left;
 5580:   padding-right: 5%;
 5581:   padding-bottom: 4px;
 5582: }
 5583: 
 5584: div.LC_clear_float_header {
 5585:   padding-bottom: 2px;
 5586: }
 5587: 
 5588: div.LC_clear_float_footer {
 5589:   padding-top: 10px;
 5590:   clear: both;
 5591: }
 5592: 
 5593: div.LC_grade_show_user {
 5594:   margin-top: 20px;
 5595:   border: 1px solid black;
 5596: }
 5597: 
 5598: div.LC_grade_user_name {
 5599:   background: #DDDDEE;
 5600:   border-bottom: 1px solid black;
 5601:   font-weight: bold;
 5602:   font-size: large;
 5603: }
 5604: 
 5605: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5606:   background: #DDEEDD;
 5607: }
 5608: 
 5609: div.LC_grade_show_problem,
 5610: div.LC_grade_submissions,
 5611: div.LC_grade_message_center,
 5612: div.LC_grade_info_links,
 5613: div.LC_grade_assign {
 5614:   margin: 5px;
 5615:   width: 99%;
 5616:   background: #FFFFFF;
 5617: }
 5618: 
 5619: div.LC_grade_show_problem_header,
 5620: div.LC_grade_submissions_header,
 5621: div.LC_grade_message_center_header,
 5622: div.LC_grade_assign_header {
 5623:   font-weight: bold;
 5624:   font-size: large;
 5625: }
 5626: 
 5627: div.LC_grade_show_problem_problem,
 5628: div.LC_grade_submissions_body,
 5629: div.LC_grade_message_center_body,
 5630: div.LC_grade_assign_body {
 5631:   border: 1px solid black;
 5632:   width: 99%;
 5633:   background: #FFFFFF;
 5634: }
 5635: 
 5636: span.LC_grade_check_note {
 5637:   font-weight: normal;
 5638:   font-size: medium;
 5639:   display: inline;
 5640:   position: absolute;
 5641:   right: 1em;
 5642: }
 5643: 
 5644: table.LC_scantron_action {
 5645:   width: 100%;
 5646: }
 5647: 
 5648: table.LC_scantron_action tr th {
 5649:   font-weight:bold;
 5650:   font-style:normal;
 5651: }
 5652: 
 5653: .LC_edit_problem_header,
 5654: div.LC_edit_problem_footer {
 5655:   font-weight: normal;
 5656:   font-size:  medium;
 5657:   margin: 2px;
 5658: }
 5659: 
 5660: div.LC_edit_problem_header,
 5661: div.LC_edit_problem_header div,
 5662: div.LC_edit_problem_footer,
 5663: div.LC_edit_problem_footer div,
 5664: div.LC_edit_problem_editxml_header,
 5665: div.LC_edit_problem_editxml_header div {
 5666:   margin-top: 5px;
 5667: }
 5668: 
 5669: div.LC_edit_problem_header_title {
 5670:   font-weight: bold;
 5671:   font-size: larger;
 5672:   background: $tabbg;
 5673:   padding: 3px;
 5674: }
 5675: 
 5676: table.LC_edit_problem_header_title {
 5677:   font-size: larger;
 5678:   font-weight:  bold;
 5679:   width: 100%;
 5680:   border-color: $pgbg;
 5681:   border-style: solid;
 5682:   border-width: $border;
 5683:   background: $tabbg;
 5684:   border-collapse: collapse;
 5685:   padding: 0;
 5686: }
 5687: 
 5688: div.LC_edit_problem_discards {
 5689:   float: left;
 5690:   padding-bottom: 5px;
 5691: }
 5692: 
 5693: div.LC_edit_problem_saves {
 5694:   float: right;
 5695:   padding-bottom: 5px;
 5696: }
 5697: 
 5698: img.stift{
 5699:   border-width: 0;
 5700:   vertical-align: middle;
 5701: }
 5702: 
 5703: table#LC_mainmenu{
 5704:  margin-top:10px;
 5705:  width:80%;
 5706: }
 5707: 
 5708: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5709:   vertical-align: top;
 5710:   width: 45%;
 5711: }
 5712: 
 5713: .LC_mainmenu_fieldset_category {
 5714:   color: $font;
 5715:   background: $pgbg;
 5716:   font-size: small;
 5717:   font-weight: bold;
 5718: }
 5719: 
 5720: div.LC_createcourse {
 5721:     margin: 10px 10px 10px 10px;
 5722: }
 5723: 
 5724: /* ---- Remove when done ----
 5725: # The following styles is part of the redesign of LON-CAPA and are
 5726: # subject to change during this project.
 5727: # Don't rely on their current functionality as they might be 
 5728: # changed or removed.
 5729: # --------------------------*/
 5730: 
 5731: a:hover,
 5732: ol.LC_smallMenu a:hover,
 5733: ol#LC_MenuBreadcrumbs a:hover,
 5734: ol#LC_PathBreadcrumbs a:hover,
 5735: ul#LC_TabMainMenuContent a:hover,
 5736: .LC_FormSectionClearButton input:hover
 5737: ul.LC_TabContent   li:hover a {
 5738: 	color:#BF2317;
 5739:         text-decoration:none;
 5740: }
 5741: 
 5742: h1 {
 5743: 	padding: 0;
 5744: 	line-height:130%;
 5745: }
 5746: 
 5747: h2,h3,h4,h5,h6 {
 5748: 	margin: 5px 0 5px 0;
 5749: 	padding: 0;
 5750: 	line-height:130%;
 5751: }
 5752: 
 5753: .LC_hcell {
 5754:         padding:3px 15px 3px 15px;
 5755:         margin: 0;
 5756: 	background-color:$tabbg;
 5757: 	color:$fontmenu;
 5758: 	border-bottom:solid 1px $lg_border_color;
 5759: }
 5760: 
 5761: .LC_Box > .LC_hcell {
 5762:     margin: 0 -10px 10px -10px;
 5763: }
 5764: 
 5765: .LC_noBorder {
 5766:         border: 0;
 5767: }
 5768: 
 5769: .LC_Right {
 5770:         float: right;
 5771:         margin: 0;
 5772:         padding: 0;
 5773: }
 5774: 
 5775: .LC_FormSectionClearButton input {
 5776:         background-color:transparent;
 5777:         border: none;
 5778:         cursor:pointer;
 5779:         text-decoration:underline;
 5780: }
 5781: 
 5782: .LC_help_open_topic {
 5783:         color: #FFFFFF;
 5784:         background-color: #EEEEFF;
 5785:         margin: 1px;
 5786:         padding: 4px;
 5787:         border: 1px solid #000033;
 5788:         white-space: nowrap;
 5789: /*		vertical-align: middle; */
 5790: }
 5791: 
 5792: dl,ul,div,fieldset {
 5793: 	margin: 10px 10px 10px 0;
 5794: /*	overflow: hidden; */
 5795: }
 5796: 
 5797: fieldset > legend {
 5798:     font-weight: bold;
 5799:     padding: 0 5px 0 5px;
 5800: }
 5801: 
 5802: #LC_nav_bar {
 5803:     float: left;
 5804:     margin: 0.2em 0 0 0;
 5805: }
 5806: 
 5807: #LC_nav_bar em{
 5808:     font-weight: bold;
 5809:     font-style: normal;
 5810: }
 5811: 
 5812: ol.LC_smallMenu {
 5813:     float: right;
 5814:     margin: 0.2em 0 0 0;
 5815: }
 5816: 
 5817: ol#LC_PathBreadcrumbs {
 5818: 	margin: 0;
 5819: }
 5820: 
 5821: ol.LC_smallMenu li {
 5822: 	display: inline;
 5823: 	padding: 5px 5px 0 10px;
 5824: 	vertical-align: top;
 5825: }
 5826: 
 5827: ol.LC_smallMenu li img {
 5828: 	vertical-align: bottom;
 5829: }
 5830: 
 5831: ol.LC_smallMenu a {
 5832: 	font-size: 90%;
 5833: 	color: RGB(80, 80, 80);
 5834: 	text-decoration: none;
 5835: }
 5836: 
 5837: ul#LC_TabMainMenuContent {
 5838:     clear: both;
 5839:     color: $fontmenu;
 5840:     background: $tabbg;
 5841:     list-style: none;
 5842:     padding: 0;
 5843:     margin: 0;
 5844:     width: 100%;
 5845: }
 5846: 
 5847: ul#LC_TabMainMenuContent li {
 5848:     font-weight: bold;
 5849:     line-height: 1.8em;
 5850:     padding: 0 0.8em; 
 5851:     border-right: 1px solid black;
 5852:     display: inline;
 5853:     vertical-align: middle;
 5854: }
 5855: 
 5856: ul.LC_TabContent {
 5857: 	display:block;
 5858: 	background: $sidebg;
 5859: 	border-bottom: solid 1px $lg_border_color;
 5860: 	list-style:none;
 5861: 	margin: 0 -10px;
 5862: 	padding: 0;
 5863: }
 5864: 
 5865: ul.LC_TabContent li,
 5866: ul.LC_TabContentBigger li {
 5867: 	float:left;
 5868: }
 5869: 
 5870: ul#LC_TabMainMenuContent li a {
 5871:     color: $fontmenu;
 5872: 	text-decoration: none;
 5873: }
 5874: 
 5875: ul.LC_TabContent {
 5876: 	min-height:1.5em;
 5877: }
 5878: 
 5879: ul.LC_TabContent li {
 5880: 	vertical-align:middle;
 5881: 	padding: 0 10px 0 10px;
 5882: 	background-color:$tabbg;
 5883: 	border-bottom:solid 1px $lg_border_color;
 5884: }
 5885: 
 5886: ul.LC_TabContent .right {
 5887: 	float:right;
 5888: }
 5889: 
 5890: ul.LC_TabContent li a, ul.LC_TabContent li {
 5891: 	color:rgb(47,47,47);
 5892: 	text-decoration:none;
 5893: 	font-size:95%;
 5894: 	font-weight:bold;
 5895: 	padding-right: 16px;
 5896: }
 5897: 
 5898: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
 5899:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5900: 	border-bottom:solid 2px #FFFFFF;
 5901: 	padding-right: 16px;
 5902: }
 5903: 
 5904: #maincoursedoc {
 5905: 	clear:both;
 5906: }
 5907: 
 5908: ul.LC_TabContentBigger {
 5909:         display:block;
 5910:         list-style:none;
 5911:         padding: 0;
 5912: }
 5913: 
 5914: ul.LC_TabContentBigger li {
 5915:         vertical-align:bottom;
 5916:         height: 30px;
 5917:         font-size:110%;
 5918:         font-weight:bold;
 5919:         color: #737373;
 5920: }
 5921: 
 5922: 
 5923: ul.LC_TabContentBigger li a {
 5924:         background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 5925: 	height: 30px;
 5926: 	line-height: 30px;
 5927: 	text-align: center;
 5928: 	display: block;
 5929: 	text-decoration: none;
 5930: }
 5931: 
 5932: ul.LC_TabContentBigger li:hover a, 
 5933: ul.LC_TabContentBigger li.active a {
 5934: 	background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 5935: 	color:$font;
 5936: 	text-decoration: underline;
 5937: }
 5938: 
 5939: 
 5940: ul.LC_TabContentBigger li b {
 5941: 	background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 5942: 	display: block;
 5943: 	float: left;
 5944: 	padding: 0 30px;
 5945: }
 5946: 
 5947: ul.LC_TabContentBigger li:hover b,
 5948: ul.LC_TabContentBigger li.active b {
 5949:         background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 5950:         color:$font;
 5951: 	border-bottom: 1px solid #FFFFFF;
 5952: }
 5953: 
 5954: 
 5955: ul.LC_CourseBreadcrumbs {
 5956:   background: $sidebg;
 5957:   line-height: 32px;
 5958:   padding-left: 10px;
 5959:   margin: 0 0 10px 0;
 5960:   list-style-position: inside;
 5961: 
 5962: }
 5963: 
 5964: ol#LC_MenuBreadcrumbs, 
 5965: ol#LC_PathBreadcrumbs {
 5966: 	padding-left: 10px;
 5967: 	margin: 0;
 5968: 	list-style-position: inside;
 5969: }
 5970: 
 5971: ol#LC_MenuBreadcrumbs li, 
 5972: ol#LC_PathBreadcrumbs li, 
 5973: ul.LC_CourseBreadcrumbs li {
 5974:     display: inline;
 5975:     white-space: nowrap;
 5976: }
 5977: 
 5978: ol#LC_MenuBreadcrumbs li a,
 5979: ul.LC_CourseBreadcrumbs li a {
 5980: 	text-decoration: none;
 5981: 	font-size:90%;
 5982: }
 5983: 
 5984: ol#LC_PathBreadcrumbs li a {
 5985: 	text-decoration:none;
 5986: 	font-size:100%;
 5987: 	font-weight:bold;
 5988: }
 5989: 
 5990: .LC_Box {
 5991:     border: solid 1px $lg_border_color;
 5992:     padding: 0 10px 10px 10px;
 5993: }
 5994: 
 5995: .LC_AboutMe_Image {
 5996: 	float:left;
 5997: 	margin-right:10px;
 5998: }
 5999: 
 6000: .LC_Clear_AboutMe_Image {
 6001: 	clear:left;
 6002: }
 6003: 
 6004: dl.LC_ListStyleClean dt {
 6005: 	padding-right: 5px;
 6006: 	display: table-header-group;
 6007: }
 6008: 
 6009: dl.LC_ListStyleClean dd {
 6010: 	display: table-row;
 6011: }
 6012: 
 6013: .LC_ListStyleClean,
 6014: .LC_ListStyleSimple,
 6015: .LC_ListStyleNormal,
 6016: .LC_ListStyle_Border,
 6017: .LC_ListStyleSpecial {
 6018: 	/*display:block;	*/
 6019: 	list-style-position: inside;
 6020: 	list-style-type: none;
 6021: 	overflow: hidden;
 6022: 	padding: 0;
 6023: }
 6024: 
 6025: .LC_ListStyleSimple li,
 6026: .LC_ListStyleSimple dd,
 6027: .LC_ListStyleNormal li,
 6028: .LC_ListStyleNormal dd,
 6029: .LC_ListStyleSpecial li,
 6030: .LC_ListStyleSpecial dd {
 6031: 	margin: 0;
 6032: 	padding: 5px 5px 5px 10px;
 6033: 	clear: both;
 6034: }
 6035: 
 6036: .LC_ListStyleClean li,
 6037: .LC_ListStyleClean dd {
 6038: 	padding-top: 0;
 6039: 	padding-bottom: 0;
 6040: }
 6041: 
 6042: .LC_ListStyleSimple dd,
 6043: .LC_ListStyleSimple li {
 6044: 	border-bottom: solid 1px $lg_border_color;
 6045: }
 6046: 
 6047: .LC_ListStyleSpecial li,
 6048: .LC_ListStyleSpecial dd {
 6049: 	list-style-type: none;
 6050: 	background-color: RGB(220, 220, 220);
 6051: 	margin-bottom: 4px;
 6052: }
 6053: 
 6054: table.LC_SimpleTable {
 6055: 	margin:5px;
 6056: 	border:solid 1px $lg_border_color;
 6057: }
 6058: 
 6059: table.LC_SimpleTable tr {
 6060: 	padding: 0;
 6061: 	border:solid 1px $lg_border_color;
 6062: }
 6063: 
 6064: table.LC_SimpleTable thead {
 6065: 	 background:rgb(220,220,220);
 6066: }
 6067: 
 6068: div.LC_columnSection {
 6069: 	display: block;
 6070: 	clear: both;
 6071: 	overflow: hidden;
 6072: 	margin: 0;
 6073: }
 6074: 
 6075: div.LC_columnSection>* {
 6076: 	float: left;
 6077: 	margin: 10px 20px 10px 0;
 6078: 	overflow:hidden;
 6079: }
 6080: 
 6081: .LC_loginpage_container {
 6082: 	text-align:left;
 6083: 	margin : 0 auto;
 6084: 	width:90%;
 6085: 	padding: 10px;
 6086: 	height: auto;
 6087: 	background-color:#FFFFFF;
 6088: 	border:1px solid #CCCCCC;
 6089: }
 6090: 
 6091: 
 6092: .LC_loginpage_loginContainer {
 6093: 	float:left;
 6094: 	width: 182px;
 6095: 	padding: 2px;
 6096: 	border:1px solid #CCCCCC;
 6097: 	background-color:$loginbg;
 6098: }
 6099: 
 6100: .LC_loginpage_loginContainer h2 {
 6101: 	margin-top: 0;
 6102: 	display:block;
 6103: 	background:$bgcol;
 6104: 	color:$textcol;
 6105: 	padding-left:5px;
 6106: }
 6107: 
 6108: .LC_loginpage_loginInfo {
 6109: 	float:left;
 6110: 	width:182px;
 6111: 	border:1px solid #CCCCCC;
 6112: 	padding:2px;
 6113: }
 6114: 
 6115: .LC_loginpage_space {
 6116: 	clear: both;
 6117: 	margin-bottom: 20px;
 6118: 	border-bottom: 1px solid #CCCCCC;
 6119: }
 6120: 
 6121: .LC_loginpage_floatLeft {
 6122: 	float: left;
 6123: 	width: 200px;
 6124: 	margin: 0;
 6125: }
 6126: 
 6127: table em {
 6128: 	font-weight: bold;
 6129: 	font-style: normal;
 6130: }
 6131: 
 6132: table.LC_tableBrowseRes,
 6133: table.LC_tableOfContent {
 6134:         border:none;
 6135: 	border-spacing: 1px;
 6136: 	padding: 3px;
 6137: 	background-color: #FFFFFF;
 6138: 	font-size: 90%;
 6139: }
 6140: 
 6141: table.LC_tableOfContent{
 6142:     border-collapse: collapse;
 6143: }
 6144: 
 6145: table.LC_tableBrowseRes a,
 6146: table.LC_tableOfContent a {
 6147:         background-color: transparent;
 6148: 	text-decoration: none;
 6149: }
 6150: 
 6151: table.LC_tableBrowseRes tr.LC_trOdd,
 6152: table.LC_tableOfContent tr.LC_trOdd{
 6153: 	background-color: #EEEEEE;
 6154: }
 6155: 
 6156: table.LC_tableOfContent img {
 6157: 	border: none;
 6158: 	height: 1.3em;
 6159: 	vertical-align: text-bottom;
 6160: 	margin-right: 0.3em;
 6161: }
 6162: 
 6163: a#LC_content_toolbar_firsthomework {
 6164: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 6165: }
 6166: 
 6167: a#LC_content_toolbar_launchnav {
 6168: 	background-image:url(/res/adm/pages/start-navigation.gif);
 6169: }
 6170: 
 6171: a#LC_content_toolbar_closenav {
 6172: 	background-image:url(/res/adm/pages/close-navigation.gif);
 6173: }
 6174: 
 6175: a#LC_content_toolbar_everything {
 6176: 	background-image:url(/res/adm/pages/show-all.gif);
 6177: }
 6178: 
 6179: a#LC_content_toolbar_uncompleted {
 6180: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6181: }
 6182: 
 6183: #LC_content_toolbar_clearbubbles {
 6184: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6185: }
 6186: 
 6187: a#LC_content_toolbar_changefolder {
 6188: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6189: }
 6190: 
 6191: a#LC_content_toolbar_changefolder_toggled {
 6192: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 6193: }
 6194: 
 6195: ul#LC_toolbar li a:hover {
 6196: 	background-position: bottom center;
 6197: }
 6198: 
 6199: ul#LC_toolbar {
 6200: 	padding: 0;
 6201: 	margin: 2px;
 6202: 	list-style:none;
 6203: 	position:relative;
 6204: 	background-color:white;
 6205: }
 6206: 
 6207: ul#LC_toolbar li {
 6208: 	border:1px solid white;
 6209: 	padding: 0;
 6210: 	margin: 0;
 6211:         float: left;
 6212: 	display:inline;
 6213: 	vertical-align:middle;
 6214: } 
 6215: 
 6216: 
 6217: a.LC_toolbarItem {
 6218: 	display:block;
 6219: 	padding: 0;
 6220: 	margin: 0;
 6221: 	height: 32px;
 6222: 	width: 32px;
 6223: 	color:white;
 6224: 	border: none;
 6225: 	background-repeat:no-repeat;
 6226: 	background-color:transparent;
 6227: }
 6228: 
 6229: ul.LC_funclist li {
 6230:   float: left;
 6231:   white-space: nowrap;
 6232:   height: 35px; /* at least as high as heighest list item */
 6233:   margin: 0 15px 15px 10px;
 6234: }
 6235: 
 6236: 
 6237: END
 6238: }
 6239: 
 6240: =pod
 6241: 
 6242: =item * &headtag()
 6243: 
 6244: Returns a uniform footer for LON-CAPA web pages.
 6245: 
 6246: Inputs: $title - optional title for the head
 6247:         $head_extra - optional extra HTML to put inside the <head>
 6248:         $args - optional arguments
 6249:             force_register - if is true call registerurl so the remote is 
 6250:                              informed
 6251:             redirect       -> array ref of
 6252:                                    1- seconds before redirect occurs
 6253:                                    2- url to redirect to
 6254:                                    3- whether the side effect should occur
 6255:                            (side effect of setting 
 6256:                                $env{'internal.head.redirect'} to the url 
 6257:                                redirected too)
 6258:             domain         -> force to color decorate a page for a specific
 6259:                                domain
 6260:             function       -> force usage of a specific rolish color scheme
 6261:             bgcolor        -> override the default page bgcolor
 6262:             no_auto_mt_title
 6263:                            -> prevent &mt()ing the title arg
 6264: 
 6265: =cut
 6266: 
 6267: sub headtag {
 6268:     my ($title,$head_extra,$args) = @_;
 6269:     
 6270:     my $function = $args->{'function'} || &get_users_function();
 6271:     my $domain   = $args->{'domain'}   || &determinedomain();
 6272:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6273:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6274: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6275: 		   #time(),
 6276: 		   $env{'environment.color.timestamp'},
 6277: 		   $function,$domain,$bgcolor);
 6278: 
 6279:     $url = '/adm/css/'.&escape($url).'.css';
 6280: 
 6281:     my $result =
 6282: 	'<head>'.
 6283: 	&font_settings();
 6284: 
 6285:     if (!$args->{'frameset'}) {
 6286: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6287:     }
 6288:     if ($args->{'force_register'}) {
 6289: 	$result .= &Apache::lonmenu::registerurl(1);
 6290:     }
 6291:     if (!$args->{'no_nav_bar'} 
 6292: 	&& !$args->{'only_body'}
 6293: 	&& !$args->{'frameset'}) {
 6294: 	$result .= &help_menu_js();
 6295:     }
 6296: 
 6297:     if (ref($args->{'redirect'})) {
 6298: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6299: 	$url = &Apache::lonenc::check_encrypt($url);
 6300: 	if (!$inhibit_continue) {
 6301: 	    $env{'internal.head.redirect'} = $url;
 6302: 	}
 6303: 	$result.=<<ADDMETA
 6304: <meta http-equiv="pragma" content="no-cache" />
 6305: <meta http-equiv="Refresh" content="$time; url=$url" />
 6306: ADDMETA
 6307:     }
 6308:     if (!defined($title)) {
 6309: 	$title = 'The LearningOnline Network with CAPA';
 6310:     }
 6311:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6312:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6313: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6314: 	.$head_extra;
 6315:     return $result;
 6316: }
 6317: 
 6318: =pod
 6319: 
 6320: =item * &font_settings()
 6321: 
 6322: Returns neccessary <meta> to set the proper encoding
 6323: 
 6324: Inputs: none
 6325: 
 6326: =cut
 6327: 
 6328: sub font_settings {
 6329:     my $headerstring='';
 6330:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6331: 	$headerstring.=
 6332: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6333:     }
 6334:     return $headerstring;
 6335: }
 6336: 
 6337: =pod
 6338: 
 6339: =item * &xml_begin()
 6340: 
 6341: Returns the needed doctype and <html>
 6342: 
 6343: Inputs: none
 6344: 
 6345: =cut
 6346: 
 6347: sub xml_begin {
 6348:     my $output='';
 6349: 
 6350:     if ($env{'internal.start_page'}==1) {
 6351: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6352:     }
 6353: 
 6354:     if ($env{'browser.mathml'}) {
 6355: 	$output='<?xml version="1.0"?>'
 6356:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6357: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6358:             
 6359: #	    .'<!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">] >'
 6360: 	    .'<!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">'
 6361:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6362: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6363:     } else {
 6364: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6365:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6366:     }
 6367:     return $output;
 6368: }
 6369: 
 6370: =pod
 6371: 
 6372: =item * &endheadtag()
 6373: 
 6374: Returns a uniform </head> for LON-CAPA web pages.
 6375: 
 6376: Inputs: none
 6377: 
 6378: =cut
 6379: 
 6380: sub endheadtag {
 6381:     return '</head>';
 6382: }
 6383: 
 6384: =pod
 6385: 
 6386: =item * &head()
 6387: 
 6388: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6389: 
 6390: Inputs:
 6391: 
 6392: =over 4
 6393: 
 6394: $title - optional title for the page
 6395: 
 6396: $head_extra - optional extra HTML to put inside the <head>
 6397: 
 6398: =back
 6399: 
 6400: =cut
 6401: 
 6402: sub head {
 6403:     my ($title,$head_extra,$args) = @_;
 6404:     return &headtag($title,$head_extra,$args).&endheadtag();
 6405: }
 6406: 
 6407: =pod
 6408: 
 6409: =item * &start_page()
 6410: 
 6411: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6412: 
 6413: Inputs:
 6414: 
 6415: =over 4
 6416: 
 6417: $title - optional title for the page
 6418: 
 6419: $head_extra - optional extra HTML to incude inside the <head>
 6420: 
 6421: $args - additional optional args supported are:
 6422: 
 6423: =over 8
 6424: 
 6425:              only_body      -> is true will set &bodytag() onlybodytag
 6426:                                     arg on
 6427:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6428:              add_entries    -> additional attributes to add to the  <body>
 6429:              domain         -> force to color decorate a page for a 
 6430:                                     specific domain
 6431:              function       -> force usage of a specific rolish color
 6432:                                     scheme
 6433:              redirect       -> see &headtag()
 6434:              bgcolor        -> override the default page bg color
 6435:              js_ready       -> return a string ready for being used in 
 6436:                                     a javascript writeln
 6437:              html_encode    -> return a string ready for being used in 
 6438:                                     a html attribute
 6439:              force_register -> if is true will turn on the &bodytag()
 6440:                                     $forcereg arg
 6441:              frameset       -> if true will start with a <frameset>
 6442:                                     rather than <body>
 6443:              skip_phases    -> hash ref of 
 6444:                                     head -> skip the <html><head> generation
 6445:                                     body -> skip all <body> generation
 6446:              no_inline_link -> if true and in remote mode, don't show the 
 6447:                                     'Switch To Inline Menu' link
 6448:              no_auto_mt_title -> prevent &mt()ing the title arg
 6449:              inherit_jsmath -> when creating popup window in a page,
 6450:                                     should it have jsmath forced on by the
 6451:                                     current page
 6452:              bread_crumbs ->             Array containing breadcrumbs
 6453:              bread_crumbs_components ->  if exists show it as headline else show only the breadcrumbs
 6454: 
 6455: =back
 6456: 
 6457: =back
 6458: 
 6459: =cut
 6460: 
 6461: sub start_page {
 6462:     my ($title,$head_extra,$args) = @_;
 6463:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6464:     my %head_args;
 6465:     foreach my $arg ('redirect','force_register','domain','function',
 6466: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6467: 		     'no_auto_mt_title') {
 6468: 	if (defined($args->{$arg})) {
 6469: 	    $head_args{$arg} = $args->{$arg};
 6470: 	}
 6471:     }
 6472: 
 6473:     $env{'internal.start_page'}++;
 6474:     my $result;
 6475:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6476: 	$result.=
 6477: 	    &xml_begin().
 6478: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6479:     }
 6480:     
 6481:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6482: 	if ($args->{'frameset'}) {
 6483: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6484: 						$args->{'add_entries'});
 6485: 	    $result .= "\n<frameset $attr_string>\n";
 6486:         } else {
 6487:             $result .=
 6488:                 &bodytag($title, 
 6489:                          $args->{'function'},       $args->{'add_entries'},
 6490:                          $args->{'only_body'},      $args->{'domain'},
 6491:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6492:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 6493:                          $args);
 6494:         }
 6495:     }
 6496: 
 6497:     if ($args->{'js_ready'}) {
 6498: 		$result = &js_ready($result);
 6499:     }
 6500:     if ($args->{'html_encode'}) {
 6501: 		$result = &html_encode($result);
 6502:     }
 6503: 
 6504:     # Preparation for new and consistent functionlist at top of screen
 6505:     # if ($args->{'functionlist'}) {
 6506:     #            $result .= &build_functionlist();
 6507:     #}
 6508: 
 6509:     # Don't add anything more if only_body wanted
 6510:     return $result if $args->{'only_body'};
 6511: 
 6512:     #Breadcrumbs
 6513:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6514: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6515: 		#if any br links exists, add them to the breadcrumbs
 6516: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6517: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6518: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6519: 			}
 6520: 		}
 6521: 
 6522: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6523: 		if(exists($args->{'bread_crumbs_component'})){
 6524: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6525: 		}else{
 6526: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6527: 		}
 6528:     }
 6529:     return $result;
 6530: }
 6531: 
 6532: 
 6533: =pod
 6534: 
 6535: =item * &head()
 6536: 
 6537: Returns a complete </body></html> section for LON-CAPA web pages.
 6538: 
 6539: Inputs:         $args - additional optional args supported are:
 6540:                  js_ready     -> return a string ready for being used in 
 6541:                                  a javascript writeln
 6542:                  html_encode  -> return a string ready for being used in 
 6543:                                  a html attribute
 6544:                  frameset     -> if true will start with a <frameset>
 6545:                                  rather than <body>
 6546:                  dicsussion   -> if true will get discussion from
 6547:                                   lonxml::xmlend
 6548:                                  (you can pass the target and parser arguments
 6549:                                   through optional 'target' and 'parser' args
 6550:                                   to this routine)
 6551: 
 6552: =cut
 6553: 
 6554: sub end_page {
 6555:     my ($args) = @_;
 6556:     $env{'internal.end_page'}++;
 6557:     my $result;
 6558:     if ($args->{'discussion'}) {
 6559: 	my ($target,$parser);
 6560: 	if (ref($args->{'discussion'})) {
 6561: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6562: 				$args->{'discussion'}{'parser'});
 6563: 	}
 6564: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6565:     }
 6566: 
 6567:     if ($args->{'frameset'}) {
 6568: 	$result .= '</frameset>';
 6569:     } else {
 6570: 	$result .= &endbodytag($args);
 6571:     }
 6572:     $result .= "\n</html>";
 6573: 
 6574:     if ($args->{'js_ready'}) {
 6575: 	$result = &js_ready($result);
 6576:     }
 6577: 
 6578:     if ($args->{'html_encode'}) {
 6579: 	$result = &html_encode($result);
 6580:     }
 6581: 
 6582:     return $result;
 6583: }
 6584: 
 6585: sub html_encode {
 6586:     my ($result) = @_;
 6587: 
 6588:     $result = &HTML::Entities::encode($result,'<>&"');
 6589:     
 6590:     return $result;
 6591: }
 6592: sub js_ready {
 6593:     my ($result) = @_;
 6594: 
 6595:     $result =~ s/[\n\r]/ /xmsg;
 6596:     $result =~ s/\\/\\\\/xmsg;
 6597:     $result =~ s/'/\\'/xmsg;
 6598:     $result =~ s{</}{<\\/}xmsg;
 6599:     
 6600:     return $result;
 6601: }
 6602: 
 6603: sub validate_page {
 6604:     if (  exists($env{'internal.start_page'})
 6605: 	  &&     $env{'internal.start_page'} > 1) {
 6606: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6607: 				 $env{'internal.start_page'}.' '.
 6608: 				 $ENV{'request.filename'});
 6609:     }
 6610:     if (  exists($env{'internal.end_page'})
 6611: 	  &&     $env{'internal.end_page'} > 1) {
 6612: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6613: 				 $env{'internal.end_page'}.' '.
 6614: 				 $env{'request.filename'});
 6615:     }
 6616:     if (     exists($env{'internal.start_page'})
 6617: 	&& ! exists($env{'internal.end_page'})) {
 6618: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6619: 				 $env{'request.filename'});
 6620:     }
 6621:     if (   ! exists($env{'internal.start_page'})
 6622: 	&&   exists($env{'internal.end_page'})) {
 6623: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6624: 				 $env{'request.filename'});
 6625:     }
 6626: }
 6627: 
 6628: sub simple_error_page {
 6629:     my ($r,$title,$msg) = @_;
 6630:     my $page =
 6631: 	&Apache::loncommon::start_page($title).
 6632: 	&mt($msg).
 6633: 	&Apache::loncommon::end_page();
 6634:     if (ref($r)) {
 6635: 	$r->print($page);
 6636: 	return;
 6637:     }
 6638:     return $page;
 6639: }
 6640: 
 6641: {
 6642:     my @row_count;
 6643:     sub start_data_table {
 6644: 	my ($add_class) = @_;
 6645: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6646: 	unshift(@row_count,0);
 6647: 	return '<table class="'.$css_class.'">'."\n";
 6648:     }
 6649: 
 6650:     sub end_data_table {
 6651: 	shift(@row_count);
 6652: 	return '</table>'."\n";;
 6653:     }
 6654: 
 6655:     sub start_data_table_row {
 6656: 	my ($add_class) = @_;
 6657: 	$row_count[0]++;
 6658: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6659: 	$css_class = (join(' ',$css_class,$add_class));
 6660: 	return  '<tr class="'.$css_class.'">'."\n";;
 6661:     }
 6662:     
 6663:     sub continue_data_table_row {
 6664: 	my ($add_class) = @_;
 6665: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6666: 	$css_class = (join(' ',$css_class,$add_class));
 6667: 	return  '<tr class="'.$css_class.'">'."\n";;
 6668:     }
 6669: 
 6670:     sub end_data_table_row {
 6671: 	return '</tr>'."\n";;
 6672:     }
 6673: 
 6674:     sub start_data_table_empty_row {
 6675: #	$row_count[0]++;
 6676: 	return  '<tr class="LC_empty_row" >'."\n";;
 6677:     }
 6678: 
 6679:     sub end_data_table_empty_row {
 6680: 	return '</tr>'."\n";;
 6681:     }
 6682: 
 6683:     sub start_data_table_header_row {
 6684: 	return  '<tr class="LC_header_row">'."\n";;
 6685:     }
 6686: 
 6687:     sub end_data_table_header_row {
 6688: 	return '</tr>'."\n";;
 6689:     }
 6690: }
 6691: 
 6692: =pod
 6693: 
 6694: =item * &inhibit_menu_check($arg)
 6695: 
 6696: Checks for a inhibitmenu state and generates output to preserve it
 6697: 
 6698: Inputs:         $arg - can be any of
 6699:                      - undef - in which case the return value is a string 
 6700:                                to add  into arguments list of a uri
 6701:                      - 'input' - in which case the return value is a HTML
 6702:                                  <form> <input> field of type hidden to
 6703:                                  preserve the value
 6704:                      - a url - in which case the return value is the url with
 6705:                                the neccesary cgi args added to preserve the
 6706:                                inhibitmenu state
 6707:                      - a ref to a url - no return value, but the string is
 6708:                                         updated to include the neccessary cgi
 6709:                                         args to preserve the inhibitmenu state
 6710: 
 6711: =cut
 6712: 
 6713: sub inhibit_menu_check {
 6714:     my ($arg) = @_;
 6715:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6716:     if ($arg eq 'input') {
 6717: 	if ($env{'form.inhibitmenu'}) {
 6718: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6719: 	} else {
 6720: 	    return
 6721: 	}
 6722:     }
 6723:     if ($env{'form.inhibitmenu'}) {
 6724: 	if (ref($arg)) {
 6725: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6726: 	} elsif ($arg eq '') {
 6727: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6728: 	} else {
 6729: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6730: 	}
 6731:     }
 6732:     if (!ref($arg)) {
 6733: 	return $arg;
 6734:     }
 6735: }
 6736: 
 6737: ###############################################
 6738: 
 6739: =pod
 6740: 
 6741: =back
 6742: 
 6743: =head1 User Information Routines
 6744: 
 6745: =over 4
 6746: 
 6747: =item * &get_users_function()
 6748: 
 6749: Used by &bodytag to determine the current users primary role.
 6750: Returns either 'student','coordinator','admin', or 'author'.
 6751: 
 6752: =cut
 6753: 
 6754: ###############################################
 6755: sub get_users_function {
 6756:     my $function = 'norole';
 6757:     if ($env{'request.role'}=~/^(st)/) {
 6758:         $function='student';
 6759:     }
 6760:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6761:         $function='coordinator';
 6762:     }
 6763:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6764:         $function='admin';
 6765:     }
 6766:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 6767:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6768:         $function='author';
 6769:     }
 6770:     return $function;
 6771: }
 6772: 
 6773: ###############################################
 6774: 
 6775: =pod
 6776: 
 6777: =item * &show_course()
 6778: 
 6779: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 6780: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 6781: 
 6782: Inputs:
 6783: None
 6784: 
 6785: Outputs:
 6786: Scalar: 1 if 'Course' to be used, 0 otherwise.
 6787: 
 6788: =cut
 6789: 
 6790: ###############################################
 6791: sub show_course {
 6792:     my $course = !$env{'user.adv'};
 6793:     if (!$env{'user.adv'}) {
 6794:         foreach my $env (keys(%env)) {
 6795:             next if ($env !~ m/^user\.priv\./);
 6796:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 6797:                 $course = 0;
 6798:                 last;
 6799:             }
 6800:         }
 6801:     }
 6802:     return $course;
 6803: }
 6804: 
 6805: ###############################################
 6806: 
 6807: =pod
 6808: 
 6809: =item * &check_user_status()
 6810: 
 6811: Determines current status of supplied role for a
 6812: specific user. Roles can be active, previous or future.
 6813: 
 6814: Inputs: 
 6815: user's domain, user's username, course's domain,
 6816: course's number, optional section ID.
 6817: 
 6818: Outputs:
 6819: role status: active, previous or future. 
 6820: 
 6821: =cut
 6822: 
 6823: sub check_user_status {
 6824:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6825:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6826:     my @uroles = keys %userinfo;
 6827:     my $srchstr;
 6828:     my $active_chk = 'none';
 6829:     my $now = time;
 6830:     if (@uroles > 0) {
 6831:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6832:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6833:         } else {
 6834:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6835:         }
 6836:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6837:             my $role_end = 0;
 6838:             my $role_start = 0;
 6839:             $active_chk = 'active';
 6840:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6841:                 $role_end = $1;
 6842:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6843:                     $role_start = $1;
 6844:                 }
 6845:             }
 6846:             if ($role_start > 0) {
 6847:                 if ($now < $role_start) {
 6848:                     $active_chk = 'future';
 6849:                 }
 6850:             }
 6851:             if ($role_end > 0) {
 6852:                 if ($now > $role_end) {
 6853:                     $active_chk = 'previous';
 6854:                 }
 6855:             }
 6856:         }
 6857:     }
 6858:     return $active_chk;
 6859: }
 6860: 
 6861: ###############################################
 6862: 
 6863: =pod
 6864: 
 6865: =item * &get_sections()
 6866: 
 6867: Determines all the sections for a course including
 6868: sections with students and sections containing other roles.
 6869: Incoming parameters: 
 6870: 
 6871: 1. domain
 6872: 2. course number 
 6873: 3. reference to array containing roles for which sections should 
 6874: be gathered (optional).
 6875: 4. reference to array containing status types for which sections 
 6876: should be gathered (optional).
 6877: 
 6878: If the third argument is undefined, sections are gathered for any role. 
 6879: If the fourth argument is undefined, sections are gathered for any status.
 6880: Permissible values are 'active' or 'future' or 'previous'.
 6881:  
 6882: Returns section hash (keys are section IDs, values are
 6883: number of users in each section), subject to the
 6884: optional roles filter, optional status filter 
 6885: 
 6886: =cut
 6887: 
 6888: ###############################################
 6889: sub get_sections {
 6890:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6891:     if (!defined($cdom) || !defined($cnum)) {
 6892:         my $cid =  $env{'request.course.id'};
 6893: 
 6894: 	return if (!defined($cid));
 6895: 
 6896:         $cdom = $env{'course.'.$cid.'.domain'};
 6897:         $cnum = $env{'course.'.$cid.'.num'};
 6898:     }
 6899: 
 6900:     my %sectioncount;
 6901:     my $now = time;
 6902: 
 6903:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6904: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6905: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6906: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6907:         my $start_index = &Apache::loncoursedata::CL_START();
 6908:         my $end_index = &Apache::loncoursedata::CL_END();
 6909:         my $status;
 6910: 	while (my ($student,$data) = each(%$classlist)) {
 6911: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6912: 				                     $data->[$status_index],
 6913:                                                      $data->[$start_index],
 6914:                                                      $data->[$end_index]);
 6915:             if ($stu_status eq 'Active') {
 6916:                 $status = 'active';
 6917:             } elsif ($end < $now) {
 6918:                 $status = 'previous';
 6919:             } elsif ($start > $now) {
 6920:                 $status = 'future';
 6921:             } 
 6922: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6923:                 if ((!defined($possible_status)) || (($status ne '') && 
 6924:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6925: 		    $sectioncount{$section}++;
 6926:                 }
 6927: 	    }
 6928: 	}
 6929:     }
 6930:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6931:     foreach my $user (sort(keys(%courseroles))) {
 6932: 	if ($user !~ /^(\w{2})/) { next; }
 6933: 	my ($role) = ($user =~ /^(\w{2})/);
 6934: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6935: 	my ($section,$status);
 6936: 	if ($role eq 'cr' &&
 6937: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6938: 	    $section=$1;
 6939: 	}
 6940: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6941: 	if (!defined($section) || $section eq '-1') { next; }
 6942:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6943:         if ($end == -1 && $start == -1) {
 6944:             next; #deleted role
 6945:         }
 6946:         if (!defined($possible_status)) { 
 6947:             $sectioncount{$section}++;
 6948:         } else {
 6949:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6950:                 $status = 'active';
 6951:             } elsif ($end < $now) {
 6952:                 $status = 'future';
 6953:             } elsif ($start > $now) {
 6954:                 $status = 'previous';
 6955:             }
 6956:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6957:                 $sectioncount{$section}++;
 6958:             }
 6959:         }
 6960:     }
 6961:     return %sectioncount;
 6962: }
 6963: 
 6964: ###############################################
 6965: 
 6966: =pod
 6967: 
 6968: =item * &get_course_users()
 6969: 
 6970: Retrieves usernames:domains for users in the specified course
 6971: with specific role(s), and access status. 
 6972: 
 6973: Incoming parameters:
 6974: 1. course domain
 6975: 2. course number
 6976: 3. access status: users must have - either active, 
 6977: previous, future, or all.
 6978: 4. reference to array of permissible roles
 6979: 5. reference to array of section restrictions (optional)
 6980: 6. reference to results object (hash of hashes).
 6981: 7. reference to optional userdata hash
 6982: 8. reference to optional statushash
 6983: 9. flag if privileged users (except those set to unhide in
 6984:    course settings) should be excluded    
 6985: Keys of top level results hash are roles.
 6986: Keys of inner hashes are username:domain, with 
 6987: values set to access type.
 6988: Optional userdata hash returns an array with arguments in the 
 6989: same order as loncoursedata::get_classlist() for student data.
 6990: 
 6991: Optional statushash returns
 6992: 
 6993: Entries for end, start, section and status are blank because
 6994: of the possibility of multiple values for non-student roles.
 6995: 
 6996: =cut
 6997: 
 6998: ###############################################
 6999: 
 7000: sub get_course_users {
 7001:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7002:     my %idx = ();
 7003:     my %seclists;
 7004: 
 7005:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7006:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7007:     $idx{end} = &Apache::loncoursedata::CL_END();
 7008:     $idx{start} = &Apache::loncoursedata::CL_START();
 7009:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7010:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7011:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7012:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7013: 
 7014:     if (grep(/^st$/,@{$roles})) {
 7015:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7016:         my $now = time;
 7017:         foreach my $student (keys(%{$classlist})) {
 7018:             my $match = 0;
 7019:             my $secmatch = 0;
 7020:             my $section = $$classlist{$student}[$idx{section}];
 7021:             my $status = $$classlist{$student}[$idx{status}];
 7022:             if ($section eq '') {
 7023:                 $section = 'none';
 7024:             }
 7025:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7026:                 if (grep(/^all$/,@{$sections})) {
 7027:                     $secmatch = 1;
 7028:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7029:                     if (grep(/^none$/,@{$sections})) {
 7030:                         $secmatch = 1;
 7031:                     }
 7032:                 } else {  
 7033: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7034: 		        $secmatch = 1;
 7035:                     }
 7036: 		}
 7037:                 if (!$secmatch) {
 7038:                     next;
 7039:                 }
 7040:             }
 7041:             if (defined($$types{'active'})) {
 7042:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7043:                     push(@{$$users{st}{$student}},'active');
 7044:                     $match = 1;
 7045:                 }
 7046:             }
 7047:             if (defined($$types{'previous'})) {
 7048:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7049:                     push(@{$$users{st}{$student}},'previous');
 7050:                     $match = 1;
 7051:                 }
 7052:             }
 7053:             if (defined($$types{'future'})) {
 7054:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7055:                     push(@{$$users{st}{$student}},'future');
 7056:                     $match = 1;
 7057:                 }
 7058:             }
 7059:             if ($match) {
 7060:                 push(@{$seclists{$student}},$section);
 7061:                 if (ref($userdata) eq 'HASH') {
 7062:                     $$userdata{$student} = $$classlist{$student};
 7063:                 }
 7064:                 if (ref($statushash) eq 'HASH') {
 7065:                     $statushash->{$student}{'st'}{$section} = $status;
 7066:                 }
 7067:             }
 7068:         }
 7069:     }
 7070:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7071:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7072:         my $now = time;
 7073:         my %displaystatus = ( previous => 'Expired',
 7074:                               active   => 'Active',
 7075:                               future   => 'Future',
 7076:                             );
 7077:         my %nothide;
 7078:         if ($hidepriv) {
 7079:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7080:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7081:                 if ($user !~ /:/) {
 7082:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7083:                 } else {
 7084:                     $nothide{$user} = 1;
 7085:                 }
 7086:             }
 7087:         }
 7088:         foreach my $person (sort(keys(%coursepersonnel))) {
 7089:             my $match = 0;
 7090:             my $secmatch = 0;
 7091:             my $status;
 7092:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7093:             $user =~ s/:$//;
 7094:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7095:             if ($end == -1 || $start == -1) {
 7096:                 next;
 7097:             }
 7098:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7099:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7100:                 my ($uname,$udom) = split(/:/,$user);
 7101:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7102:                     if (grep(/^all$/,@{$sections})) {
 7103:                         $secmatch = 1;
 7104:                     } elsif ($usec eq '') {
 7105:                         if (grep(/^none$/,@{$sections})) {
 7106:                             $secmatch = 1;
 7107:                         }
 7108:                     } else {
 7109:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7110:                             $secmatch = 1;
 7111:                         }
 7112:                     }
 7113:                     if (!$secmatch) {
 7114:                         next;
 7115:                     }
 7116:                 }
 7117:                 if ($usec eq '') {
 7118:                     $usec = 'none';
 7119:                 }
 7120:                 if ($uname ne '' && $udom ne '') {
 7121:                     if ($hidepriv) {
 7122:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7123:                             (!$nothide{$uname.':'.$udom})) {
 7124:                             next;
 7125:                         }
 7126:                     }
 7127:                     if ($end > 0 && $end < $now) {
 7128:                         $status = 'previous';
 7129:                     } elsif ($start > $now) {
 7130:                         $status = 'future';
 7131:                     } else {
 7132:                         $status = 'active';
 7133:                     }
 7134:                     foreach my $type (keys(%{$types})) { 
 7135:                         if ($status eq $type) {
 7136:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7137:                                 push(@{$$users{$role}{$user}},$type);
 7138:                             }
 7139:                             $match = 1;
 7140:                         }
 7141:                     }
 7142:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7143:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7144: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7145:                         }
 7146:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7147:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7148:                         }
 7149:                         if (ref($statushash) eq 'HASH') {
 7150:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7151:                         }
 7152:                     }
 7153:                 }
 7154:             }
 7155:         }
 7156:         if (grep(/^ow$/,@{$roles})) {
 7157:             if ((defined($cdom)) && (defined($cnum))) {
 7158:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7159:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7160:                     my $owner = $csettings{'internal.courseowner'};
 7161:                     next if ($owner eq '');
 7162:                     my ($ownername,$ownerdom);
 7163:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7164:                         $ownername = $1;
 7165:                         $ownerdom = $2;
 7166:                     } else {
 7167:                         $ownername = $owner;
 7168:                         $ownerdom = $cdom;
 7169:                         $owner = $ownername.':'.$ownerdom;
 7170:                     }
 7171:                     @{$$users{'ow'}{$owner}} = 'any';
 7172:                     if (defined($userdata) && 
 7173: 			!exists($$userdata{$owner})) {
 7174: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7175:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7176:                             push(@{$seclists{$owner}},'none');
 7177:                         }
 7178:                         if (ref($statushash) eq 'HASH') {
 7179:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7180:                         }
 7181: 		    }
 7182:                 }
 7183:             }
 7184:         }
 7185:         foreach my $user (keys(%seclists)) {
 7186:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7187:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7188:         }
 7189:     }
 7190:     return;
 7191: }
 7192: 
 7193: sub get_user_info {
 7194:     my ($udom,$uname,$idx,$userdata) = @_;
 7195:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7196: 	&plainname($uname,$udom,'lastname');
 7197:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7198:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7199:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7200:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7201:     return;
 7202: }
 7203: 
 7204: ###############################################
 7205: 
 7206: =pod
 7207: 
 7208: =item * &get_user_quota()
 7209: 
 7210: Retrieves quota assigned for storage of portfolio files for a user  
 7211: 
 7212: Incoming parameters:
 7213: 1. user's username
 7214: 2. user's domain
 7215: 
 7216: Returns:
 7217: 1. Disk quota (in Mb) assigned to student.
 7218: 2. (Optional) Type of setting: custom or default
 7219:    (individually assigned or default for user's 
 7220:    institutional status).
 7221: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7222:    or student - types as defined in localenroll::inst_usertypes 
 7223:    for user's domain, which determines default quota for user.
 7224: 4. (Optional) - Default quota which would apply to the user.
 7225: 
 7226: If a value has been stored in the user's environment, 
 7227: it will return that, otherwise it returns the maximal default
 7228: defined for the user's instituional status(es) in the domain.
 7229: 
 7230: =cut
 7231: 
 7232: ###############################################
 7233: 
 7234: 
 7235: sub get_user_quota {
 7236:     my ($uname,$udom) = @_;
 7237:     my ($quota,$quotatype,$settingstatus,$defquota);
 7238:     if (!defined($udom)) {
 7239:         $udom = $env{'user.domain'};
 7240:     }
 7241:     if (!defined($uname)) {
 7242:         $uname = $env{'user.name'};
 7243:     }
 7244:     if (($udom eq '' || $uname eq '') ||
 7245:         ($udom eq 'public') && ($uname eq 'public')) {
 7246:         $quota = 0;
 7247:         $quotatype = 'default';
 7248:         $defquota = 0; 
 7249:     } else {
 7250:         my $inststatus;
 7251:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7252:             $quota = $env{'environment.portfolioquota'};
 7253:             $inststatus = $env{'environment.inststatus'};
 7254:         } else {
 7255:             my %userenv = 
 7256:                 &Apache::lonnet::get('environment',['portfolioquota',
 7257:                                      'inststatus'],$udom,$uname);
 7258:             my ($tmp) = keys(%userenv);
 7259:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7260:                 $quota = $userenv{'portfolioquota'};
 7261:                 $inststatus = $userenv{'inststatus'};
 7262:             } else {
 7263:                 undef(%userenv);
 7264:             }
 7265:         }
 7266:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7267:         if ($quota eq '') {
 7268:             $quota = $defquota;
 7269:             $quotatype = 'default';
 7270:         } else {
 7271:             $quotatype = 'custom';
 7272:         }
 7273:     }
 7274:     if (wantarray) {
 7275:         return ($quota,$quotatype,$settingstatus,$defquota);
 7276:     } else {
 7277:         return $quota;
 7278:     }
 7279: }
 7280: 
 7281: ###############################################
 7282: 
 7283: =pod
 7284: 
 7285: =item * &default_quota()
 7286: 
 7287: Retrieves default quota assigned for storage of user portfolio files,
 7288: given an (optional) user's institutional status.
 7289: 
 7290: Incoming parameters:
 7291: 1. domain
 7292: 2. (Optional) institutional status(es).  This is a : separated list of 
 7293:    status types (e.g., faculty, staff, student etc.)
 7294:    which apply to the user for whom the default is being retrieved.
 7295:    If the institutional status string in undefined, the domain
 7296:    default quota will be returned. 
 7297: 
 7298: Returns:
 7299: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7300: 2. (Optional) institutional type which determined the value of the
 7301:    default quota.
 7302: 
 7303: If a value has been stored in the domain's configuration db,
 7304: it will return that, otherwise it returns 20 (for backwards 
 7305: compatibility with domains which have not set up a configuration
 7306: db file; the original statically defined portfolio quota was 20 Mb). 
 7307: 
 7308: If the user's status includes multiple types (e.g., staff and student),
 7309: the largest default quota which applies to the user determines the
 7310: default quota returned.
 7311: 
 7312: =back
 7313: 
 7314: =cut
 7315: 
 7316: ###############################################
 7317: 
 7318: 
 7319: sub default_quota {
 7320:     my ($udom,$inststatus) = @_;
 7321:     my ($defquota,$settingstatus);
 7322:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7323:                                             ['quotas'],$udom);
 7324:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7325:         if ($inststatus ne '') {
 7326:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7327:             foreach my $item (@statuses) {
 7328:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7329:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7330:                         if ($defquota eq '') {
 7331:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7332:                             $settingstatus = $item;
 7333:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7334:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7335:                             $settingstatus = $item;
 7336:                         }
 7337:                     }
 7338:                 } else {
 7339:                     if ($quotahash{'quotas'}{$item} ne '') {
 7340:                         if ($defquota eq '') {
 7341:                             $defquota = $quotahash{'quotas'}{$item};
 7342:                             $settingstatus = $item;
 7343:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7344:                             $defquota = $quotahash{'quotas'}{$item};
 7345:                             $settingstatus = $item;
 7346:                         }
 7347:                     }
 7348:                 }
 7349:             }
 7350:         }
 7351:         if ($defquota eq '') {
 7352:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7353:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7354:             } else {
 7355:                 $defquota = $quotahash{'quotas'}{'default'};
 7356:             }
 7357:             $settingstatus = 'default';
 7358:         }
 7359:     } else {
 7360:         $settingstatus = 'default';
 7361:         $defquota = 20;
 7362:     }
 7363:     if (wantarray) {
 7364:         return ($defquota,$settingstatus);
 7365:     } else {
 7366:         return $defquota;
 7367:     }
 7368: }
 7369: 
 7370: sub get_secgrprole_info {
 7371:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7372:     my %sections_count = &get_sections($cdom,$cnum);
 7373:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7374:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7375:     my @groups = sort(keys(%curr_groups));
 7376:     my $allroles = [];
 7377:     my $rolehash;
 7378:     my $accesshash = {
 7379:                      active => 'Currently has access',
 7380:                      future => 'Will have future access',
 7381:                      previous => 'Previously had access',
 7382:                   };
 7383:     if ($needroles) {
 7384:         $rolehash = {'all' => 'all'};
 7385:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7386: 	if (&Apache::lonnet::error(%user_roles)) {
 7387: 	    undef(%user_roles);
 7388: 	}
 7389:         foreach my $item (keys(%user_roles)) {
 7390:             my ($role)=split(/\:/,$item,2);
 7391:             if ($role eq 'cr') { next; }
 7392:             if ($role =~ /^cr/) {
 7393:                 $$rolehash{$role} = (split('/',$role))[3];
 7394:             } else {
 7395:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7396:             }
 7397:         }
 7398:         foreach my $key (sort(keys(%{$rolehash}))) {
 7399:             push(@{$allroles},$key);
 7400:         }
 7401:         push (@{$allroles},'st');
 7402:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7403:     }
 7404:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7405: }
 7406: 
 7407: sub user_picker {
 7408:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7409:     my $currdom = $dom;
 7410:     my %curr_selected = (
 7411:                         srchin => 'dom',
 7412:                         srchby => 'lastname',
 7413:                       );
 7414:     my $srchterm;
 7415:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7416:         if ($srch->{'srchby'} ne '') {
 7417:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7418:         }
 7419:         if ($srch->{'srchin'} ne '') {
 7420:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7421:         }
 7422:         if ($srch->{'srchtype'} ne '') {
 7423:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7424:         }
 7425:         if ($srch->{'srchdomain'} ne '') {
 7426:             $currdom = $srch->{'srchdomain'};
 7427:         }
 7428:         $srchterm = $srch->{'srchterm'};
 7429:     }
 7430:     my %lt=&Apache::lonlocal::texthash(
 7431:                     'usr'       => 'Search criteria',
 7432:                     'doma'      => 'Domain/institution to search',
 7433:                     'uname'     => 'username',
 7434:                     'lastname'  => 'last name',
 7435:                     'lastfirst' => 'last name, first name',
 7436:                     'crs'       => 'in this course',
 7437:                     'dom'       => 'in selected LON-CAPA domain', 
 7438:                     'alc'       => 'all LON-CAPA',
 7439:                     'instd'     => 'in institutional directory for selected domain',
 7440:                     'exact'     => 'is',
 7441:                     'contains'  => 'contains',
 7442:                     'begins'    => 'begins with',
 7443:                     'youm'      => "You must include some text to search for.",
 7444:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7445:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7446:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7447:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7448:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7449:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7450:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7451:                                        );
 7452:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7453:     my $srchinsel = ' <select name="srchin">';
 7454: 
 7455:     my @srchins = ('crs','dom','alc','instd');
 7456: 
 7457:     foreach my $option (@srchins) {
 7458:         # FIXME 'alc' option unavailable until 
 7459:         #       loncreateuser::print_user_query_page()
 7460:         #       has been completed.
 7461:         next if ($option eq 'alc');
 7462:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7463:         if ($curr_selected{'srchin'} eq $option) {
 7464:             $srchinsel .= ' 
 7465:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7466:         } else {
 7467:             $srchinsel .= '
 7468:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7469:         }
 7470:     }
 7471:     $srchinsel .= "\n  </select>\n";
 7472: 
 7473:     my $srchbysel =  ' <select name="srchby">';
 7474:     foreach my $option ('lastname','lastfirst','uname') {
 7475:         if ($curr_selected{'srchby'} eq $option) {
 7476:             $srchbysel .= '
 7477:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7478:         } else {
 7479:             $srchbysel .= '
 7480:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7481:          }
 7482:     }
 7483:     $srchbysel .= "\n  </select>\n";
 7484: 
 7485:     my $srchtypesel = ' <select name="srchtype">';
 7486:     foreach my $option ('begins','contains','exact') {
 7487:         if ($curr_selected{'srchtype'} eq $option) {
 7488:             $srchtypesel .= '
 7489:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7490:         } else {
 7491:             $srchtypesel .= '
 7492:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7493:         }
 7494:     }
 7495:     $srchtypesel .= "\n  </select>\n";
 7496: 
 7497:     my ($newuserscript,$new_user_create);
 7498: 
 7499:     if ($forcenewuser) {
 7500:         if (ref($srch) eq 'HASH') {
 7501:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7502:                 if ($cancreate) {
 7503:                     $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>';
 7504:                 } else {
 7505:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7506:                     my %usertypetext = (
 7507:                         official   => 'institutional',
 7508:                         unofficial => 'non-institutional',
 7509:                     );
 7510:                     $new_user_create = '<p class="LC_warning">'
 7511:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7512:                                       .' '
 7513:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7514:                                           ,'<a href="'.$helplink.'">','</a>')
 7515:                                       .'</p><br />';
 7516:                 }
 7517:             }
 7518:         }
 7519: 
 7520:         $newuserscript = <<"ENDSCRIPT";
 7521: 
 7522: function setSearch(createnew,callingForm) {
 7523:     if (createnew == 1) {
 7524:         for (var i=0; i<callingForm.srchby.length; i++) {
 7525:             if (callingForm.srchby.options[i].value == 'uname') {
 7526:                 callingForm.srchby.selectedIndex = i;
 7527:             }
 7528:         }
 7529:         for (var i=0; i<callingForm.srchin.length; i++) {
 7530:             if ( callingForm.srchin.options[i].value == 'dom') {
 7531: 		callingForm.srchin.selectedIndex = i;
 7532:             }
 7533:         }
 7534:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7535:             if (callingForm.srchtype.options[i].value == 'exact') {
 7536:                 callingForm.srchtype.selectedIndex = i;
 7537:             }
 7538:         }
 7539:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7540:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7541:                 callingForm.srchdomain.selectedIndex = i;
 7542:             }
 7543:         }
 7544:     }
 7545: }
 7546: ENDSCRIPT
 7547: 
 7548:     }
 7549: 
 7550:     my $output = <<"END_BLOCK";
 7551: <script type="text/javascript">
 7552: // <![CDATA[
 7553: function validateEntry(callingForm) {
 7554: 
 7555:     var checkok = 1;
 7556:     var srchin;
 7557:     for (var i=0; i<callingForm.srchin.length; i++) {
 7558: 	if ( callingForm.srchin[i].checked ) {
 7559: 	    srchin = callingForm.srchin[i].value;
 7560: 	}
 7561:     }
 7562: 
 7563:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7564:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7565:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7566:     var srchterm =  callingForm.srchterm.value;
 7567:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7568:     var msg = "";
 7569: 
 7570:     if (srchterm == "") {
 7571:         checkok = 0;
 7572:         msg += "$lt{'youm'}\\n";
 7573:     }
 7574: 
 7575:     if (srchtype== 'begins') {
 7576:         if (srchterm.length < 2) {
 7577:             checkok = 0;
 7578:             msg += "$lt{'thte'}\\n";
 7579:         }
 7580:     }
 7581: 
 7582:     if (srchtype== 'contains') {
 7583:         if (srchterm.length < 3) {
 7584:             checkok = 0;
 7585:             msg += "$lt{'thet'}\\n";
 7586:         }
 7587:     }
 7588:     if (srchin == 'instd') {
 7589:         if (srchdomain == '') {
 7590:             checkok = 0;
 7591:             msg += "$lt{'yomc'}\\n";
 7592:         }
 7593:     }
 7594:     if (srchin == 'dom') {
 7595:         if (srchdomain == '') {
 7596:             checkok = 0;
 7597:             msg += "$lt{'ymcd'}\\n";
 7598:         }
 7599:     }
 7600:     if (srchby == 'lastfirst') {
 7601:         if (srchterm.indexOf(",") == -1) {
 7602:             checkok = 0;
 7603:             msg += "$lt{'whus'}\\n";
 7604:         }
 7605:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7606:             checkok = 0;
 7607:             msg += "$lt{'whse'}\\n";
 7608:         }
 7609:     }
 7610:     if (checkok == 0) {
 7611:         alert("$lt{'thfo'}\\n"+msg);
 7612:         return;
 7613:     }
 7614:     if (checkok == 1) {
 7615:         callingForm.submit();
 7616:     }
 7617: }
 7618: 
 7619: $newuserscript
 7620: 
 7621: // ]]>
 7622: </script>
 7623: 
 7624: $new_user_create
 7625: 
 7626: <table>
 7627:  <tr>
 7628:   <td>$lt{'doma'}:</td>
 7629:   <td>$domform</td>
 7630:   </td>
 7631:  </tr>
 7632:  <tr>
 7633:   <td>$lt{'usr'}:</td>
 7634:   <td>$srchbysel
 7635:       $srchtypesel 
 7636:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7637:       $srchinsel 
 7638:   </td>
 7639:  </tr>
 7640: </table>
 7641: <br />
 7642: END_BLOCK
 7643: 
 7644:     return $output;
 7645: }
 7646: 
 7647: sub user_rule_check {
 7648:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7649:     my $response;
 7650:     if (ref($usershash) eq 'HASH') {
 7651:         foreach my $user (keys(%{$usershash})) {
 7652:             my ($uname,$udom) = split(/:/,$user);
 7653:             next if ($udom eq '' || $uname eq '');
 7654:             my ($id,$newuser);
 7655:             if (ref($usershash->{$user}) eq 'HASH') {
 7656:                 $newuser = $usershash->{$user}->{'newuser'};
 7657:                 $id = $usershash->{$user}->{'id'};
 7658:             }
 7659:             my $inst_response;
 7660:             if (ref($checks) eq 'HASH') {
 7661:                 if (defined($checks->{'username'})) {
 7662:                     ($inst_response,%{$inst_results->{$user}}) = 
 7663:                         &Apache::lonnet::get_instuser($udom,$uname);
 7664:                 } elsif (defined($checks->{'id'})) {
 7665:                     ($inst_response,%{$inst_results->{$user}}) =
 7666:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7667:                 }
 7668:             } else {
 7669:                 ($inst_response,%{$inst_results->{$user}}) =
 7670:                     &Apache::lonnet::get_instuser($udom,$uname);
 7671:                 return;
 7672:             }
 7673:             if (!$got_rules->{$udom}) {
 7674:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7675:                                                   ['usercreation'],$udom);
 7676:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7677:                     foreach my $item ('username','id') {
 7678:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7679:                             $$curr_rules{$udom}{$item} = 
 7680:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7681:                         }
 7682:                     }
 7683:                 }
 7684:                 $got_rules->{$udom} = 1;  
 7685:             }
 7686:             foreach my $item (keys(%{$checks})) {
 7687:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7688:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7689:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7690:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7691:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7692:                                 if ($rule_check{$rule}) {
 7693:                                     $$rulematch{$user}{$item} = $rule;
 7694:                                     if ($inst_response eq 'ok') {
 7695:                                         if (ref($inst_results) eq 'HASH') {
 7696:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7697:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7698:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7699:                                                 }
 7700:                                             }
 7701:                                         }
 7702:                                     }
 7703:                                     last;
 7704:                                 }
 7705:                             }
 7706:                         }
 7707:                     }
 7708:                 }
 7709:             }
 7710:         }
 7711:     }
 7712:     return;
 7713: }
 7714: 
 7715: sub user_rule_formats {
 7716:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7717:     my %text = ( 
 7718:                  'username' => 'Usernames',
 7719:                  'id'       => 'IDs',
 7720:                );
 7721:     my $output;
 7722:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7723:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7724:         if (@{$ruleorder} > 0) {
 7725:             $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>';
 7726:             foreach my $rule (@{$ruleorder}) {
 7727:                 if (ref($curr_rules) eq 'ARRAY') {
 7728:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7729:                         if (ref($rules->{$rule}) eq 'HASH') {
 7730:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7731:                                         $rules->{$rule}{'desc'}.'</li>';
 7732:                         }
 7733:                     }
 7734:                 }
 7735:             }
 7736:             $output .= '</ul>';
 7737:         }
 7738:     }
 7739:     return $output;
 7740: }
 7741: 
 7742: sub instrule_disallow_msg {
 7743:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7744:     my $response;
 7745:     my %text = (
 7746:                   item   => 'username',
 7747:                   items  => 'usernames',
 7748:                   match  => 'matches',
 7749:                   do     => 'does',
 7750:                   action => 'a username',
 7751:                   one    => 'one',
 7752:                );
 7753:     if ($count > 1) {
 7754:         $text{'item'} = 'usernames';
 7755:         $text{'match'} ='match';
 7756:         $text{'do'} = 'do';
 7757:         $text{'action'} = 'usernames',
 7758:         $text{'one'} = 'ones';
 7759:     }
 7760:     if ($checkitem eq 'id') {
 7761:         $text{'items'} = 'IDs';
 7762:         $text{'item'} = 'ID';
 7763:         $text{'action'} = 'an ID';
 7764:         if ($count > 1) {
 7765:             $text{'item'} = 'IDs';
 7766:             $text{'action'} = 'IDs';
 7767:         }
 7768:     }
 7769:     $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 />';
 7770:     if ($mode eq 'upload') {
 7771:         if ($checkitem eq 'username') {
 7772:             $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'}.");
 7773:         } elsif ($checkitem eq 'id') {
 7774:             $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.");
 7775:         }
 7776:     } elsif ($mode eq 'selfcreate') {
 7777:         if ($checkitem eq 'id') {
 7778:             $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.");
 7779:         }
 7780:     } else {
 7781:         if ($checkitem eq 'username') {
 7782:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7783:         } elsif ($checkitem eq 'id') {
 7784:             $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.");
 7785:         }
 7786:     }
 7787:     return $response;
 7788: }
 7789: 
 7790: sub personal_data_fieldtitles {
 7791:     my %fieldtitles = &Apache::lonlocal::texthash (
 7792:                         id => 'Student/Employee ID',
 7793:                         permanentemail => 'E-mail address',
 7794:                         lastname => 'Last Name',
 7795:                         firstname => 'First Name',
 7796:                         middlename => 'Middle Name',
 7797:                         generation => 'Generation',
 7798:                         gen => 'Generation',
 7799:                         inststatus => 'Affiliation',
 7800:                    );
 7801:     return %fieldtitles;
 7802: }
 7803: 
 7804: sub sorted_inst_types {
 7805:     my ($dom) = @_;
 7806:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7807:     my $othertitle = &mt('All users');
 7808:     if ($env{'request.course.id'}) {
 7809:         $othertitle  = &mt('Any users');
 7810:     }
 7811:     my @types;
 7812:     if (ref($order) eq 'ARRAY') {
 7813:         @types = @{$order};
 7814:     }
 7815:     if (@types == 0) {
 7816:         if (ref($usertypes) eq 'HASH') {
 7817:             @types = sort(keys(%{$usertypes}));
 7818:         }
 7819:     }
 7820:     if (keys(%{$usertypes}) > 0) {
 7821:         $othertitle = &mt('Other users');
 7822:     }
 7823:     return ($othertitle,$usertypes,\@types);
 7824: }
 7825: 
 7826: sub get_institutional_codes {
 7827:     my ($settings,$allcourses,$LC_code) = @_;
 7828: # Get complete list of course sections to update
 7829:     my @currsections = ();
 7830:     my @currxlists = ();
 7831:     my $coursecode = $$settings{'internal.coursecode'};
 7832: 
 7833:     if ($$settings{'internal.sectionnums'} ne '') {
 7834:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7835:     }
 7836: 
 7837:     if ($$settings{'internal.crosslistings'} ne '') {
 7838:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7839:     }
 7840: 
 7841:     if (@currxlists > 0) {
 7842:         foreach (@currxlists) {
 7843:             if (m/^([^:]+):(\w*)$/) {
 7844:                 unless (grep/^$1$/,@{$allcourses}) {
 7845:                     push @{$allcourses},$1;
 7846:                     $$LC_code{$1} = $2;
 7847:                 }
 7848:             }
 7849:         }
 7850:     }
 7851:  
 7852:     if (@currsections > 0) {
 7853:         foreach (@currsections) {
 7854:             if (m/^(\w+):(\w*)$/) {
 7855:                 my $sec = $coursecode.$1;
 7856:                 my $lc_sec = $2;
 7857:                 unless (grep/^$sec$/,@{$allcourses}) {
 7858:                     push @{$allcourses},$sec;
 7859:                     $$LC_code{$sec} = $lc_sec;
 7860:                 }
 7861:             }
 7862:         }
 7863:     }
 7864:     return;
 7865: }
 7866: 
 7867: =pod
 7868: 
 7869: =head1 Slot Helpers
 7870: 
 7871: =over 4
 7872: 
 7873: =item * sorted_slots()
 7874: 
 7875: Sorts an array of slot names in order of slot start time (earliest first). 
 7876: 
 7877: Inputs:
 7878: 
 7879: =over 4
 7880: 
 7881: slotsarr  - Reference to array of unsorted slot names.
 7882: 
 7883: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7884: 
 7885: =back
 7886: 
 7887: Returns:
 7888: 
 7889: =over 4
 7890: 
 7891: sorted   - An array of slot names sorted by the start time of the slot.
 7892: 
 7893: =back
 7894: 
 7895: =back
 7896: 
 7897: =cut
 7898: 
 7899: 
 7900: sub sorted_slots {
 7901:     my ($slotsarr,$slots) = @_;
 7902:     my @sorted;
 7903:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7904:         @sorted =
 7905:             sort {
 7906:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7907:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7908:                      }
 7909:                      if (ref($slots->{$a})) { return -1;}
 7910:                      if (ref($slots->{$b})) { return 1;}
 7911:                      return 0;
 7912:                  } @{$slotsarr};
 7913:     }
 7914:     return @sorted;
 7915: }
 7916: 
 7917: 
 7918: =pod
 7919: 
 7920: =head1 HTTP Helpers
 7921: 
 7922: =over 4
 7923: 
 7924: =item * &get_unprocessed_cgi($query,$possible_names)
 7925: 
 7926: Modify the %env hash to contain unprocessed CGI form parameters held in
 7927: $query.  The parameters listed in $possible_names (an array reference),
 7928: will be set in $env{'form.name'} if they do not already exist.
 7929: 
 7930: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7931: $possible_names is an ref to an array of form element names.  As an example:
 7932: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7933: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7934: 
 7935: =cut
 7936: 
 7937: sub get_unprocessed_cgi {
 7938:   my ($query,$possible_names)= @_;
 7939:   # $Apache::lonxml::debug=1;
 7940:   foreach my $pair (split(/&/,$query)) {
 7941:     my ($name, $value) = split(/=/,$pair);
 7942:     $name = &unescape($name);
 7943:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7944:       $value =~ tr/+/ /;
 7945:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7946:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7947:     }
 7948:   }
 7949: }
 7950: 
 7951: =pod
 7952: 
 7953: =item * &cacheheader() 
 7954: 
 7955: returns cache-controlling header code
 7956: 
 7957: =cut
 7958: 
 7959: sub cacheheader {
 7960:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7961:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7962:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7963:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7964:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7965:     return $output;
 7966: }
 7967: 
 7968: =pod
 7969: 
 7970: =item * &no_cache($r) 
 7971: 
 7972: specifies header code to not have cache
 7973: 
 7974: =cut
 7975: 
 7976: sub no_cache {
 7977:     my ($r) = @_;
 7978:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7979: 	$env{'request.method'} ne 'GET') { return ''; }
 7980:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7981:     $r->no_cache(1);
 7982:     $r->header_out("Expires" => $date);
 7983:     $r->header_out("Pragma" => "no-cache");
 7984: }
 7985: 
 7986: sub content_type {
 7987:     my ($r,$type,$charset) = @_;
 7988:     if ($r) {
 7989: 	#  Note that printout.pl calls this with undef for $r.
 7990: 	&no_cache($r);
 7991:     }
 7992:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7993:     unless ($charset) {
 7994: 	$charset=&Apache::lonlocal::current_encoding;
 7995:     }
 7996:     if ($charset) { $type.='; charset='.$charset; }
 7997:     if ($r) {
 7998: 	$r->content_type($type);
 7999:     } else {
 8000: 	print("Content-type: $type\n\n");
 8001:     }
 8002: }
 8003: 
 8004: =pod
 8005: 
 8006: =item * &add_to_env($name,$value) 
 8007: 
 8008: adds $name to the %env hash with value
 8009: $value, if $name already exists, the entry is converted to an array
 8010: reference and $value is added to the array.
 8011: 
 8012: =cut
 8013: 
 8014: sub add_to_env {
 8015:   my ($name,$value)=@_;
 8016:   if (defined($env{$name})) {
 8017:     if (ref($env{$name})) {
 8018:       #already have multiple values
 8019:       push(@{ $env{$name} },$value);
 8020:     } else {
 8021:       #first time seeing multiple values, convert hash entry to an arrayref
 8022:       my $first=$env{$name};
 8023:       undef($env{$name});
 8024:       push(@{ $env{$name} },$first,$value);
 8025:     }
 8026:   } else {
 8027:     $env{$name}=$value;
 8028:   }
 8029: }
 8030: 
 8031: =pod
 8032: 
 8033: =item * &get_env_multiple($name) 
 8034: 
 8035: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8036: values may be defined and end up as an array ref.
 8037: 
 8038: returns an array of values
 8039: 
 8040: =cut
 8041: 
 8042: sub get_env_multiple {
 8043:     my ($name) = @_;
 8044:     my @values;
 8045:     if (defined($env{$name})) {
 8046:         # exists is it an array
 8047:         if (ref($env{$name})) {
 8048:             @values=@{ $env{$name} };
 8049:         } else {
 8050:             $values[0]=$env{$name};
 8051:         }
 8052:     }
 8053:     return(@values);
 8054: }
 8055: 
 8056: sub ask_for_embedded_content {
 8057:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8058:     my $upload_output = '
 8059:    <form name="upload_embedded" action="'.$actionurl.'"
 8060:                   method="post" enctype="multipart/form-data">';
 8061:     $upload_output .= $state;
 8062:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8063: 
 8064:     my $num = 0;
 8065:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8066:         $upload_output .= &start_data_table_row().
 8067:             '<td>'.$embed_file.'</td><td>';
 8068:         if ($args->{'ignore_remote_references'}
 8069:             && $embed_file =~ m{^\w+://}) {
 8070:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8071:         } elsif ($args->{'error_on_invalid_names'}
 8072:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8073: 
 8074:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8075: 
 8076:         } else {
 8077:             $upload_output .='
 8078:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8079:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8080:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8081:             $upload_output .=
 8082:                 "\n\t\t".
 8083:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8084:                 $attrib.'" />';
 8085:             if (exists($$codebase{$embed_file})) {
 8086:                 $upload_output .=
 8087:                     "\n\t\t".
 8088:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8089:                     &escape($$codebase{$embed_file}).'" />';
 8090:             }
 8091:         }
 8092:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8093:         $num++;
 8094:     }
 8095:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8096:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8097:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8098:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8099:    </form>';
 8100:     return $upload_output;
 8101: }
 8102: 
 8103: sub upload_embedded {
 8104:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8105:         $current_disk_usage) = @_;
 8106:     my $output;
 8107:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8108:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8109:         my $orig_uploaded_filename =
 8110:             $env{'form.embedded_item_'.$i.'.filename'};
 8111: 
 8112:         $env{'form.embedded_orig_'.$i} =
 8113:             &unescape($env{'form.embedded_orig_'.$i});
 8114:         my ($path,$fname) =
 8115:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8116:         # no path, whole string is fname
 8117:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8118: 
 8119:         $path = $env{'form.currentpath'}.$path;
 8120:         $fname = &Apache::lonnet::clean_filename($fname);
 8121:         # See if there is anything left
 8122:         next if ($fname eq '');
 8123: 
 8124:         # Check if file already exists as a file or directory.
 8125:         my ($state,$msg);
 8126:         if ($context eq 'portfolio') {
 8127:             my $port_path = $dirpath;
 8128:             if ($group ne '') {
 8129:                 $port_path = "groups/$group/$port_path";
 8130:             }
 8131:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8132:                                               $dir_root,$port_path,$disk_quota,
 8133:                                               $current_disk_usage,$uname,$udom);
 8134:             if ($state eq 'will_exceed_quota'
 8135:                 || $state eq 'file_locked'
 8136:                 || $state eq 'file_exists' ) {
 8137:                 $output .= $msg;
 8138:                 next;
 8139:             }
 8140:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8141:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8142:             if ($state eq 'exists') {
 8143:                 $output .= $msg;
 8144:                 next;
 8145:             }
 8146:         }
 8147:         # Check if extension is valid
 8148:         if (($fname =~ /\.(\w+)$/) &&
 8149:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8150:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8151:             next;
 8152:         } elsif (($fname =~ /\.(\w+)$/) &&
 8153:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8154:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8155:             next;
 8156:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8157:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8158:             next;
 8159:         }
 8160: 
 8161:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8162:         if ($context eq 'portfolio') {
 8163:             my $result=
 8164:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8165:                                                 $dirpath.$path);
 8166:             if ($result !~ m|^/uploaded/|) {
 8167:                 $output .= '<span class="LC_error">'
 8168:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8169:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8170:                       .'</span><br />';
 8171:                 next;
 8172:             } else {
 8173:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8174:                            $path.$fname.'</span>').'</p>';     
 8175:             }
 8176:         } else {
 8177: # Save the file
 8178:             my $target = $env{'form.embedded_item_'.$i};
 8179:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8180:             my $dest = $fullpath.$fname;
 8181:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8182:             my @parts=split(/\//,$fullpath);
 8183:             my $count;
 8184:             my $filepath = $dir_root;
 8185:             for ($count=4;$count<=$#parts;$count++) {
 8186:                 $filepath .= "/$parts[$count]";
 8187:                 if ((-e $filepath)!=1) {
 8188:                     mkdir($filepath,0770);
 8189:                 }
 8190:             }
 8191:             my $fh;
 8192:             if (!open($fh,'>'.$dest)) {
 8193:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8194:                 $output .= '<span class="LC_error">'.
 8195:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8196:                            '</span><br />';
 8197:             } else {
 8198:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8199:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8200:                     $output .= '<span class="LC_error">'.
 8201:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8202:                               '</span><br />';
 8203:                 } else {
 8204:                     if ($context eq 'testbank') {
 8205:                         $output .= &mt('Embedded file uploaded successfully:').
 8206:                                    '&nbsp;<a href="'.$url.'">'.
 8207:                                    $orig_uploaded_filename.'</a><br />';
 8208:                     } else {
 8209:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8210:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8211:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8212:                     }
 8213:                 }
 8214:                 close($fh);
 8215:             }
 8216:         }
 8217:     }
 8218:     return $output;
 8219: }
 8220: 
 8221: sub check_for_existing {
 8222:     my ($path,$fname,$element) = @_;
 8223:     my ($state,$msg);
 8224:     if (-d $path.'/'.$fname) {
 8225:         $state = 'exists';
 8226:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8227:     } elsif (-e $path.'/'.$fname) {
 8228:         $state = 'exists';
 8229:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8230:     }
 8231:     if ($state eq 'exists') {
 8232:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8233:     }
 8234:     return ($state,$msg);
 8235: }
 8236: 
 8237: sub check_for_upload {
 8238:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8239:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8240:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8241:     my $getpropath = 1;
 8242:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8243:                                             $getpropath);
 8244:     my $found_file = 0;
 8245:     my $locked_file = 0;
 8246:     foreach my $line (@dir_list) {
 8247:         my ($file_name)=split(/\&/,$line,2);
 8248:         if ($file_name eq $fname){
 8249:             $file_name = $path.$file_name;
 8250:             if ($group ne '') {
 8251:                 $file_name = $group.$file_name;
 8252:             }
 8253:             $found_file = 1;
 8254:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8255:                 $locked_file = 1;
 8256:             }
 8257:         }
 8258:     }
 8259:     if (($current_disk_usage + $filesize) > $disk_quota){
 8260:         my $msg = '<span class="LC_error">'.
 8261:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8262:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8263:         return ('will_exceed_quota',$msg);
 8264:     } elsif ($found_file) {
 8265:         if ($locked_file) {
 8266:             my $msg = '<span class="LC_error">';
 8267:             $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>');
 8268:             $msg .= '</span><br />';
 8269:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8270:             return ('file_locked',$msg);
 8271:         } else {
 8272:             my $msg = '<span class="LC_error">';
 8273:             $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'});
 8274:             $msg .= '</span>';
 8275:             $msg .= '<br />';
 8276:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8277:             return ('file_exists',$msg);
 8278:         }
 8279:     }
 8280: }
 8281: 
 8282: 
 8283: =pod
 8284: 
 8285: =back
 8286: 
 8287: =head1 CSV Upload/Handling functions
 8288: 
 8289: =over 4
 8290: 
 8291: =item * &upfile_store($r)
 8292: 
 8293: Store uploaded file, $r should be the HTTP Request object,
 8294: needs $env{'form.upfile'}
 8295: returns $datatoken to be put into hidden field
 8296: 
 8297: =cut
 8298: 
 8299: sub upfile_store {
 8300:     my $r=shift;
 8301:     $env{'form.upfile'}=~s/\r/\n/gs;
 8302:     $env{'form.upfile'}=~s/\f/\n/gs;
 8303:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8304:     $env{'form.upfile'}=~s/\n+$//gs;
 8305: 
 8306:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8307: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8308:     {
 8309:         my $datafile = $r->dir_config('lonDaemons').
 8310:                            '/tmp/'.$datatoken.'.tmp';
 8311:         if ( open(my $fh,">$datafile") ) {
 8312:             print $fh $env{'form.upfile'};
 8313:             close($fh);
 8314:         }
 8315:     }
 8316:     return $datatoken;
 8317: }
 8318: 
 8319: =pod
 8320: 
 8321: =item * &load_tmp_file($r)
 8322: 
 8323: Load uploaded file from tmp, $r should be the HTTP Request object,
 8324: needs $env{'form.datatoken'},
 8325: sets $env{'form.upfile'} to the contents of the file
 8326: 
 8327: =cut
 8328: 
 8329: sub load_tmp_file {
 8330:     my $r=shift;
 8331:     my @studentdata=();
 8332:     {
 8333:         my $studentfile = $r->dir_config('lonDaemons').
 8334:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8335:         if ( open(my $fh,"<$studentfile") ) {
 8336:             @studentdata=<$fh>;
 8337:             close($fh);
 8338:         }
 8339:     }
 8340:     $env{'form.upfile'}=join('',@studentdata);
 8341: }
 8342: 
 8343: =pod
 8344: 
 8345: =item * &upfile_record_sep()
 8346: 
 8347: Separate uploaded file into records
 8348: returns array of records,
 8349: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8350: 
 8351: =cut
 8352: 
 8353: sub upfile_record_sep {
 8354:     if ($env{'form.upfiletype'} eq 'xml') {
 8355:     } else {
 8356: 	my @records;
 8357: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8358: 	    if ($line=~/^\s*$/) { next; }
 8359: 	    push(@records,$line);
 8360: 	}
 8361: 	return @records;
 8362:     }
 8363: }
 8364: 
 8365: =pod
 8366: 
 8367: =item * &record_sep($record)
 8368: 
 8369: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8370: 
 8371: =cut
 8372: 
 8373: sub takeleft {
 8374:     my $index=shift;
 8375:     return substr('0000'.$index,-4,4);
 8376: }
 8377: 
 8378: sub record_sep {
 8379:     my $record=shift;
 8380:     my %components=();
 8381:     if ($env{'form.upfiletype'} eq 'xml') {
 8382:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8383:         my $i=0;
 8384:         foreach my $field (split(/\s+/,$record)) {
 8385:             $field=~s/^(\"|\')//;
 8386:             $field=~s/(\"|\')$//;
 8387:             $components{&takeleft($i)}=$field;
 8388:             $i++;
 8389:         }
 8390:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8391:         my $i=0;
 8392:         foreach my $field (split(/\t/,$record)) {
 8393:             $field=~s/^(\"|\')//;
 8394:             $field=~s/(\"|\')$//;
 8395:             $components{&takeleft($i)}=$field;
 8396:             $i++;
 8397:         }
 8398:     } else {
 8399:         my $separator=',';
 8400:         if ($env{'form.upfiletype'} eq 'semisv') {
 8401:             $separator=';';
 8402:         }
 8403:         my $i=0;
 8404: # the character we are looking for to indicate the end of a quote or a record 
 8405:         my $looking_for=$separator;
 8406: # do not add the characters to the fields
 8407:         my $ignore=0;
 8408: # we just encountered a separator (or the beginning of the record)
 8409:         my $just_found_separator=1;
 8410: # store the field we are working on here
 8411:         my $field='';
 8412: # work our way through all characters in record
 8413:         foreach my $character ($record=~/(.)/g) {
 8414:             if ($character eq $looking_for) {
 8415:                if ($character ne $separator) {
 8416: # Found the end of a quote, again looking for separator
 8417:                   $looking_for=$separator;
 8418:                   $ignore=1;
 8419:                } else {
 8420: # Found a separator, store away what we got
 8421:                   $components{&takeleft($i)}=$field;
 8422: 	          $i++;
 8423:                   $just_found_separator=1;
 8424:                   $ignore=0;
 8425:                   $field='';
 8426:                }
 8427:                next;
 8428:             }
 8429: # single or double quotation marks after a separator indicate beginning of a quote
 8430: # we are now looking for the end of the quote and need to ignore separators
 8431:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8432:                $looking_for=$character;
 8433:                next;
 8434:             }
 8435: # ignore would be true after we reached the end of a quote
 8436:             if ($ignore) { next; }
 8437:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8438:             $field.=$character;
 8439:             $just_found_separator=0; 
 8440:         }
 8441: # catch the very last entry, since we never encountered the separator
 8442:         $components{&takeleft($i)}=$field;
 8443:     }
 8444:     return %components;
 8445: }
 8446: 
 8447: ######################################################
 8448: ######################################################
 8449: 
 8450: =pod
 8451: 
 8452: =item * &upfile_select_html()
 8453: 
 8454: Return HTML code to select a file from the users machine and specify 
 8455: the file type.
 8456: 
 8457: =cut
 8458: 
 8459: ######################################################
 8460: ######################################################
 8461: sub upfile_select_html {
 8462:     my %Types = (
 8463:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8464:                  semisv => &mt('Semicolon separated values'),
 8465:                  space => &mt('Space separated'),
 8466:                  tab   => &mt('Tabulator separated'),
 8467: #                 xml   => &mt('HTML/XML'),
 8468:                  );
 8469:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8470:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8471:     foreach my $type (sort(keys(%Types))) {
 8472:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8473:     }
 8474:     $Str .= "</select>\n";
 8475:     return $Str;
 8476: }
 8477: 
 8478: sub get_samples {
 8479:     my ($records,$toget) = @_;
 8480:     my @samples=({});
 8481:     my $got=0;
 8482:     foreach my $rec (@$records) {
 8483: 	my %temp = &record_sep($rec);
 8484: 	if (! grep(/\S/, values(%temp))) { next; }
 8485: 	if (%temp) {
 8486: 	    $samples[$got]=\%temp;
 8487: 	    $got++;
 8488: 	    if ($got == $toget) { last; }
 8489: 	}
 8490:     }
 8491:     return \@samples;
 8492: }
 8493: 
 8494: ######################################################
 8495: ######################################################
 8496: 
 8497: =pod
 8498: 
 8499: =item * &csv_print_samples($r,$records)
 8500: 
 8501: Prints a table of sample values from each column uploaded $r is an
 8502: Apache Request ref, $records is an arrayref from
 8503: &Apache::loncommon::upfile_record_sep
 8504: 
 8505: =cut
 8506: 
 8507: ######################################################
 8508: ######################################################
 8509: sub csv_print_samples {
 8510:     my ($r,$records) = @_;
 8511:     my $samples = &get_samples($records,5);
 8512: 
 8513:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8514:               &start_data_table_header_row());
 8515:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8516:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 8517:     $r->print(&end_data_table_header_row());
 8518:     foreach my $hash (@$samples) {
 8519: 	$r->print(&start_data_table_row());
 8520: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8521: 	    $r->print('<td>');
 8522: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8523: 	    $r->print('</td>');
 8524: 	}
 8525: 	$r->print(&end_data_table_row());
 8526:     }
 8527:     $r->print(&end_data_table().'<br />'."\n");
 8528: }
 8529: 
 8530: ######################################################
 8531: ######################################################
 8532: 
 8533: =pod
 8534: 
 8535: =item * &csv_print_select_table($r,$records,$d)
 8536: 
 8537: Prints a table to create associations between values and table columns.
 8538: 
 8539: $r is an Apache Request ref,
 8540: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8541: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8542: 
 8543: =cut
 8544: 
 8545: ######################################################
 8546: ######################################################
 8547: sub csv_print_select_table {
 8548:     my ($r,$records,$d) = @_;
 8549:     my $i=0;
 8550:     my $samples = &get_samples($records,1);
 8551:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8552: 	      &start_data_table().&start_data_table_header_row().
 8553:               '<th>'.&mt('Attribute').'</th>'.
 8554:               '<th>'.&mt('Column').'</th>'.
 8555:               &end_data_table_header_row()."\n");
 8556:     foreach my $array_ref (@$d) {
 8557: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8558: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8559: 
 8560: 	$r->print('<td><select name=f'.$i.
 8561: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8562: 	$r->print('<option value="none"></option>');
 8563: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8564: 	    $r->print('<option value="'.$sample.'"'.
 8565:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8566:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8567: 	}
 8568: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8569: 	$i++;
 8570:     }
 8571:     $r->print(&end_data_table());
 8572:     $i--;
 8573:     return $i;
 8574: }
 8575: 
 8576: ######################################################
 8577: ######################################################
 8578: 
 8579: =pod
 8580: 
 8581: =item * &csv_samples_select_table($r,$records,$d)
 8582: 
 8583: Prints a table of sample values from the upload and can make associate samples to internal names.
 8584: 
 8585: $r is an Apache Request ref,
 8586: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8587: $d is an array of 2 element arrays (internal name, displayed name)
 8588: 
 8589: =cut
 8590: 
 8591: ######################################################
 8592: ######################################################
 8593: sub csv_samples_select_table {
 8594:     my ($r,$records,$d) = @_;
 8595:     my $i=0;
 8596:     #
 8597:     my $max_samples = 5;
 8598:     my $samples = &get_samples($records,$max_samples);
 8599:     $r->print(&start_data_table().
 8600:               &start_data_table_header_row().'<th>'.
 8601:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8602:               &end_data_table_header_row());
 8603: 
 8604:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8605: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8606: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8607: 	foreach my $option (@$d) {
 8608: 	    my ($value,$display,$defaultcol)=@{ $option };
 8609: 	    $r->print('<option value="'.$value.'"'.
 8610:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8611:                       $display.'</option>');
 8612: 	}
 8613: 	$r->print('</select></td><td>');
 8614: 	foreach my $line (0..($max_samples-1)) {
 8615: 	    if (defined($samples->[$line]{$key})) { 
 8616: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8617: 	    }
 8618: 	}
 8619: 	$r->print('</td>'.&end_data_table_row());
 8620: 	$i++;
 8621:     }
 8622:     $r->print(&end_data_table());
 8623:     $i--;
 8624:     return($i);
 8625: }
 8626: 
 8627: ######################################################
 8628: ######################################################
 8629: 
 8630: =pod
 8631: 
 8632: =item * &clean_excel_name($name)
 8633: 
 8634: Returns a replacement for $name which does not contain any illegal characters.
 8635: 
 8636: =cut
 8637: 
 8638: ######################################################
 8639: ######################################################
 8640: sub clean_excel_name {
 8641:     my ($name) = @_;
 8642:     $name =~ s/[:\*\?\/\\]//g;
 8643:     if (length($name) > 31) {
 8644:         $name = substr($name,0,31);
 8645:     }
 8646:     return $name;
 8647: }
 8648: 
 8649: =pod
 8650: 
 8651: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8652: 
 8653: Returns either 1 or undef
 8654: 
 8655: 1 if the part is to be hidden, undef if it is to be shown
 8656: 
 8657: Arguments are:
 8658: 
 8659: $id the id of the part to be checked
 8660: $symb, optional the symb of the resource to check
 8661: $udom, optional the domain of the user to check for
 8662: $uname, optional the username of the user to check for
 8663: 
 8664: =cut
 8665: 
 8666: sub check_if_partid_hidden {
 8667:     my ($id,$symb,$udom,$uname) = @_;
 8668:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8669: 					 $symb,$udom,$uname);
 8670:     my $truth=1;
 8671:     #if the string starts with !, then the list is the list to show not hide
 8672:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8673:     my @hiddenlist=split(/,/,$hiddenparts);
 8674:     foreach my $checkid (@hiddenlist) {
 8675: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8676:     }
 8677:     return !$truth;
 8678: }
 8679: 
 8680: 
 8681: ############################################################
 8682: ############################################################
 8683: 
 8684: =pod
 8685: 
 8686: =back 
 8687: 
 8688: =head1 cgi-bin script and graphing routines
 8689: 
 8690: =over 4
 8691: 
 8692: =item * &get_cgi_id()
 8693: 
 8694: Inputs: none
 8695: 
 8696: Returns an id which can be used to pass environment variables
 8697: to various cgi-bin scripts.  These environment variables will
 8698: be removed from the users environment after a given time by
 8699: the routine &Apache::lonnet::transfer_profile_to_env.
 8700: 
 8701: =cut
 8702: 
 8703: ############################################################
 8704: ############################################################
 8705: my $uniq=0;
 8706: sub get_cgi_id {
 8707:     $uniq=($uniq+1)%100000;
 8708:     return (time.'_'.$$.'_'.$uniq);
 8709: }
 8710: 
 8711: ############################################################
 8712: ############################################################
 8713: 
 8714: =pod
 8715: 
 8716: =item * &DrawBarGraph()
 8717: 
 8718: Facilitates the plotting of data in a (stacked) bar graph.
 8719: Puts plot definition data into the users environment in order for 
 8720: graph.png to plot it.  Returns an <img> tag for the plot.
 8721: The bars on the plot are labeled '1','2',...,'n'.
 8722: 
 8723: Inputs:
 8724: 
 8725: =over 4
 8726: 
 8727: =item $Title: string, the title of the plot
 8728: 
 8729: =item $xlabel: string, text describing the X-axis of the plot
 8730: 
 8731: =item $ylabel: string, text describing the Y-axis of the plot
 8732: 
 8733: =item $Max: scalar, the maximum Y value to use in the plot
 8734: If $Max is < any data point, the graph will not be rendered.
 8735: 
 8736: =item $colors: array ref holding the colors to be used for the data sets when
 8737: they are plotted.  If undefined, default values will be used.
 8738: 
 8739: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8740: 
 8741: =item @Values: An array of array references.  Each array reference holds data
 8742: to be plotted in a stacked bar chart.
 8743: 
 8744: =item If the final element of @Values is a hash reference the key/value
 8745: pairs will be added to the graph definition.
 8746: 
 8747: =back
 8748: 
 8749: Returns:
 8750: 
 8751: An <img> tag which references graph.png and the appropriate identifying
 8752: information for the plot.
 8753: 
 8754: =cut
 8755: 
 8756: ############################################################
 8757: ############################################################
 8758: sub DrawBarGraph {
 8759:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8760:     #
 8761:     if (! defined($colors)) {
 8762:         $colors = ['#33ff00', 
 8763:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8764:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8765:                   ]; 
 8766:     }
 8767:     my $extra_settings = {};
 8768:     if (ref($Values[-1]) eq 'HASH') {
 8769:         $extra_settings = pop(@Values);
 8770:     }
 8771:     #
 8772:     my $identifier = &get_cgi_id();
 8773:     my $id = 'cgi.'.$identifier;        
 8774:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8775:         return '';
 8776:     }
 8777:     #
 8778:     my @Labels;
 8779:     if (defined($labels)) {
 8780:         @Labels = @$labels;
 8781:     } else {
 8782:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8783:             push (@Labels,$i+1);
 8784:         }
 8785:     }
 8786:     #
 8787:     my $NumBars = scalar(@{$Values[0]});
 8788:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8789:     my %ValuesHash;
 8790:     my $NumSets=1;
 8791:     foreach my $array (@Values) {
 8792:         next if (! ref($array));
 8793:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8794:             join(',',@$array);
 8795:     }
 8796:     #
 8797:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8798:     if ($NumBars < 3) {
 8799:         $width = 120+$NumBars*32;
 8800:         $xskip = 1;
 8801:         $bar_width = 30;
 8802:     } elsif ($NumBars < 5) {
 8803:         $width = 120+$NumBars*20;
 8804:         $xskip = 1;
 8805:         $bar_width = 20;
 8806:     } elsif ($NumBars < 10) {
 8807:         $width = 120+$NumBars*15;
 8808:         $xskip = 1;
 8809:         $bar_width = 15;
 8810:     } elsif ($NumBars <= 25) {
 8811:         $width = 120+$NumBars*11;
 8812:         $xskip = 5;
 8813:         $bar_width = 8;
 8814:     } elsif ($NumBars <= 50) {
 8815:         $width = 120+$NumBars*8;
 8816:         $xskip = 5;
 8817:         $bar_width = 4;
 8818:     } else {
 8819:         $width = 120+$NumBars*8;
 8820:         $xskip = 5;
 8821:         $bar_width = 4;
 8822:     }
 8823:     #
 8824:     $Max = 1 if ($Max < 1);
 8825:     if ( int($Max) < $Max ) {
 8826:         $Max++;
 8827:         $Max = int($Max);
 8828:     }
 8829:     $Title  = '' if (! defined($Title));
 8830:     $xlabel = '' if (! defined($xlabel));
 8831:     $ylabel = '' if (! defined($ylabel));
 8832:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8833:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8834:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8835:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8836:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8837:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8838:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8839:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8840:     $ValuesHash{$id.'.height'}   = $height;
 8841:     $ValuesHash{$id.'.width'}    = $width;
 8842:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8843:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8844:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8845:     #
 8846:     # Deal with other parameters
 8847:     while (my ($key,$value) = each(%$extra_settings)) {
 8848:         $ValuesHash{$id.'.'.$key} = $value;
 8849:     }
 8850:     #
 8851:     &Apache::lonnet::appenv(\%ValuesHash);
 8852:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8853: }
 8854: 
 8855: ############################################################
 8856: ############################################################
 8857: 
 8858: =pod
 8859: 
 8860: =item * &DrawXYGraph()
 8861: 
 8862: Facilitates the plotting of data in an XY graph.
 8863: Puts plot definition data into the users environment in order for 
 8864: graph.png to plot it.  Returns an <img> tag for the plot.
 8865: 
 8866: Inputs:
 8867: 
 8868: =over 4
 8869: 
 8870: =item $Title: string, the title of the plot
 8871: 
 8872: =item $xlabel: string, text describing the X-axis of the plot
 8873: 
 8874: =item $ylabel: string, text describing the Y-axis of the plot
 8875: 
 8876: =item $Max: scalar, the maximum Y value to use in the plot
 8877: If $Max is < any data point, the graph will not be rendered.
 8878: 
 8879: =item $colors: Array ref containing the hex color codes for the data to be 
 8880: plotted in.  If undefined, default values will be used.
 8881: 
 8882: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8883: 
 8884: =item $Ydata: Array ref containing Array refs.  
 8885: Each of the contained arrays will be plotted as a separate curve.
 8886: 
 8887: =item %Values: hash indicating or overriding any default values which are 
 8888: passed to graph.png.  
 8889: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8890: 
 8891: =back
 8892: 
 8893: Returns:
 8894: 
 8895: An <img> tag which references graph.png and the appropriate identifying
 8896: information for the plot.
 8897: 
 8898: =cut
 8899: 
 8900: ############################################################
 8901: ############################################################
 8902: sub DrawXYGraph {
 8903:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8904:     #
 8905:     # Create the identifier for the graph
 8906:     my $identifier = &get_cgi_id();
 8907:     my $id = 'cgi.'.$identifier;
 8908:     #
 8909:     $Title  = '' if (! defined($Title));
 8910:     $xlabel = '' if (! defined($xlabel));
 8911:     $ylabel = '' if (! defined($ylabel));
 8912:     my %ValuesHash = 
 8913:         (
 8914:          $id.'.title'  => &escape($Title),
 8915:          $id.'.xlabel' => &escape($xlabel),
 8916:          $id.'.ylabel' => &escape($ylabel),
 8917:          $id.'.y_max_value'=> $Max,
 8918:          $id.'.labels'     => join(',',@$Xlabels),
 8919:          $id.'.PlotType'   => 'XY',
 8920:          );
 8921:     #
 8922:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8923:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8924:     }
 8925:     #
 8926:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8927:         return '';
 8928:     }
 8929:     my $NumSets=1;
 8930:     foreach my $array (@{$Ydata}){
 8931:         next if (! ref($array));
 8932:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8933:     }
 8934:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8935:     #
 8936:     # Deal with other parameters
 8937:     while (my ($key,$value) = each(%Values)) {
 8938:         $ValuesHash{$id.'.'.$key} = $value;
 8939:     }
 8940:     #
 8941:     &Apache::lonnet::appenv(\%ValuesHash);
 8942:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8943: }
 8944: 
 8945: ############################################################
 8946: ############################################################
 8947: 
 8948: =pod
 8949: 
 8950: =item * &DrawXYYGraph()
 8951: 
 8952: Facilitates the plotting of data in an XY graph with two Y axes.
 8953: Puts plot definition data into the users environment in order for 
 8954: graph.png to plot it.  Returns an <img> tag for the plot.
 8955: 
 8956: Inputs:
 8957: 
 8958: =over 4
 8959: 
 8960: =item $Title: string, the title of the plot
 8961: 
 8962: =item $xlabel: string, text describing the X-axis of the plot
 8963: 
 8964: =item $ylabel: string, text describing the Y-axis of the plot
 8965: 
 8966: =item $colors: Array ref containing the hex color codes for the data to be 
 8967: plotted in.  If undefined, default values will be used.
 8968: 
 8969: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8970: 
 8971: =item $Ydata1: The first data set
 8972: 
 8973: =item $Min1: The minimum value of the left Y-axis
 8974: 
 8975: =item $Max1: The maximum value of the left Y-axis
 8976: 
 8977: =item $Ydata2: The second data set
 8978: 
 8979: =item $Min2: The minimum value of the right Y-axis
 8980: 
 8981: =item $Max2: The maximum value of the left Y-axis
 8982: 
 8983: =item %Values: hash indicating or overriding any default values which are 
 8984: passed to graph.png.  
 8985: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8986: 
 8987: =back
 8988: 
 8989: Returns:
 8990: 
 8991: An <img> tag which references graph.png and the appropriate identifying
 8992: information for the plot.
 8993: 
 8994: =cut
 8995: 
 8996: ############################################################
 8997: ############################################################
 8998: sub DrawXYYGraph {
 8999:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9000:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9001:     #
 9002:     # Create the identifier for the graph
 9003:     my $identifier = &get_cgi_id();
 9004:     my $id = 'cgi.'.$identifier;
 9005:     #
 9006:     $Title  = '' if (! defined($Title));
 9007:     $xlabel = '' if (! defined($xlabel));
 9008:     $ylabel = '' if (! defined($ylabel));
 9009:     my %ValuesHash = 
 9010:         (
 9011:          $id.'.title'  => &escape($Title),
 9012:          $id.'.xlabel' => &escape($xlabel),
 9013:          $id.'.ylabel' => &escape($ylabel),
 9014:          $id.'.labels' => join(',',@$Xlabels),
 9015:          $id.'.PlotType' => 'XY',
 9016:          $id.'.NumSets' => 2,
 9017:          $id.'.two_axes' => 1,
 9018:          $id.'.y1_max_value' => $Max1,
 9019:          $id.'.y1_min_value' => $Min1,
 9020:          $id.'.y2_max_value' => $Max2,
 9021:          $id.'.y2_min_value' => $Min2,
 9022:          );
 9023:     #
 9024:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9025:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9026:     }
 9027:     #
 9028:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9029:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9030:         return '';
 9031:     }
 9032:     my $NumSets=1;
 9033:     foreach my $array ($Ydata1,$Ydata2){
 9034:         next if (! ref($array));
 9035:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9036:     }
 9037:     #
 9038:     # Deal with other parameters
 9039:     while (my ($key,$value) = each(%Values)) {
 9040:         $ValuesHash{$id.'.'.$key} = $value;
 9041:     }
 9042:     #
 9043:     &Apache::lonnet::appenv(\%ValuesHash);
 9044:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9045: }
 9046: 
 9047: ############################################################
 9048: ############################################################
 9049: 
 9050: =pod
 9051: 
 9052: =back 
 9053: 
 9054: =head1 Statistics helper routines?  
 9055: 
 9056: Bad place for them but what the hell.
 9057: 
 9058: =over 4
 9059: 
 9060: =item * &chartlink()
 9061: 
 9062: Returns a link to the chart for a specific student.  
 9063: 
 9064: Inputs:
 9065: 
 9066: =over 4
 9067: 
 9068: =item $linktext: The text of the link
 9069: 
 9070: =item $sname: The students username
 9071: 
 9072: =item $sdomain: The students domain
 9073: 
 9074: =back
 9075: 
 9076: =back
 9077: 
 9078: =cut
 9079: 
 9080: ############################################################
 9081: ############################################################
 9082: sub chartlink {
 9083:     my ($linktext, $sname, $sdomain) = @_;
 9084:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9085:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9086:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9087:        '">'.$linktext.'</a>';
 9088: }
 9089: 
 9090: #######################################################
 9091: #######################################################
 9092: 
 9093: =pod
 9094: 
 9095: =head1 Course Environment Routines
 9096: 
 9097: =over 4
 9098: 
 9099: =item * &restore_course_settings()
 9100: 
 9101: =item * &store_course_settings()
 9102: 
 9103: Restores/Store indicated form parameters from the course environment.
 9104: Will not overwrite existing values of the form parameters.
 9105: 
 9106: Inputs: 
 9107: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9108: 
 9109: a hash ref describing the data to be stored.  For example:
 9110:    
 9111: %Save_Parameters = ('Status' => 'scalar',
 9112:     'chartoutputmode' => 'scalar',
 9113:     'chartoutputdata' => 'scalar',
 9114:     'Section' => 'array',
 9115:     'Group' => 'array',
 9116:     'StudentData' => 'array',
 9117:     'Maps' => 'array');
 9118: 
 9119: Returns: both routines return nothing
 9120: 
 9121: =back
 9122: 
 9123: =cut
 9124: 
 9125: #######################################################
 9126: #######################################################
 9127: sub store_course_settings {
 9128:     return &store_settings($env{'request.course.id'},@_);
 9129: }
 9130: 
 9131: sub store_settings {
 9132:     # save to the environment
 9133:     # appenv the same items, just to be safe
 9134:     my $udom  = $env{'user.domain'};
 9135:     my $uname = $env{'user.name'};
 9136:     my ($context,$prefix,$Settings) = @_;
 9137:     my %SaveHash;
 9138:     my %AppHash;
 9139:     while (my ($setting,$type) = each(%$Settings)) {
 9140:         my $basename = join('.','internal',$context,$prefix,$setting);
 9141:         my $envname = 'environment.'.$basename;
 9142:         if (exists($env{'form.'.$setting})) {
 9143:             # Save this value away
 9144:             if ($type eq 'scalar' &&
 9145:                 (! exists($env{$envname}) || 
 9146:                  $env{$envname} ne $env{'form.'.$setting})) {
 9147:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9148:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9149:             } elsif ($type eq 'array') {
 9150:                 my $stored_form;
 9151:                 if (ref($env{'form.'.$setting})) {
 9152:                     $stored_form = join(',',
 9153:                                         map {
 9154:                                             &escape($_);
 9155:                                         } sort(@{$env{'form.'.$setting}}));
 9156:                 } else {
 9157:                     $stored_form = 
 9158:                         &escape($env{'form.'.$setting});
 9159:                 }
 9160:                 # Determine if the array contents are the same.
 9161:                 if ($stored_form ne $env{$envname}) {
 9162:                     $SaveHash{$basename} = $stored_form;
 9163:                     $AppHash{$envname}   = $stored_form;
 9164:                 }
 9165:             }
 9166:         }
 9167:     }
 9168:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9169:                                           $udom,$uname);
 9170:     if ($put_result !~ /^(ok|delayed)/) {
 9171:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9172:                                  'got error:'.$put_result);
 9173:     }
 9174:     # Make sure these settings stick around in this session, too
 9175:     &Apache::lonnet::appenv(\%AppHash);
 9176:     return;
 9177: }
 9178: 
 9179: sub restore_course_settings {
 9180:     return &restore_settings($env{'request.course.id'},@_);
 9181: }
 9182: 
 9183: sub restore_settings {
 9184:     my ($context,$prefix,$Settings) = @_;
 9185:     while (my ($setting,$type) = each(%$Settings)) {
 9186:         next if (exists($env{'form.'.$setting}));
 9187:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9188:             '.'.$setting;
 9189:         if (exists($env{$envname})) {
 9190:             if ($type eq 'scalar') {
 9191:                 $env{'form.'.$setting} = $env{$envname};
 9192:             } elsif ($type eq 'array') {
 9193:                 $env{'form.'.$setting} = [ 
 9194:                                            map { 
 9195:                                                &unescape($_); 
 9196:                                            } split(',',$env{$envname})
 9197:                                            ];
 9198:             }
 9199:         }
 9200:     }
 9201: }
 9202: 
 9203: #######################################################
 9204: #######################################################
 9205: 
 9206: =pod
 9207: 
 9208: =head1 Domain E-mail Routines  
 9209: 
 9210: =over 4
 9211: 
 9212: =item * &build_recipient_list()
 9213: 
 9214: Build recipient lists for four types of e-mail:
 9215: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9216: (d) Help requests, generated by
 9217: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 9218: 
 9219: Inputs:
 9220: defmail (scalar - email address of default recipient), 
 9221: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9222: defdom (domain for which to retrieve configuration settings),
 9223: origmail (scalar - email address of recipient from loncapa.conf, 
 9224: i.e., predates configuration by DC via domainprefs.pm 
 9225: 
 9226: Returns: comma separated list of addresses to which to send e-mail.
 9227: 
 9228: =back
 9229: 
 9230: =cut
 9231: 
 9232: ############################################################
 9233: ############################################################
 9234: sub build_recipient_list {
 9235:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9236:     my @recipients;
 9237:     my $otheremails;
 9238:     my %domconfig =
 9239:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9240:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9241:         if (exists($domconfig{'contacts'}{$mailing})) {
 9242:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9243:                 my @contacts = ('adminemail','supportemail');
 9244:                 foreach my $item (@contacts) {
 9245:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9246:                         my $addr = $domconfig{'contacts'}{$item}; 
 9247:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9248:                             push(@recipients,$addr);
 9249:                         }
 9250:                     }
 9251:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9252:                 }
 9253:             }
 9254:         } elsif ($origmail ne '') {
 9255:             push(@recipients,$origmail);
 9256:         }
 9257:     } elsif ($origmail ne '') {
 9258:         push(@recipients,$origmail);
 9259:     }
 9260:     if (defined($defmail)) {
 9261:         if ($defmail ne '') {
 9262:             push(@recipients,$defmail);
 9263:         }
 9264:     }
 9265:     if ($otheremails) {
 9266:         my @others;
 9267:         if ($otheremails =~ /,/) {
 9268:             @others = split(/,/,$otheremails);
 9269:         } else {
 9270:             push(@others,$otheremails);
 9271:         }
 9272:         foreach my $addr (@others) {
 9273:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9274:                 push(@recipients,$addr);
 9275:             }
 9276:         }
 9277:     }
 9278:     my $recipientlist = join(',',@recipients); 
 9279:     return $recipientlist;
 9280: }
 9281: 
 9282: ############################################################
 9283: ############################################################
 9284: 
 9285: =pod
 9286: 
 9287: =head1 Course Catalog Routines
 9288: 
 9289: =over 4
 9290: 
 9291: =item * &gather_categories()
 9292: 
 9293: Converts category definitions - keys of categories hash stored in  
 9294: coursecategories in configuration.db on the primary library server in a 
 9295: domain - to an array.  Also generates javascript and idx hash used to 
 9296: generate Domain Coordinator interface for editing Course Categories.
 9297: 
 9298: Inputs:
 9299: 
 9300: categories (reference to hash of category definitions).
 9301: 
 9302: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9303:       categories and subcategories).
 9304: 
 9305: idx (reference to hash of counters used in Domain Coordinator interface for 
 9306:       editing Course Categories).
 9307: 
 9308: jsarray (reference to array of categories used to create Javascript arrays for
 9309:          Domain Coordinator interface for editing Course Categories).
 9310: 
 9311: Returns: nothing
 9312: 
 9313: Side effects: populates cats, idx and jsarray. 
 9314: 
 9315: =cut
 9316: 
 9317: sub gather_categories {
 9318:     my ($categories,$cats,$idx,$jsarray) = @_;
 9319:     my %counters;
 9320:     my $num = 0;
 9321:     foreach my $item (keys(%{$categories})) {
 9322:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9323:         if ($container eq '' && $depth == 0) {
 9324:             $cats->[$depth][$categories->{$item}] = $cat;
 9325:         } else {
 9326:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9327:         }
 9328:         my ($escitem,$tail) = split(/:/,$item,2);
 9329:         if ($counters{$tail} eq '') {
 9330:             $counters{$tail} = $num;
 9331:             $num ++;
 9332:         }
 9333:         if (ref($idx) eq 'HASH') {
 9334:             $idx->{$item} = $counters{$tail};
 9335:         }
 9336:         if (ref($jsarray) eq 'ARRAY') {
 9337:             push(@{$jsarray->[$counters{$tail}]},$item);
 9338:         }
 9339:     }
 9340:     return;
 9341: }
 9342: 
 9343: =pod
 9344: 
 9345: =item * &extract_categories()
 9346: 
 9347: Used to generate breadcrumb trails for course categories.
 9348: 
 9349: Inputs:
 9350: 
 9351: categories (reference to hash of category definitions).
 9352: 
 9353: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9354:       categories and subcategories).
 9355: 
 9356: trails (reference to array of breacrumb trails for each category).
 9357: 
 9358: allitems (reference to hash - key is category key 
 9359:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9360: 
 9361: idx (reference to hash of counters used in Domain Coordinator interface for
 9362:       editing Course Categories).
 9363: 
 9364: jsarray (reference to array of categories used to create Javascript arrays for
 9365:          Domain Coordinator interface for editing Course Categories).
 9366: 
 9367: subcats (reference to hash of arrays containing all subcategories within each 
 9368:          category, -recursive)
 9369: 
 9370: Returns: nothing
 9371: 
 9372: Side effects: populates trails and allitems hash references.
 9373: 
 9374: =cut
 9375: 
 9376: sub extract_categories {
 9377:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9378:     if (ref($categories) eq 'HASH') {
 9379:         &gather_categories($categories,$cats,$idx,$jsarray);
 9380:         if (ref($cats->[0]) eq 'ARRAY') {
 9381:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9382:                 my $name = $cats->[0][$i];
 9383:                 my $item = &escape($name).'::0';
 9384:                 my $trailstr;
 9385:                 if ($name eq 'instcode') {
 9386:                     $trailstr = &mt('Official courses (with institutional codes)');
 9387:                 } else {
 9388:                     $trailstr = $name;
 9389:                 }
 9390:                 if ($allitems->{$item} eq '') {
 9391:                     push(@{$trails},$trailstr);
 9392:                     $allitems->{$item} = scalar(@{$trails})-1;
 9393:                 }
 9394:                 my @parents = ($name);
 9395:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9396:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9397:                         my $category = $cats->[1]{$name}[$j];
 9398:                         if (ref($subcats) eq 'HASH') {
 9399:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9400:                         }
 9401:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9402:                     }
 9403:                 } else {
 9404:                     if (ref($subcats) eq 'HASH') {
 9405:                         $subcats->{$item} = [];
 9406:                     }
 9407:                 }
 9408:             }
 9409:         }
 9410:     }
 9411:     return;
 9412: }
 9413: 
 9414: =pod
 9415: 
 9416: =item *&recurse_categories()
 9417: 
 9418: Recursively used to generate breadcrumb trails for course categories.
 9419: 
 9420: Inputs:
 9421: 
 9422: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9423:       categories and subcategories).
 9424: 
 9425: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9426: 
 9427: category (current course category, for which breadcrumb trail is being generated).
 9428: 
 9429: trails (reference to array of breadcrumb trails for each category).
 9430: 
 9431: allitems (reference to hash - key is category key
 9432:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9433: 
 9434: parents (array containing containers directories for current category, 
 9435:          back to top level). 
 9436: 
 9437: Returns: nothing
 9438: 
 9439: Side effects: populates trails and allitems hash references
 9440: 
 9441: =cut
 9442: 
 9443: sub recurse_categories {
 9444:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9445:     my $shallower = $depth - 1;
 9446:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9447:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9448:             my $name = $cats->[$depth]{$category}[$k];
 9449:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9450:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9451:             if ($allitems->{$item} eq '') {
 9452:                 push(@{$trails},$trailstr);
 9453:                 $allitems->{$item} = scalar(@{$trails})-1;
 9454:             }
 9455:             my $deeper = $depth+1;
 9456:             push(@{$parents},$category);
 9457:             if (ref($subcats) eq 'HASH') {
 9458:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9459:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9460:                     my $higher;
 9461:                     if ($j > 0) {
 9462:                         $higher = &escape($parents->[$j]).':'.
 9463:                                   &escape($parents->[$j-1]).':'.$j;
 9464:                     } else {
 9465:                         $higher = &escape($parents->[$j]).'::'.$j;
 9466:                     }
 9467:                     push(@{$subcats->{$higher}},$subcat);
 9468:                 }
 9469:             }
 9470:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9471:                                 $subcats);
 9472:             pop(@{$parents});
 9473:         }
 9474:     } else {
 9475:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9476:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9477:         if ($allitems->{$item} eq '') {
 9478:             push(@{$trails},$trailstr);
 9479:             $allitems->{$item} = scalar(@{$trails})-1;
 9480:         }
 9481:     }
 9482:     return;
 9483: }
 9484: 
 9485: =pod
 9486: 
 9487: =item *&assign_categories_table()
 9488: 
 9489: Create a datatable for display of hierarchical categories in a domain,
 9490: with checkboxes to allow a course to be categorized. 
 9491: 
 9492: Inputs:
 9493: 
 9494: cathash - reference to hash of categories defined for the domain (from
 9495:           configuration.db)
 9496: 
 9497: currcat - scalar with an & separated list of categories assigned to a course. 
 9498: 
 9499: Returns: $output (markup to be displayed) 
 9500: 
 9501: =cut
 9502: 
 9503: sub assign_categories_table {
 9504:     my ($cathash,$currcat) = @_;
 9505:     my $output;
 9506:     if (ref($cathash) eq 'HASH') {
 9507:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9508:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9509:         $maxdepth = scalar(@cats);
 9510:         if (@cats > 0) {
 9511:             my $itemcount = 0;
 9512:             if (ref($cats[0]) eq 'ARRAY') {
 9513:                 $output = &Apache::loncommon::start_data_table();
 9514:                 my @currcategories;
 9515:                 if ($currcat ne '') {
 9516:                     @currcategories = split('&',$currcat);
 9517:                 }
 9518:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9519:                     my $parent = $cats[0][$i];
 9520:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9521:                     next if ($parent eq 'instcode');
 9522:                     my $item = &escape($parent).'::0';
 9523:                     my $checked = '';
 9524:                     if (@currcategories > 0) {
 9525:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9526:                             $checked = ' checked="checked"';
 9527:                         }
 9528:                     }
 9529:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9530:                                '<input type="checkbox" name="usecategory" value="'.
 9531:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9532:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9533:                     my $depth = 1;
 9534:                     push(@path,$parent);
 9535:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9536:                     pop(@path);
 9537:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9538:                     $itemcount ++;
 9539:                 }
 9540:                 $output .= &Apache::loncommon::end_data_table();
 9541:             }
 9542:         }
 9543:     }
 9544:     return $output;
 9545: }
 9546: 
 9547: =pod
 9548: 
 9549: =item *&assign_category_rows()
 9550: 
 9551: Create a datatable row for display of nested categories in a domain,
 9552: with checkboxes to allow a course to be categorized,called recursively.
 9553: 
 9554: Inputs:
 9555: 
 9556: itemcount - track row number for alternating colors
 9557: 
 9558: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9559:       categories and subcategories.
 9560: 
 9561: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9562: 
 9563: parent - parent of current category item
 9564: 
 9565: path - Array containing all categories back up through the hierarchy from the
 9566:        current category to the top level.
 9567: 
 9568: currcategories - reference to array of current categories assigned to the course
 9569: 
 9570: Returns: $output (markup to be displayed).
 9571: 
 9572: =cut
 9573: 
 9574: sub assign_category_rows {
 9575:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9576:     my ($text,$name,$item,$chgstr);
 9577:     if (ref($cats) eq 'ARRAY') {
 9578:         my $maxdepth = scalar(@{$cats});
 9579:         if (ref($cats->[$depth]) eq 'HASH') {
 9580:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9581:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9582:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9583:                 $text .= '<td><table class="LC_datatable">';
 9584:                 for (my $j=0; $j<$numchildren; $j++) {
 9585:                     $name = $cats->[$depth]{$parent}[$j];
 9586:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9587:                     my $deeper = $depth+1;
 9588:                     my $checked = '';
 9589:                     if (ref($currcategories) eq 'ARRAY') {
 9590:                         if (@{$currcategories} > 0) {
 9591:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9592:                                 $checked = ' checked="checked"';
 9593:                             }
 9594:                         }
 9595:                     }
 9596:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9597:                              '<input type="checkbox" name="usecategory" value="'.
 9598:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9599:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9600:                              '</td><td>';
 9601:                     if (ref($path) eq 'ARRAY') {
 9602:                         push(@{$path},$name);
 9603:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9604:                         pop(@{$path});
 9605:                     }
 9606:                     $text .= '</td></tr>';
 9607:                 }
 9608:                 $text .= '</table></td>';
 9609:             }
 9610:         }
 9611:     }
 9612:     return $text;
 9613: }
 9614: 
 9615: ############################################################
 9616: ############################################################
 9617: 
 9618: 
 9619: sub commit_customrole {
 9620:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9621:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9622:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9623:                          ($end?', ending '.localtime($end):'').': <b>'.
 9624:               &Apache::lonnet::assigncustomrole(
 9625:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9626:                  '</b><br />';
 9627:     return $output;
 9628: }
 9629: 
 9630: sub commit_standardrole {
 9631:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9632:     my ($output,$logmsg,$linefeed);
 9633:     if ($context eq 'auto') {
 9634:         $linefeed = "\n";
 9635:     } else {
 9636:         $linefeed = "<br />\n";
 9637:     }  
 9638:     if ($three eq 'st') {
 9639:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9640:                                          $one,$two,$sec,$context);
 9641:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9642:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9643:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9644:         } else {
 9645:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9646:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9647:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9648:             if ($context eq 'auto') {
 9649:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9650:             } else {
 9651:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9652:                &mt('Add to classlist').': <b>ok</b>';
 9653:             }
 9654:             $output .= $linefeed;
 9655:         }
 9656:     } else {
 9657:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9658:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9659:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9660:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9661:         if ($context eq 'auto') {
 9662:             $output .= $result.$linefeed;
 9663:         } else {
 9664:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9665:         }
 9666:     }
 9667:     return $output;
 9668: }
 9669: 
 9670: sub commit_studentrole {
 9671:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9672:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9673:     if ($context eq 'auto') {
 9674:         $linefeed = "\n";
 9675:     } else {
 9676:         $linefeed = '<br />'."\n";
 9677:     }
 9678:     if (defined($one) && defined($two)) {
 9679:         my $cid=$one.'_'.$two;
 9680:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9681:         my $secchange = 0;
 9682:         my $expire_role_result;
 9683:         my $modify_section_result;
 9684:         if ($oldsec ne '-1') { 
 9685:             if ($oldsec ne $sec) {
 9686:                 $secchange = 1;
 9687:                 my $now = time;
 9688:                 my $uurl='/'.$cid;
 9689:                 $uurl=~s/\_/\//g;
 9690:                 if ($oldsec) {
 9691:                     $uurl.='/'.$oldsec;
 9692:                 }
 9693:                 $oldsecurl = $uurl;
 9694:                 $expire_role_result = 
 9695:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9696:                 if ($env{'request.course.sec'} ne '') { 
 9697:                     if ($expire_role_result eq 'refused') {
 9698:                         my @roles = ('st');
 9699:                         my @statuses = ('previous');
 9700:                         my @roledoms = ($one);
 9701:                         my $withsec = 1;
 9702:                         my %roleshash = 
 9703:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9704:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9705:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9706:                             my ($oldstart,$oldend) = 
 9707:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9708:                             if ($oldend > 0 && $oldend <= $now) {
 9709:                                 $expire_role_result = 'ok';
 9710:                             }
 9711:                         }
 9712:                     }
 9713:                 }
 9714:                 $result = $expire_role_result;
 9715:             }
 9716:         }
 9717:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9718:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9719:             if ($modify_section_result =~ /^ok/) {
 9720:                 if ($secchange == 1) {
 9721:                     if ($sec eq '') {
 9722:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9723:                     } else {
 9724:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9725:                     }
 9726:                 } elsif ($oldsec eq '-1') {
 9727:                     if ($sec eq '') {
 9728:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9729:                     } else {
 9730:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9731:                     }
 9732:                 } else {
 9733:                     if ($sec eq '') {
 9734:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9735:                     } else {
 9736:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9737:                     }
 9738:                 }
 9739:             } else {
 9740:                 if ($secchange) {       
 9741:                     $$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;
 9742:                 } else {
 9743:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9744:                 }
 9745:             }
 9746:             $result = $modify_section_result;
 9747:         } elsif ($secchange == 1) {
 9748:             if ($oldsec eq '') {
 9749:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9750:             } else {
 9751:                 $$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;
 9752:             }
 9753:             if ($expire_role_result eq 'refused') {
 9754:                 my $newsecurl = '/'.$cid;
 9755:                 $newsecurl =~ s/\_/\//g;
 9756:                 if ($sec ne '') {
 9757:                     $newsecurl.='/'.$sec;
 9758:                 }
 9759:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9760:                     if ($sec eq '') {
 9761:                         $$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;
 9762:                     } else {
 9763:                         $$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;
 9764:                     }
 9765:                 }
 9766:             }
 9767:         }
 9768:     } else {
 9769:         $$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;
 9770:         $result = "error: incomplete course id\n";
 9771:     }
 9772:     return $result;
 9773: }
 9774: 
 9775: ############################################################
 9776: ############################################################
 9777: 
 9778: sub check_clone {
 9779:     my ($args,$linefeed) = @_;
 9780:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9781:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9782:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9783:     my $clonemsg;
 9784:     my $can_clone = 0;
 9785: 
 9786:     if ($clonehome eq 'no_host') {
 9787:         $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'});     
 9788:     } else {
 9789: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9790: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9791: 	    $can_clone = 1;
 9792: 	} else {
 9793: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9794: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9795: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9796:             if (grep(/^\*$/,@cloners)) {
 9797:                 $can_clone = 1;
 9798:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9799:                 $can_clone = 1;
 9800:             } else {
 9801: 	        my %roleshash =
 9802: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9803: 					 $args->{'ccdomain'},
 9804:                                          'userroles',['active'],['cc'],
 9805: 					 [$args->{'clonedomain'}]);
 9806: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9807: 		    $can_clone = 1;
 9808: 	        } else {
 9809:                     $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'});
 9810: 	        }
 9811: 	    }
 9812:         }
 9813:     }
 9814:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9815: }
 9816: 
 9817: sub construct_course {
 9818:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9819:     my $outcome;
 9820:     my $linefeed =  '<br />'."\n";
 9821:     if ($context eq 'auto') {
 9822:         $linefeed = "\n";
 9823:     }
 9824: 
 9825: #
 9826: # Are we cloning?
 9827: #
 9828:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9829:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9830: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9831: 	if ($context ne 'auto') {
 9832:             if ($clonemsg ne '') {
 9833: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9834:             }
 9835: 	}
 9836: 	$outcome .= $clonemsg.$linefeed;
 9837: 
 9838:         if (!$can_clone) {
 9839: 	    return (0,$outcome);
 9840: 	}
 9841:     }
 9842: 
 9843: #
 9844: # Open course
 9845: #
 9846:     my $crstype = lc($args->{'crstype'});
 9847:     my %cenv=();
 9848:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9849:                                              $args->{'cdescr'},
 9850:                                              $args->{'curl'},
 9851:                                              $args->{'course_home'},
 9852:                                              $args->{'nonstandard'},
 9853:                                              $args->{'crscode'},
 9854:                                              $args->{'ccuname'}.':'.
 9855:                                              $args->{'ccdomain'},
 9856:                                              $args->{'crstype'});
 9857: 
 9858:     # Note: The testing routines depend on this being output; see 
 9859:     # Utils::Course. This needs to at least be output as a comment
 9860:     # if anyone ever decides to not show this, and Utils::Course::new
 9861:     # will need to be suitably modified.
 9862:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9863: #
 9864: # Check if created correctly
 9865: #
 9866:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9867:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9868:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9869: 
 9870: #
 9871: # Do the cloning
 9872: #   
 9873:     if ($can_clone && $cloneid) {
 9874: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9875: 	if ($context ne 'auto') {
 9876: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9877: 	}
 9878: 	$outcome .= $clonemsg.$linefeed;
 9879: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9880: # Copy all files
 9881: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9882: # Restore URL
 9883: 	$cenv{'url'}=$oldcenv{'url'};
 9884: # Restore title
 9885: 	$cenv{'description'}=$oldcenv{'description'};
 9886: # Mark as cloned
 9887: 	$cenv{'clonedfrom'}=$cloneid;
 9888: # Need to clone grading mode
 9889:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9890:         $cenv{'grading'}=$newenv{'grading'};
 9891: # Do not clone these environment entries
 9892:         &Apache::lonnet::del('environment',
 9893:                   ['default_enrollment_start_date',
 9894:                    'default_enrollment_end_date',
 9895:                    'question.email',
 9896:                    'policy.email',
 9897:                    'comment.email',
 9898:                    'pch.users.denied',
 9899:                    'plc.users.denied',
 9900:                    'hidefromcat',
 9901:                    'categories'],
 9902:                    $$crsudom,$$crsunum);
 9903:     }
 9904: 
 9905: #
 9906: # Set environment (will override cloned, if existing)
 9907: #
 9908:     my @sections = ();
 9909:     my @xlists = ();
 9910:     if ($args->{'crstype'}) {
 9911:         $cenv{'type'}=$args->{'crstype'};
 9912:     }
 9913:     if ($args->{'crsid'}) {
 9914:         $cenv{'courseid'}=$args->{'crsid'};
 9915:     }
 9916:     if ($args->{'crscode'}) {
 9917:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9918:     }
 9919:     if ($args->{'crsquota'} ne '') {
 9920:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9921:     } else {
 9922:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9923:     }
 9924:     if ($args->{'ccuname'}) {
 9925:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9926:                                         ':'.$args->{'ccdomain'};
 9927:     } else {
 9928:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9929:     }
 9930:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9931:     if ($args->{'crssections'}) {
 9932:         $cenv{'internal.sectionnums'} = '';
 9933:         if ($args->{'crssections'} =~ m/,/) {
 9934:             @sections = split/,/,$args->{'crssections'};
 9935:         } else {
 9936:             $sections[0] = $args->{'crssections'};
 9937:         }
 9938:         if (@sections > 0) {
 9939:             foreach my $item (@sections) {
 9940:                 my ($sec,$gp) = split/:/,$item;
 9941:                 my $class = $args->{'crscode'}.$sec;
 9942:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9943:                 $cenv{'internal.sectionnums'} .= $item.',';
 9944:                 unless ($addcheck eq 'ok') {
 9945:                     push @badclasses, $class;
 9946:                 }
 9947:             }
 9948:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9949:         }
 9950:     }
 9951: # do not hide course coordinator from staff listing, 
 9952: # even if privileged
 9953:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9954: # add crosslistings
 9955:     if ($args->{'crsxlist'}) {
 9956:         $cenv{'internal.crosslistings'}='';
 9957:         if ($args->{'crsxlist'} =~ m/,/) {
 9958:             @xlists = split/,/,$args->{'crsxlist'};
 9959:         } else {
 9960:             $xlists[0] = $args->{'crsxlist'};
 9961:         }
 9962:         if (@xlists > 0) {
 9963:             foreach my $item (@xlists) {
 9964:                 my ($xl,$gp) = split/:/,$item;
 9965:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9966:                 $cenv{'internal.crosslistings'} .= $item.',';
 9967:                 unless ($addcheck eq 'ok') {
 9968:                     push @badclasses, $xl;
 9969:                 }
 9970:             }
 9971:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9972:         }
 9973:     }
 9974:     if ($args->{'autoadds'}) {
 9975:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9976:     }
 9977:     if ($args->{'autodrops'}) {
 9978:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9979:     }
 9980: # check for notification of enrollment changes
 9981:     my @notified = ();
 9982:     if ($args->{'notify_owner'}) {
 9983:         if ($args->{'ccuname'} ne '') {
 9984:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9985:         }
 9986:     }
 9987:     if ($args->{'notify_dc'}) {
 9988:         if ($uname ne '') { 
 9989:             push(@notified,$uname.':'.$udom);
 9990:         }
 9991:     }
 9992:     if (@notified > 0) {
 9993:         my $notifylist;
 9994:         if (@notified > 1) {
 9995:             $notifylist = join(',',@notified);
 9996:         } else {
 9997:             $notifylist = $notified[0];
 9998:         }
 9999:         $cenv{'internal.notifylist'} = $notifylist;
10000:     }
10001:     if (@badclasses > 0) {
10002:         my %lt=&Apache::lonlocal::texthash(
10003:                 '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',
10004:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10005:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10006:         );
10007:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10008:                            ' ('.$lt{'adby'}.')';
10009:         if ($context eq 'auto') {
10010:             $outcome .= $badclass_msg.$linefeed;
10011:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10012:             foreach my $item (@badclasses) {
10013:                 if ($context eq 'auto') {
10014:                     $outcome .= " - $item\n";
10015:                 } else {
10016:                     $outcome .= "<li>$item</li>\n";
10017:                 }
10018:             }
10019:             if ($context eq 'auto') {
10020:                 $outcome .= $linefeed;
10021:             } else {
10022:                 $outcome .= "</ul><br /><br /></div>\n";
10023:             }
10024:         } 
10025:     }
10026:     if ($args->{'no_end_date'}) {
10027:         $args->{'endaccess'} = 0;
10028:     }
10029:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10030:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10031:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10032:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10033:     if ($args->{'showphotos'}) {
10034:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10035:     }
10036:     $cenv{'internal.authtype'} = $args->{'authtype'};
10037:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10038:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10039:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10040:             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'); 
10041:             if ($context eq 'auto') {
10042:                 $outcome .= $krb_msg;
10043:             } else {
10044:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10045:             }
10046:             $outcome .= $linefeed;
10047:         }
10048:     }
10049:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10050:        if ($args->{'setpolicy'}) {
10051:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10052:        }
10053:        if ($args->{'setcontent'}) {
10054:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10055:        }
10056:     }
10057:     if ($args->{'reshome'}) {
10058: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10059: 	$cenv{'reshome'}=~s/\/+$/\//;
10060:     }
10061: #
10062: # course has keyed access
10063: #
10064:     if ($args->{'setkeys'}) {
10065:        $cenv{'keyaccess'}='yes';
10066:     }
10067: # if specified, key authority is not course, but user
10068: # only active if keyaccess is yes
10069:     if ($args->{'keyauth'}) {
10070: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10071: 	$user = &LONCAPA::clean_username($user);
10072: 	$domain = &LONCAPA::clean_username($domain);
10073: 	if ($user ne '' && $domain ne '') {
10074: 	    $cenv{'keyauth'}=$user.':'.$domain;
10075: 	}
10076:     }
10077: 
10078:     if ($args->{'disresdis'}) {
10079:         $cenv{'pch.roles.denied'}='st';
10080:     }
10081:     if ($args->{'disablechat'}) {
10082:         $cenv{'plc.roles.denied'}='st';
10083:     }
10084: 
10085:     # Record we've not yet viewed the Course Initialization Helper for this 
10086:     # course
10087:     $cenv{'course.helper.not.run'} = 1;
10088:     #
10089:     # Use new Randomseed
10090:     #
10091:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10092:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10093:     #
10094:     # The encryption code and receipt prefix for this course
10095:     #
10096:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10097:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10098:     #
10099:     # By default, use standard grading
10100:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10101: 
10102:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10103:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10104: #
10105: # Open all assignments
10106: #
10107:     if ($args->{'openall'}) {
10108:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10109:        my %storecontent = ($storeunder         => time,
10110:                            $storeunder.'.type' => 'date_start');
10111:        
10112:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10113:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10114:    }
10115: #
10116: # Set first page
10117: #
10118:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10119: 	    || ($cloneid)) {
10120: 	use LONCAPA::map;
10121: 	$outcome .= &mt('Setting first resource').': ';
10122: 
10123: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10124:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10125: 
10126:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10127:         my $title; my $url;
10128:         if ($args->{'firstres'} eq 'syl') {
10129: 	    $title=&mt('Syllabus');
10130:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10131:         } else {
10132:             $title=&mt('Navigate Contents');
10133:             $url='/adm/navmaps';
10134:         }
10135: 
10136:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10137: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10138: 
10139: 	if ($errtext) { $fatal=2; }
10140:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10141:     }
10142: 
10143:     return (1,$outcome);
10144: }
10145: 
10146: ############################################################
10147: ############################################################
10148: 
10149: sub course_type {
10150:     my ($cid) = @_;
10151:     if (!defined($cid)) {
10152:         $cid = $env{'request.course.id'};
10153:     }
10154:     if (defined($env{'course.'.$cid.'.type'})) {
10155:         return $env{'course.'.$cid.'.type'};
10156:     } else {
10157:         return 'Course';
10158:     }
10159: }
10160: 
10161: sub group_term {
10162:     my $crstype = &course_type();
10163:     my %names = (
10164:                   'Course' => 'group',
10165:                   'Community' => 'group',
10166:                 );
10167:     return $names{$crstype};
10168: }
10169: 
10170: sub icon {
10171:     my ($file)=@_;
10172:     my $curfext = lc((split(/\./,$file))[-1]);
10173:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10174:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10175:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10176: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10177: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10178: 	            $curfext.".gif") {
10179: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10180: 		$curfext.".gif";
10181: 	}
10182:     }
10183:     return &lonhttpdurl($iconname);
10184: } 
10185: 
10186: sub lonhttpdurl {
10187: #
10188: # Had been used for "small fry" static images on separate port 8080.
10189: # Modify here if lightweight http functionality desired again.
10190: # Currently eliminated due to increasing firewall issues.
10191: #
10192:     my ($url)=@_;
10193:     return $url;
10194: }
10195: 
10196: sub connection_aborted {
10197:     my ($r)=@_;
10198:     $r->print(" ");$r->rflush();
10199:     my $c = $r->connection;
10200:     return $c->aborted();
10201: }
10202: 
10203: #    Escapes strings that may have embedded 's that will be put into
10204: #    strings as 'strings'.
10205: sub escape_single {
10206:     my ($input) = @_;
10207:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10208:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10209:     return $input;
10210: }
10211: 
10212: #  Same as escape_single, but escape's "'s  This 
10213: #  can be used for  "strings"
10214: sub escape_double {
10215:     my ($input) = @_;
10216:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10217:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10218:     return $input;
10219: }
10220:  
10221: #   Escapes the last element of a full URL.
10222: sub escape_url {
10223:     my ($url)   = @_;
10224:     my @urlslices = split(/\//, $url,-1);
10225:     my $lastitem = &escape(pop(@urlslices));
10226:     return join('/',@urlslices).'/'.$lastitem;
10227: }
10228: 
10229: sub compare_arrays {
10230:     my ($arrayref1,$arrayref2) = @_;
10231:     my (@difference,%count);
10232:     @difference = ();
10233:     %count = ();
10234:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10235:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10236:         foreach my $element (keys(%count)) {
10237:             if ($count{$element} == 1) {
10238:                 push(@difference,$element);
10239:             }
10240:         }
10241:     }
10242:     return @difference;
10243: }
10244: 
10245: # -------------------------------------------------------- Initialize user login
10246: sub init_user_environment {
10247:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10248:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10249: 
10250:     my $public=($username eq 'public' && $domain eq 'public');
10251: 
10252: # See if old ID present, if so, remove
10253: 
10254:     my ($filename,$cookie,$userroles);
10255:     my $now=time;
10256: 
10257:     if ($public) {
10258: 	my $max_public=100;
10259: 	my $oldest;
10260: 	my $oldest_time=0;
10261: 	for(my $next=1;$next<=$max_public;$next++) {
10262: 	    if (-e $lonids."/publicuser_$next.id") {
10263: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10264: 		if ($mtime<$oldest_time || !$oldest_time) {
10265: 		    $oldest_time=$mtime;
10266: 		    $oldest=$next;
10267: 		}
10268: 	    } else {
10269: 		$cookie="publicuser_$next";
10270: 		last;
10271: 	    }
10272: 	}
10273: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10274:     } else {
10275: 	# if this isn't a robot, kill any existing non-robot sessions
10276: 	if (!$args->{'robot'}) {
10277: 	    opendir(DIR,$lonids);
10278: 	    while ($filename=readdir(DIR)) {
10279: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10280: 		    unlink($lonids.'/'.$filename);
10281: 		}
10282: 	    }
10283: 	    closedir(DIR);
10284: 	}
10285: # Give them a new cookie
10286: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10287: 		                   : $now.$$.int(rand(10000)));
10288: 	$cookie="$username\_$id\_$domain\_$authhost";
10289:     
10290: # Initialize roles
10291: 
10292: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10293:     }
10294: # ------------------------------------ Check browser type and MathML capability
10295: 
10296:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10297:         $clientunicode,$clientos) = &decode_user_agent($r);
10298: 
10299: # ------------------------------------------------------------- Get environment
10300: 
10301:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10302:     my ($tmp) = keys(%userenv);
10303:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10304: 	# default remote control to off
10305: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10306:     } else {
10307: 	undef(%userenv);
10308:     }
10309:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10310: 	$form->{'interface'}=$userenv{'interface'};
10311:     }
10312:     $env{'environment.remote'}=$userenv{'remote'};
10313:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10314: 
10315: # --------------- Do not trust query string to be put directly into environment
10316:     foreach my $option ('interface','localpath','localres') {
10317:         $form->{$option}=~s/[\n\r\=]//gs;
10318:     }
10319: # --------------------------------------------------------- Write first profile
10320: 
10321:     {
10322: 	my %initial_env = 
10323: 	    ("user.name"          => $username,
10324: 	     "user.domain"        => $domain,
10325: 	     "user.home"          => $authhost,
10326: 	     "browser.type"       => $clientbrowser,
10327: 	     "browser.version"    => $clientversion,
10328: 	     "browser.mathml"     => $clientmathml,
10329: 	     "browser.unicode"    => $clientunicode,
10330: 	     "browser.os"         => $clientos,
10331: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10332: 	     "request.course.fn"  => '',
10333: 	     "request.course.uri" => '',
10334: 	     "request.course.sec" => '',
10335: 	     "request.role"       => 'cm',
10336: 	     "request.role.adv"   => $env{'user.adv'},
10337: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10338: 
10339:         if ($form->{'localpath'}) {
10340: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10341: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10342:         }
10343: 	
10344: 	if ($public) {
10345: 	    $initial_env{"environment.remote"} = "off";
10346: 	}
10347: 	if ($form->{'interface'}) {
10348: 	    $form->{'interface'}=~s/\W//gs;
10349: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10350: 	    $env{'browser.interface'}=$form->{'interface'};
10351: 	}
10352: 
10353:         foreach my $tool ('aboutme','blog','portfolio') {
10354:             $userenv{'availabletools.'.$tool} = 
10355:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10356:         }
10357: 
10358:         foreach my $crstype ('official','unofficial','community') {
10359:             $userenv{'canrequest.'.$crstype} =
10360:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10361:                                                   'reload','requestcourses');
10362:         }
10363: 
10364: 	$env{'user.environment'} = "$lonids/$cookie.id";
10365: 	
10366: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10367: 		 &GDBM_WRCREAT(),0640)) {
10368: 	    &_add_to_env(\%disk_env,\%initial_env);
10369: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10370: 	    &_add_to_env(\%disk_env,$userroles);
10371: 	    if (ref($args->{'extra_env'})) {
10372: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10373: 	    }
10374: 	    untie(%disk_env);
10375: 	} else {
10376: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10377: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10378: 	    return 'error: '.$!;
10379: 	}
10380:     }
10381:     $env{'request.role'}='cm';
10382:     $env{'request.role.adv'}=$env{'user.adv'};
10383:     $env{'browser.type'}=$clientbrowser;
10384: 
10385:     return $cookie;
10386: 
10387: }
10388: 
10389: sub _add_to_env {
10390:     my ($idf,$env_data,$prefix) = @_;
10391:     if (ref($env_data) eq 'HASH') {
10392:         while (my ($key,$value) = each(%$env_data)) {
10393: 	    $idf->{$prefix.$key} = $value;
10394: 	    $env{$prefix.$key}   = $value;
10395:         }
10396:     }
10397: }
10398: 
10399: # --- Get the symbolic name of a problem and the url
10400: sub get_symb {
10401:     my ($request,$silent) = @_;
10402:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10403:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10404:     if ($symb eq '') {
10405:         if (!$silent) {
10406:             $request->print("Unable to handle ambiguous references:$url:.");
10407:             return ();
10408:         }
10409:     }
10410:     &Apache::lonenc::check_decrypt(\$symb);
10411:     return ($symb);
10412: }
10413: 
10414: # --------------------------------------------------------------Get annotation
10415: 
10416: sub get_annotation {
10417:     my ($symb,$enc) = @_;
10418: 
10419:     my $key = $symb;
10420:     if (!$enc) {
10421:         $key =
10422:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10423:     }
10424:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10425:     return $annotation{$key};
10426: }
10427: 
10428: sub clean_symb {
10429:     my ($symb,$delete_enc) = @_;
10430: 
10431:     &Apache::lonenc::check_decrypt(\$symb);
10432:     my $enc = $env{'request.enc'};
10433:     if ($delete_enc) {
10434:         delete($env{'request.enc'});
10435:     }
10436: 
10437:     return ($symb,$enc);
10438: }
10439: 
10440: =pod
10441: 
10442: =back
10443: 
10444: =cut
10445: 
10446: 1;
10447: __END__;
10448: 

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