File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.799: download - view: text, annotated - select for diffs
Wed Apr 29 16:57:29 2009 UTC (15 years, 1 month ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Banned HTML tags (<a>) from translation files
and adjusted corresponding translation phrases

(more to do)

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.799 2009/04/29 16:57:29 bisitz Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410:     var stdeditbrowser;
  411:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
  412:         var url = '/adm/pickstudent?';
  413:         var filter;
  414: 	if (!ignorefilter) {
  415: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  416: 	}
  417:         if (filter != null) {
  418:            if (filter != '') {
  419:                url += 'filter='+filter+'&';
  420: 	   }
  421:         }
  422:         url += 'form=' + formname + '&unameelement='+uname+
  423:                                     '&udomelement='+udom;
  424: 	if (roleflag) { url+="&roles=1"; }
  425:         if (courseadvonly) { url+="&courseadvonly=1"; }
  426:         var title = 'Student_Browser';
  427:         var options = 'scrollbars=1,resizable=1,menubar=0';
  428:         options += ',width=700,height=600';
  429:         stdeditbrowser = open(url,title,options,'1');
  430:         stdeditbrowser.focus();
  431:     }
  432: </script>
  433: ENDSTDBRW
  434: }
  435: 
  436: sub selectstudent_link {
  437:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  438:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  439:    if ($env{'request.course.id'}) {  
  440:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  441: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  442: 					'/'.$env{'request.course.sec'})) {
  443: 	   return '';
  444:        }
  445:        if ($courseadvonly)  {
  446:            $callargs .= ",'',1,1";
  447:        }
  448:        return '<span class="LC_nobreak">'.
  449:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  450:               &mt('Select User').'</a></span>';
  451:    }
  452:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  453:        $callargs .= ",1"; 
  454:        return '<span class="LC_nobreak">'.
  455:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  456:               &mt('Select User').'</a></span>';
  457:    }
  458:    return '';
  459: }
  460: 
  461: sub authorbrowser_javascript {
  462:     return <<"ENDAUTHORBRW";
  463: <script type="text/javascript" language="JavaScript">
  464: var stdeditbrowser;
  465: 
  466: function openauthorbrowser(formname,udom) {
  467:     var url = '/adm/pickauthor?';
  468:     url += 'form='+formname+'&roledom='+udom;
  469:     var title = 'Author_Browser';
  470:     var options = 'scrollbars=1,resizable=1,menubar=0';
  471:     options += ',width=700,height=600';
  472:     stdeditbrowser = open(url,title,options,'1');
  473:     stdeditbrowser.focus();
  474: }
  475: 
  476: </script>
  477: ENDAUTHORBRW
  478: }
  479: 
  480: sub coursebrowser_javascript {
  481:     my ($domainfilter,$sec_element,$formname)=@_;
  482:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  483:    my $output = '
  484: <script type="text/javascript" language="JavaScript">
  485:     var stdeditbrowser;'."\n";
  486:    $output .= <<"ENDSTDBRW";
  487:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  488:         var url = '/adm/pickcourse?';
  489:         var domainfilter = '';
  490:         var formid = getFormIdByName(formname);
  491:         if (formid > -1) {
  492:             var domid = getIndexByName(formid,udom);
  493:             if (domid > -1) {
  494:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  495:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  496:                 }
  497:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  498:                     domainfilter=document.forms[formid].elements[domid].value;
  499:                 }
  500:             }
  501:         }
  502:         if (domainfilter != null) {
  503:            if (domainfilter != '') {
  504:                url += 'domainfilter='+domainfilter+'&';
  505: 	   }
  506:         }
  507:         url += 'form=' + formname + '&cnumelement='+uname+
  508: 	                            '&cdomelement='+udom+
  509:                                     '&cnameelement='+desc;
  510:         if (extra_element !=null && extra_element != '') {
  511:             if (formname == 'rolechoice' || formname == 'studentform') {
  512:                 url += '&roleelement='+extra_element;
  513:                 if (domainfilter == null || domainfilter == '') {
  514:                     url += '&domainfilter='+extra_element;
  515:                 }
  516:             }
  517:             else {
  518:                 if (formname == 'portform') {
  519:                     url += '&setroles='+extra_element;
  520:                 }
  521:             }     
  522:         }
  523:         if (multflag !=null && multflag != '') {
  524:             url += '&multiple='+multflag;
  525:         }
  526:         if (crstype == 'Course/Group') {
  527:             if (formname == 'cu') {
  528:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  529:                 if (crstype == "") {
  530:                     alert("$crs_or_grp_alert");
  531:                     return;
  532:                 }
  533:             }
  534:         }
  535:         if (crstype !=null && crstype != '') {
  536:             url += '&type='+crstype;
  537:         }
  538:         var title = 'Course_Browser';
  539:         var options = 'scrollbars=1,resizable=1,menubar=0';
  540:         options += ',width=700,height=600';
  541:         stdeditbrowser = open(url,title,options,'1');
  542:         stdeditbrowser.focus();
  543:     }
  544: 
  545:     function getFormIdByName(formname) {
  546:         for (var i=0;i<document.forms.length;i++) {
  547:             if (document.forms[i].name == formname) {
  548:                 return i;
  549:             }
  550:         }
  551:         return -1; 
  552:     }
  553: 
  554:     function getIndexByName(formid,item) {
  555:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  556:             if (document.forms[formid].elements[i].name == item) {
  557:                 return i;
  558:             }
  559:         }
  560:         return -1;
  561:     }
  562: ENDSTDBRW
  563:     if ($sec_element ne '') {
  564:         $output .= &setsec_javascript($sec_element,$formname);
  565:     }
  566:     $output .= '
  567: </script>';
  568:     return $output;
  569: }
  570: 
  571: sub setsec_javascript {
  572:     my ($sec_element,$formname) = @_;
  573:     my $setsections = qq|
  574: function setSect(sectionlist) {
  575:     var sectionsArray = new Array();
  576:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  577:         sectionsArray = sectionlist.split(",");
  578:     }
  579:     var numSections = sectionsArray.length;
  580:     document.$formname.$sec_element.length = 0;
  581:     if (numSections == 0) {
  582:         document.$formname.$sec_element.multiple=false;
  583:         document.$formname.$sec_element.size=1;
  584:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  585:     } else {
  586:         if (numSections == 1) {
  587:             document.$formname.$sec_element.multiple=false;
  588:             document.$formname.$sec_element.size=1;
  589:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  590:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  591:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  592:         } else {
  593:             for (var i=0; i<numSections; i++) {
  594:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  595:             }
  596:             document.$formname.$sec_element.multiple=true
  597:             if (numSections < 3) {
  598:                 document.$formname.$sec_element.size=numSections;
  599:             } else {
  600:                 document.$formname.$sec_element.size=3;
  601:             }
  602:             document.$formname.$sec_element.options[0].selected = false
  603:         }
  604:     }
  605: }
  606: |;
  607:     return $setsections;
  608: }
  609: 
  610: 
  611: sub selectcourse_link {
  612:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  613:    return '<span class="LC_nobreak">'
  614:          ."<a href='"
  615:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  616:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  617:          .'","'.$multflag.'","'.$selecttype.'");'
  618:          ."'>".&mt('Select Course').'</a>'
  619:          .'</span>';
  620: }
  621: 
  622: sub selectauthor_link {
  623:    my ($form,$udom)=@_;
  624:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  625:           &mt('Select Author').'</a>';
  626: }
  627: 
  628: sub check_uncheck_jscript {
  629:     my $jscript = <<"ENDSCRT";
  630: function checkAll(field) {
  631:     if (field.length > 0) {
  632:         for (i = 0; i < field.length; i++) {
  633:             field[i].checked = true ;
  634:         }
  635:     } else {
  636:         field.checked = true
  637:     }
  638: }
  639:  
  640: function uncheckAll(field) {
  641:     if (field.length > 0) {
  642:         for (i = 0; i < field.length; i++) {
  643:             field[i].checked = false ;
  644:         }
  645:     } else {
  646:         field.checked = false ;
  647:     }
  648: }
  649: ENDSCRT
  650:     return $jscript;
  651: }
  652: 
  653: sub select_timezone {
  654:    my ($name,$selected,$onchange,$includeempty)=@_;
  655:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  656:    if ($includeempty) {
  657:        $output .= '<option value=""';
  658:        if (($selected eq '') || ($selected eq 'local')) {
  659:            $output .= ' selected="selected" ';
  660:        }
  661:        $output .= '> </option>';
  662:    }
  663:    my @timezones = DateTime::TimeZone->all_names;
  664:    foreach my $tzone (@timezones) {
  665:        $output.= '<option value="'.$tzone.'"';
  666:        if ($tzone eq $selected) {
  667:            $output.=' selected="selected"';
  668:        }
  669:        $output.=">$tzone</option>\n";
  670:    }
  671:    $output.="</select>";
  672:    return $output;
  673: }
  674: 
  675: sub select_datelocale {
  676:     my ($name,$selected,$onchange,$includeempty)=@_;
  677:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  678:     if ($includeempty) {
  679:         $output .= '<option value=""';
  680:         if ($selected eq '') {
  681:             $output .= ' selected="selected" ';
  682:         }
  683:         $output .= '> </option>';
  684:     }
  685:     my (@possibles,%locale_names);
  686:     my @locales = DateTime::Locale::Catalog::Locales;
  687:     foreach my $locale (@locales) {
  688:         if (ref($locale) eq 'HASH') {
  689:             my $id = $locale->{'id'};
  690:             if ($id ne '') {
  691:                 my $en_terr = $locale->{'en_territory'};
  692:                 my $native_terr = $locale->{'native_territory'};
  693:                 my @languages = &Apache::lonlocal::preferred_languages();
  694:                 if (grep(/^en$/,@languages) || !@languages) {
  695:                     if ($en_terr ne '') {
  696:                         $locale_names{$id} = '('.$en_terr.')';
  697:                     } elsif ($native_terr ne '') {
  698:                         $locale_names{$id} = $native_terr;
  699:                     }
  700:                 } else {
  701:                     if ($native_terr ne '') {
  702:                         $locale_names{$id} = $native_terr.' ';
  703:                     } elsif ($en_terr ne '') {
  704:                         $locale_names{$id} = '('.$en_terr.')';
  705:                     }
  706:                 }
  707:                 push (@possibles,$id);
  708:             }
  709:         }
  710:     }
  711:     foreach my $item (sort(@possibles)) {
  712:         $output.= '<option value="'.$item.'"';
  713:         if ($item eq $selected) {
  714:             $output.=' selected="selected"';
  715:         }
  716:         $output.=">$item";
  717:         if ($locale_names{$item} ne '') {
  718:             $output.="  $locale_names{$item}</option>\n";
  719:         }
  720:         $output.="</option>\n";
  721:     }
  722:     $output.="</select>";
  723:     return $output;
  724: }
  725: 
  726: sub select_language {
  727:     my ($name,$selected,$includeempty) = @_;
  728:     my %langchoices;
  729:     if ($includeempty) {
  730:         %langchoices = ('' => 'No language preference');
  731:     }
  732:     foreach my $id (&languageids()) {
  733:         my $code = &supportedlanguagecode($id);
  734:         if ($code) {
  735:             $langchoices{$code} = &plainlanguagedescription($id);
  736:         }
  737:     }
  738:     return &select_form($selected,$name,%langchoices);
  739: }
  740: 
  741: =pod
  742: 
  743: =item * &linked_select_forms(...)
  744: 
  745: linked_select_forms returns a string containing a <script></script> block
  746: and html for two <select> menus.  The select menus will be linked in that
  747: changing the value of the first menu will result in new values being placed
  748: in the second menu.  The values in the select menu will appear in alphabetical
  749: order unless a defined order is provided.
  750: 
  751: linked_select_forms takes the following ordered inputs:
  752: 
  753: =over 4
  754: 
  755: =item * $formname, the name of the <form> tag
  756: 
  757: =item * $middletext, the text which appears between the <select> tags
  758: 
  759: =item * $firstdefault, the default value for the first menu
  760: 
  761: =item * $firstselectname, the name of the first <select> tag
  762: 
  763: =item * $secondselectname, the name of the second <select> tag
  764: 
  765: =item * $hashref, a reference to a hash containing the data for the menus.
  766: 
  767: =item * $menuorder, the order of values in the first menu
  768: 
  769: =back 
  770: 
  771: Below is an example of such a hash.  Only the 'text', 'default', and 
  772: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  773: values for the first select menu.  The text that coincides with the 
  774: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  775: and text for the second menu are given in the hash pointed to by 
  776: $menu{$choice1}->{'select2'}.  
  777: 
  778:  my %menu = ( A1 => { text =>"Choice A1" ,
  779:                        default => "B3",
  780:                        select2 => { 
  781:                            B1 => "Choice B1",
  782:                            B2 => "Choice B2",
  783:                            B3 => "Choice B3",
  784:                            B4 => "Choice B4"
  785:                            },
  786:                        order => ['B4','B3','B1','B2'],
  787:                    },
  788:                A2 => { text =>"Choice A2" ,
  789:                        default => "C2",
  790:                        select2 => { 
  791:                            C1 => "Choice C1",
  792:                            C2 => "Choice C2",
  793:                            C3 => "Choice C3"
  794:                            },
  795:                        order => ['C2','C1','C3'],
  796:                    },
  797:                A3 => { text =>"Choice A3" ,
  798:                        default => "D6",
  799:                        select2 => { 
  800:                            D1 => "Choice D1",
  801:                            D2 => "Choice D2",
  802:                            D3 => "Choice D3",
  803:                            D4 => "Choice D4",
  804:                            D5 => "Choice D5",
  805:                            D6 => "Choice D6",
  806:                            D7 => "Choice D7"
  807:                            },
  808:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  809:                    }
  810:                );
  811: 
  812: =cut
  813: 
  814: sub linked_select_forms {
  815:     my ($formname,
  816:         $middletext,
  817:         $firstdefault,
  818:         $firstselectname,
  819:         $secondselectname, 
  820:         $hashref,
  821:         $menuorder,
  822:         ) = @_;
  823:     my $second = "document.$formname.$secondselectname";
  824:     my $first = "document.$formname.$firstselectname";
  825:     # output the javascript to do the changing
  826:     my $result = '';
  827:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  828:     $result.="var select2data = new Object();\n";
  829:     $" = '","';
  830:     my $debug = '';
  831:     foreach my $s1 (sort(keys(%$hashref))) {
  832:         $result.="select2data.d_$s1 = new Object();\n";        
  833:         $result.="select2data.d_$s1.def = new String('".
  834:             $hashref->{$s1}->{'default'}."');\n";
  835:         $result.="select2data.d_$s1.values = new Array(";
  836:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  837:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  838:             @s2values = @{$hashref->{$s1}->{'order'}};
  839:         }
  840:         $result.="\"@s2values\");\n";
  841:         $result.="select2data.d_$s1.texts = new Array(";        
  842:         my @s2texts;
  843:         foreach my $value (@s2values) {
  844:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  845:         }
  846:         $result.="\"@s2texts\");\n";
  847:     }
  848:     $"=' ';
  849:     $result.= <<"END";
  850: 
  851: function select1_changed() {
  852:     // Determine new choice
  853:     var newvalue = "d_" + $first.value;
  854:     // update select2
  855:     var values     = select2data[newvalue].values;
  856:     var texts      = select2data[newvalue].texts;
  857:     var select2def = select2data[newvalue].def;
  858:     var i;
  859:     // out with the old
  860:     for (i = 0; i < $second.options.length; i++) {
  861:         $second.options[i] = null;
  862:     }
  863:     // in with the nuclear
  864:     for (i=0;i<values.length; i++) {
  865:         $second.options[i] = new Option(values[i]);
  866:         $second.options[i].value = values[i];
  867:         $second.options[i].text = texts[i];
  868:         if (values[i] == select2def) {
  869:             $second.options[i].selected = true;
  870:         }
  871:     }
  872: }
  873: </script>
  874: END
  875:     # output the initial values for the selection lists
  876:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  877:     my @order = sort(keys(%{$hashref}));
  878:     if (ref($menuorder) eq 'ARRAY') {
  879:         @order = @{$menuorder};
  880:     }
  881:     foreach my $value (@order) {
  882:         $result.="    <option value=\"$value\" ";
  883:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  884:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  885:     }
  886:     $result .= "</select>\n";
  887:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  888:     $result .= $middletext;
  889:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  890:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  891:     
  892:     my @secondorder = sort(keys(%select2));
  893:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  894:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  895:     }
  896:     foreach my $value (@secondorder) {
  897:         $result.="    <option value=\"$value\" ";        
  898:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  899:         $result.=">".&mt($select2{$value})."</option>\n";
  900:     }
  901:     $result .= "</select>\n";
  902:     #    return $debug;
  903:     return $result;
  904: }   #  end of sub linked_select_forms {
  905: 
  906: =pod
  907: 
  908: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  909: 
  910: Returns a string corresponding to an HTML link to the given help
  911: $topic, where $topic corresponds to the name of a .tex file in
  912: /home/httpd/html/adm/help/tex, with underscores replaced by
  913: spaces. 
  914: 
  915: $text will optionally be linked to the same topic, allowing you to
  916: link text in addition to the graphic. If you do not want to link
  917: text, but wish to specify one of the later parameters, pass an
  918: empty string. 
  919: 
  920: $stayOnPage is a value that will be interpreted as a boolean. If true,
  921: the link will not open a new window. If false, the link will open
  922: a new window using Javascript. (Default is false.) 
  923: 
  924: $width and $height are optional numerical parameters that will
  925: override the width and height of the popped up window, which may
  926: be useful for certain help topics with big pictures included. 
  927: 
  928: =cut
  929: 
  930: sub help_open_topic {
  931:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  932:     $text = "" if (not defined $text);
  933:     $stayOnPage = 0 if (not defined $stayOnPage);
  934:     $width = 350 if (not defined $width);
  935:     $height = 400 if (not defined $height);
  936:     my $filename = $topic;
  937:     $filename =~ s/ /_/g;
  938: 
  939:     my $template = "";
  940:     my $link;
  941:     
  942:     $topic=~s/\W/\_/g;
  943: 
  944:     if (!$stayOnPage) {
  945: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  946:     } else {
  947: 	$link = "/adm/help/${filename}.hlp";
  948:     }
  949: 
  950:     # Add the text
  951:     if ($text ne "") {	
  952: 	$template.='<span class="LC_help_open_topic">'
  953:                   .'<a target="_top" href="'.$link.'">'
  954:                   .$text.'</a>';
  955:     }
  956: 
  957:     # (Always) Add the graphic
  958:     my $title = &mt('Online Help');
  959:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  960:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  961:               .'<img src="'.$helpicon.'" border="0"'
  962:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  963:               .' title="'.$title.'"' 
  964:               .' /></a>';
  965:     if ($text ne "") {	
  966:         $template.='</span>';
  967:     }
  968:     return $template;
  969: 
  970: }
  971: 
  972: # This is a quicky function for Latex cheatsheet editing, since it 
  973: # appears in at least four places
  974: sub helpLatexCheatsheet {
  975:     my ($topic,$text,$not_author) = @_;
  976:     my $out;
  977:     my $addOther = '';
  978:     if ($topic) {
  979: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  980: 							       undef, undef, 600).
  981: 								   '</span> ';
  982:     }
  983:     $out = '<span>' # Start cheatsheet
  984: 	  .$addOther
  985:           .'<span>'
  986: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  987: 					       undef,undef,600)
  988: 	  .'</span> <span>'
  989: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  990: 					       undef,undef,600)
  991: 	  .'</span>';
  992:     unless ($not_author) {
  993:         $out .= ' <span>'
  994: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  995: 	                                            undef,undef,600)
  996: 	       .'</span>';
  997:     }
  998:     $out .= '</span>'; # End cheatsheet
  999:     return $out;
 1000: }
 1001: 
 1002: sub general_help {
 1003:     my $helptopic='Student_Intro';
 1004:     if ($env{'request.role'}=~/^(ca|au)/) {
 1005: 	$helptopic='Authoring_Intro';
 1006:     } elsif ($env{'request.role'}=~/^cc/) {
 1007: 	$helptopic='Course_Coordination_Intro';
 1008:     } elsif ($env{'request.role'}=~/^dc/) {
 1009:         $helptopic='Domain_Coordination_Intro';
 1010:     }
 1011:     return $helptopic;
 1012: }
 1013: 
 1014: sub update_help_link {
 1015:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1016:     my $origurl = $ENV{'REQUEST_URI'};
 1017:     $origurl=~s|^/~|/priv/|;
 1018:     my $timestamp = time;
 1019:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1020:         $$datum = &escape($$datum);
 1021:     }
 1022: 
 1023:     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";
 1024:     my $output .= <<"ENDOUTPUT";
 1025: <script type="text/javascript">
 1026: banner_link = '$banner_link';
 1027: </script>
 1028: ENDOUTPUT
 1029:     return $output;
 1030: }
 1031: 
 1032: # now just updates the help link and generates a blue icon
 1033: sub help_open_menu {
 1034:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1035: 	= @_;    
 1036:     $stayOnPage = 0 if (not defined $stayOnPage);
 1037:     # only use pop-up help (stayOnPage == 0)
 1038:     # if environment.remote is on (using remote control UI)
 1039:     if ($env{'environment.remote'} eq 'off' ) {
 1040:         $stayOnPage=1;
 1041:     }
 1042:     my $output;
 1043:     if ($component_help) {
 1044: 	if (!$text) {
 1045: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1046: 				       $width,$height);
 1047: 	} else {
 1048: 	    my $help_text;
 1049: 	    $help_text=&unescape($topic);
 1050: 	    $output='<table><tr><td>'.
 1051: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1052: 				 $width,$height).'</td></tr></table>';
 1053: 	}
 1054:     }
 1055:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1056:     return $output.$banner_link;
 1057: }
 1058: 
 1059: sub top_nav_help {
 1060:     my ($text) = @_;
 1061:     $text = &mt($text);
 1062:     my $stay_on_page = 
 1063: 	($env{'environment.remote'} eq 'off' );
 1064:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1065: 	                     : "javascript:helpMenu('open')";
 1066:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1067: 
 1068:     my $title = &mt('Get help');
 1069: 
 1070:     return <<"END";
 1071: $banner_link
 1072:  <a href="$link" title="$title">$text</a>
 1073: END
 1074: }
 1075: 
 1076: sub help_menu_js {
 1077:     my ($text) = @_;
 1078: 
 1079:     my $stayOnPage = 
 1080: 	($env{'environment.remote'} eq 'off' );
 1081: 
 1082:     my $width = 620;
 1083:     my $height = 600;
 1084:     my $helptopic=&general_help();
 1085:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1086:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1087:     my $start_page =
 1088:         &Apache::loncommon::start_page('Help Menu', undef,
 1089: 				       {'frameset'    => 1,
 1090: 					'js_ready'    => 1,
 1091: 					'add_entries' => {
 1092: 					    'border' => '0',
 1093: 					    'rows'   => "110,*",},});
 1094:     my $end_page =
 1095:         &Apache::loncommon::end_page({'frameset' => 1,
 1096: 				      'js_ready' => 1,});
 1097: 
 1098:     my $template .= <<"ENDTEMPLATE";
 1099: <script type="text/javascript">
 1100: // <!-- BEGIN LON-CAPA Internal
 1101: // <![CDATA[
 1102: var banner_link = '';
 1103: function helpMenu(target) {
 1104:     var caller = this;
 1105:     if (target == 'open') {
 1106:         var newWindow = null;
 1107:         try {
 1108:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1109:         }
 1110:         catch(error) {
 1111:             writeHelp(caller);
 1112:             return;
 1113:         }
 1114:         if (newWindow) {
 1115:             caller = newWindow;
 1116:         }
 1117:     }
 1118:     writeHelp(caller);
 1119:     return;
 1120: }
 1121: function writeHelp(caller) {
 1122:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1123:     caller.document.close()
 1124:     caller.focus()
 1125: }
 1126: // ]]>
 1127: // END LON-CAPA Internal -->
 1128: </script>
 1129: ENDTEMPLATE
 1130:     return $template;
 1131: }
 1132: 
 1133: sub help_open_bug {
 1134:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1135:     unless ($env{'user.adv'}) { return ''; }
 1136:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1137:     $text = "" if (not defined $text);
 1138:     $stayOnPage = 0 if (not defined $stayOnPage);
 1139:     if ($env{'environment.remote'} eq 'off' ) {
 1140: 	$stayOnPage=1;
 1141:     }
 1142:     $width = 600 if (not defined $width);
 1143:     $height = 600 if (not defined $height);
 1144: 
 1145:     $topic=~s/\W+/\+/g;
 1146:     my $link='';
 1147:     my $template='';
 1148:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1149: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1150:     if (!$stayOnPage)
 1151:     {
 1152: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1153:     }
 1154:     else
 1155:     {
 1156: 	$link = $url;
 1157:     }
 1158:     # Add the text
 1159:     if ($text ne "")
 1160:     {
 1161: 	$template .= 
 1162:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1163:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1164:     }
 1165: 
 1166:     # Add the graphic
 1167:     my $title = &mt('Report a Bug');
 1168:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1169:     $template .= <<"ENDTEMPLATE";
 1170:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1171: ENDTEMPLATE
 1172:     if ($text ne '') { $template.='</td></tr></table>' };
 1173:     return $template;
 1174: 
 1175: }
 1176: 
 1177: sub help_open_faq {
 1178:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1179:     unless ($env{'user.adv'}) { return ''; }
 1180:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1181:     $text = "" if (not defined $text);
 1182:     $stayOnPage = 0 if (not defined $stayOnPage);
 1183:     if ($env{'environment.remote'} eq 'off' ) {
 1184: 	$stayOnPage=1;
 1185:     }
 1186:     $width = 350 if (not defined $width);
 1187:     $height = 400 if (not defined $height);
 1188: 
 1189:     $topic=~s/\W+/\+/g;
 1190:     my $link='';
 1191:     my $template='';
 1192:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1193:     if (!$stayOnPage)
 1194:     {
 1195: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1196:     }
 1197:     else
 1198:     {
 1199: 	$link = $url;
 1200:     }
 1201: 
 1202:     # Add the text
 1203:     if ($text ne "")
 1204:     {
 1205: 	$template .= 
 1206:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1207:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1208:     }
 1209: 
 1210:     # Add the graphic
 1211:     my $title = &mt('View the FAQ');
 1212:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1213:     $template .= <<"ENDTEMPLATE";
 1214:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1215: ENDTEMPLATE
 1216:     if ($text ne '') { $template.='</td></tr></table>' };
 1217:     return $template;
 1218: 
 1219: }
 1220: 
 1221: ###############################################################
 1222: ###############################################################
 1223: 
 1224: =pod
 1225: 
 1226: =item * &change_content_javascript():
 1227: 
 1228: This and the next function allow you to create small sections of an
 1229: otherwise static HTML page that you can update on the fly with
 1230: Javascript, even in Netscape 4.
 1231: 
 1232: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1233: must be written to the HTML page once. It will prove the Javascript
 1234: function "change(name, content)". Calling the change function with the
 1235: name of the section 
 1236: you want to update, matching the name passed to C<changable_area>, and
 1237: the new content you want to put in there, will put the content into
 1238: that area.
 1239: 
 1240: B<Note>: Netscape 4 only reserves enough space for the changable area
 1241: to contain room for the original contents. You need to "make space"
 1242: for whatever changes you wish to make, and be B<sure> to check your
 1243: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1244: it's adequate for updating a one-line status display, but little more.
 1245: This script will set the space to 100% width, so you only need to
 1246: worry about height in Netscape 4.
 1247: 
 1248: Modern browsers are much less limiting, and if you can commit to the
 1249: user not using Netscape 4, this feature may be used freely with
 1250: pretty much any HTML.
 1251: 
 1252: =cut
 1253: 
 1254: sub change_content_javascript {
 1255:     # If we're on Netscape 4, we need to use Layer-based code
 1256:     if ($env{'browser.type'} eq 'netscape' &&
 1257: 	$env{'browser.version'} =~ /^4\./) {
 1258: 	return (<<NETSCAPE4);
 1259: 	function change(name, content) {
 1260: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1261: 	    doc.open();
 1262: 	    doc.write(content);
 1263: 	    doc.close();
 1264: 	}
 1265: NETSCAPE4
 1266:     } else {
 1267: 	# Otherwise, we need to use semi-standards-compliant code
 1268: 	# (technically, "innerHTML" isn't standard but the equivalent
 1269: 	# is really scary, and every useful browser supports it
 1270: 	return (<<DOMBASED);
 1271: 	function change(name, content) {
 1272: 	    element = document.getElementById(name);
 1273: 	    element.innerHTML = content;
 1274: 	}
 1275: DOMBASED
 1276:     }
 1277: }
 1278: 
 1279: =pod
 1280: 
 1281: =item * &changable_area($name,$origContent):
 1282: 
 1283: This provides a "changable area" that can be modified on the fly via
 1284: the Javascript code provided in C<change_content_javascript>. $name is
 1285: the name you will use to reference the area later; do not repeat the
 1286: same name on a given HTML page more then once. $origContent is what
 1287: the area will originally contain, which can be left blank.
 1288: 
 1289: =cut
 1290: 
 1291: sub changable_area {
 1292:     my ($name, $origContent) = @_;
 1293: 
 1294:     if ($env{'browser.type'} eq 'netscape' &&
 1295: 	$env{'browser.version'} =~ /^4\./) {
 1296: 	# If this is netscape 4, we need to use the Layer tag
 1297: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1298:     } else {
 1299: 	return "<span id='$name'>$origContent</span>";
 1300:     }
 1301: }
 1302: 
 1303: =pod
 1304: 
 1305: =item * &viewport_geometry_js 
 1306: 
 1307: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1308: 
 1309: =cut
 1310: 
 1311: 
 1312: sub viewport_geometry_js { 
 1313:     return <<"GEOMETRY";
 1314: var Geometry = {};
 1315: function init_geometry() {
 1316:     if (Geometry.init) { return };
 1317:     Geometry.init=1;
 1318:     if (window.innerHeight) {
 1319:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1320:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1321:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1322:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1323:     }
 1324:     else if (document.documentElement && document.documentElement.clientHeight) {
 1325:         Geometry.getViewportHeight =
 1326:             function() { return document.documentElement.clientHeight; };
 1327:         Geometry.getViewportWidth =
 1328:             function() { return document.documentElement.clientWidth; };
 1329: 
 1330:         Geometry.getHorizontalScroll =
 1331:             function() { return document.documentElement.scrollLeft; };
 1332:         Geometry.getVerticalScroll =
 1333:             function() { return document.documentElement.scrollTop; };
 1334:     }
 1335:     else if (document.body.clientHeight) {
 1336:         Geometry.getViewportHeight =
 1337:             function() { return document.body.clientHeight; };
 1338:         Geometry.getViewportWidth =
 1339:             function() { return document.body.clientWidth; };
 1340:         Geometry.getHorizontalScroll =
 1341:             function() { return document.body.scrollLeft; };
 1342:         Geometry.getVerticalScroll =
 1343:             function() { return document.body.scrollTop; };
 1344:     }
 1345: }
 1346: 
 1347: GEOMETRY
 1348: }
 1349: 
 1350: =pod
 1351: 
 1352: =item * &viewport_size_js()
 1353: 
 1354: 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. 
 1355: 
 1356: =cut
 1357: 
 1358: sub viewport_size_js {
 1359:     my $geometry = &viewport_geometry_js();
 1360:     return <<"DIMS";
 1361: 
 1362: $geometry
 1363: 
 1364: function getViewportDims(width,height) {
 1365:     init_geometry();
 1366:     width.value = Geometry.getViewportWidth();
 1367:     height.value = Geometry.getViewportHeight();
 1368:     return;
 1369: }
 1370: 
 1371: DIMS
 1372: }
 1373: 
 1374: =pod
 1375: 
 1376: =item * &resize_textarea_js()
 1377: 
 1378: emits the needed javascript to resize a textarea to be as big as possible
 1379: 
 1380: creates a function resize_textrea that takes two IDs first should be
 1381: the id of the element to resize, second should be the id of a div that
 1382: surrounds everything that comes after the textarea, this routine needs
 1383: to be attached to the <body> for the onload and onresize events.
 1384: 
 1385: =back
 1386: 
 1387: =cut
 1388: 
 1389: sub resize_textarea_js {
 1390:     my $geometry = &viewport_geometry_js();
 1391:     return <<"RESIZE";
 1392:     <script type="text/javascript">
 1393: $geometry
 1394: 
 1395: function getX(element) {
 1396:     var x = 0;
 1397:     while (element) {
 1398: 	x += element.offsetLeft;
 1399: 	element = element.offsetParent;
 1400:     }
 1401:     return x;
 1402: }
 1403: function getY(element) {
 1404:     var y = 0;
 1405:     while (element) {
 1406: 	y += element.offsetTop;
 1407: 	element = element.offsetParent;
 1408:     }
 1409:     return y;
 1410: }
 1411: 
 1412: 
 1413: function resize_textarea(textarea_id,bottom_id) {
 1414:     init_geometry();
 1415:     var textarea        = document.getElementById(textarea_id);
 1416:     //alert(textarea);
 1417: 
 1418:     var textarea_top    = getY(textarea);
 1419:     var textarea_height = textarea.offsetHeight;
 1420:     var bottom          = document.getElementById(bottom_id);
 1421:     var bottom_top      = getY(bottom);
 1422:     var bottom_height   = bottom.offsetHeight;
 1423:     var window_height   = Geometry.getViewportHeight();
 1424:     var fudge           = 23;
 1425:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1426:     if (new_height < 300) {
 1427: 	new_height = 300;
 1428:     }
 1429:     textarea.style.height=new_height+'px';
 1430: }
 1431: </script>
 1432: RESIZE
 1433: 
 1434: }
 1435: 
 1436: =pod
 1437: 
 1438: =head1 Excel and CSV file utility routines
 1439: 
 1440: =over 4
 1441: 
 1442: =cut
 1443: 
 1444: ###############################################################
 1445: ###############################################################
 1446: 
 1447: =pod
 1448: 
 1449: =item * &csv_translate($text) 
 1450: 
 1451: Translate $text to allow it to be output as a 'comma separated values' 
 1452: format.
 1453: 
 1454: =cut
 1455: 
 1456: ###############################################################
 1457: ###############################################################
 1458: sub csv_translate {
 1459:     my $text = shift;
 1460:     $text =~ s/\"/\"\"/g;
 1461:     $text =~ s/\n/ /g;
 1462:     return $text;
 1463: }
 1464: 
 1465: ###############################################################
 1466: ###############################################################
 1467: 
 1468: =pod
 1469: 
 1470: =item * &define_excel_formats()
 1471: 
 1472: Define some commonly used Excel cell formats.
 1473: 
 1474: Currently supported formats:
 1475: 
 1476: =over 4
 1477: 
 1478: =item header
 1479: 
 1480: =item bold
 1481: 
 1482: =item h1
 1483: 
 1484: =item h2
 1485: 
 1486: =item h3
 1487: 
 1488: =item h4
 1489: 
 1490: =item i
 1491: 
 1492: =item date
 1493: 
 1494: =back
 1495: 
 1496: Inputs: $workbook
 1497: 
 1498: Returns: $format, a hash reference.
 1499: 
 1500: =cut
 1501: 
 1502: ###############################################################
 1503: ###############################################################
 1504: sub define_excel_formats {
 1505:     my ($workbook) = @_;
 1506:     my $format;
 1507:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1508:                                                 bottom    => 1,
 1509:                                                 align     => 'center');
 1510:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1511:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1512:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1513:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1514:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1515:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1516:     $format->{'date'} = $workbook->add_format(num_format=>
 1517:                                             'mm/dd/yyyy hh:mm:ss');
 1518:     return $format;
 1519: }
 1520: 
 1521: ###############################################################
 1522: ###############################################################
 1523: 
 1524: =pod
 1525: 
 1526: =item * &create_workbook()
 1527: 
 1528: Create an Excel worksheet.  If it fails, output message on the
 1529: request object and return undefs.
 1530: 
 1531: Inputs: Apache request object
 1532: 
 1533: Returns (undef) on failure, 
 1534:     Excel worksheet object, scalar with filename, and formats 
 1535:     from &Apache::loncommon::define_excel_formats on success
 1536: 
 1537: =cut
 1538: 
 1539: ###############################################################
 1540: ###############################################################
 1541: sub create_workbook {
 1542:     my ($r) = @_;
 1543:         #
 1544:     # Create the excel spreadsheet
 1545:     my $filename = '/prtspool/'.
 1546:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1547:         time.'_'.rand(1000000000).'.xls';
 1548:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1549:     if (! defined($workbook)) {
 1550:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1551:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1552:                             "This error has been logged.  ".
 1553:                             "Please alert your LON-CAPA administrator").
 1554:                   '</p>');
 1555:         return (undef);
 1556:     }
 1557:     #
 1558:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1559:     #
 1560:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1561:     return ($workbook,$filename,$format);
 1562: }
 1563: 
 1564: ###############################################################
 1565: ###############################################################
 1566: 
 1567: =pod
 1568: 
 1569: =item * &create_text_file()
 1570: 
 1571: Create a file to write to and eventually make available to the user.
 1572: If file creation fails, outputs an error message on the request object and 
 1573: return undefs.
 1574: 
 1575: Inputs: Apache request object, and file suffix
 1576: 
 1577: Returns (undef) on failure, 
 1578:     Filehandle and filename on success.
 1579: 
 1580: =cut
 1581: 
 1582: ###############################################################
 1583: ###############################################################
 1584: sub create_text_file {
 1585:     my ($r,$suffix) = @_;
 1586:     if (! defined($suffix)) { $suffix = 'txt'; };
 1587:     my $fh;
 1588:     my $filename = '/prtspool/'.
 1589:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1590:         time.'_'.rand(1000000000).'.'.$suffix;
 1591:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1592:     if (! defined($fh)) {
 1593:         $r->log_error("Couldn't open $filename for output $!");
 1594:         $r->print(&mt('Problems occurred in creating the output file. '
 1595:                      .'This error has been logged. '
 1596:                      .'Please alert your LON-CAPA administrator.'));
 1597:     }
 1598:     return ($fh,$filename)
 1599: }
 1600: 
 1601: 
 1602: =pod 
 1603: 
 1604: =back
 1605: 
 1606: =cut
 1607: 
 1608: ###############################################################
 1609: ##        Home server <option> list generating code          ##
 1610: ###############################################################
 1611: 
 1612: # ------------------------------------------
 1613: 
 1614: sub domain_select {
 1615:     my ($name,$value,$multiple)=@_;
 1616:     my %domains=map { 
 1617: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1618:     } &Apache::lonnet::all_domains();
 1619:     if ($multiple) {
 1620: 	$domains{''}=&mt('Any domain');
 1621: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1622: 	return &multiple_select_form($name,$value,4,\%domains);
 1623:     } else {
 1624: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1625: 	return &select_form($name,$value,%domains);
 1626:     }
 1627: }
 1628: 
 1629: #-------------------------------------------
 1630: 
 1631: =pod
 1632: 
 1633: =head1 Routines for form select boxes
 1634: 
 1635: =over 4
 1636: 
 1637: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1638: 
 1639: Returns a string containing a <select> element int multiple mode
 1640: 
 1641: 
 1642: Args:
 1643:   $name - name of the <select> element
 1644:   $value - scalar or array ref of values that should already be selected
 1645:   $size - number of rows long the select element is
 1646:   $hash - the elements should be 'option' => 'shown text'
 1647:           (shown text should already have been &mt())
 1648:   $order - (optional) array ref of the order to show the elements in
 1649: 
 1650: =cut
 1651: 
 1652: #-------------------------------------------
 1653: sub multiple_select_form {
 1654:     my ($name,$value,$size,$hash,$order)=@_;
 1655:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1656:     my $output='';
 1657:     if (! defined($size)) {
 1658:         $size = 4;
 1659:         if (scalar(keys(%$hash))<4) {
 1660:             $size = scalar(keys(%$hash));
 1661:         }
 1662:     }
 1663:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1664:     my @order;
 1665:     if (ref($order) eq 'ARRAY')  {
 1666:         @order = @{$order};
 1667:     } else {
 1668:         @order = sort(keys(%$hash));
 1669:     }
 1670:     if (exists($$hash{'select_form_order'})) {
 1671:         @order = @{$$hash{'select_form_order'}};
 1672:     }
 1673:         
 1674:     foreach my $key (@order) {
 1675:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1676:         $output.='selected="selected" ' if ($selected{$key});
 1677:         $output.='>'.$hash->{$key}."</option>\n";
 1678:     }
 1679:     $output.="</select>\n";
 1680:     return $output;
 1681: }
 1682: 
 1683: #-------------------------------------------
 1684: 
 1685: =pod
 1686: 
 1687: =item * &select_form($defdom,$name,%hash)
 1688: 
 1689: Returns a string containing a <select name='$name' size='1'> form to 
 1690: allow a user to select options from a hash option_name => displayed text.  
 1691: See lonrights.pm for an example invocation and use.
 1692: 
 1693: =cut
 1694: 
 1695: #-------------------------------------------
 1696: sub select_form {
 1697:     my ($def,$name,%hash) = @_;
 1698:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1699:     my @keys;
 1700:     if (exists($hash{'select_form_order'})) {
 1701: 	@keys=@{$hash{'select_form_order'}};
 1702:     } else {
 1703: 	@keys=sort(keys(%hash));
 1704:     }
 1705:     foreach my $key (@keys) {
 1706:         $selectform.=
 1707: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1708:             ($key eq $def ? 'selected="selected" ' : '').
 1709:                 ">".&mt($hash{$key})."</option>\n";
 1710:     }
 1711:     $selectform.="</select>";
 1712:     return $selectform;
 1713: }
 1714: 
 1715: # For display filters
 1716: 
 1717: sub display_filter {
 1718:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1719:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1720:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1721: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1722: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1723: 	   '</label></span> <span class="LC_nobreak">'.
 1724:            &mt('Filter [_1]',
 1725: 	   &select_form($env{'form.displayfilter'},
 1726: 			'displayfilter',
 1727: 			('currentfolder' => 'Current folder/page',
 1728: 			 'containing' => 'Containing phrase',
 1729: 			 'none' => 'None'))).
 1730: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1731: }
 1732: 
 1733: sub gradeleveldescription {
 1734:     my $gradelevel=shift;
 1735:     my %gradelevels=(0 => 'Not specified',
 1736: 		     1 => 'Grade 1',
 1737: 		     2 => 'Grade 2',
 1738: 		     3 => 'Grade 3',
 1739: 		     4 => 'Grade 4',
 1740: 		     5 => 'Grade 5',
 1741: 		     6 => 'Grade 6',
 1742: 		     7 => 'Grade 7',
 1743: 		     8 => 'Grade 8',
 1744: 		     9 => 'Grade 9',
 1745: 		     10 => 'Grade 10',
 1746: 		     11 => 'Grade 11',
 1747: 		     12 => 'Grade 12',
 1748: 		     13 => 'Grade 13',
 1749: 		     14 => '100 Level',
 1750: 		     15 => '200 Level',
 1751: 		     16 => '300 Level',
 1752: 		     17 => '400 Level',
 1753: 		     18 => 'Graduate Level');
 1754:     return &mt($gradelevels{$gradelevel});
 1755: }
 1756: 
 1757: sub select_level_form {
 1758:     my ($deflevel,$name)=@_;
 1759:     unless ($deflevel) { $deflevel=0; }
 1760:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1761:     for (my $i=0; $i<=18; $i++) {
 1762:         $selectform.="<option value=\"$i\" ".
 1763:             ($i==$deflevel ? 'selected="selected" ' : '').
 1764:                 ">".&gradeleveldescription($i)."</option>\n";
 1765:     }
 1766:     $selectform.="</select>";
 1767:     return $selectform;
 1768: }
 1769: 
 1770: #-------------------------------------------
 1771: 
 1772: =pod
 1773: 
 1774: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1775: 
 1776: Returns a string containing a <select name='$name' size='1'> form to 
 1777: allow a user to select the domain to preform an operation in.  
 1778: See loncreateuser.pm for an example invocation and use.
 1779: 
 1780: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1781: selected");
 1782: 
 1783: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1784: 
 1785: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1786: 
 1787: =cut
 1788: 
 1789: #-------------------------------------------
 1790: sub select_dom_form {
 1791:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1792:     my $onchange;
 1793:     if ($autosubmit) {
 1794:         $onchange = ' onchange="this.form.submit()"';
 1795:     }
 1796:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1797:     if ($includeempty) { @domains=('',@domains); }
 1798:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1799:     foreach my $dom (@domains) {
 1800:         $selectdomain.="<option value=\"$dom\" ".
 1801:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1802:         if ($showdomdesc) {
 1803:             if ($dom ne '') {
 1804:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1805:                 if ($domdesc ne '') {
 1806:                     $selectdomain .= ' ('.$domdesc.')';
 1807:                 }
 1808:             } 
 1809:         }
 1810:         $selectdomain .= "</option>\n";
 1811:     }
 1812:     $selectdomain.="</select>";
 1813:     return $selectdomain;
 1814: }
 1815: 
 1816: #-------------------------------------------
 1817: 
 1818: =pod
 1819: 
 1820: =item * &home_server_form_item($domain,$name,$defaultflag)
 1821: 
 1822: input: 4 arguments (two required, two optional) - 
 1823:     $domain - domain of new user
 1824:     $name - name of form element
 1825:     $default - Value of 'default' causes a default item to be first 
 1826:                             option, and selected by default. 
 1827:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1828:                             if 1 server found, or default, if 0 found.
 1829: output: returns 2 items: 
 1830: (a) form element which contains either:
 1831:    (i) <select name="$name">
 1832:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1833:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1834:        </select>
 1835:        form item if there are multiple library servers in $domain, or
 1836:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1837:        if there is only one library server in $domain.
 1838: 
 1839: (b) number of library servers found.
 1840: 
 1841: See loncreateuser.pm for example of use.
 1842: 
 1843: =cut
 1844: 
 1845: #-------------------------------------------
 1846: sub home_server_form_item {
 1847:     my ($domain,$name,$default,$hide) = @_;
 1848:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1849:     my $result;
 1850:     my $numlib = keys(%servers);
 1851:     if ($numlib > 1) {
 1852:         $result .= '<select name="'.$name.'" />'."\n";
 1853:         if ($default) {
 1854:             $result .= '<option value="default" selected>'.&mt('default').
 1855:                        '</option>'."\n";
 1856:         }
 1857:         foreach my $hostid (sort(keys(%servers))) {
 1858:             $result.= '<option value="'.$hostid.'">'.
 1859: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1860:         }
 1861:         $result .= '</select>'."\n";
 1862:     } elsif ($numlib == 1) {
 1863:         my $hostid;
 1864:         foreach my $item (keys(%servers)) {
 1865:             $hostid = $item;
 1866:         }
 1867:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1868:                    $hostid.'" />';
 1869:                    if (!$hide) {
 1870:                        $result .= $hostid.' '.$servers{$hostid};
 1871:                    }
 1872:                    $result .= "\n";
 1873:     } elsif ($default) {
 1874:         $result .= '<input type="hidden" name="'.$name.
 1875:                    '" value="default" />';
 1876:                    if (!$hide) {
 1877:                        $result .= &mt('default');
 1878:                    }
 1879:                    $result .= "\n";
 1880:     }
 1881:     return ($result,$numlib);
 1882: }
 1883: 
 1884: =pod
 1885: 
 1886: =back 
 1887: 
 1888: =cut
 1889: 
 1890: ###############################################################
 1891: ##                  Decoding User Agent                      ##
 1892: ###############################################################
 1893: 
 1894: =pod
 1895: 
 1896: =head1 Decoding the User Agent
 1897: 
 1898: =over 4
 1899: 
 1900: =item * &decode_user_agent()
 1901: 
 1902: Inputs: $r
 1903: 
 1904: Outputs:
 1905: 
 1906: =over 4
 1907: 
 1908: =item * $httpbrowser
 1909: 
 1910: =item * $clientbrowser
 1911: 
 1912: =item * $clientversion
 1913: 
 1914: =item * $clientmathml
 1915: 
 1916: =item * $clientunicode
 1917: 
 1918: =item * $clientos
 1919: 
 1920: =back
 1921: 
 1922: =back 
 1923: 
 1924: =cut
 1925: 
 1926: ###############################################################
 1927: ###############################################################
 1928: sub decode_user_agent {
 1929:     my ($r)=@_;
 1930:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1931:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1932:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1933:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1934:     my $clientbrowser='unknown';
 1935:     my $clientversion='0';
 1936:     my $clientmathml='';
 1937:     my $clientunicode='0';
 1938:     for (my $i=0;$i<=$#browsertype;$i++) {
 1939:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1940: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1941: 	    $clientbrowser=$bname;
 1942:             $httpbrowser=~/$vreg/i;
 1943: 	    $clientversion=$1;
 1944:             $clientmathml=($clientversion>=$minv);
 1945:             $clientunicode=($clientversion>=$univ);
 1946: 	}
 1947:     }
 1948:     my $clientos='unknown';
 1949:     if (($httpbrowser=~/linux/i) ||
 1950:         ($httpbrowser=~/unix/i) ||
 1951:         ($httpbrowser=~/ux/i) ||
 1952:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1953:     if (($httpbrowser=~/vax/i) ||
 1954:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1955:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1956:     if (($httpbrowser=~/mac/i) ||
 1957:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1958:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1959:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1960:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1961:             $clientunicode,$clientos,);
 1962: }
 1963: 
 1964: ###############################################################
 1965: ##    Authentication changing form generation subroutines    ##
 1966: ###############################################################
 1967: ##
 1968: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1969: ## hash, and have reasonable default values.
 1970: ##
 1971: ##    formname = the name given in the <form> tag.
 1972: #-------------------------------------------
 1973: 
 1974: =pod
 1975: 
 1976: =head1 Authentication Routines
 1977: 
 1978: =over 4
 1979: 
 1980: =item * &authform_xxxxxx()
 1981: 
 1982: The authform_xxxxxx subroutines provide javascript and html forms which 
 1983: handle some of the conveniences required for authentication forms.  
 1984: This is not an optimal method, but it works.  
 1985: 
 1986: =over 4
 1987: 
 1988: =item * authform_header
 1989: 
 1990: =item * authform_authorwarning
 1991: 
 1992: =item * authform_nochange
 1993: 
 1994: =item * authform_kerberos
 1995: 
 1996: =item * authform_internal
 1997: 
 1998: =item * authform_filesystem
 1999: 
 2000: =back
 2001: 
 2002: See loncreateuser.pm for invocation and use examples.
 2003: 
 2004: =cut
 2005: 
 2006: #-------------------------------------------
 2007: sub authform_header{  
 2008:     my %in = (
 2009:         formname => 'cu',
 2010:         kerb_def_dom => '',
 2011:         @_,
 2012:     );
 2013:     $in{'formname'} = 'document.' . $in{'formname'};
 2014:     my $result='';
 2015: 
 2016: #---------------------------------------------- Code for upper case translation
 2017:     my $Javascript_toUpperCase;
 2018:     unless ($in{kerb_def_dom}) {
 2019:         $Javascript_toUpperCase =<<"END";
 2020:         switch (choice) {
 2021:            case 'krb': currentform.elements[choicearg].value =
 2022:                currentform.elements[choicearg].value.toUpperCase();
 2023:                break;
 2024:            default:
 2025:         }
 2026: END
 2027:     } else {
 2028:         $Javascript_toUpperCase = "";
 2029:     }
 2030: 
 2031:     my $radioval = "'nochange'";
 2032:     if (defined($in{'curr_authtype'})) {
 2033:         if ($in{'curr_authtype'} ne '') {
 2034:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2035:         }
 2036:     }
 2037:     my $argfield = 'null';
 2038:     if (defined($in{'mode'})) {
 2039:         if ($in{'mode'} eq 'modifycourse')  {
 2040:             if (defined($in{'curr_autharg'})) {
 2041:                 if ($in{'curr_autharg'} ne '') {
 2042:                     $argfield = "'$in{'curr_autharg'}'";
 2043:                 }
 2044:             }
 2045:         }
 2046:     }
 2047: 
 2048:     $result.=<<"END";
 2049: var current = new Object();
 2050: current.radiovalue = $radioval;
 2051: current.argfield = $argfield;
 2052: 
 2053: function changed_radio(choice,currentform) {
 2054:     var choicearg = choice + 'arg';
 2055:     // If a radio button in changed, we need to change the argfield
 2056:     if (current.radiovalue != choice) {
 2057:         current.radiovalue = choice;
 2058:         if (current.argfield != null) {
 2059:             currentform.elements[current.argfield].value = '';
 2060:         }
 2061:         if (choice == 'nochange') {
 2062:             current.argfield = null;
 2063:         } else {
 2064:             current.argfield = choicearg;
 2065:             switch(choice) {
 2066:                 case 'krb': 
 2067:                     currentform.elements[current.argfield].value = 
 2068:                         "$in{'kerb_def_dom'}";
 2069:                 break;
 2070:               default:
 2071:                 break;
 2072:             }
 2073:         }
 2074:     }
 2075:     return;
 2076: }
 2077: 
 2078: function changed_text(choice,currentform) {
 2079:     var choicearg = choice + 'arg';
 2080:     if (currentform.elements[choicearg].value !='') {
 2081:         $Javascript_toUpperCase
 2082:         // clear old field
 2083:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2084:             currentform.elements[current.argfield].value = '';
 2085:         }
 2086:         current.argfield = choicearg;
 2087:     }
 2088:     set_auth_radio_buttons(choice,currentform);
 2089:     return;
 2090: }
 2091: 
 2092: function set_auth_radio_buttons(newvalue,currentform) {
 2093:     var i=0;
 2094:     while (i < currentform.login.length) {
 2095:         if (currentform.login[i].value == newvalue) { break; }
 2096:         i++;
 2097:     }
 2098:     if (i == currentform.login.length) {
 2099:         return;
 2100:     }
 2101:     current.radiovalue = newvalue;
 2102:     currentform.login[i].checked = true;
 2103:     return;
 2104: }
 2105: END
 2106:     return $result;
 2107: }
 2108: 
 2109: sub authform_authorwarning{
 2110:     my $result='';
 2111:     $result='<i>'.
 2112:         &mt('As a general rule, only authors or co-authors should be '.
 2113:             'filesystem authenticated '.
 2114:             '(which allows access to the server filesystem).')."</i>\n";
 2115:     return $result;
 2116: }
 2117: 
 2118: sub authform_nochange{  
 2119:     my %in = (
 2120:               formname => 'document.cu',
 2121:               kerb_def_dom => 'MSU.EDU',
 2122:               @_,
 2123:           );
 2124:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2125:     my $result;
 2126:     if (keys(%can_assign) == 0) {
 2127:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2128:     } else {
 2129:         $result = '<label>'.&mt('[_1] Do not change login data',
 2130:                   '<input type="radio" name="login" value="nochange" '.
 2131:                   'checked="checked" onclick="'.
 2132:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2133: 	    '</label>';
 2134:     }
 2135:     return $result;
 2136: }
 2137: 
 2138: sub authform_kerberos {
 2139:     my %in = (
 2140:               formname => 'document.cu',
 2141:               kerb_def_dom => 'MSU.EDU',
 2142:               kerb_def_auth => 'krb4',
 2143:               @_,
 2144:               );
 2145:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2146:         $autharg,$jscall);
 2147:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2148:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2149:        $check5 = ' checked="checked"';
 2150:     } else {
 2151:        $check4 = ' checked="checked"';
 2152:     }
 2153:     $krbarg = $in{'kerb_def_dom'};
 2154:     if (defined($in{'curr_authtype'})) {
 2155:         if ($in{'curr_authtype'} eq 'krb') {
 2156:             $krbcheck = ' checked="checked"';
 2157:             if (defined($in{'mode'})) {
 2158:                 if ($in{'mode'} eq 'modifyuser') {
 2159:                     $krbcheck = '';
 2160:                 }
 2161:             }
 2162:             if (defined($in{'curr_kerb_ver'})) {
 2163:                 if ($in{'curr_krb_ver'} eq '5') {
 2164:                     $check5 = ' checked="checked"';
 2165:                     $check4 = '';
 2166:                 } else {
 2167:                     $check4 = ' checked="checked"';
 2168:                     $check5 = '';
 2169:                 }
 2170:             }
 2171:             if (defined($in{'curr_autharg'})) {
 2172:                 $krbarg = $in{'curr_autharg'};
 2173:             }
 2174:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2175:                 if (defined($in{'curr_autharg'})) {
 2176:                     $result = 
 2177:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2178:         $in{'curr_autharg'},$krbver);
 2179:                 } else {
 2180:                     $result =
 2181:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2182:                 }
 2183:                 return $result; 
 2184:             }
 2185:         }
 2186:     } else {
 2187:         if ($authnum == 1) {
 2188:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2189:         }
 2190:     }
 2191:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2192:         return;
 2193:     } elsif ($authtype eq '') {
 2194:         if (defined($in{'mode'})) {
 2195:             if ($in{'mode'} eq 'modifycourse') {
 2196:                 if ($authnum == 1) {
 2197:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2198:                 }
 2199:             }
 2200:         }
 2201:     }
 2202:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2203:     if ($authtype eq '') {
 2204:         $authtype = '<input type="radio" name="login" value="krb" '.
 2205:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2206:                     $krbcheck.' />';
 2207:     }
 2208:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2209:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2210:          $in{'curr_authtype'} eq 'krb5') ||
 2211:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2212:          $in{'curr_authtype'} eq 'krb4')) {
 2213:         $result .= &mt
 2214:         ('[_1] Kerberos authenticated with domain [_2] '.
 2215:          '[_3] Version 4 [_4] Version 5 [_5]',
 2216:          '<label>'.$authtype,
 2217:          '</label><input type="text" size="10" name="krbarg" '.
 2218:              'value="'.$krbarg.'" '.
 2219:              'onchange="'.$jscall.'" />',
 2220:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2221:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2222: 	 '</label>');
 2223:     } elsif ($can_assign{'krb4'}) {
 2224:         $result .= &mt
 2225:         ('[_1] Kerberos authenticated with domain [_2] '.
 2226:          '[_3] Version 4 [_4]',
 2227:          '<label>'.$authtype,
 2228:          '</label><input type="text" size="10" name="krbarg" '.
 2229:              'value="'.$krbarg.'" '.
 2230:              'onchange="'.$jscall.'" />',
 2231:          '<label><input type="hidden" name="krbver" value="4" />',
 2232:          '</label>');
 2233:     } elsif ($can_assign{'krb5'}) {
 2234:         $result .= &mt
 2235:         ('[_1] Kerberos authenticated with domain [_2] '.
 2236:          '[_3] Version 5 [_4]',
 2237:          '<label>'.$authtype,
 2238:          '</label><input type="text" size="10" name="krbarg" '.
 2239:              'value="'.$krbarg.'" '.
 2240:              'onchange="'.$jscall.'" />',
 2241:          '<label><input type="hidden" name="krbver" value="5" />',
 2242:          '</label>');
 2243:     }
 2244:     return $result;
 2245: }
 2246: 
 2247: sub authform_internal{  
 2248:     my %in = (
 2249:                 formname => 'document.cu',
 2250:                 kerb_def_dom => 'MSU.EDU',
 2251:                 @_,
 2252:                 );
 2253:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2254:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2255:     if (defined($in{'curr_authtype'})) {
 2256:         if ($in{'curr_authtype'} eq 'int') {
 2257:             if ($can_assign{'int'}) {
 2258:                 $intcheck = 'checked="checked" ';
 2259:                 if (defined($in{'mode'})) {
 2260:                     if ($in{'mode'} eq 'modifyuser') {
 2261:                         $intcheck = '';
 2262:                     }
 2263:                 }
 2264:                 if (defined($in{'curr_autharg'})) {
 2265:                     $intarg = $in{'curr_autharg'};
 2266:                 }
 2267:             } else {
 2268:                 $result = &mt('Currently internally authenticated.');
 2269:                 return $result;
 2270:             }
 2271:         }
 2272:     } else {
 2273:         if ($authnum == 1) {
 2274:             $authtype = '<input type="hidden" name="login" value="int" />';
 2275:         }
 2276:     }
 2277:     if (!$can_assign{'int'}) {
 2278:         return;
 2279:     } elsif ($authtype eq '') {
 2280:         if (defined($in{'mode'})) {
 2281:             if ($in{'mode'} eq 'modifycourse') {
 2282:                 if ($authnum == 1) {
 2283:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2284:                 }
 2285:             }
 2286:         }
 2287:     }
 2288:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2289:     if ($authtype eq '') {
 2290:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2291:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2292:     }
 2293:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2294:                $intarg.'" onchange="'.$jscall.'" />';
 2295:     $result = &mt
 2296:         ('[_1] Internally authenticated (with initial password [_2])',
 2297:          '<label>'.$authtype,'</label>'.$autharg);
 2298:     $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>';
 2299:     return $result;
 2300: }
 2301: 
 2302: sub authform_local{  
 2303:     my %in = (
 2304:               formname => 'document.cu',
 2305:               kerb_def_dom => 'MSU.EDU',
 2306:               @_,
 2307:               );
 2308:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2309:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2310:     if (defined($in{'curr_authtype'})) {
 2311:         if ($in{'curr_authtype'} eq 'loc') {
 2312:             if ($can_assign{'loc'}) {
 2313:                 $loccheck = 'checked="checked" ';
 2314:                 if (defined($in{'mode'})) {
 2315:                     if ($in{'mode'} eq 'modifyuser') {
 2316:                         $loccheck = '';
 2317:                     }
 2318:                 }
 2319:                 if (defined($in{'curr_autharg'})) {
 2320:                     $locarg = $in{'curr_autharg'};
 2321:                 }
 2322:             } else {
 2323:                 $result = &mt('Currently using local (institutional) authentication.');
 2324:                 return $result;
 2325:             }
 2326:         }
 2327:     } else {
 2328:         if ($authnum == 1) {
 2329:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2330:         }
 2331:     }
 2332:     if (!$can_assign{'loc'}) {
 2333:         return;
 2334:     } elsif ($authtype eq '') {
 2335:         if (defined($in{'mode'})) {
 2336:             if ($in{'mode'} eq 'modifycourse') {
 2337:                 if ($authnum == 1) {
 2338:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2339:                 }
 2340:             }
 2341:         }
 2342:     }
 2343:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2344:     if ($authtype eq '') {
 2345:         $authtype = '<input type="radio" name="login" value="loc" '.
 2346:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2347:                     $jscall.'" />';
 2348:     }
 2349:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2350:                $locarg.'" onchange="'.$jscall.'" />';
 2351:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2352:                   '<label>'.$authtype,'</label>'.$autharg);
 2353:     return $result;
 2354: }
 2355: 
 2356: sub authform_filesystem{  
 2357:     my %in = (
 2358:               formname => 'document.cu',
 2359:               kerb_def_dom => 'MSU.EDU',
 2360:               @_,
 2361:               );
 2362:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2363:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2364:     if (defined($in{'curr_authtype'})) {
 2365:         if ($in{'curr_authtype'} eq 'fsys') {
 2366:             if ($can_assign{'fsys'}) {
 2367:                 $fsyscheck = 'checked="checked" ';
 2368:                 if (defined($in{'mode'})) {
 2369:                     if ($in{'mode'} eq 'modifyuser') {
 2370:                         $fsyscheck = '';
 2371:                     }
 2372:                 }
 2373:             } else {
 2374:                 $result = &mt('Currently Filesystem Authenticated.');
 2375:                 return $result;
 2376:             }           
 2377:         }
 2378:     } else {
 2379:         if ($authnum == 1) {
 2380:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2381:         }
 2382:     }
 2383:     if (!$can_assign{'fsys'}) {
 2384:         return;
 2385:     } elsif ($authtype eq '') {
 2386:         if (defined($in{'mode'})) {
 2387:             if ($in{'mode'} eq 'modifycourse') {
 2388:                 if ($authnum == 1) {
 2389:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2390:                 }
 2391:             }
 2392:         }
 2393:     }
 2394:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2395:     if ($authtype eq '') {
 2396:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2397:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2398:                     $jscall.'" />';
 2399:     }
 2400:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2401:                ' onchange="'.$jscall.'" />';
 2402:     $result = &mt
 2403:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2404:          '<label><input type="radio" name="login" value="fsys" '.
 2405:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2406:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2407:                   'onchange="'.$jscall.'" />');
 2408:     return $result;
 2409: }
 2410: 
 2411: sub get_assignable_auth {
 2412:     my ($dom) = @_;
 2413:     if ($dom eq '') {
 2414:         $dom = $env{'request.role.domain'};
 2415:     }
 2416:     my %can_assign = (
 2417:                           krb4 => 1,
 2418:                           krb5 => 1,
 2419:                           int  => 1,
 2420:                           loc  => 1,
 2421:                      );
 2422:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2423:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2424:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2425:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2426:             my $context;
 2427:             if ($env{'request.role'} =~ /^au/) {
 2428:                 $context = 'author';
 2429:             } elsif ($env{'request.role'} =~ /^dc/) {
 2430:                 $context = 'domain';
 2431:             } elsif ($env{'request.course.id'}) {
 2432:                 $context = 'course';
 2433:             }
 2434:             if ($context) {
 2435:                 if (ref($authhash->{$context}) eq 'HASH') {
 2436:                    %can_assign = %{$authhash->{$context}}; 
 2437:                 }
 2438:             }
 2439:         }
 2440:     }
 2441:     my $authnum = 0;
 2442:     foreach my $key (keys(%can_assign)) {
 2443:         if ($can_assign{$key}) {
 2444:             $authnum ++;
 2445:         }
 2446:     }
 2447:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2448:         $authnum --;
 2449:     }
 2450:     return ($authnum,%can_assign);
 2451: }
 2452: 
 2453: ###############################################################
 2454: ##    Get Kerberos Defaults for Domain                 ##
 2455: ###############################################################
 2456: ##
 2457: ## Returns default kerberos version and an associated argument
 2458: ## as listed in file domain.tab. If not listed, provides
 2459: ## appropriate default domain and kerberos version.
 2460: ##
 2461: #-------------------------------------------
 2462: 
 2463: =pod
 2464: 
 2465: =item * &get_kerberos_defaults()
 2466: 
 2467: get_kerberos_defaults($target_domain) returns the default kerberos
 2468: version and domain. If not found, it defaults to version 4 and the 
 2469: domain of the server.
 2470: 
 2471: =over 4
 2472: 
 2473: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2474: 
 2475: =back
 2476: 
 2477: =back
 2478: 
 2479: =cut
 2480: 
 2481: #-------------------------------------------
 2482: sub get_kerberos_defaults {
 2483:     my $domain=shift;
 2484:     my ($krbdef,$krbdefdom);
 2485:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2486:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2487:         $krbdef = $domdefaults{'auth_def'};
 2488:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2489:     } else {
 2490:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2491:         my $krbdefdom=$1;
 2492:         $krbdefdom=~tr/a-z/A-Z/;
 2493:         $krbdef = "krb4";
 2494:     }
 2495:     return ($krbdef,$krbdefdom);
 2496: }
 2497: 
 2498: 
 2499: ###############################################################
 2500: ##                Thesaurus Functions                        ##
 2501: ###############################################################
 2502: 
 2503: =pod
 2504: 
 2505: =head1 Thesaurus Functions
 2506: 
 2507: =over 4
 2508: 
 2509: =item * &initialize_keywords()
 2510: 
 2511: Initializes the package variable %Keywords if it is empty.  Uses the
 2512: package variable $thesaurus_db_file.
 2513: 
 2514: =cut
 2515: 
 2516: ###################################################
 2517: 
 2518: sub initialize_keywords {
 2519:     return 1 if (scalar keys(%Keywords));
 2520:     # If we are here, %Keywords is empty, so fill it up
 2521:     #   Make sure the file we need exists...
 2522:     if (! -e $thesaurus_db_file) {
 2523:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2524:                                  " failed because it does not exist");
 2525:         return 0;
 2526:     }
 2527:     #   Set up the hash as a database
 2528:     my %thesaurus_db;
 2529:     if (! tie(%thesaurus_db,'GDBM_File',
 2530:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2531:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2532:                                  $thesaurus_db_file);
 2533:         return 0;
 2534:     } 
 2535:     #  Get the average number of appearances of a word.
 2536:     my $avecount = $thesaurus_db{'average.count'};
 2537:     #  Put keywords (those that appear > average) into %Keywords
 2538:     while (my ($word,$data)=each (%thesaurus_db)) {
 2539:         my ($count,undef) = split /:/,$data;
 2540:         $Keywords{$word}++ if ($count > $avecount);
 2541:     }
 2542:     untie %thesaurus_db;
 2543:     # Remove special values from %Keywords.
 2544:     foreach my $value ('total.count','average.count') {
 2545:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2546:   }
 2547:     return 1;
 2548: }
 2549: 
 2550: ###################################################
 2551: 
 2552: =pod
 2553: 
 2554: =item * &keyword($word)
 2555: 
 2556: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2557: than the average number of times in the thesaurus database.  Calls 
 2558: &initialize_keywords
 2559: 
 2560: =cut
 2561: 
 2562: ###################################################
 2563: 
 2564: sub keyword {
 2565:     return if (!&initialize_keywords());
 2566:     my $word=lc(shift());
 2567:     $word=~s/\W//g;
 2568:     return exists($Keywords{$word});
 2569: }
 2570: 
 2571: ###############################################################
 2572: 
 2573: =pod 
 2574: 
 2575: =item * &get_related_words()
 2576: 
 2577: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2578: an array of words.  If the keyword is not in the thesaurus, an empty array
 2579: will be returned.  The order of the words returned is determined by the
 2580: database which holds them.
 2581: 
 2582: Uses global $thesaurus_db_file.
 2583: 
 2584: =cut
 2585: 
 2586: ###############################################################
 2587: sub get_related_words {
 2588:     my $keyword = shift;
 2589:     my %thesaurus_db;
 2590:     if (! -e $thesaurus_db_file) {
 2591:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2592:                                  "failed because the file does not exist");
 2593:         return ();
 2594:     }
 2595:     if (! tie(%thesaurus_db,'GDBM_File',
 2596:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2597:         return ();
 2598:     } 
 2599:     my @Words=();
 2600:     my $count=0;
 2601:     if (exists($thesaurus_db{$keyword})) {
 2602: 	# The first element is the number of times
 2603: 	# the word appears.  We do not need it now.
 2604: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2605: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2606: 	my $threshold=$mostfrequentcount/10;
 2607:         foreach my $possibleword (@RelatedWords) {
 2608:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2609:             if ($wordcount>$threshold) {
 2610: 		push(@Words,$word);
 2611:                 $count++;
 2612:                 if ($count>10) { last; }
 2613: 	    }
 2614:         }
 2615:     }
 2616:     untie %thesaurus_db;
 2617:     return @Words;
 2618: }
 2619: 
 2620: =pod
 2621: 
 2622: =back
 2623: 
 2624: =cut
 2625: 
 2626: # -------------------------------------------------------------- Plaintext name
 2627: =pod
 2628: 
 2629: =head1 User Name Functions
 2630: 
 2631: =over 4
 2632: 
 2633: =item * &plainname($uname,$udom,$first)
 2634: 
 2635: Takes a users logon name and returns it as a string in
 2636: "first middle last generation" form 
 2637: if $first is set to 'lastname' then it returns it as
 2638: 'lastname generation, firstname middlename' if their is a lastname
 2639: 
 2640: =cut
 2641: 
 2642: 
 2643: ###############################################################
 2644: sub plainname {
 2645:     my ($uname,$udom,$first)=@_;
 2646:     return if (!defined($uname) || !defined($udom));
 2647:     my %names=&getnames($uname,$udom);
 2648:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2649: 					  $names{'middlename'},
 2650: 					  $names{'lastname'},
 2651: 					  $names{'generation'},$first);
 2652:     $name=~s/^\s+//;
 2653:     $name=~s/\s+$//;
 2654:     $name=~s/\s+/ /g;
 2655:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2656:     return $name;
 2657: }
 2658: 
 2659: # -------------------------------------------------------------------- Nickname
 2660: =pod
 2661: 
 2662: =item * &nickname($uname,$udom)
 2663: 
 2664: Gets a users name and returns it as a string as
 2665: 
 2666: "&quot;nickname&quot;"
 2667: 
 2668: if the user has a nickname or
 2669: 
 2670: "first middle last generation"
 2671: 
 2672: if the user does not
 2673: 
 2674: =cut
 2675: 
 2676: sub nickname {
 2677:     my ($uname,$udom)=@_;
 2678:     return if (!defined($uname) || !defined($udom));
 2679:     my %names=&getnames($uname,$udom);
 2680:     my $name=$names{'nickname'};
 2681:     if ($name) {
 2682:        $name='&quot;'.$name.'&quot;'; 
 2683:     } else {
 2684:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2685: 	     $names{'lastname'}.' '.$names{'generation'};
 2686:        $name=~s/\s+$//;
 2687:        $name=~s/\s+/ /g;
 2688:     }
 2689:     return $name;
 2690: }
 2691: 
 2692: sub getnames {
 2693:     my ($uname,$udom)=@_;
 2694:     return if (!defined($uname) || !defined($udom));
 2695:     if ($udom eq 'public' && $uname eq 'public') {
 2696: 	return ('lastname' => &mt('Public'));
 2697:     }
 2698:     my $id=$uname.':'.$udom;
 2699:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2700:     if ($cached) {
 2701: 	return %{$names};
 2702:     } else {
 2703: 	my %loadnames=&Apache::lonnet::get('environment',
 2704:                     ['firstname','middlename','lastname','generation','nickname'],
 2705: 					 $udom,$uname);
 2706: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2707: 	return %loadnames;
 2708:     }
 2709: }
 2710: 
 2711: # -------------------------------------------------------------------- getemails
 2712: 
 2713: =pod
 2714: 
 2715: =item * &getemails($uname,$udom)
 2716: 
 2717: Gets a user's email information and returns it as a hash with keys:
 2718: notification, critnotification, permanentemail
 2719: 
 2720: For notification and critnotification, values are comma-separated lists 
 2721: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2722:  
 2723: 
 2724: =cut
 2725: 
 2726: 
 2727: sub getemails {
 2728:     my ($uname,$udom)=@_;
 2729:     if ($udom eq 'public' && $uname eq 'public') {
 2730: 	return;
 2731:     }
 2732:     if (!$udom) { $udom=$env{'user.domain'}; }
 2733:     if (!$uname) { $uname=$env{'user.name'}; }
 2734:     my $id=$uname.':'.$udom;
 2735:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2736:     if ($cached) {
 2737: 	return %{$names};
 2738:     } else {
 2739: 	my %loadnames=&Apache::lonnet::get('environment',
 2740:                     			   ['notification','critnotification',
 2741: 					    'permanentemail'],
 2742: 					   $udom,$uname);
 2743: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2744: 	return %loadnames;
 2745:     }
 2746: }
 2747: 
 2748: sub flush_email_cache {
 2749:     my ($uname,$udom)=@_;
 2750:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2751:     if (!$uname) { $uname=$env{'user.name'};   }
 2752:     return if ($udom eq 'public' && $uname eq 'public');
 2753:     my $id=$uname.':'.$udom;
 2754:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2755: }
 2756: 
 2757: # -------------------------------------------------------------------- getlangs
 2758: 
 2759: =pod
 2760: 
 2761: =item * &getlangs($uname,$udom)
 2762: 
 2763: Gets a user's language preference and returns it as a hash with key:
 2764: language.
 2765: 
 2766: =cut
 2767: 
 2768: 
 2769: sub getlangs {
 2770:     my ($uname,$udom) = @_;
 2771:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2772:     if (!$uname) { $uname=$env{'user.name'};   }
 2773:     my $id=$uname.':'.$udom;
 2774:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2775:     if ($cached) {
 2776:         return %{$langs};
 2777:     } else {
 2778:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2779:                                            $udom,$uname);
 2780:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2781:         return %loadlangs;
 2782:     }
 2783: }
 2784: 
 2785: sub flush_langs_cache {
 2786:     my ($uname,$udom)=@_;
 2787:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2788:     if (!$uname) { $uname=$env{'user.name'};   }
 2789:     return if ($udom eq 'public' && $uname eq 'public');
 2790:     my $id=$uname.':'.$udom;
 2791:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2792: }
 2793: 
 2794: # ------------------------------------------------------------------ Screenname
 2795: 
 2796: =pod
 2797: 
 2798: =item * &screenname($uname,$udom)
 2799: 
 2800: Gets a users screenname and returns it as a string
 2801: 
 2802: =cut
 2803: 
 2804: sub screenname {
 2805:     my ($uname,$udom)=@_;
 2806:     if ($uname eq $env{'user.name'} &&
 2807: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2808:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2809:     return $names{'screenname'};
 2810: }
 2811: 
 2812: 
 2813: # ------------------------------------------------------------- Message Wrapper
 2814: 
 2815: sub messagewrapper {
 2816:     my ($link,$username,$domain,$subject,$text)=@_;
 2817:     return 
 2818:         '<a href="/adm/email?compose=individual&amp;'.
 2819:         'recname='.$username.'&amp;recdom='.$domain.
 2820: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2821:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2822: }
 2823: # --------------------------------------------------------------- Notes Wrapper
 2824: 
 2825: sub noteswrapper {
 2826:     my ($link,$un,$do)=@_;
 2827:     return 
 2828: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2829: }
 2830: # ------------------------------------------------------------- Aboutme Wrapper
 2831: 
 2832: sub aboutmewrapper {
 2833:     my ($link,$username,$domain,$target)=@_;
 2834:     if (!defined($username)  && !defined($domain)) {
 2835:         return;
 2836:     }
 2837:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2838: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2839: }
 2840: 
 2841: # ------------------------------------------------------------ Syllabus Wrapper
 2842: 
 2843: 
 2844: sub syllabuswrapper {
 2845:     my ($linktext,$coursedir,$domain)=@_;
 2846:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2847: }
 2848: 
 2849: sub track_student_link {
 2850:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2851:     my $link ="/adm/trackstudent?";
 2852:     my $title = 'View recent activity';
 2853:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2854:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2855:         $link .= "selected_student=$sname:$sdom";
 2856:         $title .= ' of this student';
 2857:     } 
 2858:     if (defined($target) && $target !~ /^\s*$/) {
 2859:         $target = qq{target="$target"};
 2860:     } else {
 2861:         $target = '';
 2862:     }
 2863:     if ($start) { $link.='&amp;start='.$start; }
 2864:     $title = &mt($title);
 2865:     $linktext = &mt($linktext);
 2866:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2867: 	&help_open_topic('View_recent_activity');
 2868: }
 2869: 
 2870: sub slot_reservations_link {
 2871:     my ($linktext,$sname,$sdom,$target) = @_;
 2872:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2873:     my $title = 'View slot reservation history';
 2874:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2875:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2876:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2877:         $title .= ' of this student';
 2878:     }
 2879:     if (defined($target) && $target !~ /^\s*$/) {
 2880:         $target = qq{target="$target"};
 2881:     } else {
 2882:         $target = '';
 2883:     }
 2884:     $title = &mt($title);
 2885:     $linktext = &mt($linktext);
 2886:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2887: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2888: 
 2889: }
 2890: 
 2891: # ===================================================== Display a student photo
 2892: 
 2893: 
 2894: sub student_image_tag {
 2895:     my ($domain,$user)=@_;
 2896:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2897:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2898: 	return '<img src="'.$imgsrc.'" align="right" />';
 2899:     } else {
 2900: 	return '';
 2901:     }
 2902: }
 2903: 
 2904: =pod
 2905: 
 2906: =back
 2907: 
 2908: =head1 Access .tab File Data
 2909: 
 2910: =over 4
 2911: 
 2912: =item * &languageids() 
 2913: 
 2914: returns list of all language ids
 2915: 
 2916: =cut
 2917: 
 2918: sub languageids {
 2919:     return sort(keys(%language));
 2920: }
 2921: 
 2922: =pod
 2923: 
 2924: =item * &languagedescription() 
 2925: 
 2926: returns description of a specified language id
 2927: 
 2928: =cut
 2929: 
 2930: sub languagedescription {
 2931:     my $code=shift;
 2932:     return  ($supported_language{$code}?'* ':'').
 2933:             $language{$code}.
 2934: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2935: }
 2936: 
 2937: sub plainlanguagedescription {
 2938:     my $code=shift;
 2939:     return $language{$code};
 2940: }
 2941: 
 2942: sub supportedlanguagecode {
 2943:     my $code=shift;
 2944:     return $supported_language{$code};
 2945: }
 2946: 
 2947: =pod
 2948: 
 2949: =item * &copyrightids() 
 2950: 
 2951: returns list of all copyrights
 2952: 
 2953: =cut
 2954: 
 2955: sub copyrightids {
 2956:     return sort(keys(%cprtag));
 2957: }
 2958: 
 2959: =pod
 2960: 
 2961: =item * &copyrightdescription() 
 2962: 
 2963: returns description of a specified copyright id
 2964: 
 2965: =cut
 2966: 
 2967: sub copyrightdescription {
 2968:     return &mt($cprtag{shift(@_)});
 2969: }
 2970: 
 2971: =pod
 2972: 
 2973: =item * &source_copyrightids() 
 2974: 
 2975: returns list of all source copyrights
 2976: 
 2977: =cut
 2978: 
 2979: sub source_copyrightids {
 2980:     return sort(keys(%scprtag));
 2981: }
 2982: 
 2983: =pod
 2984: 
 2985: =item * &source_copyrightdescription() 
 2986: 
 2987: returns description of a specified source copyright id
 2988: 
 2989: =cut
 2990: 
 2991: sub source_copyrightdescription {
 2992:     return &mt($scprtag{shift(@_)});
 2993: }
 2994: 
 2995: =pod
 2996: 
 2997: =item * &filecategories() 
 2998: 
 2999: returns list of all file categories
 3000: 
 3001: =cut
 3002: 
 3003: sub filecategories {
 3004:     return sort(keys(%category_extensions));
 3005: }
 3006: 
 3007: =pod
 3008: 
 3009: =item * &filecategorytypes() 
 3010: 
 3011: returns list of file types belonging to a given file
 3012: category
 3013: 
 3014: =cut
 3015: 
 3016: sub filecategorytypes {
 3017:     my ($cat) = @_;
 3018:     return @{$category_extensions{lc($cat)}};
 3019: }
 3020: 
 3021: =pod
 3022: 
 3023: =item * &fileembstyle() 
 3024: 
 3025: returns embedding style for a specified file type
 3026: 
 3027: =cut
 3028: 
 3029: sub fileembstyle {
 3030:     return $fe{lc(shift(@_))};
 3031: }
 3032: 
 3033: sub filemimetype {
 3034:     return $fm{lc(shift(@_))};
 3035: }
 3036: 
 3037: 
 3038: sub filecategoryselect {
 3039:     my ($name,$value)=@_;
 3040:     return &select_form($value,$name,
 3041: 			'' => &mt('Any category'),
 3042: 			map { $_,$_ } sort(keys(%category_extensions)));
 3043: }
 3044: 
 3045: =pod
 3046: 
 3047: =item * &filedescription() 
 3048: 
 3049: returns description for a specified file type
 3050: 
 3051: =cut
 3052: 
 3053: sub filedescription {
 3054:     my $file_description = $fd{lc(shift())};
 3055:     $file_description =~ s:([\[\]]):~$1:g;
 3056:     return &mt($file_description);
 3057: }
 3058: 
 3059: =pod
 3060: 
 3061: =item * &filedescriptionex() 
 3062: 
 3063: returns description for a specified file type with
 3064: extra formatting
 3065: 
 3066: =cut
 3067: 
 3068: sub filedescriptionex {
 3069:     my $ex=shift;
 3070:     my $file_description = $fd{lc($ex)};
 3071:     $file_description =~ s:([\[\]]):~$1:g;
 3072:     return '.'.$ex.' '.&mt($file_description);
 3073: }
 3074: 
 3075: # End of .tab access
 3076: =pod
 3077: 
 3078: =back
 3079: 
 3080: =cut
 3081: 
 3082: # ------------------------------------------------------------------ File Types
 3083: sub fileextensions {
 3084:     return sort(keys(%fe));
 3085: }
 3086: 
 3087: # ----------------------------------------------------------- Display Languages
 3088: # returns a hash with all desired display languages
 3089: #
 3090: 
 3091: sub display_languages {
 3092:     my %languages=();
 3093:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3094: 	$languages{$lang}=1;
 3095:     }
 3096:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3097:     if ($env{'form.displaylanguage'}) {
 3098: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3099: 	    $languages{$lang}=1;
 3100:         }
 3101:     }
 3102:     return %languages;
 3103: }
 3104: 
 3105: sub languages {
 3106:     my ($possible_langs) = @_;
 3107:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3108:     if (!ref($possible_langs)) {
 3109: 	if( wantarray ) {
 3110: 	    return @preferred_langs;
 3111: 	} else {
 3112: 	    return $preferred_langs[0];
 3113: 	}
 3114:     }
 3115:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3116:     my @preferred_possibilities;
 3117:     foreach my $preferred_lang (@preferred_langs) {
 3118: 	if (exists($possibilities{$preferred_lang})) {
 3119: 	    push(@preferred_possibilities, $preferred_lang);
 3120: 	}
 3121:     }
 3122:     if( wantarray ) {
 3123: 	return @preferred_possibilities;
 3124:     }
 3125:     return $preferred_possibilities[0];
 3126: }
 3127: 
 3128: sub user_lang {
 3129:     my ($touname,$toudom,$fromcid) = @_;
 3130:     my @userlangs;
 3131:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3132:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3133:                     $env{'course.'.$fromcid.'.languages'}));
 3134:     } else {
 3135:         my %langhash = &getlangs($touname,$toudom);
 3136:         if ($langhash{'languages'} ne '') {
 3137:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3138:         } else {
 3139:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3140:             if ($domdefs{'lang_def'} ne '') {
 3141:                 @userlangs = ($domdefs{'lang_def'});
 3142:             }
 3143:         }
 3144:     }
 3145:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3146:     my $user_lh = Apache::localize->get_handle(@languages);
 3147:     return $user_lh;
 3148: }
 3149: 
 3150: 
 3151: ###############################################################
 3152: ##               Student Answer Attempts                     ##
 3153: ###############################################################
 3154: 
 3155: =pod
 3156: 
 3157: =head1 Alternate Problem Views
 3158: 
 3159: =over 4
 3160: 
 3161: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3162:     $getattempt, $regexp, $gradesub)
 3163: 
 3164: Return string with previous attempt on problem. Arguments:
 3165: 
 3166: =over 4
 3167: 
 3168: =item * $symb: Problem, including path
 3169: 
 3170: =item * $username: username of the desired student
 3171: 
 3172: =item * $domain: domain of the desired student
 3173: 
 3174: =item * $course: Course ID
 3175: 
 3176: =item * $getattempt: Leave blank for all attempts, otherwise put
 3177:     something
 3178: 
 3179: =item * $regexp: if string matches this regexp, the string will be
 3180:     sent to $gradesub
 3181: 
 3182: =item * $gradesub: routine that processes the string if it matches $regexp
 3183: 
 3184: =back
 3185: 
 3186: The output string is a table containing all desired attempts, if any.
 3187: 
 3188: =cut
 3189: 
 3190: sub get_previous_attempt {
 3191:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3192:   my $prevattempts='';
 3193:   no strict 'refs';
 3194:   if ($symb) {
 3195:     my (%returnhash)=
 3196:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3197:     if ($returnhash{'version'}) {
 3198:       my %lasthash=();
 3199:       my $version;
 3200:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3201:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3202: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3203:         }
 3204:       }
 3205:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3206:       $prevattempts.='<th>'.&mt('History').'</th>';
 3207:       foreach my $key (sort(keys(%lasthash))) {
 3208: 	my ($ign,@parts) = split(/\./,$key);
 3209: 	if ($#parts > 0) {
 3210: 	  my $data=$parts[-1];
 3211: 	  pop(@parts);
 3212: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3213: 	} else {
 3214: 	  if ($#parts == 0) {
 3215: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3216: 	  } else {
 3217: 	    $prevattempts.='<th>'.$ign.'</th>';
 3218: 	  }
 3219: 	}
 3220:       }
 3221:       $prevattempts.=&end_data_table_header_row();
 3222:       if ($getattempt eq '') {
 3223: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3224: 	  $prevattempts.=&start_data_table_row().
 3225: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3226: 	    foreach my $key (sort(keys(%lasthash))) {
 3227: 		my $value = &format_previous_attempt_value($key,
 3228: 							   $returnhash{$version.':'.$key});
 3229: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3230: 	    }
 3231: 	  $prevattempts.=&end_data_table_row();
 3232: 	 }
 3233:       }
 3234:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3235:       foreach my $key (sort(keys(%lasthash))) {
 3236: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3237: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3238: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3239:       }
 3240:       $prevattempts.= &end_data_table_row().&end_data_table();
 3241:     } else {
 3242:       $prevattempts=
 3243: 	  &start_data_table().&start_data_table_row().
 3244: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3245: 	  &end_data_table_row().&end_data_table();
 3246:     }
 3247:   } else {
 3248:     $prevattempts=
 3249: 	  &start_data_table().&start_data_table_row().
 3250: 	  '<td>'.&mt('No data.').'</td>'.
 3251: 	  &end_data_table_row().&end_data_table();
 3252:   }
 3253: }
 3254: 
 3255: sub format_previous_attempt_value {
 3256:     my ($key,$value) = @_;
 3257:     if ($key =~ /timestamp/) {
 3258: 	$value = &Apache::lonlocal::locallocaltime($value);
 3259:     } elsif (ref($value) eq 'ARRAY') {
 3260: 	$value = '('.join(', ', @{ $value }).')';
 3261:     } else {
 3262: 	$value = &unescape($value);
 3263:     }
 3264:     return $value;
 3265: }
 3266: 
 3267: 
 3268: sub relative_to_absolute {
 3269:     my ($url,$output)=@_;
 3270:     my $parser=HTML::TokeParser->new(\$output);
 3271:     my $token;
 3272:     my $thisdir=$url;
 3273:     my @rlinks=();
 3274:     while ($token=$parser->get_token) {
 3275: 	if ($token->[0] eq 'S') {
 3276: 	    if ($token->[1] eq 'a') {
 3277: 		if ($token->[2]->{'href'}) {
 3278: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3279: 		}
 3280: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3281: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3282: 	    } elsif ($token->[1] eq 'base') {
 3283: 		$thisdir=$token->[2]->{'href'};
 3284: 	    }
 3285: 	}
 3286:     }
 3287:     $thisdir=~s-/[^/]*$--;
 3288:     foreach my $link (@rlinks) {
 3289: 	unless (($link=~/^https?\:\/\//i) ||
 3290: 		($link=~/^\//) ||
 3291: 		($link=~/^javascript:/i) ||
 3292: 		($link=~/^mailto:/i) ||
 3293: 		($link=~/^\#/)) {
 3294: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3295: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3296: 	}
 3297:     }
 3298: # -------------------------------------------------- Deal with Applet codebases
 3299:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3300:     return $output;
 3301: }
 3302: 
 3303: =pod
 3304: 
 3305: =item * &get_student_view()
 3306: 
 3307: show a snapshot of what student was looking at
 3308: 
 3309: =cut
 3310: 
 3311: sub get_student_view {
 3312:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3313:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3314:   my (%form);
 3315:   my @elements=('symb','courseid','domain','username');
 3316:   foreach my $element (@elements) {
 3317:       $form{'grade_'.$element}=eval '$'.$element #'
 3318:   }
 3319:   if (defined($moreenv)) {
 3320:       %form=(%form,%{$moreenv});
 3321:   }
 3322:   if (defined($target)) { $form{'grade_target'} = $target; }
 3323:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3324:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3325:   $userview=~s/\<body[^\>]*\>//gi;
 3326:   $userview=~s/\<\/body\>//gi;
 3327:   $userview=~s/\<html\>//gi;
 3328:   $userview=~s/\<\/html\>//gi;
 3329:   $userview=~s/\<head\>//gi;
 3330:   $userview=~s/\<\/head\>//gi;
 3331:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3332:   $userview=&relative_to_absolute($feedurl,$userview);
 3333:   if (wantarray) {
 3334:      return ($userview,$response);
 3335:   } else {
 3336:      return $userview;
 3337:   }
 3338: }
 3339: 
 3340: sub get_student_view_with_retries {
 3341:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3342: 
 3343:     my $ok = 0;                 # True if we got a good response.
 3344:     my $content;
 3345:     my $response;
 3346: 
 3347:     # Try to get the student_view done. within the retries count:
 3348:     
 3349:     do {
 3350:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3351:          $ok      = $response->is_success;
 3352:          if (!$ok) {
 3353:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3354:          }
 3355:          $retries--;
 3356:     } while (!$ok && ($retries > 0));
 3357:     
 3358:     if (!$ok) {
 3359:        $content = '';          # On error return an empty content.
 3360:     }
 3361:     if (wantarray) {
 3362:        return ($content, $response);
 3363:     } else {
 3364:        return $content;
 3365:     }
 3366: }
 3367: 
 3368: =pod
 3369: 
 3370: =item * &get_student_answers() 
 3371: 
 3372: show a snapshot of how student was answering problem
 3373: 
 3374: =cut
 3375: 
 3376: sub get_student_answers {
 3377:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3378:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3379:   my (%moreenv);
 3380:   my @elements=('symb','courseid','domain','username');
 3381:   foreach my $element (@elements) {
 3382:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3383:   }
 3384:   $moreenv{'grade_target'}='answer';
 3385:   %moreenv=(%form,%moreenv);
 3386:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3387:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3388:   return $userview;
 3389: }
 3390: 
 3391: =pod
 3392: 
 3393: =item * &submlink()
 3394: 
 3395: Inputs: $text $uname $udom $symb $target
 3396: 
 3397: Returns: A link to grades.pm such as to see the SUBM view of a student
 3398: 
 3399: =cut
 3400: 
 3401: ###############################################
 3402: sub submlink {
 3403:     my ($text,$uname,$udom,$symb,$target)=@_;
 3404:     if (!($uname && $udom)) {
 3405: 	(my $cursymb, my $courseid,$udom,$uname)=
 3406: 	    &Apache::lonnet::whichuser($symb);
 3407: 	if (!$symb) { $symb=$cursymb; }
 3408:     }
 3409:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3410:     $symb=&escape($symb);
 3411:     if ($target) { $target="target=\"$target\""; }
 3412:     return '<a href="/adm/grades?&command=submission&'.
 3413: 	'symb='.$symb.'&student='.$uname.
 3414: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3415: }
 3416: ##############################################
 3417: 
 3418: =pod
 3419: 
 3420: =item * &pgrdlink()
 3421: 
 3422: Inputs: $text $uname $udom $symb $target
 3423: 
 3424: Returns: A link to grades.pm such as to see the PGRD view of a student
 3425: 
 3426: =cut
 3427: 
 3428: ###############################################
 3429: sub pgrdlink {
 3430:     my $link=&submlink(@_);
 3431:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3432:     return $link;
 3433: }
 3434: ##############################################
 3435: 
 3436: =pod
 3437: 
 3438: =item * &pprmlink()
 3439: 
 3440: Inputs: $text $uname $udom $symb $target
 3441: 
 3442: Returns: A link to parmset.pm such as to see the PPRM view of a
 3443: student and a specific resource
 3444: 
 3445: =cut
 3446: 
 3447: ###############################################
 3448: sub pprmlink {
 3449:     my ($text,$uname,$udom,$symb,$target)=@_;
 3450:     if (!($uname && $udom)) {
 3451: 	(my $cursymb, my $courseid,$udom,$uname)=
 3452: 	    &Apache::lonnet::whichuser($symb);
 3453: 	if (!$symb) { $symb=$cursymb; }
 3454:     }
 3455:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3456:     $symb=&escape($symb);
 3457:     if ($target) { $target="target=\"$target\""; }
 3458:     return '<a href="/adm/parmset?command=set&amp;'.
 3459: 	'symb='.$symb.'&amp;uname='.$uname.
 3460: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3461: }
 3462: ##############################################
 3463: 
 3464: =pod
 3465: 
 3466: =back
 3467: 
 3468: =cut
 3469: 
 3470: ###############################################
 3471: 
 3472: 
 3473: sub timehash {
 3474:     my ($thistime) = @_;
 3475:     my $timezone = &Apache::lonlocal::gettimezone();
 3476:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3477:                      ->set_time_zone($timezone);
 3478:     my $wday = $dt->day_of_week();
 3479:     if ($wday == 7) { $wday = 0; }
 3480:     return ( 'second' => $dt->second(),
 3481:              'minute' => $dt->minute(),
 3482:              'hour'   => $dt->hour(),
 3483:              'day'     => $dt->day_of_month(),
 3484:              'month'   => $dt->month(),
 3485:              'year'    => $dt->year(),
 3486:              'weekday' => $wday,
 3487:              'dayyear' => $dt->day_of_year(),
 3488:              'dlsav'   => $dt->is_dst() );
 3489: }
 3490: 
 3491: sub utc_string {
 3492:     my ($date)=@_;
 3493:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3494: }
 3495: 
 3496: sub maketime {
 3497:     my %th=@_;
 3498:     my ($epoch_time,$timezone,$dt);
 3499:     $timezone = &Apache::lonlocal::gettimezone();
 3500:     eval {
 3501:         $dt = DateTime->new( year   => $th{'year'},
 3502:                              month  => $th{'month'},
 3503:                              day    => $th{'day'},
 3504:                              hour   => $th{'hour'},
 3505:                              minute => $th{'minute'},
 3506:                              second => $th{'second'},
 3507:                              time_zone => $timezone,
 3508:                          );
 3509:     };
 3510:     if (!$@) {
 3511:         $epoch_time = $dt->epoch;
 3512:         if ($epoch_time) {
 3513:             return $epoch_time;
 3514:         }
 3515:     }
 3516:     return POSIX::mktime(
 3517:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3518:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3519: }
 3520: 
 3521: #########################################
 3522: 
 3523: sub findallcourses {
 3524:     my ($roles,$uname,$udom) = @_;
 3525:     my %roles;
 3526:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3527:     my %courses;
 3528:     my $now=time;
 3529:     if (!defined($uname)) {
 3530:         $uname = $env{'user.name'};
 3531:     }
 3532:     if (!defined($udom)) {
 3533:         $udom = $env{'user.domain'};
 3534:     }
 3535:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3536:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3537:         if (!%roles) {
 3538:             %roles = (
 3539:                        cc => 1,
 3540:                        in => 1,
 3541:                        ep => 1,
 3542:                        ta => 1,
 3543:                        cr => 1,
 3544:                        st => 1,
 3545:              );
 3546:         }
 3547:         foreach my $entry (keys(%roleshash)) {
 3548:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3549:             if ($trole =~ /^cr/) { 
 3550:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3551:             } else {
 3552:                 next if (!exists($roles{$trole}));
 3553:             }
 3554:             if ($tend) {
 3555:                 next if ($tend < $now);
 3556:             }
 3557:             if ($tstart) {
 3558:                 next if ($tstart > $now);
 3559:             }
 3560:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3561:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3562:             if ($secpart eq '') {
 3563:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3564:                 $sec = 'none';
 3565:                 $realsec = '';
 3566:             } else {
 3567:                 $cnum = $cnumpart;
 3568:                 ($sec,$role) = split(/_/,$secpart);
 3569:                 $realsec = $sec;
 3570:             }
 3571:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3572:         }
 3573:     } else {
 3574:         foreach my $key (keys(%env)) {
 3575: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3576:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3577: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3578: 	        next if ($role eq 'ca' || $role eq 'aa');
 3579: 	        next if (%roles && !exists($roles{$role}));
 3580: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3581:                 my $active=1;
 3582:                 if ($starttime) {
 3583: 		    if ($now<$starttime) { $active=0; }
 3584:                 }
 3585:                 if ($endtime) {
 3586:                     if ($now>$endtime) { $active=0; }
 3587:                 }
 3588:                 if ($active) {
 3589:                     if ($sec eq '') {
 3590:                         $sec = 'none';
 3591:                     }
 3592:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3593:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3594:                 }
 3595:             }
 3596:         }
 3597:     }
 3598:     return %courses;
 3599: }
 3600: 
 3601: ###############################################
 3602: 
 3603: sub blockcheck {
 3604:     my ($setters,$activity,$uname,$udom) = @_;
 3605: 
 3606:     if (!defined($udom)) {
 3607:         $udom = $env{'user.domain'};
 3608:     }
 3609:     if (!defined($uname)) {
 3610:         $uname = $env{'user.name'};
 3611:     }
 3612: 
 3613:     # If uname and udom are for a course, check for blocks in the course.
 3614: 
 3615:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3616:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3617:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3618:         return ($startblock,$endblock);
 3619:     }
 3620: 
 3621:     my $startblock = 0;
 3622:     my $endblock = 0;
 3623:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3624: 
 3625:     # If uname is for a user, and activity is course-specific, i.e.,
 3626:     # boards, chat or groups, check for blocking in current course only.
 3627: 
 3628:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3629:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3630:         foreach my $key (keys(%live_courses)) {
 3631:             if ($key ne $env{'request.course.id'}) {
 3632:                 delete($live_courses{$key});
 3633:             }
 3634:         }
 3635:     }
 3636: 
 3637:     my $otheruser = 0;
 3638:     my %own_courses;
 3639:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3640:         # Resource belongs to user other than current user.
 3641:         $otheruser = 1;
 3642:         # Gather courses for current user
 3643:         %own_courses = 
 3644:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3645:     }
 3646: 
 3647:     # Gather active course roles - course coordinator, instructor, 
 3648:     # exam proctor, ta, student, or custom role.
 3649: 
 3650:     foreach my $course (keys(%live_courses)) {
 3651:         my ($cdom,$cnum);
 3652:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3653:             $cdom = $env{'course.'.$course.'.domain'};
 3654:             $cnum = $env{'course.'.$course.'.num'};
 3655:         } else {
 3656:             ($cdom,$cnum) = split(/_/,$course); 
 3657:         }
 3658:         my $no_ownblock = 0;
 3659:         my $no_userblock = 0;
 3660:         if ($otheruser && $activity ne 'com') {
 3661:             # Check if current user has 'evb' priv for this
 3662:             if (defined($own_courses{$course})) {
 3663:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3664:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3665:                     if ($sec ne 'none') {
 3666:                         $checkrole .= '/'.$sec;
 3667:                     }
 3668:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3669:                         $no_ownblock = 1;
 3670:                         last;
 3671:                     }
 3672:                 }
 3673:             }
 3674:             # if they have 'evb' priv and are currently not playing student
 3675:             next if (($no_ownblock) &&
 3676:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3677:         }
 3678:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3679:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3680:             if ($sec ne 'none') {
 3681:                 $checkrole .= '/'.$sec;
 3682:             }
 3683:             if ($otheruser) {
 3684:                 # Resource belongs to user other than current user.
 3685:                 # Assemble privs for that user, and check for 'evb' priv.
 3686:                 my ($trole,$tdom,$tnum,$tsec);
 3687:                 my $entry = $live_courses{$course}{$sec};
 3688:                 if ($entry =~ /^cr/) {
 3689:                     ($trole,$tdom,$tnum,$tsec) = 
 3690:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3691:                 } else {
 3692:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3693:                 }
 3694:                 my ($spec,$area,$trest,%allroles,%userroles);
 3695:                 $area = '/'.$tdom.'/'.$tnum;
 3696:                 $trest = $tnum;
 3697:                 if ($tsec ne '') {
 3698:                     $area .= '/'.$tsec;
 3699:                     $trest .= '/'.$tsec;
 3700:                 }
 3701:                 $spec = $trole.'.'.$area;
 3702:                 if ($trole =~ /^cr/) {
 3703:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3704:                                                       $tdom,$spec,$trest,$area);
 3705:                 } else {
 3706:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3707:                                                        $tdom,$spec,$trest,$area);
 3708:                 }
 3709:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3710:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3711:                     if ($1) {
 3712:                         $no_userblock = 1;
 3713:                         last;
 3714:                     }
 3715:                 }
 3716:             } else {
 3717:                 # Resource belongs to current user
 3718:                 # Check for 'evb' priv via lonnet::allowed().
 3719:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3720:                     $no_ownblock = 1;
 3721:                     last;
 3722:                 }
 3723:             }
 3724:         }
 3725:         # if they have the evb priv and are currently not playing student
 3726:         next if (($no_ownblock) &&
 3727:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3728:         next if ($no_userblock);
 3729: 
 3730:         # Retrieve blocking times and identity of blocker for course
 3731:         # of specified user, unless user has 'evb' privilege.
 3732:         
 3733:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3734:         if (($start != 0) && 
 3735:             (($startblock == 0) || ($startblock > $start))) {
 3736:             $startblock = $start;
 3737:         }
 3738:         if (($end != 0)  &&
 3739:             (($endblock == 0) || ($endblock < $end))) {
 3740:             $endblock = $end;
 3741:         }
 3742:     }
 3743:     return ($startblock,$endblock);
 3744: }
 3745: 
 3746: sub get_blocks {
 3747:     my ($setters,$activity,$cdom,$cnum) = @_;
 3748:     my $startblock = 0;
 3749:     my $endblock = 0;
 3750:     my $course = $cdom.'_'.$cnum;
 3751:     $setters->{$course} = {};
 3752:     $setters->{$course}{'staff'} = [];
 3753:     $setters->{$course}{'times'} = [];
 3754:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3755:     foreach my $record (keys(%records)) {
 3756:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3757:         if ($start <= time && $end >= time) {
 3758:             my ($staff_name,$staff_dom,$title,$blocks) =
 3759:                 &parse_block_record($records{$record});
 3760:             if ($blocks->{$activity} eq 'on') {
 3761:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3762:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3763:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3764:                     $startblock = $start;
 3765:                 }
 3766:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3767:                     $endblock = $end;
 3768:                 }
 3769:             }
 3770:         }
 3771:     }
 3772:     return ($startblock,$endblock);
 3773: }
 3774: 
 3775: sub parse_block_record {
 3776:     my ($record) = @_;
 3777:     my ($setuname,$setudom,$title,$blocks);
 3778:     if (ref($record) eq 'HASH') {
 3779:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3780:         $title = &unescape($record->{'event'});
 3781:         $blocks = $record->{'blocks'};
 3782:     } else {
 3783:         my @data = split(/:/,$record,3);
 3784:         if (scalar(@data) eq 2) {
 3785:             $title = $data[1];
 3786:             ($setuname,$setudom) = split(/@/,$data[0]);
 3787:         } else {
 3788:             ($setuname,$setudom,$title) = @data;
 3789:         }
 3790:         $blocks = { 'com' => 'on' };
 3791:     }
 3792:     return ($setuname,$setudom,$title,$blocks);
 3793: }
 3794: 
 3795: sub build_block_table {
 3796:     my ($startblock,$endblock,$setters) = @_;
 3797:     my %lt = &Apache::lonlocal::texthash(
 3798:         'cacb' => 'Currently active communication blocks',
 3799:         'cour' => 'Course',
 3800:         'dura' => 'Duration',
 3801:         'blse' => 'Block set by'
 3802:     );
 3803:     my $output;
 3804:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3805:     $output .= &start_data_table();
 3806:     $output .= '
 3807: <tr>
 3808:  <th>'.$lt{'cour'}.'</th>
 3809:  <th>'.$lt{'dura'}.'</th>
 3810:  <th>'.$lt{'blse'}.'</th>
 3811: </tr>
 3812: ';
 3813:     foreach my $course (keys(%{$setters})) {
 3814:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3815:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3816:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3817:             my $fullname = &plainname($uname,$udom);
 3818:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3819:                 && $env{'user.name'} ne 'public' 
 3820:                 && $env{'user.domain'} ne 'public') {
 3821:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3822:             }
 3823:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3824:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3825:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3826:             $output .= &Apache::loncommon::start_data_table_row().
 3827:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3828:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3829:                        '<td>'.$fullname.'</td>'.
 3830:                         &Apache::loncommon::end_data_table_row();
 3831:         }
 3832:     }
 3833:     $output .= &end_data_table();
 3834: }
 3835: 
 3836: sub blocking_status {
 3837:     my ($activity,$uname,$udom) = @_;
 3838:     my %setters;
 3839:     my ($blocked,$output,$ownitem,$is_course);
 3840:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3841:     if ($startblock && $endblock) {
 3842:         $blocked = 1;
 3843:         if (wantarray) {
 3844:             my $category;
 3845:             if ($activity eq 'boards') {
 3846:                 $category = 'Discussion posts in this course';
 3847:             } elsif ($activity eq 'blogs') {
 3848:                 $category = 'Blogs';
 3849:             } elsif ($activity eq 'port') {
 3850:                 if (defined($uname) && defined($udom)) {
 3851:                     if ($uname eq $env{'user.name'} &&
 3852:                         $udom eq $env{'user.domain'}) {
 3853:                         $ownitem = 1;
 3854:                     }
 3855:                 }
 3856:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3857:                 if ($ownitem) { 
 3858:                     $category = 'Your portfolio files';  
 3859:                 } elsif ($is_course) {
 3860:                     my $coursedesc;
 3861:                     foreach my $course (keys(%setters)) {
 3862:                         my %courseinfo =
 3863:                              &Apache::lonnet::coursedescription($course);
 3864:                         $coursedesc = $courseinfo{'description'};
 3865:                     }
 3866:                     $category = "Group portfolio in the course '$coursedesc'";
 3867:                 } else {
 3868:                     $category = 'Portfolio files belonging to ';
 3869:                     if ($env{'user.name'} eq 'public' && 
 3870:                         $env{'user.domain'} eq 'public') {
 3871:                         $category .= &plainname($uname,$udom);
 3872:                     } else {
 3873:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3874:                     }
 3875:                 }
 3876:             } elsif ($activity eq 'groups') {
 3877:                 $category = 'Groups in this course';
 3878:             }
 3879:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3880:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3881:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3882:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3883:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3884:             }
 3885:         }
 3886:     }
 3887:     if (wantarray) {
 3888:         return ($blocked,$output);
 3889:     } else {
 3890:         return $blocked;
 3891:     }
 3892: }
 3893: 
 3894: ###############################################
 3895: 
 3896: sub check_ip_acc {
 3897:     my ($acc)=@_;
 3898:     &Apache::lonxml::debug("acc is $acc");
 3899:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3900:         return 1;
 3901:     }
 3902:     my $allowed=0;
 3903:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3904: 
 3905:     my $name;
 3906:     foreach my $pattern (split(',',$acc)) {
 3907:         $pattern =~ s/^\s*//;
 3908:         $pattern =~ s/\s*$//;
 3909:         if ($pattern =~ /\*$/) {
 3910:             #35.8.*
 3911:             $pattern=~s/\*//;
 3912:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3913:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3914:             #35.8.3.[34-56]
 3915:             my $low=$2;
 3916:             my $high=$3;
 3917:             $pattern=$1;
 3918:             if ($ip =~ /^\Q$pattern\E/) {
 3919:                 my $last=(split(/\./,$ip))[3];
 3920:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3921:             }
 3922:         } elsif ($pattern =~ /^\*/) {
 3923:             #*.msu.edu
 3924:             $pattern=~s/\*//;
 3925:             if (!defined($name)) {
 3926:                 use Socket;
 3927:                 my $netaddr=inet_aton($ip);
 3928:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3929:             }
 3930:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3931:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3932:             #127.0.0.1
 3933:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3934:         } else {
 3935:             #some.name.com
 3936:             if (!defined($name)) {
 3937:                 use Socket;
 3938:                 my $netaddr=inet_aton($ip);
 3939:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3940:             }
 3941:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3942:         }
 3943:         if ($allowed) { last; }
 3944:     }
 3945:     return $allowed;
 3946: }
 3947: 
 3948: ###############################################
 3949: 
 3950: =pod
 3951: 
 3952: =head1 Domain Template Functions
 3953: 
 3954: =over 4
 3955: 
 3956: =item * &determinedomain()
 3957: 
 3958: Inputs: $domain (usually will be undef)
 3959: 
 3960: Returns: Determines which domain should be used for designs
 3961: 
 3962: =cut
 3963: 
 3964: ###############################################
 3965: sub determinedomain {
 3966:     my $domain=shift;
 3967:     if (! $domain) {
 3968:         # Determine domain if we have not been given one
 3969:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3970:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3971:         if ($env{'request.role.domain'}) { 
 3972:             $domain=$env{'request.role.domain'}; 
 3973:         }
 3974:     }
 3975:     return $domain;
 3976: }
 3977: ###############################################
 3978: 
 3979: sub devalidate_domconfig_cache {
 3980:     my ($udom)=@_;
 3981:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3982: }
 3983: 
 3984: # ---------------------- Get domain configuration for a domain
 3985: sub get_domainconf {
 3986:     my ($udom) = @_;
 3987:     my $cachetime=1800;
 3988:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3989:     if (defined($cached)) { return %{$result}; }
 3990: 
 3991:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3992: 					     ['login','rolecolors'],$udom);
 3993:     my (%designhash,%legacy);
 3994:     if (keys(%domconfig) > 0) {
 3995:         if (ref($domconfig{'login'}) eq 'HASH') {
 3996:             if (keys(%{$domconfig{'login'}})) {
 3997:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 3998:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 3999:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4000:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4001:                                 $domconfig{'login'}{$key}{$img};
 4002:                         }
 4003:                     } else {
 4004:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4005:                     }
 4006:                 }
 4007:             } else {
 4008:                 $legacy{'login'} = 1;
 4009:             }
 4010:         } else {
 4011:             $legacy{'login'} = 1;
 4012:         }
 4013:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4014:             if (keys(%{$domconfig{'rolecolors'}})) {
 4015:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4016:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4017:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4018:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4019:                         }
 4020:                     }
 4021:                 }
 4022:             } else {
 4023:                 $legacy{'rolecolors'} = 1;
 4024:             }
 4025:         } else {
 4026:             $legacy{'rolecolors'} = 1;
 4027:         }
 4028:         if (keys(%legacy) > 0) {
 4029:             my %legacyhash = &get_legacy_domconf($udom);
 4030:             foreach my $item (keys(%legacyhash)) {
 4031:                 if ($item =~ /^\Q$udom\E\.login/) {
 4032:                     if ($legacy{'login'}) { 
 4033:                         $designhash{$item} = $legacyhash{$item};
 4034:                     }
 4035:                 } else {
 4036:                     if ($legacy{'rolecolors'}) {
 4037:                         $designhash{$item} = $legacyhash{$item};
 4038:                     }
 4039:                 }
 4040:             }
 4041:         }
 4042:     } else {
 4043:         %designhash = &get_legacy_domconf($udom); 
 4044:     }
 4045:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4046: 				  $cachetime);
 4047:     return %designhash;
 4048: }
 4049: 
 4050: sub get_legacy_domconf {
 4051:     my ($udom) = @_;
 4052:     my %legacyhash;
 4053:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4054:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4055:     if (-e $designfile) {
 4056:         if ( open (my $fh,"<$designfile") ) {
 4057:             while (my $line = <$fh>) {
 4058:                 next if ($line =~ /^\#/);
 4059:                 chomp($line);
 4060:                 my ($key,$val)=(split(/\=/,$line));
 4061:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4062:             }
 4063:             close($fh);
 4064:         }
 4065:     }
 4066:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4067:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4068:     }
 4069:     return %legacyhash;
 4070: }
 4071: 
 4072: =pod
 4073: 
 4074: =item * &domainlogo()
 4075: 
 4076: Inputs: $domain (usually will be undef)
 4077: 
 4078: Returns: A link to a domain logo, if the domain logo exists.
 4079: If the domain logo does not exist, a description of the domain.
 4080: 
 4081: =cut
 4082: 
 4083: ###############################################
 4084: sub domainlogo {
 4085:     my $domain = &determinedomain(shift);
 4086:     my %designhash = &get_domainconf($domain);    
 4087:     # See if there is a logo
 4088:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4089:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4090:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4091: 	    if ($imgsrc =~ m{^/res/}) {
 4092: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4093: 		&Apache::lonnet::repcopy($local_name);
 4094: 	    }
 4095: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4096:         } 
 4097:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4098:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4099:         return &Apache::lonnet::domain($domain,'description');
 4100:     } else {
 4101:         return '';
 4102:     }
 4103: }
 4104: ##############################################
 4105: 
 4106: =pod
 4107: 
 4108: =item * &designparm()
 4109: 
 4110: Inputs: $which parameter; $domain (usually will be undef)
 4111: 
 4112: Returns: value of designparamter $which
 4113: 
 4114: =cut
 4115: 
 4116: 
 4117: ##############################################
 4118: sub designparm {
 4119:     my ($which,$domain)=@_;
 4120:     if ($env{'browser.blackwhite'} eq 'on') {
 4121: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4122: 	    return '#000000';
 4123: 	}
 4124: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4125: 	    return '#FFFFFF';
 4126: 	}
 4127: 	if ($which=~/\.tabbg$/) {
 4128: 	    return '#CCCCCC';
 4129: 	}
 4130:     }
 4131:     if (exists($env{'environment.color.'.$which})) {
 4132: 	return $env{'environment.color.'.$which};
 4133:     }
 4134:     $domain=&determinedomain($domain);
 4135:     my %domdesign = &get_domainconf($domain);
 4136:     my $output;
 4137:     if ($domdesign{$domain.'.'.$which} ne '') {
 4138: 	$output = $domdesign{$domain.'.'.$which};
 4139:     } else {
 4140:         $output = $defaultdesign{$which};
 4141:     }
 4142:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4143:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4144:         if ($output =~ m{^/(adm|res)/}) {
 4145: 	    if ($output =~ m{^/res/}) {
 4146: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4147: 		&Apache::lonnet::repcopy($local_name);
 4148: 	    }
 4149:             $output = &lonhttpdurl($output);
 4150:         }
 4151:     }
 4152:     return $output;
 4153: }
 4154: 
 4155: ###############################################
 4156: ###############################################
 4157: 
 4158: =pod
 4159: 
 4160: =back
 4161: 
 4162: =head1 HTML Helpers
 4163: 
 4164: =over 4
 4165: 
 4166: =item * &bodytag()
 4167: 
 4168: Returns a uniform header for LON-CAPA web pages.
 4169: 
 4170: Inputs: 
 4171: 
 4172: =over 4
 4173: 
 4174: =item * $title, A title to be displayed on the page.
 4175: 
 4176: =item * $function, the current role (can be undef).
 4177: 
 4178: =item * $addentries, extra parameters for the <body> tag.
 4179: 
 4180: =item * $bodyonly, if defined, only return the <body> tag.
 4181: 
 4182: =item * $domain, if defined, force a given domain.
 4183: 
 4184: =item * $forcereg, if page should register as content page (relevant for 
 4185:             text interface only)
 4186: 
 4187: =item * $customtitle, alternate text to use instead of $title
 4188:                       in the title box that appears, this text
 4189:                       is not auto translated like the $title is
 4190: 
 4191: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4192:                    navigational links
 4193: 
 4194: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4195: 
 4196: =item * $notitle, if true keep the nav controls, but remove the title bar
 4197: 
 4198: =item * $no_inline_link, if true and in remote mode, don't show the 
 4199:          'Switch To Inline Menu' link
 4200: 
 4201: =item * $args, optional argument valid values are
 4202:             no_auto_mt_title -> prevents &mt()ing the title arg
 4203:             inherit_jsmath -> when creating popup window in a page,
 4204:                               should it have jsmath forced on by the
 4205:                               current page
 4206: 
 4207: =back
 4208: 
 4209: Returns: A uniform header for LON-CAPA web pages.  
 4210: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4211: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4212: other decorations will be returned.
 4213: 
 4214: =cut
 4215: 
 4216: sub bodytag {
 4217:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4218: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4219: 
 4220:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4221: 
 4222:     $function = &get_users_function() if (!$function);
 4223:     my $img =    &designparm($function.'.img',$domain);
 4224:     my $font =   &designparm($function.'.font',$domain);
 4225:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4226: 
 4227:     my %design = ( 'style'   => 'margin-top: 0px',
 4228: 		   'bgcolor' => $pgbg,
 4229: 		   'text'    => $font,
 4230:                    'alink'   => &designparm($function.'.alink',$domain),
 4231: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4232: 		   'link'    => &designparm($function.'.link',$domain),);
 4233:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4234: 
 4235:  # role and realm
 4236:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4237:     if ($role  eq 'ca') {
 4238:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4239:         $realm = &plainname($rname,$rdom);
 4240:     } 
 4241: # realm
 4242:     if ($env{'request.course.id'}) {
 4243:         if ($env{'request.role'} !~ /^cr/) {
 4244:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4245:         }
 4246: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4247:     } else {
 4248:         $role = &Apache::lonnet::plaintext($role);
 4249:     }
 4250: 
 4251:     if (!$realm) { $realm='&nbsp;'; }
 4252: # Set messages
 4253:     my $messages=&domainlogo($domain);
 4254: 
 4255:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4256: 
 4257: # construct main body tag
 4258:     my $bodytag = "<body $extra_body_attr>".
 4259: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4260: 
 4261:     if ($bodyonly) {
 4262:         return $bodytag;
 4263:     } 
 4264: 
 4265:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4266:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4267: 	undef($role);
 4268:     } else {
 4269: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4270:     }
 4271:     
 4272:     my $roleinfo=(<<ENDROLE);
 4273: <td class="LC_title_bar_who">
 4274: <div class="LC_title_bar_name">
 4275:     $name
 4276:     &nbsp;
 4277: </div>
 4278: <div class="LC_title_bar_role">
 4279: $role&nbsp;
 4280: </div>
 4281: <div class="LC_title_bar_realm">
 4282: $realm&nbsp;
 4283: </div>
 4284: </td>
 4285: ENDROLE
 4286: 
 4287:     my $titleinfo = '<h1>'.$title.'</h1>';
 4288:     if ($customtitle) {
 4289:         $titleinfo = $customtitle;
 4290:     }
 4291:     #
 4292:     # Extra info if you are the DC
 4293:     my $dc_info = '';
 4294:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4295:                         $env{'course.'.$env{'request.course.id'}.
 4296:                                  '.domain'}.'/'})) {
 4297:         my $cid = $env{'request.course.id'};
 4298:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4299:         $dc_info =~ s/\s+$//;
 4300:         $dc_info = '('.$dc_info.')';
 4301:     }
 4302: 
 4303:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4304:         # No Remote
 4305: 	if ($env{'request.state'} eq 'construct') {
 4306: 	    $forcereg=1;
 4307: 	}
 4308: 
 4309: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4310: 	    # this is for resources; directories have customtitle, and crumbs
 4311:             # and select recent are created in lonpubdir.pm  
 4312: 	    my ($uname,$thisdisfn)=
 4313: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4314: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4315: 	    $formaction=~s/\/+/\//g;
 4316: 
 4317: 	    my $parentpath = '';
 4318: 	    my $lastitem = '';
 4319: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4320: 		$parentpath = $1;
 4321: 		$lastitem = $2;
 4322: 	    } else {
 4323: 		$lastitem = $thisdisfn;
 4324: 	    }
 4325: 	    $titleinfo = 
 4326: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4327: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4328: 		.'<form name="dirs" method="post" action="'.$formaction
 4329: 		.'" target="_top"><tt><b>'
 4330: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4331: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4332: 		.'</form>'
 4333: 		.&Apache::lonmenu::constspaceform();
 4334:         }
 4335: 
 4336:         my $titletable;
 4337: 	if (!$notitle) {
 4338: 	    $titletable =
 4339: 		'<table id="LC_title_bar">'.
 4340:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4341: 			 '</tr></table>';
 4342: 	}
 4343: 	if ($notopbar) {
 4344: 	    $bodytag .= $titletable;
 4345: 	} else {
 4346: 	    if ($env{'request.state'} eq 'construct') {
 4347:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4348: 							  $titletable);
 4349:             } else {
 4350:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4351: 		    $titletable;
 4352:             }
 4353:         }
 4354:         return $bodytag;
 4355:     }
 4356: 
 4357: #
 4358: # Top frame rendering, Remote is up
 4359: #
 4360: 
 4361:     my $imgsrc = $img;
 4362:     if ($img =~ /^\/adm/) {
 4363:         $imgsrc = &lonhttpdurl($img);
 4364:     }
 4365:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4366: 
 4367:     # Explicit link to get inline menu
 4368:     my $menu= ($no_inline_link?''
 4369: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4370:     #
 4371:     if ($notitle) {
 4372: 	return $bodytag;
 4373:     }
 4374:     return(<<ENDBODY);
 4375: $bodytag
 4376: <table id="LC_title_bar" class="LC_with_remote">
 4377: <tr><td>$upperleft</td>
 4378:     <td>$messages&nbsp;</td>
 4379: </tr>
 4380: <tr><td>$titleinfo $dc_info $menu</td>
 4381: $roleinfo
 4382: </tr>
 4383: </table>
 4384: ENDBODY
 4385: }
 4386: 
 4387: sub make_attr_string {
 4388:     my ($register,$attr_ref) = @_;
 4389: 
 4390:     if ($attr_ref && !ref($attr_ref)) {
 4391: 	die("addentries Must be a hash ref ".
 4392: 	    join(':',caller(1))." ".
 4393: 	    join(':',caller(0))." ");
 4394:     }
 4395: 
 4396:     if ($register) {
 4397: 	my ($on_load,$on_unload);
 4398: 	foreach my $key (keys(%{$attr_ref})) {
 4399: 	    if      (lc($key) eq 'onload') {
 4400: 		$on_load.=$attr_ref->{$key}.';';
 4401: 		delete($attr_ref->{$key});
 4402: 
 4403: 	    } elsif (lc($key) eq 'onunload') {
 4404: 		$on_unload.=$attr_ref->{$key}.';';
 4405: 		delete($attr_ref->{$key});
 4406: 	    }
 4407: 	}
 4408: 	$attr_ref->{'onload'}  =
 4409: 	    &Apache::lonmenu::loadevents().  $on_load;
 4410: 	$attr_ref->{'onunload'}=
 4411: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4412:     }
 4413: 
 4414: # Accessibility font enhance
 4415:     if ($env{'browser.fontenhance'} eq 'on') {
 4416: 	my $style;
 4417: 	foreach my $key (keys(%{$attr_ref})) {
 4418: 	    if (lc($key) eq 'style') {
 4419: 		$style.=$attr_ref->{$key}.';';
 4420: 		delete($attr_ref->{$key});
 4421: 	    }
 4422: 	}
 4423: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4424:     }
 4425: 
 4426:     if ($env{'browser.blackwhite'} eq 'on') {
 4427: 	delete($attr_ref->{'font'});
 4428: 	delete($attr_ref->{'link'});
 4429: 	delete($attr_ref->{'alink'});
 4430: 	delete($attr_ref->{'vlink'});
 4431: 	delete($attr_ref->{'bgcolor'});
 4432: 	delete($attr_ref->{'background'});
 4433:     }
 4434: 
 4435:     my $attr_string;
 4436:     foreach my $attr (keys(%$attr_ref)) {
 4437: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4438:     }
 4439:     return $attr_string;
 4440: }
 4441: 
 4442: 
 4443: ###############################################
 4444: ###############################################
 4445: 
 4446: =pod
 4447: 
 4448: =item * &endbodytag()
 4449: 
 4450: Returns a uniform footer for LON-CAPA web pages.
 4451: 
 4452: Inputs: 1 - optional reference to an args hash
 4453: If in the hash, key for noredirectlink has a value which evaluates to true,
 4454: a 'Continue' link is not displayed if the page contains an
 4455: internal redirect in the <head></head> section,
 4456: i.e., $env{'internal.head.redirect'} exists   
 4457: 
 4458: =cut
 4459: 
 4460: sub endbodytag {
 4461:     my ($args) = @_;
 4462:     my $endbodytag='</body>';
 4463:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4464:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4465:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4466: 	    $endbodytag=
 4467: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4468: 	        &mt('Continue').'</a>'.
 4469: 	        $endbodytag;
 4470:         }
 4471:     }
 4472:     return $endbodytag;
 4473: }
 4474: 
 4475: =pod
 4476: 
 4477: =item * &standard_css()
 4478: 
 4479: Returns a style sheet
 4480: 
 4481: Inputs: (all optional)
 4482:             domain         -> force to color decorate a page for a specific
 4483:                                domain
 4484:             function       -> force usage of a specific rolish color scheme
 4485:             bgcolor        -> override the default page bgcolor
 4486: 
 4487: =cut
 4488: 
 4489: sub standard_css {
 4490:     my ($function,$domain,$bgcolor) = @_;
 4491:     $function  = &get_users_function() if (!$function);
 4492:     my $img    = &designparm($function.'.img',   $domain);
 4493:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4494:     my $font   = &designparm($function.'.font',  $domain);
 4495: #second colour for later usage
 4496:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4497:     my $pgbg_or_bgcolor =
 4498: 	         $bgcolor ||
 4499: 	         &designparm($function.'.pgbg',  $domain);
 4500:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4501:     my $alink  = &designparm($function.'.alink', $domain);
 4502:     my $vlink  = &designparm($function.'.vlink', $domain);
 4503:     my $link   = &designparm($function.'.link',  $domain);
 4504: 
 4505:     my $loginbg = &designparm('login.sidebg',$domain);
 4506:     my $bgcol = &designparm('login.bgcol',$domain);
 4507:     my $textcol = &designparm('login.textcol',$domain);
 4508: 
 4509:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4510:     my $mono                 = 'monospace';
 4511:     my $data_table_head      = $tabbg;
 4512:     my $data_table_light     = '#EEEEEE';
 4513:     my $data_table_dark      = '#DDDDDD';
 4514:     my $data_table_darker    = '#CCCCCC';
 4515:     my $data_table_highlight = '#FFFF00';
 4516:     my $mail_new             = '#FFBB77';
 4517:     my $mail_new_hover       = '#DD9955';
 4518:     my $mail_read            = '#BBBB77';
 4519:     my $mail_read_hover      = '#999944';
 4520:     my $mail_replied         = '#AAAA88';
 4521:     my $mail_replied_hover   = '#888855';
 4522:     my $mail_other           = '#99BBBB';
 4523:     my $mail_other_hover     = '#669999';
 4524:     my $table_header         = '#DDDDDD';
 4525:     my $feedback_link_bg     = '#BBBBBB';
 4526:     my $lg_border_color	     = '#C8C8C8';
 4527: 
 4528:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4529: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4530: 	                                                 : '0px 3px 0px 4px';
 4531: 
 4532: 
 4533:     return <<END;
 4534: body {
 4535:    font-family: $sans;
 4536:    line-height:130%;
 4537:    font-size:0.83em;
 4538:    color:$font;
 4539: }
 4540: 
 4541: a:link, a:visited { 
 4542:   font-size:100%; 
 4543: }
 4544: 
 4545: a:focus { 
 4546:   color: red;
 4547:   background: yellow 
 4548: }
 4549: 
 4550: table.thinborder,
 4551: table.thinborder tr th {
 4552:   border-style: solid;
 4553:   border-width: 1px;
 4554:   border-color: $lg_border_color;
 4555:   background: $tabbg;
 4556: }
 4557: 
 4558: table.thinborder tr td {
 4559:   border-style: solid;
 4560:   border-width: 1px;
 4561:   border-color: $lg_border_color;
 4562: }
 4563: 
 4564: form, .inline { 
 4565:    display: inline; 
 4566: }
 4567: 
 4568: .LC_right {
 4569:    text-align:right;
 4570: }
 4571: 
 4572: .LC_middle {
 4573:    vertical-align:middle;
 4574: }
 4575: 
 4576: /* just for tests */
 4577: .LC_400Box {width:400px; }
 4578: /* end */
 4579: 
 4580: .LC_filename {
 4581:   font-family: $mono;
 4582:   white-space:pre;
 4583: }
 4584: 
 4585: .LC_fileicon {
 4586:   border: none;
 4587:   height: 1.3em;
 4588:   vertical-align: text-bottom;
 4589:   margin-right: 0.3em;
 4590:   text-decoration:none;
 4591: }
 4592: 
 4593: .LC_error {
 4594:   color: red;
 4595:   font-size: larger;
 4596: }
 4597: 
 4598: .LC_warning,
 4599: .LC_diff_removed {
 4600:   color: red;
 4601: }
 4602: 
 4603: .LC_info,
 4604: .LC_success,
 4605: .LC_diff_added {
 4606:   color: green;
 4607: }
 4608: 
 4609: .LC_unknown {
 4610:   color: yellow;
 4611: }
 4612: 
 4613: .LC_icon {
 4614:   border: none;
 4615:   vertical-align: middle;
 4616: }
 4617: 
 4618: .LC_indexer_icon {
 4619:   border: 0px;
 4620:   height: 22px;
 4621: }
 4622: 
 4623: .LC_docs_spacer {
 4624:   width: 25px;
 4625:   height: 1px;
 4626:   border: none;
 4627: }
 4628: 
 4629: .LC_internal_info {
 4630:   color: #999999;
 4631: }
 4632: 
 4633: .LC_discussion {
 4634:    background: $tabbg;
 4635:    border: 1px solid black;
 4636:    margin: 2px;
 4637: }
 4638: 
 4639: .LC_disc_action_links_bar {
 4640:    background: $tabbg;
 4641:    font-family: $sans;
 4642:    border: 0px;
 4643:    margin: 4px;
 4644: }
 4645: 
 4646: .LC_disc_action_left {
 4647:    text-align: left;
 4648: }
 4649: 
 4650: .LC_disc_action_right {
 4651:    text-align: right;
 4652: }
 4653: 
 4654: .LC_disc_new_item {
 4655:    background: white;
 4656:    border: 2px solid red;
 4657:    margin: 2px;
 4658: }
 4659: 
 4660: .LC_disc_old_item {
 4661:    background: white;
 4662:    border: 1px solid black;
 4663:    margin: 2px;
 4664: }
 4665: 
 4666: table.LC_pastsubmission {
 4667:   border: 1px solid black;
 4668:   margin: 2px;
 4669: }
 4670: 
 4671: table#LC_top_nav,
 4672: table#LC_menubuttons,
 4673: table#LC_nav_location {
 4674:   width: 100%;
 4675:   background: $pgbg;
 4676:   border: 2px;
 4677:   border-collapse: separate;
 4678:   padding: 0px;
 4679: }
 4680: 
 4681: table#LC_title_bar,
 4682: table.LC_breadcrumbs,
 4683: table#LC_title_bar.LC_with_remote {
 4684:   width: 100%;
 4685:   border-color: $pgbg;
 4686:   border-style: solid;
 4687:   border-width: $border;
 4688:   background: $pgbg;
 4689:   font-family: $sans;
 4690:   border-collapse: collapse;
 4691:   padding: 0px;
 4692: }
 4693: 
 4694: table.LC_docs_path {
 4695:   width: 100%;
 4696:   border: 0;
 4697:   background: $pgbg;
 4698:   font-family: $sans;
 4699:   border-collapse: collapse;
 4700:   padding: 0px;
 4701: }
 4702: 
 4703: table#LC_title_bar td {
 4704:   background: $tabbg;
 4705: }
 4706: 
 4707: table#LC_title_bar .LC_title_bar_who {
 4708:   background: $tabbg;
 4709:   color: $font;
 4710:   font: small $sans;
 4711:   text-align: right;
 4712:   margin: 0px;
 4713: }
 4714: 
 4715: table#LC_title_bar .LC_title_bar_name {
 4716:   margin: 0px;
 4717: }
 4718: 
 4719: table#LC_title_bar .LC_title_bar_role {
 4720:   margin: 0px;
 4721: }
 4722: 
 4723: table#LC_title_bar .LC_title_bar_realm {
 4724:   margin: 0px;
 4725: }
 4726: 
 4727: span.LC_metadata {
 4728:   font-family: $sans;
 4729: }
 4730: 
 4731: table#LC_menubuttons img{
 4732:   border: 0px;
 4733: }
 4734: 
 4735: table#LC_top_nav td {
 4736:   background: $tabbg;
 4737:   border: 0px;
 4738:   font-size: small;
 4739:   vertical-align:top;
 4740:   padding:2px 5px 2px 5px;
 4741: }
 4742: 
 4743: table#LC_top_nav td a,
 4744: div#LC_top_nav a {
 4745:   color: $font;
 4746:   font-family: $sans;
 4747: }
 4748: 
 4749: table#LC_top_nav td.LC_top_nav_logo {
 4750:   background: $tabbg;
 4751:   text-align: left;
 4752:   white-space: nowrap;
 4753:   width: 31px;
 4754: }
 4755: 
 4756: table#LC_top_nav td.LC_top_nav_logo img {
 4757:   border: 0px;
 4758:   vertical-align: bottom;
 4759: }
 4760: 
 4761: table#LC_top_nav td.LC_top_nav_exit,
 4762: table#LC_top_nav td.LC_top_nav_help {
 4763:   width: 2.0em;
 4764: }
 4765: 
 4766: table#LC_top_nav td.LC_top_nav_login {
 4767:   width: 4.0em;
 4768:   text-align: center;
 4769: }
 4770: 
 4771: table.LC_breadcrumbs td,
 4772: table.LC_docs_path td  {
 4773:   background: $tabbg;
 4774:   color: $font;
 4775:   font-family: $sans;
 4776:   font-size: smaller;
 4777: }
 4778: 
 4779: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4780: table.LC_docs_path td.LC_docs_path_component {
 4781:   background: $tabbg;
 4782:   color: $font;
 4783:   font-family: $sans;
 4784:   font-size: larger;
 4785:   text-align: right;
 4786: }
 4787: 
 4788: td.LC_table_cell_checkbox {
 4789:   text-align: center;
 4790: }
 4791: 
 4792: table#LC_mainmenu td.LC_mainmenu_column {
 4793:     vertical-align: top;
 4794: }
 4795: 
 4796: .LC_fontsize_small {
 4797:  font-size: 70%;
 4798: }
 4799: 
 4800: .LC_fontsize_medium {
 4801:  font-size: 85%;
 4802: }
 4803: 
 4804: .LC_fontsize_large {
 4805:  font-size: 120%;
 4806: }
 4807: 
 4808: .LC_menubuttons_inline_text {
 4809:   color: $font;
 4810:   font-family: $sans;
 4811:   font-size: 90%;
 4812:   padding-left:3px;
 4813: }
 4814: 
 4815: .LC_menubuttons_link {
 4816:   text-decoration: none;
 4817: }
 4818: 
 4819: .LC_menubuttons_category {
 4820:   color: $font;
 4821:   background: $pgbg;
 4822:   font-family: $sans;
 4823:   font-size: larger;
 4824:   font-weight: bold;
 4825: }
 4826: 
 4827: td.LC_menubuttons_text {
 4828:  	color: $font;
 4829: }
 4830: 
 4831: .LC_current_location {
 4832:   font-family: $sans;
 4833:   background: $tabbg;
 4834: }
 4835: 
 4836: .LC_new_mail {
 4837:   font-family: $sans;
 4838:   background: $tabbg;
 4839:   font-weight: bold;
 4840: }
 4841: 
 4842: .LC_dropadd_labeltext {
 4843:   font-family: $sans;
 4844:   text-align: right;
 4845: }
 4846: 
 4847: .LC_preferences_labeltext {
 4848:   font-family: $sans;
 4849:   text-align: right;
 4850: }
 4851: 
 4852: .LC_roleslog_note {
 4853:   font-size: small;
 4854: }
 4855: 
 4856: .LC_mail_functions {
 4857:     font-weight: bold;
 4858: }
 4859: 
 4860: table.LC_aboutme_port {
 4861:   border: 0px;
 4862:   border-collapse: collapse;
 4863:   border-spacing: 0px;
 4864: }
 4865: 
 4866: table.LC_data_table,
 4867: table.LC_mail_list {
 4868:   border: 1px solid #000000;
 4869:   border-collapse: separate;
 4870:   border-spacing: 1px;
 4871:   background: $pgbg;
 4872: }
 4873: 
 4874: .LC_data_table_dense {
 4875:   font-size: small;
 4876: }
 4877: 
 4878: table.LC_nested_outer {
 4879:   border: 1px solid #000000;
 4880:   border-collapse: collapse;
 4881:   border-spacing: 0px;
 4882:   width: 100%;
 4883: }
 4884: 
 4885: table.LC_nested {
 4886:   border: 0px;
 4887:   border-collapse: collapse;
 4888:   border-spacing: 0px;
 4889:   width: 100%;
 4890: }
 4891: 
 4892: table.LC_data_table tr th, 
 4893: table.LC_calendar tr th, 
 4894: table.LC_mail_list tr th,
 4895: table.LC_prior_tries tr th {
 4896:   font-weight: bold;
 4897:   background-color: $data_table_head;
 4898:   font-size:90%;
 4899: }
 4900: 
 4901: table.LC_data_table tr.LC_info_row > td {
 4902:   background-color: #CCCCCC;
 4903:   font-weight: bold;
 4904:   text-align: left;
 4905: }
 4906: 
 4907: table.LC_data_table tr.LC_odd_row > td,
 4908: table.LC_pick_box tr > td.LC_odd_row,
 4909: table.LC_aboutme_port tr td {
 4910:   background-color: $data_table_light;
 4911:   padding: 2px;
 4912: }
 4913: 
 4914: table.LC_data_table tr.LC_even_row > td,
 4915: table.LC_pick_box tr > td.LC_even_row,
 4916: table.LC_aboutme_port tr.LC_even_row td {
 4917:   background-color: $data_table_dark;
 4918:   padding: 2px;
 4919: }
 4920: 
 4921: table.LC_data_table tr.LC_data_table_highlight td {
 4922:   background-color: $data_table_darker;
 4923: }
 4924: 
 4925: table.LC_data_table tr td.LC_leftcol_header {
 4926:   background-color: $data_table_head;
 4927:   font-weight: bold;
 4928: }
 4929: 
 4930: table.LC_data_table tr.LC_empty_row td,
 4931: table.LC_nested tr.LC_empty_row td {
 4932:   background-color: #FFFFFF;
 4933:   font-weight: bold;
 4934:   font-style: italic;
 4935:   text-align: center;
 4936:   padding: 8px;
 4937: }
 4938: 
 4939: table.LC_nested tr.LC_empty_row td {
 4940:   padding: 4ex
 4941: }
 4942: 
 4943: table.LC_nested_outer tr th {
 4944:   font-weight: bold;
 4945:   background-color: $data_table_head;
 4946:   font-size: small;
 4947:   border-bottom: 1px solid #000000;
 4948: }
 4949: 
 4950: table.LC_nested_outer tr td.LC_subheader {
 4951:   background-color: $data_table_head;
 4952:   font-weight: bold;
 4953:   font-size: small;
 4954:   border-bottom: 1px solid #000000;
 4955:   text-align: right;
 4956: }
 4957: 
 4958: table.LC_nested tr.LC_info_row td {
 4959:   background-color: #CCCCCC;
 4960:   font-weight: bold;
 4961:   font-size: small;
 4962:   text-align: center;
 4963: }
 4964: 
 4965: table.LC_nested tr.LC_info_row td.LC_left_item,
 4966: table.LC_nested_outer tr th.LC_left_item {
 4967:   text-align: left;
 4968: }
 4969: 
 4970: table.LC_nested td {
 4971:   background-color: #FFFFFF;
 4972:   font-size: small;
 4973: }
 4974: 
 4975: table.LC_nested_outer tr th.LC_right_item,
 4976: table.LC_nested tr.LC_info_row td.LC_right_item,
 4977: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4978: table.LC_nested tr td.LC_right_item {
 4979:   text-align: right;
 4980: }
 4981: 
 4982: table.LC_nested tr.LC_odd_row td {
 4983:   background-color: #EEEEEE;
 4984: }
 4985: 
 4986: table.LC_createuser {
 4987: }
 4988: 
 4989: table.LC_createuser tr.LC_section_row td {
 4990:   font-size: small;
 4991: }
 4992: 
 4993: table.LC_createuser tr.LC_info_row td  {
 4994:   background-color: #CCCCCC;
 4995:   font-weight: bold;
 4996:   text-align: center;
 4997: }
 4998: 
 4999: table.LC_calendar {
 5000:   border: 1px solid #000000;
 5001:   border-collapse: collapse;
 5002: }
 5003: 
 5004: table.LC_calendar_pickdate {
 5005:   font-size: xx-small;
 5006: }
 5007: 
 5008: table.LC_calendar tr td {
 5009:   border: 1px solid #000000;
 5010:   vertical-align: top;
 5011: }
 5012: 
 5013: table.LC_calendar tr td.LC_calendar_day_empty {
 5014:   background-color: $data_table_dark;
 5015: }
 5016: 
 5017: table.LC_calendar tr td.LC_calendar_day_current {
 5018:   background-color: $data_table_highlight;
 5019: }
 5020: 
 5021: table.LC_mail_list tr.LC_mail_new {
 5022:   background-color: $mail_new;
 5023: }
 5024: 
 5025: table.LC_mail_list tr.LC_mail_new:hover {
 5026:   background-color: $mail_new_hover;
 5027: }
 5028: 
 5029: table.LC_mail_list tr.LC_mail_even {
 5030: }
 5031: 
 5032: table.LC_mail_list tr.LC_mail_odd {
 5033: }
 5034: 
 5035: table.LC_mail_list tr.LC_mail_read {
 5036:   background-color: $mail_read;
 5037: }
 5038: 
 5039: table.LC_mail_list tr.LC_mail_read:hover {
 5040:   background-color: $mail_read_hover;
 5041: }
 5042: 
 5043: table.LC_mail_list tr.LC_mail_replied {
 5044:   background-color: $mail_replied;
 5045: }
 5046: 
 5047: table.LC_mail_list tr.LC_mail_replied:hover {
 5048:   background-color: $mail_replied_hover;
 5049: }
 5050: 
 5051: table.LC_mail_list tr.LC_mail_other {
 5052:   background-color: $mail_other;
 5053: }
 5054: 
 5055: table.LC_mail_list tr.LC_mail_other:hover {
 5056:   background-color: $mail_other_hover;
 5057: }
 5058: 
 5059: table.LC_data_table tr > td.LC_browser_file,
 5060: table.LC_data_table tr > td.LC_browser_file_published {
 5061:   background: #CCFF88;
 5062: }
 5063: 
 5064: table.LC_data_table tr > td.LC_browser_file_locked,
 5065: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5066:   background: #FFAA99;
 5067: }
 5068: 
 5069: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5070:   background: #AAAAAA;
 5071: }
 5072: 
 5073: table.LC_data_table tr > td.LC_browser_file_modified,
 5074: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5075:   background: #FFFF77;
 5076: }
 5077: 
 5078: table.LC_data_table tr.LC_browser_folder > td {
 5079:   background: #CCCCFF;
 5080: }
 5081: 
 5082: table.LC_data_table tr > td.LC_roles_is {
 5083: /*  background: #77FF77; */
 5084: }
 5085: 
 5086: table.LC_data_table tr > td.LC_roles_future {
 5087:   background: #FFFF77;
 5088: }
 5089: 
 5090: table.LC_data_table tr > td.LC_roles_will {
 5091:   background: #FFAA77;
 5092: }
 5093: 
 5094: table.LC_data_table tr > td.LC_roles_expired {
 5095:   background: #FF7777;
 5096: }
 5097: 
 5098: table.LC_data_table tr > td.LC_roles_will_not {
 5099:   background: #AAFF77;
 5100: }
 5101: 
 5102: table.LC_data_table tr > td.LC_roles_selected {
 5103:   background: #11CC55;
 5104: }
 5105: 
 5106: span.LC_current_location {
 5107:   font-size:larger;
 5108:   background: $pgbg;
 5109: }
 5110: 
 5111: span.LC_parm_menu_item {
 5112:   font-size: larger;
 5113:   font-family: $sans;
 5114: }
 5115: 
 5116: span.LC_parm_scope_all {
 5117:   color: red;
 5118: }
 5119: 
 5120: span.LC_parm_scope_folder {
 5121:   color: green;
 5122: }
 5123: 
 5124: span.LC_parm_scope_resource {
 5125:   color: orange;
 5126: }
 5127: 
 5128: span.LC_parm_part {
 5129:   color: blue;
 5130: }
 5131: 
 5132: span.LC_parm_folder, span.LC_parm_symb {
 5133:   font-size: x-small;
 5134:   font-family: $mono;
 5135:   color: #AAAAAA;
 5136: }
 5137: 
 5138: td.LC_parm_overview_level_menu,
 5139: td.LC_parm_overview_map_menu,
 5140: td.LC_parm_overview_parm_selectors,
 5141: td.LC_parm_overview_restrictions  {
 5142:   border: 1px solid black;
 5143:   border-collapse: collapse;
 5144: }
 5145: 
 5146: table.LC_parm_overview_restrictions td {
 5147:   border-width: 1px 4px 1px 4px;
 5148:   border-style: solid;
 5149:   border-color: $pgbg;
 5150:   text-align: center;
 5151: }
 5152: 
 5153: table.LC_parm_overview_restrictions th {
 5154:   background: $tabbg;
 5155:   border-width: 1px 4px 1px 4px;
 5156:   border-style: solid;
 5157:   border-color: $pgbg;
 5158: }
 5159: 
 5160: table#LC_helpmenu {
 5161:   border: 0px;
 5162:   height: 55px;
 5163:   border-spacing: 0px;
 5164: }
 5165: 
 5166: table#LC_helpmenu fieldset legend {
 5167:   font-size: larger;
 5168:   font-weight: bold;
 5169: }
 5170: 
 5171: table#LC_helpmenu_links {
 5172:   width: 100%;
 5173:   border: 1px solid black;
 5174:   background: $pgbg;
 5175:   padding: 0px;
 5176:   border-spacing: 1px;
 5177: }
 5178: 
 5179: table#LC_helpmenu_links tr td {
 5180:   padding: 1px;
 5181:   background: $tabbg;
 5182:   text-align: center;
 5183:   font-weight: bold;
 5184: }
 5185: 
 5186: table#LC_helpmenu_links a:link,
 5187: table#LC_helpmenu_links a:visited,
 5188: table#LC_helpmenu_links a:active {
 5189:   text-decoration: none;
 5190:   color: $font;
 5191: }
 5192: 
 5193: table#LC_helpmenu_links a:hover {
 5194:   text-decoration: underline;
 5195:   color: $vlink;
 5196: }
 5197: 
 5198: .LC_chrt_popup_exists {
 5199:   border: 1px solid #339933;
 5200:   margin: -1px;
 5201: }
 5202: 
 5203: .LC_chrt_popup_up {
 5204:   border: 1px solid yellow;
 5205:   margin: -1px;
 5206: }
 5207: 
 5208: .LC_chrt_popup {
 5209:   border: 1px solid #8888FF;
 5210:   background: #CCCCFF;
 5211: }
 5212: 
 5213: table.LC_pick_box {
 5214:   border-collapse: separate;
 5215:   background: white;
 5216:   border: 1px solid black;
 5217:   border-spacing: 1px;
 5218: }
 5219: 
 5220: table.LC_pick_box td.LC_pick_box_title {
 5221:   background: $tabbg;
 5222:   font-weight: bold;
 5223:   text-align: right;
 5224:   vertical-align: top;
 5225:   width: 184px;
 5226:   padding: 8px;
 5227: }
 5228: 
 5229: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5230:   background: $tabbg;
 5231:   font-weight: bold;
 5232:   text-align: right;
 5233:   width: 350px;
 5234:   padding: 8px;
 5235: }
 5236: 
 5237: table.LC_pick_box td.LC_pick_box_value {
 5238:   text-align: left;
 5239:   padding: 8px;
 5240: }
 5241: 
 5242: table.LC_pick_box td.LC_pick_box_select {
 5243:   text-align: left;
 5244:   padding: 8px;
 5245: }
 5246: 
 5247: table.LC_pick_box td.LC_pick_box_separator {
 5248:   padding: 0px;
 5249:   height: 1px;
 5250:   background: black;
 5251: }
 5252: 
 5253: table.LC_pick_box td.LC_pick_box_submit {
 5254:   text-align: right;
 5255: }
 5256: 
 5257: table.LC_pick_box td.LC_evenrow_value {
 5258:   text-align: left;
 5259:   padding: 8px;
 5260:   background-color: $data_table_light;
 5261: }
 5262: 
 5263: table.LC_pick_box td.LC_oddrow_value {
 5264:   text-align: left;
 5265:   padding: 8px;
 5266:   background-color: $data_table_light;
 5267: }
 5268: 
 5269: table.LC_helpform_receipt {
 5270:   width: 620px;
 5271:   border-collapse: separate;
 5272:   background: white;
 5273:   border: 1px solid black;
 5274:   border-spacing: 1px;
 5275: }
 5276: 
 5277: table.LC_helpform_receipt td.LC_pick_box_title {
 5278:   background: $tabbg;
 5279:   font-weight: bold;
 5280:   text-align: right;
 5281:   width: 184px;
 5282:   padding: 8px;
 5283: }
 5284: 
 5285: table.LC_helpform_receipt td.LC_evenrow_value {
 5286:   text-align: left;
 5287:   padding: 8px;
 5288:   background-color: $data_table_light;
 5289: }
 5290: 
 5291: table.LC_helpform_receipt td.LC_oddrow_value {
 5292:   text-align: left;
 5293:   padding: 8px;
 5294:   background-color: $data_table_light;
 5295: }
 5296: 
 5297: table.LC_helpform_receipt td.LC_pick_box_separator {
 5298:   padding: 0px;
 5299:   height: 1px;
 5300:   background: black;
 5301: }
 5302: 
 5303: span.LC_helpform_receipt_cat {
 5304:   font-weight: bold;
 5305: }
 5306: 
 5307: table.LC_group_priv_box {
 5308:   background: white;
 5309:   border: 1px solid black;
 5310:   border-spacing: 1px;
 5311: }
 5312: 
 5313: table.LC_group_priv_box td.LC_pick_box_title {
 5314:   background: $tabbg;
 5315:   font-weight: bold;
 5316:   text-align: right;
 5317:   width: 184px;
 5318: }
 5319: 
 5320: table.LC_group_priv_box td.LC_groups_fixed {
 5321:   background: $data_table_light;
 5322:   text-align: center;
 5323: }
 5324: 
 5325: table.LC_group_priv_box td.LC_groups_optional {
 5326:   background: $data_table_dark;
 5327:   text-align: center;
 5328: }
 5329: 
 5330: table.LC_group_priv_box td.LC_groups_functionality {
 5331:   background: $data_table_darker;
 5332:   text-align: center;
 5333:   font-weight: bold;
 5334: }
 5335: 
 5336: table.LC_group_priv td {
 5337:   text-align: left;
 5338:   padding: 0px;
 5339: }
 5340: 
 5341: table.LC_notify_front_page {
 5342:   background: white;
 5343:   border: 1px solid black;
 5344:   padding: 8px;
 5345: }
 5346: 
 5347: table.LC_notify_front_page td {
 5348:   padding: 8px;
 5349: }
 5350: 
 5351: .LC_navbuttons {
 5352:   margin: 2ex 0ex 2ex 0ex;
 5353: }
 5354: 
 5355: .LC_topic_bar {
 5356:   font-family: $sans;
 5357:   font-weight: bold;
 5358:   width: 100%;
 5359:   background: $tabbg;
 5360:   vertical-align: middle;
 5361:   margin: 2ex 0ex 2ex 0ex;
 5362: }
 5363: 
 5364: .LC_topic_bar span {
 5365:   vertical-align: middle;
 5366: }
 5367: 
 5368: .LC_topic_bar img {
 5369:   vertical-align: bottom;
 5370: }
 5371: 
 5372: table.LC_course_group_status {
 5373:   margin: 20px;
 5374: }
 5375: 
 5376: table.LC_status_selector td {
 5377:   vertical-align: top;
 5378:   text-align: center;
 5379:   padding: 4px;
 5380: }
 5381: 
 5382: table.LC_descriptive_input td.LC_description {
 5383:   vertical-align: top;
 5384:   text-align: right;
 5385:   font-weight: bold;
 5386: }
 5387: 
 5388: div.LC_feedback_link {
 5389:   clear: both;
 5390:   background: white;
 5391:   width: 100%;
 5392: }
 5393: 
 5394: span.LC_feedback_link {
 5395:   background: $feedback_link_bg;
 5396:   font-size: larger;
 5397: }
 5398: 
 5399: span.LC_message_link {
 5400:   background: $feedback_link_bg;
 5401:   font-size: larger;
 5402:   position: absolute;
 5403:   right: 1em;
 5404: }
 5405: 
 5406: table.LC_prior_tries {
 5407:   border: 1px solid #000000;
 5408:   border-collapse: separate;
 5409:   border-spacing: 1px;
 5410: }
 5411: 
 5412: table.LC_prior_tries td {
 5413:   padding: 2px;
 5414: }
 5415: 
 5416: .LC_answer_correct {
 5417:   background: lightgreen;
 5418:   font-family: $sans;
 5419:   color: darkgreen;
 5420:   padding: 6px;
 5421: }
 5422: 
 5423: .LC_answer_charged_try {
 5424:   background: #FFAAAA;
 5425:   font-family: $sans;
 5426:   color: darkred;
 5427:   padding: 6px;
 5428: }
 5429: 
 5430: .LC_answer_not_charged_try,
 5431: .LC_answer_no_grade,
 5432: .LC_answer_late {
 5433:   background: lightyellow;
 5434:   font-family: $sans;
 5435:   color: black;
 5436:   padding: 6px;
 5437: }
 5438: 
 5439: .LC_answer_previous {
 5440:   background: lightblue;
 5441:   font-family: $sans;
 5442:   color: darkblue;
 5443:   padding: 6px;
 5444: }
 5445: 
 5446: .LC_answer_no_message {
 5447:   background: #FFFFFF;
 5448:   font-family: $sans;
 5449:   color: black;
 5450:   padding: 6px;
 5451: }
 5452: 
 5453: .LC_answer_unknown {
 5454:   background: orange;
 5455:   font-family: $sans;
 5456:   color: black;
 5457:   padding: 6px;
 5458: }
 5459: 
 5460: span.LC_prior_numerical,
 5461: span.LC_prior_string,
 5462: span.LC_prior_custom,
 5463: span.LC_prior_reaction,
 5464: span.LC_prior_math {
 5465:   font-family: monospace;
 5466:   white-space: pre;
 5467: }
 5468: 
 5469: span.LC_prior_string {
 5470:   font-family: monospace;
 5471:   white-space: pre;
 5472: }
 5473: 
 5474: table.LC_prior_option {
 5475:   width: 100%;
 5476:   border-collapse: collapse;
 5477: }
 5478: 
 5479: table.LC_prior_rank, 
 5480: table.LC_prior_match {
 5481:   border-collapse: collapse;
 5482: }
 5483: 
 5484: table.LC_prior_option tr td,
 5485: table.LC_prior_rank tr td,
 5486: table.LC_prior_match tr td {
 5487:   border: 1px solid #000000;
 5488: }
 5489: 
 5490: td.LC_nobreak,
 5491: span.LC_nobreak {
 5492:   white-space: nowrap;
 5493: }
 5494: 
 5495: span.LC_cusr_emph {
 5496:   font-style: italic;
 5497: }
 5498: 
 5499: span.LC_cusr_subheading {
 5500:   font-weight: normal;
 5501:   font-size: 85%;
 5502: }
 5503: 
 5504: table.LC_docs_documents {
 5505:   background: #BBBBBB;
 5506:   border-width: 0px;
 5507:   border-collapse: collapse;
 5508: }
 5509: 
 5510: table.LC_docs_documents td.LC_docs_document {
 5511:   border: 2px solid black;
 5512:   padding: 4px;
 5513: }
 5514: 
 5515: .LC_docs_entry_move {
 5516:   border: 0px;
 5517:   border-collapse: collapse;
 5518: }
 5519: 
 5520: .LC_docs_entry_move td {
 5521:   border: 2px solid #BBBBBB;
 5522:   background: #DDDDDD;
 5523: }
 5524: 
 5525: .LC_docs_editor td.LC_docs_entry_commands {
 5526:   background: #DDDDDD;
 5527:   font-size: x-small;
 5528: }
 5529: 
 5530: .LC_docs_copy {
 5531:   color: #000099;
 5532: }
 5533: 
 5534: .LC_docs_cut {
 5535:   color: #550044;
 5536: }
 5537: 
 5538: .LC_docs_rename {
 5539:   color: #009900;
 5540: }
 5541: 
 5542: .LC_docs_remove {
 5543:   color: #990000;
 5544: }
 5545: 
 5546: .LC_docs_reinit_warn,
 5547: .LC_docs_ext_edit {
 5548:   font-size: x-small;
 5549: }
 5550: 
 5551: .LC_docs_editor td.LC_docs_entry_title,
 5552: .LC_docs_editor td.LC_docs_entry_icon {
 5553:   background: #FFFFBB;
 5554: }
 5555: 
 5556: .LC_docs_editor td.LC_docs_entry_parameter {
 5557:   background: #BBBBFF;
 5558:   font-size: x-small;
 5559:   white-space: nowrap;
 5560: }
 5561: 
 5562: table.LC_docs_adddocs td,
 5563: table.LC_docs_adddocs th {
 5564:   border: 1px solid #BBBBBB;
 5565:   padding: 4px;
 5566:   background: #DDDDDD;
 5567: }
 5568: 
 5569: table.LC_sty_begin {
 5570:   background: #BBFFBB;
 5571: }
 5572: 
 5573: table.LC_sty_end {
 5574:   background: #FFBBBB;
 5575: }
 5576: 
 5577: table.LC_double_column {
 5578:   border-width: 0px;
 5579:   border-collapse: collapse;
 5580:   width: 100%;
 5581:   padding: 2px;
 5582: }
 5583: 
 5584: table.LC_double_column tr td.LC_left_col {
 5585:   top: 2px;
 5586:   left: 2px;
 5587:   width: 47%;
 5588:   vertical-align: top;
 5589: }
 5590: 
 5591: table.LC_double_column tr td.LC_right_col {
 5592:   top: 2px;
 5593:   right: 2px;
 5594:   width: 47%;
 5595:   vertical-align: top;
 5596: }
 5597: 
 5598: span.LC_role_level {
 5599:   font-weight: bold;
 5600: }
 5601: 
 5602: div.LC_left_float {
 5603:   float: left;
 5604:   padding-right: 5%;
 5605:   padding-bottom: 4px;
 5606: }
 5607: 
 5608: div.LC_clear_float_header {
 5609:   padding-bottom: 2px;
 5610: }
 5611: 
 5612: div.LC_clear_float_footer {
 5613:   padding-top: 10px;
 5614:   clear: both;
 5615: }
 5616: 
 5617: div.LC_grade_show_user {
 5618:   margin-top: 20px;
 5619:   border: 1px solid black;
 5620: }
 5621: 
 5622: div.LC_grade_user_name {
 5623:   background: #DDDDEE;
 5624:   border-bottom: 1px solid black;
 5625:   font-weight: bold;
 5626:   font-size: large;
 5627: }
 5628: 
 5629: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5630:   background: #DDEEDD;
 5631: }
 5632: 
 5633: div.LC_grade_show_problem,
 5634: div.LC_grade_submissions,
 5635: div.LC_grade_message_center,
 5636: div.LC_grade_info_links,
 5637: div.LC_grade_assign {
 5638:   margin: 5px;
 5639:   width: 99%;
 5640:   background: #FFFFFF;
 5641: }
 5642: 
 5643: div.LC_grade_show_problem_header,
 5644: div.LC_grade_submissions_header,
 5645: div.LC_grade_message_center_header,
 5646: div.LC_grade_assign_header {
 5647:   font-weight: bold;
 5648:   font-size: large;
 5649: }
 5650: 
 5651: div.LC_grade_show_problem_problem,
 5652: div.LC_grade_submissions_body,
 5653: div.LC_grade_message_center_body,
 5654: div.LC_grade_assign_body {
 5655:   border: 1px solid black;
 5656:   width: 99%;
 5657:   background: #FFFFFF;
 5658: }
 5659: 
 5660: span.LC_grade_check_note {
 5661:   font-weight: normal;
 5662:   font-size: medium;
 5663:   display: inline;
 5664:   position: absolute;
 5665:   right: 1em;
 5666: }
 5667: 
 5668: table.LC_scantron_action {
 5669:   width: 100%;
 5670: }
 5671: 
 5672: table.LC_scantron_action tr th {
 5673:   font-weight:bold;
 5674:   font-style:normal;
 5675: }
 5676: 
 5677: .LC_edit_problem_header,
 5678: div.LC_edit_problem_footer {
 5679:   font-weight: normal;
 5680:   font-size:  medium;
 5681:   margin: 2px;
 5682: }
 5683: 
 5684: div.LC_edit_problem_header,
 5685: div.LC_edit_problem_header div,
 5686: div.LC_edit_problem_footer,
 5687: div.LC_edit_problem_footer div,
 5688: div.LC_edit_problem_editxml_header,
 5689: div.LC_edit_problem_editxml_header div {
 5690:   margin-top: 5px;
 5691: }
 5692: 
 5693: div.LC_edit_problem_header_edit_row {
 5694:   background: $tabbg;
 5695:   padding: 3px;
 5696:   margin-bottom: 5px;
 5697: }
 5698: 
 5699: div.LC_edit_problem_header_title {
 5700:   font-weight: bold;
 5701:   font-size: larger;
 5702:   background: $tabbg;
 5703:   padding: 3px;
 5704: }
 5705: 
 5706: table.LC_edit_problem_header_title {
 5707:   font-size: larger;
 5708:   font-weight:  bold;
 5709:   width: 100%;
 5710:   border-color: $pgbg;
 5711:   border-style: solid;
 5712:   border-width: $border;
 5713:   background: $tabbg;
 5714:   border-collapse: collapse;
 5715:   padding: 0px
 5716: }
 5717: 
 5718: div.LC_edit_problem_discards {
 5719:   float: left;
 5720:   padding-bottom: 5px;
 5721: }
 5722: 
 5723: div.LC_edit_problem_saves {
 5724:   float: right;
 5725:   padding-bottom: 5px;
 5726: }
 5727: 
 5728: hr.LC_edit_problem_divide {
 5729:   clear: both;
 5730:   color: $tabbg;
 5731:   background-color: $tabbg;
 5732:   height: 3px;
 5733:   border: 0px;
 5734: }
 5735: 
 5736: img.stift{
 5737:   border-width:0;
 5738:   vertical-align:middle;
 5739: }
 5740: 
 5741: table#LC_mainmenu{
 5742:  margin-top:10px;
 5743:  width:80%;
 5744: }
 5745: 
 5746: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5747:   vertical-align: top;
 5748:   width: 45%;
 5749: }
 5750: 
 5751: .LC_mainmenu_fieldset_category {
 5752:   color: $font;
 5753:   background: $pgbg;
 5754:   font-family: $sans;
 5755:   font-size: small;
 5756:   font-weight: bold;
 5757: }
 5758: 
 5759: div.LC_createcourse {
 5760:     margin: 10px 10px 10px 10px;
 5761: }
 5762: 
 5763: /* ---- Remove when done ----
 5764: # The following styles is part of the redesign of LON-CAPA and are
 5765: # subject to change during this project.
 5766: # Don't rely on their current functionality as they might be 
 5767: # changed or removed.
 5768: # --------------------------*/
 5769: 
 5770: a:hover,
 5771: ol.LC_smallMenu a:hover,
 5772: ol#LC_MenuBreadcrumbs a:hover,
 5773: ol#LC_PathBreadcrumbs a:hover,
 5774: ul#LC_TabMainMenuContent a:hover,
 5775: .LC_FormSectionClearButton input:hover
 5776: ul.LC_TabContent   li:hover a {
 5777: 	color:#BF2317;
 5778:         text-decoration:none;
 5779: }
 5780: 
 5781: h1 {
 5782: 	padding:5px 10px 5px 20px;
 5783: 	line-height:130%;
 5784: }
 5785: 
 5786: h2,h3,h4,h5,h6 {
 5787: 	margin:5px 0px 5px 0px;
 5788: 	padding:0px;
 5789: 	line-height:130%;
 5790: }
 5791: 
 5792: .LC_hcell {
 5793:         padding:3px 15px 3px 15px;
 5794:         margin:0px;
 5795: 	background-color:$tabbg;
 5796: 	border-bottom:solid 1px $lg_border_color;
 5797: }
 5798: 
 5799: .LC_noBorder {
 5800:         border:0px;
 5801: }
 5802: 
 5803: 
 5804: /* Main Header with discription of Person, Course, etc. */
 5805: 
 5806: .LC_Right {
 5807:         float: right;
 5808:         margin: 0px;
 5809:         padding: 0px;
 5810: }
 5811: 
 5812: .LC_FormSectionClearButton input {
 5813:         background-color:transparent;
 5814:         border:0px;
 5815:         cursor:pointer;
 5816:         text-decoration:underline;
 5817: }
 5818: 
 5819: .LC_help_open_topic {
 5820:         color: #FFFFFF;
 5821:         background-color: #EEEEFF;
 5822:         margin: 1px;
 5823:         padding: 4px;
 5824:         border: 1px solid #000033;
 5825:         white-space: nowrap;
 5826: /*		vertical-align: middle; */
 5827: }
 5828: 
 5829: dl,ul,div,fieldset {
 5830: 	margin: 10px 10px 10px 0px;
 5831: 	overflow:hidden;
 5832: }
 5833: 
 5834: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5835: 	margin: 0px;
 5836: }
 5837: 
 5838: ol.LC_smallMenu li {
 5839: 	display: inline;
 5840: 	padding: 5px 5px 0px 10px;
 5841: 	vertical-align: top;
 5842: }
 5843: 
 5844: ol.LC_smallMenu li img {
 5845: 	vertical-align: bottom;
 5846: }
 5847: 
 5848: ol.LC_smallMenu a {
 5849: 	font-size: 90%;
 5850: 	color: RGB(80, 80, 80);
 5851: 	text-decoration: none;
 5852: }
 5853: 
 5854: ol#LC_TabMainMenuContent, 
 5855: ul.LC_TabContent ,
 5856: ul.LC_TabContentBigger {
 5857: 	display:block;
 5858: 	list-style:none;
 5859: 	margin: 0px;
 5860: 	padding: 0px;
 5861: }
 5862: 
 5863: ol#LC_TabMainMenuContent li,
 5864: ul.LC_TabContent li,
 5865: ul.LC_TabContentBigger li {
 5866: 	display: inline;
 5867: 	border-right: solid 1px $lg_border_color;
 5868: 	float:left;
 5869: 	line-height:140%;
 5870: 	white-space:nowrap;
 5871: }
 5872: 
 5873: ol#LC_TabMainMenuContent li {
 5874: 	vertical-align: bottom;
 5875: 	border-bottom: solid 1px RGB(175, 175, 175);
 5876: 	padding: 5px 10px 5px 10px;
 5877: 	margin-right:5px;
 5878: 	margin-bottom:3px;
 5879: 	font-weight: bold;
 5880: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5881: }
 5882: 
 5883: ol#LC_TabMainMenuContent li a {
 5884: 	color: RGB(47, 47, 47);
 5885: 	text-decoration: none;
 5886: }
 5887: 
 5888: ul.LC_TabContent {
 5889: 	min-height:1.6em;
 5890: }
 5891: 
 5892: ul.LC_TabContent li {
 5893: 	vertical-align:middle;
 5894: 	padding:0px 10px 0px 10px;
 5895: 	background-color:$tabbg;
 5896: 	border-bottom:solid 1px $lg_border_color;
 5897: }
 5898: 
 5899: ul.LC_TabContent li a, ul.LC_TabContent li {
 5900: 	color:rgb(47,47,47);
 5901: 	text-decoration:none;
 5902: 	font-size:95%;
 5903: 	font-weight:bold;
 5904: 	padding-right: 16px;
 5905: }
 5906: 
 5907: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
 5908:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5909: 	border-bottom:solid 1px #FFFFFF;
 5910: 	padding-right: 16px;
 5911: }
 5912: 
 5913: ul.LC_TabContentBigger li {
 5914: 	vertical-align:bottom;
 5915: 	border-top:solid 1px $lg_border_color;
 5916: 	border-left:solid 1px $lg_border_color;
 5917: 	padding:5px 10px 5px 10px;
 5918: 	margin-left:2px;
 5919: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5920: }
 5921: 
 5922: ul.LC_TabContentBigger li:hover, 
 5923: ul.LC_TabContentBigger li.active {
 5924: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5925: }
 5926: 
 5927: ul.LC_TabContentBigger li, 
 5928: ul.LC_TabContentBigger li a {
 5929: 	font-size:110%;
 5930: 	font-weight:bold;
 5931: }
 5932: 
 5933: ol#LC_MenuBreadcrumbs, 
 5934: ol#LC_PathBreadcrumbs, 
 5935: ul.LC_CourseBreadcrumbs {
 5936: 	border-top: solid 1px RGB(255, 255, 255);
 5937: 	height: 20px;
 5938: 	line-height: 20px;
 5939: 	vertical-align: bottom;
 5940: 	margin: 0px 0px 30px 0px;
 5941: 	padding-left: 10px;
 5942: 	list-style-position: inside;
 5943: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5944: }
 5945: 
 5946: ol#LC_MenuBreadcrumbs li, 
 5947: ol#LC_PathBreadcrumbs li, 
 5948: ul.LC_CourseBreadcrumbs li {
 5949: /*
 5950: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5951: */
 5952: 	display: inline;
 5953: 	padding: 0px 0px 0px 10px;
 5954: /*	vertical-align: bottom; */
 5955: 	overflow:hidden;
 5956: }
 5957: 
 5958: ol#LC_MenuBreadcrumbs li a, ul.LC_CourseBreadcrumbs li a {
 5959: 	text-decoration: none;
 5960: 	font-size:90%;
 5961: }
 5962: 
 5963: ol#LC_PathBreadcrumbs li a {
 5964: 	text-decoration:none;
 5965: 	font-size:100%;
 5966: 	font-weight:bold;
 5967: }
 5968: 
 5969: .LC_BoxPadding {
 5970: 	padding: 10px;
 5971: }
 5972: 
 5973: .LC_ContentBoxSpecial {
 5974: 	border: solid 1px $lg_border_color;
 5975: }
 5976: 
 5977: .LC_ContentBoxSpecialContactInfo {
 5978: 	border: solid 1px $lg_border_color;
 5979: 	max-width:25%;
 5980: 	min-width:25%;
 5981: }
 5982: 
 5983: .LC_AboutMe_Image {
 5984: 	float:left;
 5985: 	margin-right:10px;
 5986: }
 5987: 
 5988: .LC_Clear_AboutMe_Image {
 5989: 	clear:left;
 5990: }
 5991: 
 5992: dl.LC_ListStyleClean dt {
 5993: 	padding-right: 5px;
 5994: 	display: table-header-group;
 5995: }
 5996: 
 5997: dl.LC_ListStyleClean dd {
 5998: 	display: table-row;
 5999: }
 6000: 
 6001: .LC_ListStyleClean,
 6002: .LC_ListStyleSimple,
 6003: .LC_ListStyleNormal,
 6004: .LC_ListStyle_Border,
 6005: .LC_ListStyleSpecial {
 6006: 	/*display:block;	*/
 6007: 	list-style-position: inside;
 6008: 	list-style-type: none;
 6009: 	overflow: hidden;
 6010: 	padding: 0px;
 6011: }
 6012: 
 6013: .LC_ListStyleSimple li,
 6014: .LC_ListStyleSimple dd,
 6015: .LC_ListStyleNormal li,
 6016: .LC_ListStyleNormal dd,
 6017: .LC_ListStyleSpecial li,
 6018: .LC_ListStyleSpecial dd {
 6019: 	margin: 0px;
 6020: 	padding: 5px 5px 5px 10px;
 6021: 	clear: both;
 6022: }
 6023: 
 6024: .LC_ListStyleClean li,
 6025: .LC_ListStyleClean dd {
 6026: 	padding-top: 0px;
 6027: 	padding-bottom: 0px;
 6028: }
 6029: 
 6030: .LC_ListStyleSimple dd,
 6031: .LC_ListStyleSimple li {
 6032: 	border-bottom: solid 1px $lg_border_color;
 6033: }
 6034: 
 6035: .LC_ListStyleSpecial li,
 6036: .LC_ListStyleSpecial dd {
 6037: 	list-style-type: none;
 6038: 	background-color: RGB(220, 220, 220);
 6039: 	margin-bottom: 4px;
 6040: }
 6041: 
 6042: table.LC_SimpleTable {
 6043: 	margin:5px;
 6044: 	border:solid 1px $lg_border_color;
 6045: }
 6046: 
 6047: table.LC_SimpleTable tr {
 6048: 	padding:0px;
 6049: 	border:solid 1px $lg_border_color;
 6050: }
 6051: 
 6052: table.LC_SimpleTable thead {
 6053: 	 background:rgb(220,220,220);
 6054: }
 6055: 
 6056: div.LC_columnSection {
 6057: 	display: block;
 6058: 	clear: both;
 6059: 	overflow: hidden;
 6060: 	margin:0px;
 6061: }
 6062: 
 6063: div.LC_columnSection>* {
 6064: 	float: left;
 6065: 	margin: 10px 20px 10px 0px;
 6066: 	overflow:hidden;
 6067: }
 6068: 
 6069: .ContentBoxSpecialTemplate {
 6070:         border: solid 1px $lg_border_color;
 6071: }
 6072: 
 6073: .ContentBoxTemplate {
 6074:         padding:10px;
 6075: }
 6076: 
 6077: div.LC_columnSection > .ContentBoxTemplate,
 6078: div.LC_columnSection > .ContentBoxSpecialTemplate {
 6079:         width: 600px;
 6080: }
 6081: 
 6082: .clear {
 6083: 	clear: both;
 6084: 	line-height: 0px;
 6085: 	font-size: 0px;
 6086: 	height: 0px;
 6087: }
 6088: 
 6089: .LC_loginpage_container {
 6090: 	text-align:left;
 6091: 	margin : 0 auto;
 6092: 	width:90%;
 6093: 	padding: 10px;
 6094: 	height: auto;
 6095: 	background-color:#FFFFFF;
 6096: 	border:1px solid #CCCCCC;
 6097: }
 6098: 
 6099: 
 6100: .LC_loginpage_loginContainer {
 6101: 	float:left;
 6102: 	width: 182px;
 6103: 	padding: 2px;
 6104: 	border:1px solid #CCCCCC;
 6105: 	background-color:$loginbg;
 6106: }
 6107: 
 6108: .LC_loginpage_loginContainer h2 {
 6109: 	margin-top:0;
 6110: 	display:block;
 6111: 	background:$bgcol;
 6112: 	color:$textcol;
 6113: 	padding-left:5px;
 6114: }
 6115: 
 6116: .LC_loginpage_loginInfo {
 6117: 	float:left;
 6118: 	width:182px;
 6119: 	border:1px solid #CCCCCC;
 6120: 	padding:2px;
 6121: }
 6122: 
 6123: .LC_loginpage_space {
 6124: 	clear: both;
 6125: 	margin-bottom: 20px;
 6126: 	border-bottom: 1px solid #CCCCCC;
 6127: }
 6128: 
 6129: .LC_loginpage_floatLeft {
 6130: 	float: left;
 6131: 	width: 200px;
 6132: 	margin: 0;
 6133: }
 6134: 
 6135: table em {
 6136: 	font-weight: bold;
 6137: 	font-style: normal;
 6138: }
 6139: 
 6140: table.LC_tableBrowseRes,
 6141: table.LC_tableOfContent {
 6142:         border:none;
 6143: 	border-spacing: 1;
 6144: 	padding: 3px;
 6145: 	background-color: #FFFFFF;
 6146: 	font-size: 90%;
 6147: }
 6148: 
 6149: table.LC_tableOfContent{
 6150:     border-collapse: collapse;
 6151: }
 6152: 
 6153: table.LC_tableBrowseRes a,
 6154: table.LC_tableOfContent a {
 6155:         background-color: transparent;
 6156: 	text-decoration: none;
 6157: }
 6158: 
 6159: table.LC_tableBrowseRes tr.LC_trOdd,
 6160: table.LC_tableOfContent tr.LC_trOdd{
 6161: 	background-color: #EEEEEE;
 6162: }
 6163: 
 6164: table.LC_tableOfContent img {
 6165: 	border: none;
 6166: 	height: 1.3em;
 6167: 	vertical-align: text-bottom;
 6168: 	margin-right: 0.3em;
 6169: }
 6170: 
 6171: a#LC_content_toolbar_firsthomework {
 6172: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 6173: }
 6174: 
 6175: a#LC_content_toolbar_launchnav {
 6176: 	background-image:url(/res/adm/pages/start-navigation.gif);
 6177: }
 6178: 
 6179: a#LC_content_toolbar_closenav {
 6180: 	background-image:url(/res/adm/pages/close-navigation.gif);
 6181: }
 6182: 
 6183: a#LC_content_toolbar_everything {
 6184: 	background-image:url(/res/adm/pages/show-all.gif);
 6185: }
 6186: 
 6187: a#LC_content_toolbar_uncompleted {
 6188: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6189: }
 6190: 
 6191: #LC_content_toolbar_clearbubbles {
 6192: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6193: }
 6194: 
 6195: a#LC_content_toolbar_changefolder {
 6196: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6197: }
 6198: 
 6199: a#LC_content_toolbar_changefolder_toggled {
 6200: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 6201: }
 6202: 
 6203: ul#LC_toolbar li a:hover {
 6204: 	background-position: bottom center;
 6205: }
 6206: 
 6207: ul#LC_toolbar {
 6208: 	padding:0;
 6209: 	margin: 2px;
 6210: 	list-style:none;
 6211: 	position:relative;
 6212: 	background-color:white;
 6213: }
 6214: 
 6215: ul#LC_toolbar li {
 6216: 	border:1px solid white;
 6217: 	padding:0;
 6218: 	margin: 0;
 6219:         float: left;
 6220: 	display:inline;
 6221: 	vertical-align:middle;
 6222: } 
 6223: 
 6224: 
 6225: a.LC_toolbarItem {
 6226: 	display:block;
 6227: 	padding:0;
 6228: 	margin:0;
 6229: 	height: 32px;
 6230: 	width: 32px;
 6231: 	color:white;
 6232: 	border:0 none;
 6233: 	background-repeat:no-repeat;
 6234: 	background-color:transparent;
 6235: }
 6236: 
 6237: ul.LC_functionslist li {
 6238:   float: left;
 6239:   white-space: nowrap;
 6240:   height: 35px; /* at least as high as heighest list item */
 6241:   margin: 0px 15px 15px 10px;
 6242: }
 6243: 
 6244: 
 6245: END
 6246: }
 6247: 
 6248: =pod
 6249: 
 6250: =item * &headtag()
 6251: 
 6252: Returns a uniform footer for LON-CAPA web pages.
 6253: 
 6254: Inputs: $title - optional title for the head
 6255:         $head_extra - optional extra HTML to put inside the <head>
 6256:         $args - optional arguments
 6257:             force_register - if is true call registerurl so the remote is 
 6258:                              informed
 6259:             redirect       -> array ref of
 6260:                                    1- seconds before redirect occurs
 6261:                                    2- url to redirect to
 6262:                                    3- whether the side effect should occur
 6263:                            (side effect of setting 
 6264:                                $env{'internal.head.redirect'} to the url 
 6265:                                redirected too)
 6266:             domain         -> force to color decorate a page for a specific
 6267:                                domain
 6268:             function       -> force usage of a specific rolish color scheme
 6269:             bgcolor        -> override the default page bgcolor
 6270:             no_auto_mt_title
 6271:                            -> prevent &mt()ing the title arg
 6272: 
 6273: =cut
 6274: 
 6275: sub headtag {
 6276:     my ($title,$head_extra,$args) = @_;
 6277:     
 6278:     my $function = $args->{'function'} || &get_users_function();
 6279:     my $domain   = $args->{'domain'}   || &determinedomain();
 6280:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6281:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6282: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6283: 		   #time(),
 6284: 		   $env{'environment.color.timestamp'},
 6285: 		   $function,$domain,$bgcolor);
 6286: 
 6287:     $url = '/adm/css/'.&escape($url).'.css';
 6288: 
 6289:     my $result =
 6290: 	'<head>'.
 6291: 	&font_settings();
 6292: 
 6293:     if (!$args->{'frameset'}) {
 6294: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6295:     }
 6296:     if ($args->{'force_register'}) {
 6297: 	$result .= &Apache::lonmenu::registerurl(1);
 6298:     }
 6299:     if (!$args->{'no_nav_bar'} 
 6300: 	&& !$args->{'only_body'}
 6301: 	&& !$args->{'frameset'}) {
 6302: 	$result .= &help_menu_js();
 6303:     }
 6304: 
 6305:     if (ref($args->{'redirect'})) {
 6306: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6307: 	$url = &Apache::lonenc::check_encrypt($url);
 6308: 	if (!$inhibit_continue) {
 6309: 	    $env{'internal.head.redirect'} = $url;
 6310: 	}
 6311: 	$result.=<<ADDMETA
 6312: <meta http-equiv="pragma" content="no-cache" />
 6313: <meta http-equiv="Refresh" content="$time; url=$url" />
 6314: ADDMETA
 6315:     }
 6316:     if (!defined($title)) {
 6317: 	$title = 'The LearningOnline Network with CAPA';
 6318:     }
 6319:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6320:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6321: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6322: 	.$head_extra;
 6323:     return $result;
 6324: }
 6325: 
 6326: =pod
 6327: 
 6328: =item * &font_settings()
 6329: 
 6330: Returns neccessary <meta> to set the proper encoding
 6331: 
 6332: Inputs: none
 6333: 
 6334: =cut
 6335: 
 6336: sub font_settings {
 6337:     my $headerstring='';
 6338:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6339: 	$headerstring.=
 6340: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6341:     }
 6342:     return $headerstring;
 6343: }
 6344: 
 6345: =pod
 6346: 
 6347: =item * &xml_begin()
 6348: 
 6349: Returns the needed doctype and <html>
 6350: 
 6351: Inputs: none
 6352: 
 6353: =cut
 6354: 
 6355: sub xml_begin {
 6356:     my $output='';
 6357: 
 6358:     if ($env{'internal.start_page'}==1) {
 6359: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6360:     }
 6361: 
 6362:     if ($env{'browser.mathml'}) {
 6363: 	$output='<?xml version="1.0"?>'
 6364:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6365: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6366:             
 6367: #	    .'<!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">] >'
 6368: 	    .'<!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">'
 6369:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6370: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6371:     } else {
 6372: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6373:     }
 6374:     return $output;
 6375: }
 6376: 
 6377: =pod
 6378: 
 6379: =item * &endheadtag()
 6380: 
 6381: Returns a uniform </head> for LON-CAPA web pages.
 6382: 
 6383: Inputs: none
 6384: 
 6385: =cut
 6386: 
 6387: sub endheadtag {
 6388:     return '</head>';
 6389: }
 6390: 
 6391: =pod
 6392: 
 6393: =item * &head()
 6394: 
 6395: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6396: 
 6397: Inputs:
 6398: 
 6399: =over 4
 6400: 
 6401: $title - optional title for the page
 6402: 
 6403: $head_extra - optional extra HTML to put inside the <head>
 6404: 
 6405: =back
 6406: 
 6407: =cut
 6408: 
 6409: sub head {
 6410:     my ($title,$head_extra,$args) = @_;
 6411:     return &headtag($title,$head_extra,$args).&endheadtag();
 6412: }
 6413: 
 6414: =pod
 6415: 
 6416: =item * &start_page()
 6417: 
 6418: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6419: 
 6420: Inputs:
 6421: 
 6422: =over 4
 6423: 
 6424: $title - optional title for the page
 6425: 
 6426: $head_extra - optional extra HTML to incude inside the <head>
 6427: 
 6428: $args - additional optional args supported are:
 6429: 
 6430: =over 8
 6431: 
 6432:              only_body      -> is true will set &bodytag() onlybodytag
 6433:                                     arg on
 6434:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6435:              add_entries    -> additional attributes to add to the  <body>
 6436:              domain         -> force to color decorate a page for a 
 6437:                                     specific domain
 6438:              function       -> force usage of a specific rolish color
 6439:                                     scheme
 6440:              redirect       -> see &headtag()
 6441:              bgcolor        -> override the default page bg color
 6442:              js_ready       -> return a string ready for being used in 
 6443:                                     a javascript writeln
 6444:              html_encode    -> return a string ready for being used in 
 6445:                                     a html attribute
 6446:              force_register -> if is true will turn on the &bodytag()
 6447:                                     $forcereg arg
 6448:              body_title     -> alternate text to use instead of $title
 6449:                                     in the title box that appears, this text
 6450:                                     is not auto translated like the $title is
 6451:              frameset       -> if true will start with a <frameset>
 6452:                                     rather than <body>
 6453:              no_title       -> if true the title bar won't be shown
 6454:              skip_phases    -> hash ref of 
 6455:                                     head -> skip the <html><head> generation
 6456:                                     body -> skip all <body> generation
 6457:              no_inline_link -> if true and in remote mode, don't show the 
 6458:                                     'Switch To Inline Menu' link
 6459:              no_auto_mt_title -> prevent &mt()ing the title arg
 6460:              inherit_jsmath -> when creating popup window in a page,
 6461:                                     should it have jsmath forced on by the
 6462:                                     current page
 6463: 
 6464: =back
 6465: 
 6466: =back
 6467: 
 6468: =cut
 6469: 
 6470: sub start_page {
 6471:     my ($title,$head_extra,$args) = @_;
 6472:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6473:     my %head_args;
 6474:     foreach my $arg ('redirect','force_register','domain','function',
 6475: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6476: 		     'no_auto_mt_title') {
 6477: 	if (defined($args->{$arg})) {
 6478: 	    $head_args{$arg} = $args->{$arg};
 6479: 	}
 6480:     }
 6481: 
 6482:     $env{'internal.start_page'}++;
 6483:     my $result;
 6484:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6485: 	$result.=
 6486: 	    &xml_begin().
 6487: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6488:     }
 6489:     
 6490:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6491: 	if ($args->{'frameset'}) {
 6492: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6493: 						$args->{'add_entries'});
 6494: 	    $result .= "\n<frameset $attr_string>\n";
 6495: 	} else {
 6496: 	    $result .=
 6497: 		&bodytag($title, 
 6498: 			 $args->{'function'},       $args->{'add_entries'},
 6499: 			 $args->{'only_body'},      $args->{'domain'},
 6500: 			 $args->{'force_register'}, $args->{'body_title'},
 6501: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6502: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6503: 			 $args);
 6504: 	}
 6505:     }
 6506: 
 6507:     if ($args->{'js_ready'}) {
 6508: 		$result = &js_ready($result);
 6509:     }
 6510:     if ($args->{'html_encode'}) {
 6511: 		$result = &html_encode($result);
 6512:     }
 6513: 
 6514: 	#Breadcrumbs
 6515:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6516: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6517: 		#if any br links exists, add them to the breadcrumbs
 6518: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6519: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6520: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6521: 			}
 6522: 		}
 6523: 
 6524: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6525: 		if(exists($args->{'bread_crumbs_component'})){
 6526: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6527: 		}else{
 6528: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6529: 		}
 6530:     }
 6531:     return $result;
 6532: }
 6533: 
 6534: 
 6535: =pod
 6536: 
 6537: =item * &head()
 6538: 
 6539: Returns a complete </body></html> section for LON-CAPA web pages.
 6540: 
 6541: Inputs:         $args - additional optional args supported are:
 6542:                  js_ready     -> return a string ready for being used in 
 6543:                                  a javascript writeln
 6544:                  html_encode  -> return a string ready for being used in 
 6545:                                  a html attribute
 6546:                  frameset     -> if true will start with a <frameset>
 6547:                                  rather than <body>
 6548:                  dicsussion   -> if true will get discussion from
 6549:                                   lonxml::xmlend
 6550:                                  (you can pass the target and parser arguments
 6551:                                   through optional 'target' and 'parser' args
 6552:                                   to this routine)
 6553: 
 6554: =cut
 6555: 
 6556: sub end_page {
 6557:     my ($args) = @_;
 6558:     $env{'internal.end_page'}++;
 6559:     my $result;
 6560:     if ($args->{'discussion'}) {
 6561: 	my ($target,$parser);
 6562: 	if (ref($args->{'discussion'})) {
 6563: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6564: 				$args->{'discussion'}{'parser'});
 6565: 	}
 6566: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6567:     }
 6568: 
 6569:     if ($args->{'frameset'}) {
 6570: 	$result .= '</frameset>';
 6571:     } else {
 6572: 	$result .= &endbodytag($args);
 6573:     }
 6574:     $result .= "\n</html>";
 6575: 
 6576:     if ($args->{'js_ready'}) {
 6577: 	$result = &js_ready($result);
 6578:     }
 6579: 
 6580:     if ($args->{'html_encode'}) {
 6581: 	$result = &html_encode($result);
 6582:     }
 6583: 
 6584:     return $result;
 6585: }
 6586: 
 6587: sub html_encode {
 6588:     my ($result) = @_;
 6589: 
 6590:     $result = &HTML::Entities::encode($result,'<>&"');
 6591:     
 6592:     return $result;
 6593: }
 6594: sub js_ready {
 6595:     my ($result) = @_;
 6596: 
 6597:     $result =~ s/[\n\r]/ /xmsg;
 6598:     $result =~ s/\\/\\\\/xmsg;
 6599:     $result =~ s/'/\\'/xmsg;
 6600:     $result =~ s{</}{<\\/}xmsg;
 6601:     
 6602:     return $result;
 6603: }
 6604: 
 6605: sub validate_page {
 6606:     if (  exists($env{'internal.start_page'})
 6607: 	  &&     $env{'internal.start_page'} > 1) {
 6608: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6609: 				 $env{'internal.start_page'}.' '.
 6610: 				 $ENV{'request.filename'});
 6611:     }
 6612:     if (  exists($env{'internal.end_page'})
 6613: 	  &&     $env{'internal.end_page'} > 1) {
 6614: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6615: 				 $env{'internal.end_page'}.' '.
 6616: 				 $env{'request.filename'});
 6617:     }
 6618:     if (     exists($env{'internal.start_page'})
 6619: 	&& ! exists($env{'internal.end_page'})) {
 6620: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6621: 				 $env{'request.filename'});
 6622:     }
 6623:     if (   ! exists($env{'internal.start_page'})
 6624: 	&&   exists($env{'internal.end_page'})) {
 6625: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6626: 				 $env{'request.filename'});
 6627:     }
 6628: }
 6629: 
 6630: sub simple_error_page {
 6631:     my ($r,$title,$msg) = @_;
 6632:     my $page =
 6633: 	&Apache::loncommon::start_page($title).
 6634: 	&mt($msg).
 6635: 	&Apache::loncommon::end_page();
 6636:     if (ref($r)) {
 6637: 	$r->print($page);
 6638: 	return;
 6639:     }
 6640:     return $page;
 6641: }
 6642: 
 6643: {
 6644:     my @row_count;
 6645:     sub start_data_table {
 6646: 	my ($add_class) = @_;
 6647: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6648: 	unshift(@row_count,0);
 6649: 	return '<table class="'.$css_class.'">'."\n";
 6650:     }
 6651: 
 6652:     sub end_data_table {
 6653: 	shift(@row_count);
 6654: 	return '</table>'."\n";;
 6655:     }
 6656: 
 6657:     sub start_data_table_row {
 6658: 	my ($add_class) = @_;
 6659: 	$row_count[0]++;
 6660: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6661: 	$css_class = (join(' ',$css_class,$add_class));
 6662: 	return  '<tr class="'.$css_class.'">'."\n";;
 6663:     }
 6664:     
 6665:     sub continue_data_table_row {
 6666: 	my ($add_class) = @_;
 6667: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6668: 	$css_class = (join(' ',$css_class,$add_class));
 6669: 	return  '<tr class="'.$css_class.'">'."\n";;
 6670:     }
 6671: 
 6672:     sub end_data_table_row {
 6673: 	return '</tr>'."\n";;
 6674:     }
 6675: 
 6676:     sub start_data_table_empty_row {
 6677: #	$row_count[0]++;
 6678: 	return  '<tr class="LC_empty_row" >'."\n";;
 6679:     }
 6680: 
 6681:     sub end_data_table_empty_row {
 6682: 	return '</tr>'."\n";;
 6683:     }
 6684: 
 6685:     sub start_data_table_header_row {
 6686: 	return  '<tr class="LC_header_row">'."\n";;
 6687:     }
 6688: 
 6689:     sub end_data_table_header_row {
 6690: 	return '</tr>'."\n";;
 6691:     }
 6692: }
 6693: 
 6694: =pod
 6695: 
 6696: =item * &inhibit_menu_check($arg)
 6697: 
 6698: Checks for a inhibitmenu state and generates output to preserve it
 6699: 
 6700: Inputs:         $arg - can be any of
 6701:                      - undef - in which case the return value is a string 
 6702:                                to add  into arguments list of a uri
 6703:                      - 'input' - in which case the return value is a HTML
 6704:                                  <form> <input> field of type hidden to
 6705:                                  preserve the value
 6706:                      - a url - in which case the return value is the url with
 6707:                                the neccesary cgi args added to preserve the
 6708:                                inhibitmenu state
 6709:                      - a ref to a url - no return value, but the string is
 6710:                                         updated to include the neccessary cgi
 6711:                                         args to preserve the inhibitmenu state
 6712: 
 6713: =cut
 6714: 
 6715: sub inhibit_menu_check {
 6716:     my ($arg) = @_;
 6717:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6718:     if ($arg eq 'input') {
 6719: 	if ($env{'form.inhibitmenu'}) {
 6720: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6721: 	} else {
 6722: 	    return
 6723: 	}
 6724:     }
 6725:     if ($env{'form.inhibitmenu'}) {
 6726: 	if (ref($arg)) {
 6727: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6728: 	} elsif ($arg eq '') {
 6729: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6730: 	} else {
 6731: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6732: 	}
 6733:     }
 6734:     if (!ref($arg)) {
 6735: 	return $arg;
 6736:     }
 6737: }
 6738: 
 6739: ###############################################
 6740: 
 6741: =pod
 6742: 
 6743: =back
 6744: 
 6745: =head1 User Information Routines
 6746: 
 6747: =over 4
 6748: 
 6749: =item * &get_users_function()
 6750: 
 6751: Used by &bodytag to determine the current users primary role.
 6752: Returns either 'student','coordinator','admin', or 'author'.
 6753: 
 6754: =cut
 6755: 
 6756: ###############################################
 6757: sub get_users_function {
 6758:     my $function = 'student';
 6759:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6760:         $function='coordinator';
 6761:     }
 6762:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6763:         $function='admin';
 6764:     }
 6765:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6766:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6767:         $function='author';
 6768:     }
 6769:     return $function;
 6770: }
 6771: 
 6772: ###############################################
 6773: 
 6774: =pod
 6775: 
 6776: =item * &check_user_status()
 6777: 
 6778: Determines current status of supplied role for a
 6779: specific user. Roles can be active, previous or future.
 6780: 
 6781: Inputs: 
 6782: user's domain, user's username, course's domain,
 6783: course's number, optional section ID.
 6784: 
 6785: Outputs:
 6786: role status: active, previous or future. 
 6787: 
 6788: =cut
 6789: 
 6790: sub check_user_status {
 6791:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6792:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6793:     my @uroles = keys %userinfo;
 6794:     my $srchstr;
 6795:     my $active_chk = 'none';
 6796:     my $now = time;
 6797:     if (@uroles > 0) {
 6798:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6799:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6800:         } else {
 6801:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6802:         }
 6803:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6804:             my $role_end = 0;
 6805:             my $role_start = 0;
 6806:             $active_chk = 'active';
 6807:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6808:                 $role_end = $1;
 6809:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6810:                     $role_start = $1;
 6811:                 }
 6812:             }
 6813:             if ($role_start > 0) {
 6814:                 if ($now < $role_start) {
 6815:                     $active_chk = 'future';
 6816:                 }
 6817:             }
 6818:             if ($role_end > 0) {
 6819:                 if ($now > $role_end) {
 6820:                     $active_chk = 'previous';
 6821:                 }
 6822:             }
 6823:         }
 6824:     }
 6825:     return $active_chk;
 6826: }
 6827: 
 6828: ###############################################
 6829: 
 6830: =pod
 6831: 
 6832: =item * &get_sections()
 6833: 
 6834: Determines all the sections for a course including
 6835: sections with students and sections containing other roles.
 6836: Incoming parameters: 
 6837: 
 6838: 1. domain
 6839: 2. course number 
 6840: 3. reference to array containing roles for which sections should 
 6841: be gathered (optional).
 6842: 4. reference to array containing status types for which sections 
 6843: should be gathered (optional).
 6844: 
 6845: If the third argument is undefined, sections are gathered for any role. 
 6846: If the fourth argument is undefined, sections are gathered for any status.
 6847: Permissible values are 'active' or 'future' or 'previous'.
 6848:  
 6849: Returns section hash (keys are section IDs, values are
 6850: number of users in each section), subject to the
 6851: optional roles filter, optional status filter 
 6852: 
 6853: =cut
 6854: 
 6855: ###############################################
 6856: sub get_sections {
 6857:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6858:     if (!defined($cdom) || !defined($cnum)) {
 6859:         my $cid =  $env{'request.course.id'};
 6860: 
 6861: 	return if (!defined($cid));
 6862: 
 6863:         $cdom = $env{'course.'.$cid.'.domain'};
 6864:         $cnum = $env{'course.'.$cid.'.num'};
 6865:     }
 6866: 
 6867:     my %sectioncount;
 6868:     my $now = time;
 6869: 
 6870:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6871: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6872: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6873: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6874:         my $start_index = &Apache::loncoursedata::CL_START();
 6875:         my $end_index = &Apache::loncoursedata::CL_END();
 6876:         my $status;
 6877: 	while (my ($student,$data) = each(%$classlist)) {
 6878: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6879: 				                     $data->[$status_index],
 6880:                                                      $data->[$start_index],
 6881:                                                      $data->[$end_index]);
 6882:             if ($stu_status eq 'Active') {
 6883:                 $status = 'active';
 6884:             } elsif ($end < $now) {
 6885:                 $status = 'previous';
 6886:             } elsif ($start > $now) {
 6887:                 $status = 'future';
 6888:             } 
 6889: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6890:                 if ((!defined($possible_status)) || (($status ne '') && 
 6891:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6892: 		    $sectioncount{$section}++;
 6893:                 }
 6894: 	    }
 6895: 	}
 6896:     }
 6897:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6898:     foreach my $user (sort(keys(%courseroles))) {
 6899: 	if ($user !~ /^(\w{2})/) { next; }
 6900: 	my ($role) = ($user =~ /^(\w{2})/);
 6901: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6902: 	my ($section,$status);
 6903: 	if ($role eq 'cr' &&
 6904: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6905: 	    $section=$1;
 6906: 	}
 6907: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6908: 	if (!defined($section) || $section eq '-1') { next; }
 6909:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6910:         if ($end == -1 && $start == -1) {
 6911:             next; #deleted role
 6912:         }
 6913:         if (!defined($possible_status)) { 
 6914:             $sectioncount{$section}++;
 6915:         } else {
 6916:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6917:                 $status = 'active';
 6918:             } elsif ($end < $now) {
 6919:                 $status = 'future';
 6920:             } elsif ($start > $now) {
 6921:                 $status = 'previous';
 6922:             }
 6923:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6924:                 $sectioncount{$section}++;
 6925:             }
 6926:         }
 6927:     }
 6928:     return %sectioncount;
 6929: }
 6930: 
 6931: ###############################################
 6932: 
 6933: =pod
 6934: 
 6935: =item * &get_course_users()
 6936: 
 6937: Retrieves usernames:domains for users in the specified course
 6938: with specific role(s), and access status. 
 6939: 
 6940: Incoming parameters:
 6941: 1. course domain
 6942: 2. course number
 6943: 3. access status: users must have - either active, 
 6944: previous, future, or all.
 6945: 4. reference to array of permissible roles
 6946: 5. reference to array of section restrictions (optional)
 6947: 6. reference to results object (hash of hashes).
 6948: 7. reference to optional userdata hash
 6949: 8. reference to optional statushash
 6950: 9. flag if privileged users (except those set to unhide in
 6951:    course settings) should be excluded    
 6952: Keys of top level results hash are roles.
 6953: Keys of inner hashes are username:domain, with 
 6954: values set to access type.
 6955: Optional userdata hash returns an array with arguments in the 
 6956: same order as loncoursedata::get_classlist() for student data.
 6957: 
 6958: Optional statushash returns
 6959: 
 6960: Entries for end, start, section and status are blank because
 6961: of the possibility of multiple values for non-student roles.
 6962: 
 6963: =cut
 6964: 
 6965: ###############################################
 6966: 
 6967: sub get_course_users {
 6968:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6969:     my %idx = ();
 6970:     my %seclists;
 6971: 
 6972:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6973:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6974:     $idx{end} = &Apache::loncoursedata::CL_END();
 6975:     $idx{start} = &Apache::loncoursedata::CL_START();
 6976:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6977:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6978:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6979:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6980: 
 6981:     if (grep(/^st$/,@{$roles})) {
 6982:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6983:         my $now = time;
 6984:         foreach my $student (keys(%{$classlist})) {
 6985:             my $match = 0;
 6986:             my $secmatch = 0;
 6987:             my $section = $$classlist{$student}[$idx{section}];
 6988:             my $status = $$classlist{$student}[$idx{status}];
 6989:             if ($section eq '') {
 6990:                 $section = 'none';
 6991:             }
 6992:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6993:                 if (grep(/^all$/,@{$sections})) {
 6994:                     $secmatch = 1;
 6995:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6996:                     if (grep(/^none$/,@{$sections})) {
 6997:                         $secmatch = 1;
 6998:                     }
 6999:                 } else {  
 7000: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7001: 		        $secmatch = 1;
 7002:                     }
 7003: 		}
 7004:                 if (!$secmatch) {
 7005:                     next;
 7006:                 }
 7007:             }
 7008:             if (defined($$types{'active'})) {
 7009:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7010:                     push(@{$$users{st}{$student}},'active');
 7011:                     $match = 1;
 7012:                 }
 7013:             }
 7014:             if (defined($$types{'previous'})) {
 7015:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7016:                     push(@{$$users{st}{$student}},'previous');
 7017:                     $match = 1;
 7018:                 }
 7019:             }
 7020:             if (defined($$types{'future'})) {
 7021:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7022:                     push(@{$$users{st}{$student}},'future');
 7023:                     $match = 1;
 7024:                 }
 7025:             }
 7026:             if ($match) {
 7027:                 push(@{$seclists{$student}},$section);
 7028:                 if (ref($userdata) eq 'HASH') {
 7029:                     $$userdata{$student} = $$classlist{$student};
 7030:                 }
 7031:                 if (ref($statushash) eq 'HASH') {
 7032:                     $statushash->{$student}{'st'}{$section} = $status;
 7033:                 }
 7034:             }
 7035:         }
 7036:     }
 7037:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7038:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7039:         my $now = time;
 7040:         my %displaystatus = ( previous => 'Expired',
 7041:                               active   => 'Active',
 7042:                               future   => 'Future',
 7043:                             );
 7044:         my %nothide;
 7045:         if ($hidepriv) {
 7046:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7047:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7048:                 if ($user !~ /:/) {
 7049:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7050:                 } else {
 7051:                     $nothide{$user} = 1;
 7052:                 }
 7053:             }
 7054:         }
 7055:         foreach my $person (sort(keys(%coursepersonnel))) {
 7056:             my $match = 0;
 7057:             my $secmatch = 0;
 7058:             my $status;
 7059:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7060:             $user =~ s/:$//;
 7061:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7062:             if ($end == -1 || $start == -1) {
 7063:                 next;
 7064:             }
 7065:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7066:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7067:                 my ($uname,$udom) = split(/:/,$user);
 7068:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7069:                     if (grep(/^all$/,@{$sections})) {
 7070:                         $secmatch = 1;
 7071:                     } elsif ($usec eq '') {
 7072:                         if (grep(/^none$/,@{$sections})) {
 7073:                             $secmatch = 1;
 7074:                         }
 7075:                     } else {
 7076:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7077:                             $secmatch = 1;
 7078:                         }
 7079:                     }
 7080:                     if (!$secmatch) {
 7081:                         next;
 7082:                     }
 7083:                 }
 7084:                 if ($usec eq '') {
 7085:                     $usec = 'none';
 7086:                 }
 7087:                 if ($uname ne '' && $udom ne '') {
 7088:                     if ($hidepriv) {
 7089:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7090:                             (!$nothide{$uname.':'.$udom})) {
 7091:                             next;
 7092:                         }
 7093:                     }
 7094:                     if ($end > 0 && $end < $now) {
 7095:                         $status = 'previous';
 7096:                     } elsif ($start > $now) {
 7097:                         $status = 'future';
 7098:                     } else {
 7099:                         $status = 'active';
 7100:                     }
 7101:                     foreach my $type (keys(%{$types})) { 
 7102:                         if ($status eq $type) {
 7103:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7104:                                 push(@{$$users{$role}{$user}},$type);
 7105:                             }
 7106:                             $match = 1;
 7107:                         }
 7108:                     }
 7109:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7110:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7111: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7112:                         }
 7113:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7114:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7115:                         }
 7116:                         if (ref($statushash) eq 'HASH') {
 7117:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7118:                         }
 7119:                     }
 7120:                 }
 7121:             }
 7122:         }
 7123:         if (grep(/^ow$/,@{$roles})) {
 7124:             if ((defined($cdom)) && (defined($cnum))) {
 7125:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7126:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7127:                     my $owner = $csettings{'internal.courseowner'};
 7128:                     next if ($owner eq '');
 7129:                     my ($ownername,$ownerdom);
 7130:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7131:                         $ownername = $1;
 7132:                         $ownerdom = $2;
 7133:                     } else {
 7134:                         $ownername = $owner;
 7135:                         $ownerdom = $cdom;
 7136:                         $owner = $ownername.':'.$ownerdom;
 7137:                     }
 7138:                     @{$$users{'ow'}{$owner}} = 'any';
 7139:                     if (defined($userdata) && 
 7140: 			!exists($$userdata{$owner})) {
 7141: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7142:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7143:                             push(@{$seclists{$owner}},'none');
 7144:                         }
 7145:                         if (ref($statushash) eq 'HASH') {
 7146:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7147:                         }
 7148: 		    }
 7149:                 }
 7150:             }
 7151:         }
 7152:         foreach my $user (keys(%seclists)) {
 7153:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7154:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7155:         }
 7156:     }
 7157:     return;
 7158: }
 7159: 
 7160: sub get_user_info {
 7161:     my ($udom,$uname,$idx,$userdata) = @_;
 7162:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7163: 	&plainname($uname,$udom,'lastname');
 7164:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7165:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7166:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7167:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7168:     return;
 7169: }
 7170: 
 7171: ###############################################
 7172: 
 7173: =pod
 7174: 
 7175: =item * &get_user_quota()
 7176: 
 7177: Retrieves quota assigned for storage of portfolio files for a user  
 7178: 
 7179: Incoming parameters:
 7180: 1. user's username
 7181: 2. user's domain
 7182: 
 7183: Returns:
 7184: 1. Disk quota (in Mb) assigned to student.
 7185: 2. (Optional) Type of setting: custom or default
 7186:    (individually assigned or default for user's 
 7187:    institutional status).
 7188: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7189:    or student - types as defined in localenroll::inst_usertypes 
 7190:    for user's domain, which determines default quota for user.
 7191: 4. (Optional) - Default quota which would apply to the user.
 7192: 
 7193: If a value has been stored in the user's environment, 
 7194: it will return that, otherwise it returns the maximal default
 7195: defined for the user's instituional status(es) in the domain.
 7196: 
 7197: =cut
 7198: 
 7199: ###############################################
 7200: 
 7201: 
 7202: sub get_user_quota {
 7203:     my ($uname,$udom) = @_;
 7204:     my ($quota,$quotatype,$settingstatus,$defquota);
 7205:     if (!defined($udom)) {
 7206:         $udom = $env{'user.domain'};
 7207:     }
 7208:     if (!defined($uname)) {
 7209:         $uname = $env{'user.name'};
 7210:     }
 7211:     if (($udom eq '' || $uname eq '') ||
 7212:         ($udom eq 'public') && ($uname eq 'public')) {
 7213:         $quota = 0;
 7214:         $quotatype = 'default';
 7215:         $defquota = 0; 
 7216:     } else {
 7217:         my $inststatus;
 7218:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7219:             $quota = $env{'environment.portfolioquota'};
 7220:             $inststatus = $env{'environment.inststatus'};
 7221:         } else {
 7222:             my %userenv = 
 7223:                 &Apache::lonnet::get('environment',['portfolioquota',
 7224:                                      'inststatus'],$udom,$uname);
 7225:             my ($tmp) = keys(%userenv);
 7226:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7227:                 $quota = $userenv{'portfolioquota'};
 7228:                 $inststatus = $userenv{'inststatus'};
 7229:             } else {
 7230:                 undef(%userenv);
 7231:             }
 7232:         }
 7233:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7234:         if ($quota eq '') {
 7235:             $quota = $defquota;
 7236:             $quotatype = 'default';
 7237:         } else {
 7238:             $quotatype = 'custom';
 7239:         }
 7240:     }
 7241:     if (wantarray) {
 7242:         return ($quota,$quotatype,$settingstatus,$defquota);
 7243:     } else {
 7244:         return $quota;
 7245:     }
 7246: }
 7247: 
 7248: ###############################################
 7249: 
 7250: =pod
 7251: 
 7252: =item * &default_quota()
 7253: 
 7254: Retrieves default quota assigned for storage of user portfolio files,
 7255: given an (optional) user's institutional status.
 7256: 
 7257: Incoming parameters:
 7258: 1. domain
 7259: 2. (Optional) institutional status(es).  This is a : separated list of 
 7260:    status types (e.g., faculty, staff, student etc.)
 7261:    which apply to the user for whom the default is being retrieved.
 7262:    If the institutional status string in undefined, the domain
 7263:    default quota will be returned. 
 7264: 
 7265: Returns:
 7266: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7267: 2. (Optional) institutional type which determined the value of the
 7268:    default quota.
 7269: 
 7270: If a value has been stored in the domain's configuration db,
 7271: it will return that, otherwise it returns 20 (for backwards 
 7272: compatibility with domains which have not set up a configuration
 7273: db file; the original statically defined portfolio quota was 20 Mb). 
 7274: 
 7275: If the user's status includes multiple types (e.g., staff and student),
 7276: the largest default quota which applies to the user determines the
 7277: default quota returned.
 7278: 
 7279: =back
 7280: 
 7281: =cut
 7282: 
 7283: ###############################################
 7284: 
 7285: 
 7286: sub default_quota {
 7287:     my ($udom,$inststatus) = @_;
 7288:     my ($defquota,$settingstatus);
 7289:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7290:                                             ['quotas'],$udom);
 7291:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7292:         if ($inststatus ne '') {
 7293:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7294:             foreach my $item (@statuses) {
 7295:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7296:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7297:                         if ($defquota eq '') {
 7298:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7299:                             $settingstatus = $item;
 7300:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7301:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7302:                             $settingstatus = $item;
 7303:                         }
 7304:                     }
 7305:                 } else {
 7306:                     if ($quotahash{'quotas'}{$item} ne '') {
 7307:                         if ($defquota eq '') {
 7308:                             $defquota = $quotahash{'quotas'}{$item};
 7309:                             $settingstatus = $item;
 7310:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7311:                             $defquota = $quotahash{'quotas'}{$item};
 7312:                             $settingstatus = $item;
 7313:                         }
 7314:                     }
 7315:                 }
 7316:             }
 7317:         }
 7318:         if ($defquota eq '') {
 7319:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7320:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7321:             } else {
 7322:                 $defquota = $quotahash{'quotas'}{'default'};
 7323:             }
 7324:             $settingstatus = 'default';
 7325:         }
 7326:     } else {
 7327:         $settingstatus = 'default';
 7328:         $defquota = 20;
 7329:     }
 7330:     if (wantarray) {
 7331:         return ($defquota,$settingstatus);
 7332:     } else {
 7333:         return $defquota;
 7334:     }
 7335: }
 7336: 
 7337: sub get_secgrprole_info {
 7338:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7339:     my %sections_count = &get_sections($cdom,$cnum);
 7340:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7341:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7342:     my @groups = sort(keys(%curr_groups));
 7343:     my $allroles = [];
 7344:     my $rolehash;
 7345:     my $accesshash = {
 7346:                      active => 'Currently has access',
 7347:                      future => 'Will have future access',
 7348:                      previous => 'Previously had access',
 7349:                   };
 7350:     if ($needroles) {
 7351:         $rolehash = {'all' => 'all'};
 7352:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7353: 	if (&Apache::lonnet::error(%user_roles)) {
 7354: 	    undef(%user_roles);
 7355: 	}
 7356:         foreach my $item (keys(%user_roles)) {
 7357:             my ($role)=split(/\:/,$item,2);
 7358:             if ($role eq 'cr') { next; }
 7359:             if ($role =~ /^cr/) {
 7360:                 $$rolehash{$role} = (split('/',$role))[3];
 7361:             } else {
 7362:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7363:             }
 7364:         }
 7365:         foreach my $key (sort(keys(%{$rolehash}))) {
 7366:             push(@{$allroles},$key);
 7367:         }
 7368:         push (@{$allroles},'st');
 7369:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7370:     }
 7371:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7372: }
 7373: 
 7374: sub user_picker {
 7375:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7376:     my $currdom = $dom;
 7377:     my %curr_selected = (
 7378:                         srchin => 'dom',
 7379:                         srchby => 'lastname',
 7380:                       );
 7381:     my $srchterm;
 7382:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7383:         if ($srch->{'srchby'} ne '') {
 7384:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7385:         }
 7386:         if ($srch->{'srchin'} ne '') {
 7387:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7388:         }
 7389:         if ($srch->{'srchtype'} ne '') {
 7390:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7391:         }
 7392:         if ($srch->{'srchdomain'} ne '') {
 7393:             $currdom = $srch->{'srchdomain'};
 7394:         }
 7395:         $srchterm = $srch->{'srchterm'};
 7396:     }
 7397:     my %lt=&Apache::lonlocal::texthash(
 7398:                     'usr'       => 'Search criteria',
 7399:                     'doma'      => 'Domain/institution to search',
 7400:                     'uname'     => 'username',
 7401:                     'lastname'  => 'last name',
 7402:                     'lastfirst' => 'last name, first name',
 7403:                     'crs'       => 'in this course',
 7404:                     'dom'       => 'in selected LON-CAPA domain', 
 7405:                     'alc'       => 'all LON-CAPA',
 7406:                     'instd'     => 'in institutional directory for selected domain',
 7407:                     'exact'     => 'is',
 7408:                     'contains'  => 'contains',
 7409:                     'begins'    => 'begins with',
 7410:                     'youm'      => "You must include some text to search for.",
 7411:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7412:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7413:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7414:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7415:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7416:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7417:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7418:                                        );
 7419:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7420:     my $srchinsel = ' <select name="srchin">';
 7421: 
 7422:     my @srchins = ('crs','dom','alc','instd');
 7423: 
 7424:     foreach my $option (@srchins) {
 7425:         # FIXME 'alc' option unavailable until 
 7426:         #       loncreateuser::print_user_query_page()
 7427:         #       has been completed.
 7428:         next if ($option eq 'alc');
 7429:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7430:         if ($curr_selected{'srchin'} eq $option) {
 7431:             $srchinsel .= ' 
 7432:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7433:         } else {
 7434:             $srchinsel .= '
 7435:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7436:         }
 7437:     }
 7438:     $srchinsel .= "\n  </select>\n";
 7439: 
 7440:     my $srchbysel =  ' <select name="srchby">';
 7441:     foreach my $option ('lastname','lastfirst','uname') {
 7442:         if ($curr_selected{'srchby'} eq $option) {
 7443:             $srchbysel .= '
 7444:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7445:         } else {
 7446:             $srchbysel .= '
 7447:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7448:          }
 7449:     }
 7450:     $srchbysel .= "\n  </select>\n";
 7451: 
 7452:     my $srchtypesel = ' <select name="srchtype">';
 7453:     foreach my $option ('begins','contains','exact') {
 7454:         if ($curr_selected{'srchtype'} eq $option) {
 7455:             $srchtypesel .= '
 7456:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7457:         } else {
 7458:             $srchtypesel .= '
 7459:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7460:         }
 7461:     }
 7462:     $srchtypesel .= "\n  </select>\n";
 7463: 
 7464:     my ($newuserscript,$new_user_create);
 7465: 
 7466:     if ($forcenewuser) {
 7467:         if (ref($srch) eq 'HASH') {
 7468:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7469:                 if ($cancreate) {
 7470:                     $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>';
 7471:                 } else {
 7472:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7473:                     my %usertypetext = (
 7474:                         official   => 'institutional',
 7475:                         unofficial => 'non-institutional',
 7476:                     );
 7477:                     $new_user_create = '<p class="LC_warning">'
 7478:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7479:                                       .' '
 7480:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7481:                                           ,'<a href="'.$helplink.'">','</a>')
 7482:                                       .'</p><br />';
 7483:                 }
 7484:             }
 7485:         }
 7486: 
 7487:         $newuserscript = <<"ENDSCRIPT";
 7488: 
 7489: function setSearch(createnew,callingForm) {
 7490:     if (createnew == 1) {
 7491:         for (var i=0; i<callingForm.srchby.length; i++) {
 7492:             if (callingForm.srchby.options[i].value == 'uname') {
 7493:                 callingForm.srchby.selectedIndex = i;
 7494:             }
 7495:         }
 7496:         for (var i=0; i<callingForm.srchin.length; i++) {
 7497:             if ( callingForm.srchin.options[i].value == 'dom') {
 7498: 		callingForm.srchin.selectedIndex = i;
 7499:             }
 7500:         }
 7501:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7502:             if (callingForm.srchtype.options[i].value == 'exact') {
 7503:                 callingForm.srchtype.selectedIndex = i;
 7504:             }
 7505:         }
 7506:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7507:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7508:                 callingForm.srchdomain.selectedIndex = i;
 7509:             }
 7510:         }
 7511:     }
 7512: }
 7513: ENDSCRIPT
 7514: 
 7515:     }
 7516: 
 7517:     my $output = <<"END_BLOCK";
 7518: <script type="text/javascript">
 7519: function validateEntry(callingForm) {
 7520: 
 7521:     var checkok = 1;
 7522:     var srchin;
 7523:     for (var i=0; i<callingForm.srchin.length; i++) {
 7524: 	if ( callingForm.srchin[i].checked ) {
 7525: 	    srchin = callingForm.srchin[i].value;
 7526: 	}
 7527:     }
 7528: 
 7529:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7530:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7531:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7532:     var srchterm =  callingForm.srchterm.value;
 7533:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7534:     var msg = "";
 7535: 
 7536:     if (srchterm == "") {
 7537:         checkok = 0;
 7538:         msg += "$lt{'youm'}\\n";
 7539:     }
 7540: 
 7541:     if (srchtype== 'begins') {
 7542:         if (srchterm.length < 2) {
 7543:             checkok = 0;
 7544:             msg += "$lt{'thte'}\\n";
 7545:         }
 7546:     }
 7547: 
 7548:     if (srchtype== 'contains') {
 7549:         if (srchterm.length < 3) {
 7550:             checkok = 0;
 7551:             msg += "$lt{'thet'}\\n";
 7552:         }
 7553:     }
 7554:     if (srchin == 'instd') {
 7555:         if (srchdomain == '') {
 7556:             checkok = 0;
 7557:             msg += "$lt{'yomc'}\\n";
 7558:         }
 7559:     }
 7560:     if (srchin == 'dom') {
 7561:         if (srchdomain == '') {
 7562:             checkok = 0;
 7563:             msg += "$lt{'ymcd'}\\n";
 7564:         }
 7565:     }
 7566:     if (srchby == 'lastfirst') {
 7567:         if (srchterm.indexOf(",") == -1) {
 7568:             checkok = 0;
 7569:             msg += "$lt{'whus'}\\n";
 7570:         }
 7571:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7572:             checkok = 0;
 7573:             msg += "$lt{'whse'}\\n";
 7574:         }
 7575:     }
 7576:     if (checkok == 0) {
 7577:         alert("$lt{'thfo'}\\n"+msg);
 7578:         return;
 7579:     }
 7580:     if (checkok == 1) {
 7581:         callingForm.submit();
 7582:     }
 7583: }
 7584: 
 7585: $newuserscript
 7586: 
 7587: </script>
 7588: 
 7589: $new_user_create
 7590: 
 7591: <table>
 7592:  <tr>
 7593:   <td>$lt{'doma'}:</td>
 7594:   <td>$domform</td>
 7595:   </td>
 7596:  </tr>
 7597:  <tr>
 7598:   <td>$lt{'usr'}:</td>
 7599:   <td>$srchbysel
 7600:       $srchtypesel 
 7601:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7602:       $srchinsel 
 7603:   </td>
 7604:  </tr>
 7605: </table>
 7606: <br />
 7607: END_BLOCK
 7608: 
 7609:     return $output;
 7610: }
 7611: 
 7612: sub user_rule_check {
 7613:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7614:     my $response;
 7615:     if (ref($usershash) eq 'HASH') {
 7616:         foreach my $user (keys(%{$usershash})) {
 7617:             my ($uname,$udom) = split(/:/,$user);
 7618:             next if ($udom eq '' || $uname eq '');
 7619:             my ($id,$newuser);
 7620:             if (ref($usershash->{$user}) eq 'HASH') {
 7621:                 $newuser = $usershash->{$user}->{'newuser'};
 7622:                 $id = $usershash->{$user}->{'id'};
 7623:             }
 7624:             my $inst_response;
 7625:             if (ref($checks) eq 'HASH') {
 7626:                 if (defined($checks->{'username'})) {
 7627:                     ($inst_response,%{$inst_results->{$user}}) = 
 7628:                         &Apache::lonnet::get_instuser($udom,$uname);
 7629:                 } elsif (defined($checks->{'id'})) {
 7630:                     ($inst_response,%{$inst_results->{$user}}) =
 7631:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7632:                 }
 7633:             } else {
 7634:                 ($inst_response,%{$inst_results->{$user}}) =
 7635:                     &Apache::lonnet::get_instuser($udom,$uname);
 7636:                 return;
 7637:             }
 7638:             if (!$got_rules->{$udom}) {
 7639:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7640:                                                   ['usercreation'],$udom);
 7641:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7642:                     foreach my $item ('username','id') {
 7643:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7644:                             $$curr_rules{$udom}{$item} = 
 7645:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7646:                         }
 7647:                     }
 7648:                 }
 7649:                 $got_rules->{$udom} = 1;  
 7650:             }
 7651:             foreach my $item (keys(%{$checks})) {
 7652:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7653:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7654:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7655:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7656:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7657:                                 if ($rule_check{$rule}) {
 7658:                                     $$rulematch{$user}{$item} = $rule;
 7659:                                     if ($inst_response eq 'ok') {
 7660:                                         if (ref($inst_results) eq 'HASH') {
 7661:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7662:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7663:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7664:                                                 }
 7665:                                             }
 7666:                                         }
 7667:                                     }
 7668:                                     last;
 7669:                                 }
 7670:                             }
 7671:                         }
 7672:                     }
 7673:                 }
 7674:             }
 7675:         }
 7676:     }
 7677:     return;
 7678: }
 7679: 
 7680: sub user_rule_formats {
 7681:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7682:     my %text = ( 
 7683:                  'username' => 'Usernames',
 7684:                  'id'       => 'IDs',
 7685:                );
 7686:     my $output;
 7687:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7688:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7689:         if (@{$ruleorder} > 0) {
 7690:             $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>';
 7691:             foreach my $rule (@{$ruleorder}) {
 7692:                 if (ref($curr_rules) eq 'ARRAY') {
 7693:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7694:                         if (ref($rules->{$rule}) eq 'HASH') {
 7695:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7696:                                         $rules->{$rule}{'desc'}.'</li>';
 7697:                         }
 7698:                     }
 7699:                 }
 7700:             }
 7701:             $output .= '</ul>';
 7702:         }
 7703:     }
 7704:     return $output;
 7705: }
 7706: 
 7707: sub instrule_disallow_msg {
 7708:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7709:     my $response;
 7710:     my %text = (
 7711:                   item   => 'username',
 7712:                   items  => 'usernames',
 7713:                   match  => 'matches',
 7714:                   do     => 'does',
 7715:                   action => 'a username',
 7716:                   one    => 'one',
 7717:                );
 7718:     if ($count > 1) {
 7719:         $text{'item'} = 'usernames';
 7720:         $text{'match'} ='match';
 7721:         $text{'do'} = 'do';
 7722:         $text{'action'} = 'usernames',
 7723:         $text{'one'} = 'ones';
 7724:     }
 7725:     if ($checkitem eq 'id') {
 7726:         $text{'items'} = 'IDs';
 7727:         $text{'item'} = 'ID';
 7728:         $text{'action'} = 'an ID';
 7729:         if ($count > 1) {
 7730:             $text{'item'} = 'IDs';
 7731:             $text{'action'} = 'IDs';
 7732:         }
 7733:     }
 7734:     $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 />';
 7735:     if ($mode eq 'upload') {
 7736:         if ($checkitem eq 'username') {
 7737:             $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'}.");
 7738:         } elsif ($checkitem eq 'id') {
 7739:             $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.");
 7740:         }
 7741:     } elsif ($mode eq 'selfcreate') {
 7742:         if ($checkitem eq 'id') {
 7743:             $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.");
 7744:         }
 7745:     } else {
 7746:         if ($checkitem eq 'username') {
 7747:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7748:         } elsif ($checkitem eq 'id') {
 7749:             $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.");
 7750:         }
 7751:     }
 7752:     return $response;
 7753: }
 7754: 
 7755: sub personal_data_fieldtitles {
 7756:     my %fieldtitles = &Apache::lonlocal::texthash (
 7757:                         id => 'Student/Employee ID',
 7758:                         permanentemail => 'E-mail address',
 7759:                         lastname => 'Last Name',
 7760:                         firstname => 'First Name',
 7761:                         middlename => 'Middle Name',
 7762:                         generation => 'Generation',
 7763:                         gen => 'Generation',
 7764:                         inststatus => 'Affiliation',
 7765:                    );
 7766:     return %fieldtitles;
 7767: }
 7768: 
 7769: sub sorted_inst_types {
 7770:     my ($dom) = @_;
 7771:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7772:     my $othertitle = &mt('All users');
 7773:     if ($env{'request.course.id'}) {
 7774:         $othertitle  = &mt('Any users');
 7775:     }
 7776:     my @types;
 7777:     if (ref($order) eq 'ARRAY') {
 7778:         @types = @{$order};
 7779:     }
 7780:     if (@types == 0) {
 7781:         if (ref($usertypes) eq 'HASH') {
 7782:             @types = sort(keys(%{$usertypes}));
 7783:         }
 7784:     }
 7785:     if (keys(%{$usertypes}) > 0) {
 7786:         $othertitle = &mt('Other users');
 7787:     }
 7788:     return ($othertitle,$usertypes,\@types);
 7789: }
 7790: 
 7791: sub get_institutional_codes {
 7792:     my ($settings,$allcourses,$LC_code) = @_;
 7793: # Get complete list of course sections to update
 7794:     my @currsections = ();
 7795:     my @currxlists = ();
 7796:     my $coursecode = $$settings{'internal.coursecode'};
 7797: 
 7798:     if ($$settings{'internal.sectionnums'} ne '') {
 7799:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7800:     }
 7801: 
 7802:     if ($$settings{'internal.crosslistings'} ne '') {
 7803:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7804:     }
 7805: 
 7806:     if (@currxlists > 0) {
 7807:         foreach (@currxlists) {
 7808:             if (m/^([^:]+):(\w*)$/) {
 7809:                 unless (grep/^$1$/,@{$allcourses}) {
 7810:                     push @{$allcourses},$1;
 7811:                     $$LC_code{$1} = $2;
 7812:                 }
 7813:             }
 7814:         }
 7815:     }
 7816:  
 7817:     if (@currsections > 0) {
 7818:         foreach (@currsections) {
 7819:             if (m/^(\w+):(\w*)$/) {
 7820:                 my $sec = $coursecode.$1;
 7821:                 my $lc_sec = $2;
 7822:                 unless (grep/^$sec$/,@{$allcourses}) {
 7823:                     push @{$allcourses},$sec;
 7824:                     $$LC_code{$sec} = $lc_sec;
 7825:                 }
 7826:             }
 7827:         }
 7828:     }
 7829:     return;
 7830: }
 7831: 
 7832: =pod
 7833: 
 7834: =head1 Slot Helpers
 7835: 
 7836: =over 4
 7837: 
 7838: =item * sorted_slots()
 7839: 
 7840: Sorts an array of slot names in order of slot start time (earliest first). 
 7841: 
 7842: Inputs:
 7843: 
 7844: =over 4
 7845: 
 7846: slotsarr  - Reference to array of unsorted slot names.
 7847: 
 7848: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7849: 
 7850: =back
 7851: 
 7852: Returns:
 7853: 
 7854: =over 4
 7855: 
 7856: sorted   - An array of slot names sorted by the start time of the slot.
 7857: 
 7858: =back
 7859: 
 7860: =back
 7861: 
 7862: =cut
 7863: 
 7864: 
 7865: sub sorted_slots {
 7866:     my ($slotsarr,$slots) = @_;
 7867:     my @sorted;
 7868:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7869:         @sorted =
 7870:             sort {
 7871:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7872:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7873:                      }
 7874:                      if (ref($slots->{$a})) { return -1;}
 7875:                      if (ref($slots->{$b})) { return 1;}
 7876:                      return 0;
 7877:                  } @{$slotsarr};
 7878:     }
 7879:     return @sorted;
 7880: }
 7881: 
 7882: 
 7883: =pod
 7884: 
 7885: =head1 HTTP Helpers
 7886: 
 7887: =over 4
 7888: 
 7889: =item * &get_unprocessed_cgi($query,$possible_names)
 7890: 
 7891: Modify the %env hash to contain unprocessed CGI form parameters held in
 7892: $query.  The parameters listed in $possible_names (an array reference),
 7893: will be set in $env{'form.name'} if they do not already exist.
 7894: 
 7895: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7896: $possible_names is an ref to an array of form element names.  As an example:
 7897: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7898: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7899: 
 7900: =cut
 7901: 
 7902: sub get_unprocessed_cgi {
 7903:   my ($query,$possible_names)= @_;
 7904:   # $Apache::lonxml::debug=1;
 7905:   foreach my $pair (split(/&/,$query)) {
 7906:     my ($name, $value) = split(/=/,$pair);
 7907:     $name = &unescape($name);
 7908:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7909:       $value =~ tr/+/ /;
 7910:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7911:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7912:     }
 7913:   }
 7914: }
 7915: 
 7916: =pod
 7917: 
 7918: =item * &cacheheader() 
 7919: 
 7920: returns cache-controlling header code
 7921: 
 7922: =cut
 7923: 
 7924: sub cacheheader {
 7925:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7926:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7927:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7928:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7929:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7930:     return $output;
 7931: }
 7932: 
 7933: =pod
 7934: 
 7935: =item * &no_cache($r) 
 7936: 
 7937: specifies header code to not have cache
 7938: 
 7939: =cut
 7940: 
 7941: sub no_cache {
 7942:     my ($r) = @_;
 7943:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7944: 	$env{'request.method'} ne 'GET') { return ''; }
 7945:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7946:     $r->no_cache(1);
 7947:     $r->header_out("Expires" => $date);
 7948:     $r->header_out("Pragma" => "no-cache");
 7949: }
 7950: 
 7951: sub content_type {
 7952:     my ($r,$type,$charset) = @_;
 7953:     if ($r) {
 7954: 	#  Note that printout.pl calls this with undef for $r.
 7955: 	&no_cache($r);
 7956:     }
 7957:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7958:     unless ($charset) {
 7959: 	$charset=&Apache::lonlocal::current_encoding;
 7960:     }
 7961:     if ($charset) { $type.='; charset='.$charset; }
 7962:     if ($r) {
 7963: 	$r->content_type($type);
 7964:     } else {
 7965: 	print("Content-type: $type\n\n");
 7966:     }
 7967: }
 7968: 
 7969: =pod
 7970: 
 7971: =item * &add_to_env($name,$value) 
 7972: 
 7973: adds $name to the %env hash with value
 7974: $value, if $name already exists, the entry is converted to an array
 7975: reference and $value is added to the array.
 7976: 
 7977: =cut
 7978: 
 7979: sub add_to_env {
 7980:   my ($name,$value)=@_;
 7981:   if (defined($env{$name})) {
 7982:     if (ref($env{$name})) {
 7983:       #already have multiple values
 7984:       push(@{ $env{$name} },$value);
 7985:     } else {
 7986:       #first time seeing multiple values, convert hash entry to an arrayref
 7987:       my $first=$env{$name};
 7988:       undef($env{$name});
 7989:       push(@{ $env{$name} },$first,$value);
 7990:     }
 7991:   } else {
 7992:     $env{$name}=$value;
 7993:   }
 7994: }
 7995: 
 7996: =pod
 7997: 
 7998: =item * &get_env_multiple($name) 
 7999: 
 8000: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8001: values may be defined and end up as an array ref.
 8002: 
 8003: returns an array of values
 8004: 
 8005: =cut
 8006: 
 8007: sub get_env_multiple {
 8008:     my ($name) = @_;
 8009:     my @values;
 8010:     if (defined($env{$name})) {
 8011:         # exists is it an array
 8012:         if (ref($env{$name})) {
 8013:             @values=@{ $env{$name} };
 8014:         } else {
 8015:             $values[0]=$env{$name};
 8016:         }
 8017:     }
 8018:     return(@values);
 8019: }
 8020: 
 8021: sub ask_for_embedded_content {
 8022:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8023:     my $upload_output = '
 8024:    <form name="upload_embedded" action="'.$actionurl.'"
 8025:                   method="post" enctype="multipart/form-data">';
 8026:     $upload_output .= $state;
 8027:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8028: 
 8029:     my $num = 0;
 8030:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8031:         $upload_output .= &start_data_table_row().
 8032:             '<td>'.$embed_file.'</td><td>';
 8033:         if ($args->{'ignore_remote_references'}
 8034:             && $embed_file =~ m{^\w+://}) {
 8035:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8036:         } elsif ($args->{'error_on_invalid_names'}
 8037:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8038: 
 8039:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8040: 
 8041:         } else {
 8042:             $upload_output .='
 8043:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8044:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8045:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8046:             $upload_output .=
 8047:                 "\n\t\t".
 8048:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8049:                 $attrib.'" />';
 8050:             if (exists($$codebase{$embed_file})) {
 8051:                 $upload_output .=
 8052:                     "\n\t\t".
 8053:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8054:                     &escape($$codebase{$embed_file}).'" />';
 8055:             }
 8056:         }
 8057:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8058:         $num++;
 8059:     }
 8060:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8061:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8062:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8063:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8064:    </form>';
 8065:     return $upload_output;
 8066: }
 8067: 
 8068: sub upload_embedded {
 8069:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8070:         $current_disk_usage) = @_;
 8071:     my $output;
 8072:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8073:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8074:         my $orig_uploaded_filename =
 8075:             $env{'form.embedded_item_'.$i.'.filename'};
 8076: 
 8077:         $env{'form.embedded_orig_'.$i} =
 8078:             &unescape($env{'form.embedded_orig_'.$i});
 8079:         my ($path,$fname) =
 8080:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8081:         # no path, whole string is fname
 8082:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8083: 
 8084:         $path = $env{'form.currentpath'}.$path;
 8085:         $fname = &Apache::lonnet::clean_filename($fname);
 8086:         # See if there is anything left
 8087:         next if ($fname eq '');
 8088: 
 8089:         # Check if file already exists as a file or directory.
 8090:         my ($state,$msg);
 8091:         if ($context eq 'portfolio') {
 8092:             my $port_path = $dirpath;
 8093:             if ($group ne '') {
 8094:                 $port_path = "groups/$group/$port_path";
 8095:             }
 8096:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8097:                                               $dir_root,$port_path,$disk_quota,
 8098:                                               $current_disk_usage,$uname,$udom);
 8099:             if ($state eq 'will_exceed_quota'
 8100:                 || $state eq 'file_locked'
 8101:                 || $state eq 'file_exists' ) {
 8102:                 $output .= $msg;
 8103:                 next;
 8104:             }
 8105:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8106:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8107:             if ($state eq 'exists') {
 8108:                 $output .= $msg;
 8109:                 next;
 8110:             }
 8111:         }
 8112:         # Check if extension is valid
 8113:         if (($fname =~ /\.(\w+)$/) &&
 8114:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8115:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8116:             next;
 8117:         } elsif (($fname =~ /\.(\w+)$/) &&
 8118:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8119:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8120:             next;
 8121:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8122:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8123:             next;
 8124:         }
 8125: 
 8126:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8127:         if ($context eq 'portfolio') {
 8128:             my $result=
 8129:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8130:                                                 $dirpath.$path);
 8131:             if ($result !~ m|^/uploaded/|) {
 8132:                 $output .= '<span class="LC_error">'
 8133:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8134:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8135:                       .'</span><br />';
 8136:                 next;
 8137:             } else {
 8138:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8139:                            $path.$fname.'</span>').'</p>';     
 8140:             }
 8141:         } else {
 8142: # Save the file
 8143:             my $target = $env{'form.embedded_item_'.$i};
 8144:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8145:             my $dest = $fullpath.$fname;
 8146:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8147:             my @parts=split(/\//,$fullpath);
 8148:             my $count;
 8149:             my $filepath = $dir_root;
 8150:             for ($count=4;$count<=$#parts;$count++) {
 8151:                 $filepath .= "/$parts[$count]";
 8152:                 if ((-e $filepath)!=1) {
 8153:                     mkdir($filepath,0770);
 8154:                 }
 8155:             }
 8156:             my $fh;
 8157:             if (!open($fh,'>'.$dest)) {
 8158:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8159:                 $output .= '<span class="LC_error">'.
 8160:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8161:                            '</span><br />';
 8162:             } else {
 8163:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8164:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8165:                     $output .= '<span class="LC_error">'.
 8166:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8167:                               '</span><br />';
 8168:                 } else {
 8169:                     if ($context eq 'testbank') {
 8170:                         $output .= &mt('Embedded file uploaded successfully:').
 8171:                                    '&nbsp;<a href="'.$url.'">'.
 8172:                                    $orig_uploaded_filename.'</a><br />';
 8173:                     } else {
 8174:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8175:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8176:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8177:                     }
 8178:                 }
 8179:                 close($fh);
 8180:             }
 8181:         }
 8182:     }
 8183:     return $output;
 8184: }
 8185: 
 8186: sub check_for_existing {
 8187:     my ($path,$fname,$element) = @_;
 8188:     my ($state,$msg);
 8189:     if (-d $path.'/'.$fname) {
 8190:         $state = 'exists';
 8191:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8192:     } elsif (-e $path.'/'.$fname) {
 8193:         $state = 'exists';
 8194:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8195:     }
 8196:     if ($state eq 'exists') {
 8197:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8198:     }
 8199:     return ($state,$msg);
 8200: }
 8201: 
 8202: sub check_for_upload {
 8203:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8204:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8205:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8206:     my $getpropath = 1;
 8207:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8208:                                             $getpropath);
 8209:     my $found_file = 0;
 8210:     my $locked_file = 0;
 8211:     foreach my $line (@dir_list) {
 8212:         my ($file_name)=split(/\&/,$line,2);
 8213:         if ($file_name eq $fname){
 8214:             $file_name = $path.$file_name;
 8215:             if ($group ne '') {
 8216:                 $file_name = $group.$file_name;
 8217:             }
 8218:             $found_file = 1;
 8219:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8220:                 $locked_file = 1;
 8221:             }
 8222:         }
 8223:     }
 8224:     if (($current_disk_usage + $filesize) > $disk_quota){
 8225:         my $msg = '<span class="LC_error">'.
 8226:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8227:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8228:         return ('will_exceed_quota',$msg);
 8229:     } elsif ($found_file) {
 8230:         if ($locked_file) {
 8231:             my $msg = '<span class="LC_error">';
 8232:             $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>');
 8233:             $msg .= '</span><br />';
 8234:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8235:             return ('file_locked',$msg);
 8236:         } else {
 8237:             my $msg = '<span class="LC_error">';
 8238:             $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'});
 8239:             $msg .= '</span>';
 8240:             $msg .= '<br />';
 8241:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8242:             return ('file_exists',$msg);
 8243:         }
 8244:     }
 8245: }
 8246: 
 8247: 
 8248: =pod
 8249: 
 8250: =back
 8251: 
 8252: =head1 CSV Upload/Handling functions
 8253: 
 8254: =over 4
 8255: 
 8256: =item * &upfile_store($r)
 8257: 
 8258: Store uploaded file, $r should be the HTTP Request object,
 8259: needs $env{'form.upfile'}
 8260: returns $datatoken to be put into hidden field
 8261: 
 8262: =cut
 8263: 
 8264: sub upfile_store {
 8265:     my $r=shift;
 8266:     $env{'form.upfile'}=~s/\r/\n/gs;
 8267:     $env{'form.upfile'}=~s/\f/\n/gs;
 8268:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8269:     $env{'form.upfile'}=~s/\n+$//gs;
 8270: 
 8271:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8272: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8273:     {
 8274:         my $datafile = $r->dir_config('lonDaemons').
 8275:                            '/tmp/'.$datatoken.'.tmp';
 8276:         if ( open(my $fh,">$datafile") ) {
 8277:             print $fh $env{'form.upfile'};
 8278:             close($fh);
 8279:         }
 8280:     }
 8281:     return $datatoken;
 8282: }
 8283: 
 8284: =pod
 8285: 
 8286: =item * &load_tmp_file($r)
 8287: 
 8288: Load uploaded file from tmp, $r should be the HTTP Request object,
 8289: needs $env{'form.datatoken'},
 8290: sets $env{'form.upfile'} to the contents of the file
 8291: 
 8292: =cut
 8293: 
 8294: sub load_tmp_file {
 8295:     my $r=shift;
 8296:     my @studentdata=();
 8297:     {
 8298:         my $studentfile = $r->dir_config('lonDaemons').
 8299:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8300:         if ( open(my $fh,"<$studentfile") ) {
 8301:             @studentdata=<$fh>;
 8302:             close($fh);
 8303:         }
 8304:     }
 8305:     $env{'form.upfile'}=join('',@studentdata);
 8306: }
 8307: 
 8308: =pod
 8309: 
 8310: =item * &upfile_record_sep()
 8311: 
 8312: Separate uploaded file into records
 8313: returns array of records,
 8314: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8315: 
 8316: =cut
 8317: 
 8318: sub upfile_record_sep {
 8319:     if ($env{'form.upfiletype'} eq 'xml') {
 8320:     } else {
 8321: 	my @records;
 8322: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8323: 	    if ($line=~/^\s*$/) { next; }
 8324: 	    push(@records,$line);
 8325: 	}
 8326: 	return @records;
 8327:     }
 8328: }
 8329: 
 8330: =pod
 8331: 
 8332: =item * &record_sep($record)
 8333: 
 8334: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8335: 
 8336: =cut
 8337: 
 8338: sub takeleft {
 8339:     my $index=shift;
 8340:     return substr('0000'.$index,-4,4);
 8341: }
 8342: 
 8343: sub record_sep {
 8344:     my $record=shift;
 8345:     my %components=();
 8346:     if ($env{'form.upfiletype'} eq 'xml') {
 8347:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8348:         my $i=0;
 8349:         foreach my $field (split(/\s+/,$record)) {
 8350:             $field=~s/^(\"|\')//;
 8351:             $field=~s/(\"|\')$//;
 8352:             $components{&takeleft($i)}=$field;
 8353:             $i++;
 8354:         }
 8355:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8356:         my $i=0;
 8357:         foreach my $field (split(/\t/,$record)) {
 8358:             $field=~s/^(\"|\')//;
 8359:             $field=~s/(\"|\')$//;
 8360:             $components{&takeleft($i)}=$field;
 8361:             $i++;
 8362:         }
 8363:     } else {
 8364:         my $separator=',';
 8365:         if ($env{'form.upfiletype'} eq 'semisv') {
 8366:             $separator=';';
 8367:         }
 8368:         my $i=0;
 8369: # the character we are looking for to indicate the end of a quote or a record 
 8370:         my $looking_for=$separator;
 8371: # do not add the characters to the fields
 8372:         my $ignore=0;
 8373: # we just encountered a separator (or the beginning of the record)
 8374:         my $just_found_separator=1;
 8375: # store the field we are working on here
 8376:         my $field='';
 8377: # work our way through all characters in record
 8378:         foreach my $character ($record=~/(.)/g) {
 8379:             if ($character eq $looking_for) {
 8380:                if ($character ne $separator) {
 8381: # Found the end of a quote, again looking for separator
 8382:                   $looking_for=$separator;
 8383:                   $ignore=1;
 8384:                } else {
 8385: # Found a separator, store away what we got
 8386:                   $components{&takeleft($i)}=$field;
 8387: 	          $i++;
 8388:                   $just_found_separator=1;
 8389:                   $ignore=0;
 8390:                   $field='';
 8391:                }
 8392:                next;
 8393:             }
 8394: # single or double quotation marks after a separator indicate beginning of a quote
 8395: # we are now looking for the end of the quote and need to ignore separators
 8396:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8397:                $looking_for=$character;
 8398:                next;
 8399:             }
 8400: # ignore would be true after we reached the end of a quote
 8401:             if ($ignore) { next; }
 8402:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8403:             $field.=$character;
 8404:             $just_found_separator=0; 
 8405:         }
 8406: # catch the very last entry, since we never encountered the separator
 8407:         $components{&takeleft($i)}=$field;
 8408:     }
 8409:     return %components;
 8410: }
 8411: 
 8412: ######################################################
 8413: ######################################################
 8414: 
 8415: =pod
 8416: 
 8417: =item * &upfile_select_html()
 8418: 
 8419: Return HTML code to select a file from the users machine and specify 
 8420: the file type.
 8421: 
 8422: =cut
 8423: 
 8424: ######################################################
 8425: ######################################################
 8426: sub upfile_select_html {
 8427:     my %Types = (
 8428:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8429:                  semisv => &mt('Semicolon separated values'),
 8430:                  space => &mt('Space separated'),
 8431:                  tab   => &mt('Tabulator separated'),
 8432: #                 xml   => &mt('HTML/XML'),
 8433:                  );
 8434:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8435:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8436:     foreach my $type (sort(keys(%Types))) {
 8437:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8438:     }
 8439:     $Str .= "</select>\n";
 8440:     return $Str;
 8441: }
 8442: 
 8443: sub get_samples {
 8444:     my ($records,$toget) = @_;
 8445:     my @samples=({});
 8446:     my $got=0;
 8447:     foreach my $rec (@$records) {
 8448: 	my %temp = &record_sep($rec);
 8449: 	if (! grep(/\S/, values(%temp))) { next; }
 8450: 	if (%temp) {
 8451: 	    $samples[$got]=\%temp;
 8452: 	    $got++;
 8453: 	    if ($got == $toget) { last; }
 8454: 	}
 8455:     }
 8456:     return \@samples;
 8457: }
 8458: 
 8459: ######################################################
 8460: ######################################################
 8461: 
 8462: =pod
 8463: 
 8464: =item * &csv_print_samples($r,$records)
 8465: 
 8466: Prints a table of sample values from each column uploaded $r is an
 8467: Apache Request ref, $records is an arrayref from
 8468: &Apache::loncommon::upfile_record_sep
 8469: 
 8470: =cut
 8471: 
 8472: ######################################################
 8473: ######################################################
 8474: sub csv_print_samples {
 8475:     my ($r,$records) = @_;
 8476:     my $samples = &get_samples($records,5);
 8477: 
 8478:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8479:               &start_data_table_header_row());
 8480:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8481:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8482:     $r->print(&end_data_table_header_row());
 8483:     foreach my $hash (@$samples) {
 8484: 	$r->print(&start_data_table_row());
 8485: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8486: 	    $r->print('<td>');
 8487: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8488: 	    $r->print('</td>');
 8489: 	}
 8490: 	$r->print(&end_data_table_row());
 8491:     }
 8492:     $r->print(&end_data_table().'<br />'."\n");
 8493: }
 8494: 
 8495: ######################################################
 8496: ######################################################
 8497: 
 8498: =pod
 8499: 
 8500: =item * &csv_print_select_table($r,$records,$d)
 8501: 
 8502: Prints a table to create associations between values and table columns.
 8503: 
 8504: $r is an Apache Request ref,
 8505: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8506: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8507: 
 8508: =cut
 8509: 
 8510: ######################################################
 8511: ######################################################
 8512: sub csv_print_select_table {
 8513:     my ($r,$records,$d) = @_;
 8514:     my $i=0;
 8515:     my $samples = &get_samples($records,1);
 8516:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8517: 	      &start_data_table().&start_data_table_header_row().
 8518:               '<th>'.&mt('Attribute').'</th>'.
 8519:               '<th>'.&mt('Column').'</th>'.
 8520:               &end_data_table_header_row()."\n");
 8521:     foreach my $array_ref (@$d) {
 8522: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8523: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8524: 
 8525: 	$r->print('<td><select name=f'.$i.
 8526: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8527: 	$r->print('<option value="none"></option>');
 8528: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8529: 	    $r->print('<option value="'.$sample.'"'.
 8530:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8531:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8532: 	}
 8533: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8534: 	$i++;
 8535:     }
 8536:     $r->print(&end_data_table());
 8537:     $i--;
 8538:     return $i;
 8539: }
 8540: 
 8541: ######################################################
 8542: ######################################################
 8543: 
 8544: =pod
 8545: 
 8546: =item * &csv_samples_select_table($r,$records,$d)
 8547: 
 8548: Prints a table of sample values from the upload and can make associate samples to internal names.
 8549: 
 8550: $r is an Apache Request ref,
 8551: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8552: $d is an array of 2 element arrays (internal name, displayed name)
 8553: 
 8554: =cut
 8555: 
 8556: ######################################################
 8557: ######################################################
 8558: sub csv_samples_select_table {
 8559:     my ($r,$records,$d) = @_;
 8560:     my $i=0;
 8561:     #
 8562:     my $max_samples = 5;
 8563:     my $samples = &get_samples($records,$max_samples);
 8564:     $r->print(&start_data_table().
 8565:               &start_data_table_header_row().'<th>'.
 8566:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8567:               &end_data_table_header_row());
 8568: 
 8569:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8570: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8571: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8572: 	foreach my $option (@$d) {
 8573: 	    my ($value,$display,$defaultcol)=@{ $option };
 8574: 	    $r->print('<option value="'.$value.'"'.
 8575:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8576:                       $display.'</option>');
 8577: 	}
 8578: 	$r->print('</select></td><td>');
 8579: 	foreach my $line (0..($max_samples-1)) {
 8580: 	    if (defined($samples->[$line]{$key})) { 
 8581: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8582: 	    }
 8583: 	}
 8584: 	$r->print('</td>'.&end_data_table_row());
 8585: 	$i++;
 8586:     }
 8587:     $r->print(&end_data_table());
 8588:     $i--;
 8589:     return($i);
 8590: }
 8591: 
 8592: ######################################################
 8593: ######################################################
 8594: 
 8595: =pod
 8596: 
 8597: =item * &clean_excel_name($name)
 8598: 
 8599: Returns a replacement for $name which does not contain any illegal characters.
 8600: 
 8601: =cut
 8602: 
 8603: ######################################################
 8604: ######################################################
 8605: sub clean_excel_name {
 8606:     my ($name) = @_;
 8607:     $name =~ s/[:\*\?\/\\]//g;
 8608:     if (length($name) > 31) {
 8609:         $name = substr($name,0,31);
 8610:     }
 8611:     return $name;
 8612: }
 8613: 
 8614: =pod
 8615: 
 8616: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8617: 
 8618: Returns either 1 or undef
 8619: 
 8620: 1 if the part is to be hidden, undef if it is to be shown
 8621: 
 8622: Arguments are:
 8623: 
 8624: $id the id of the part to be checked
 8625: $symb, optional the symb of the resource to check
 8626: $udom, optional the domain of the user to check for
 8627: $uname, optional the username of the user to check for
 8628: 
 8629: =cut
 8630: 
 8631: sub check_if_partid_hidden {
 8632:     my ($id,$symb,$udom,$uname) = @_;
 8633:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8634: 					 $symb,$udom,$uname);
 8635:     my $truth=1;
 8636:     #if the string starts with !, then the list is the list to show not hide
 8637:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8638:     my @hiddenlist=split(/,/,$hiddenparts);
 8639:     foreach my $checkid (@hiddenlist) {
 8640: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8641:     }
 8642:     return !$truth;
 8643: }
 8644: 
 8645: 
 8646: ############################################################
 8647: ############################################################
 8648: 
 8649: =pod
 8650: 
 8651: =back 
 8652: 
 8653: =head1 cgi-bin script and graphing routines
 8654: 
 8655: =over 4
 8656: 
 8657: =item * &get_cgi_id()
 8658: 
 8659: Inputs: none
 8660: 
 8661: Returns an id which can be used to pass environment variables
 8662: to various cgi-bin scripts.  These environment variables will
 8663: be removed from the users environment after a given time by
 8664: the routine &Apache::lonnet::transfer_profile_to_env.
 8665: 
 8666: =cut
 8667: 
 8668: ############################################################
 8669: ############################################################
 8670: my $uniq=0;
 8671: sub get_cgi_id {
 8672:     $uniq=($uniq+1)%100000;
 8673:     return (time.'_'.$$.'_'.$uniq);
 8674: }
 8675: 
 8676: ############################################################
 8677: ############################################################
 8678: 
 8679: =pod
 8680: 
 8681: =item * &DrawBarGraph()
 8682: 
 8683: Facilitates the plotting of data in a (stacked) bar graph.
 8684: Puts plot definition data into the users environment in order for 
 8685: graph.png to plot it.  Returns an <img> tag for the plot.
 8686: The bars on the plot are labeled '1','2',...,'n'.
 8687: 
 8688: Inputs:
 8689: 
 8690: =over 4
 8691: 
 8692: =item $Title: string, the title of the plot
 8693: 
 8694: =item $xlabel: string, text describing the X-axis of the plot
 8695: 
 8696: =item $ylabel: string, text describing the Y-axis of the plot
 8697: 
 8698: =item $Max: scalar, the maximum Y value to use in the plot
 8699: If $Max is < any data point, the graph will not be rendered.
 8700: 
 8701: =item $colors: array ref holding the colors to be used for the data sets when
 8702: they are plotted.  If undefined, default values will be used.
 8703: 
 8704: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8705: 
 8706: =item @Values: An array of array references.  Each array reference holds data
 8707: to be plotted in a stacked bar chart.
 8708: 
 8709: =item If the final element of @Values is a hash reference the key/value
 8710: pairs will be added to the graph definition.
 8711: 
 8712: =back
 8713: 
 8714: Returns:
 8715: 
 8716: An <img> tag which references graph.png and the appropriate identifying
 8717: information for the plot.
 8718: 
 8719: =cut
 8720: 
 8721: ############################################################
 8722: ############################################################
 8723: sub DrawBarGraph {
 8724:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8725:     #
 8726:     if (! defined($colors)) {
 8727:         $colors = ['#33ff00', 
 8728:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8729:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8730:                   ]; 
 8731:     }
 8732:     my $extra_settings = {};
 8733:     if (ref($Values[-1]) eq 'HASH') {
 8734:         $extra_settings = pop(@Values);
 8735:     }
 8736:     #
 8737:     my $identifier = &get_cgi_id();
 8738:     my $id = 'cgi.'.$identifier;        
 8739:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8740:         return '';
 8741:     }
 8742:     #
 8743:     my @Labels;
 8744:     if (defined($labels)) {
 8745:         @Labels = @$labels;
 8746:     } else {
 8747:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8748:             push (@Labels,$i+1);
 8749:         }
 8750:     }
 8751:     #
 8752:     my $NumBars = scalar(@{$Values[0]});
 8753:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8754:     my %ValuesHash;
 8755:     my $NumSets=1;
 8756:     foreach my $array (@Values) {
 8757:         next if (! ref($array));
 8758:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8759:             join(',',@$array);
 8760:     }
 8761:     #
 8762:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8763:     if ($NumBars < 3) {
 8764:         $width = 120+$NumBars*32;
 8765:         $xskip = 1;
 8766:         $bar_width = 30;
 8767:     } elsif ($NumBars < 5) {
 8768:         $width = 120+$NumBars*20;
 8769:         $xskip = 1;
 8770:         $bar_width = 20;
 8771:     } elsif ($NumBars < 10) {
 8772:         $width = 120+$NumBars*15;
 8773:         $xskip = 1;
 8774:         $bar_width = 15;
 8775:     } elsif ($NumBars <= 25) {
 8776:         $width = 120+$NumBars*11;
 8777:         $xskip = 5;
 8778:         $bar_width = 8;
 8779:     } elsif ($NumBars <= 50) {
 8780:         $width = 120+$NumBars*8;
 8781:         $xskip = 5;
 8782:         $bar_width = 4;
 8783:     } else {
 8784:         $width = 120+$NumBars*8;
 8785:         $xskip = 5;
 8786:         $bar_width = 4;
 8787:     }
 8788:     #
 8789:     $Max = 1 if ($Max < 1);
 8790:     if ( int($Max) < $Max ) {
 8791:         $Max++;
 8792:         $Max = int($Max);
 8793:     }
 8794:     $Title  = '' if (! defined($Title));
 8795:     $xlabel = '' if (! defined($xlabel));
 8796:     $ylabel = '' if (! defined($ylabel));
 8797:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8798:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8799:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8800:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8801:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8802:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8803:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8804:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8805:     $ValuesHash{$id.'.height'}   = $height;
 8806:     $ValuesHash{$id.'.width'}    = $width;
 8807:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8808:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8809:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8810:     #
 8811:     # Deal with other parameters
 8812:     while (my ($key,$value) = each(%$extra_settings)) {
 8813:         $ValuesHash{$id.'.'.$key} = $value;
 8814:     }
 8815:     #
 8816:     &Apache::lonnet::appenv(\%ValuesHash);
 8817:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8818: }
 8819: 
 8820: ############################################################
 8821: ############################################################
 8822: 
 8823: =pod
 8824: 
 8825: =item * &DrawXYGraph()
 8826: 
 8827: Facilitates the plotting of data in an XY graph.
 8828: Puts plot definition data into the users environment in order for 
 8829: graph.png to plot it.  Returns an <img> tag for the plot.
 8830: 
 8831: Inputs:
 8832: 
 8833: =over 4
 8834: 
 8835: =item $Title: string, the title of the plot
 8836: 
 8837: =item $xlabel: string, text describing the X-axis of the plot
 8838: 
 8839: =item $ylabel: string, text describing the Y-axis of the plot
 8840: 
 8841: =item $Max: scalar, the maximum Y value to use in the plot
 8842: If $Max is < any data point, the graph will not be rendered.
 8843: 
 8844: =item $colors: Array ref containing the hex color codes for the data to be 
 8845: plotted in.  If undefined, default values will be used.
 8846: 
 8847: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8848: 
 8849: =item $Ydata: Array ref containing Array refs.  
 8850: Each of the contained arrays will be plotted as a separate curve.
 8851: 
 8852: =item %Values: hash indicating or overriding any default values which are 
 8853: passed to graph.png.  
 8854: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8855: 
 8856: =back
 8857: 
 8858: Returns:
 8859: 
 8860: An <img> tag which references graph.png and the appropriate identifying
 8861: information for the plot.
 8862: 
 8863: =cut
 8864: 
 8865: ############################################################
 8866: ############################################################
 8867: sub DrawXYGraph {
 8868:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8869:     #
 8870:     # Create the identifier for the graph
 8871:     my $identifier = &get_cgi_id();
 8872:     my $id = 'cgi.'.$identifier;
 8873:     #
 8874:     $Title  = '' if (! defined($Title));
 8875:     $xlabel = '' if (! defined($xlabel));
 8876:     $ylabel = '' if (! defined($ylabel));
 8877:     my %ValuesHash = 
 8878:         (
 8879:          $id.'.title'  => &escape($Title),
 8880:          $id.'.xlabel' => &escape($xlabel),
 8881:          $id.'.ylabel' => &escape($ylabel),
 8882:          $id.'.y_max_value'=> $Max,
 8883:          $id.'.labels'     => join(',',@$Xlabels),
 8884:          $id.'.PlotType'   => 'XY',
 8885:          );
 8886:     #
 8887:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8888:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8889:     }
 8890:     #
 8891:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8892:         return '';
 8893:     }
 8894:     my $NumSets=1;
 8895:     foreach my $array (@{$Ydata}){
 8896:         next if (! ref($array));
 8897:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8898:     }
 8899:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8900:     #
 8901:     # Deal with other parameters
 8902:     while (my ($key,$value) = each(%Values)) {
 8903:         $ValuesHash{$id.'.'.$key} = $value;
 8904:     }
 8905:     #
 8906:     &Apache::lonnet::appenv(\%ValuesHash);
 8907:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8908: }
 8909: 
 8910: ############################################################
 8911: ############################################################
 8912: 
 8913: =pod
 8914: 
 8915: =item * &DrawXYYGraph()
 8916: 
 8917: Facilitates the plotting of data in an XY graph with two Y axes.
 8918: Puts plot definition data into the users environment in order for 
 8919: graph.png to plot it.  Returns an <img> tag for the plot.
 8920: 
 8921: Inputs:
 8922: 
 8923: =over 4
 8924: 
 8925: =item $Title: string, the title of the plot
 8926: 
 8927: =item $xlabel: string, text describing the X-axis of the plot
 8928: 
 8929: =item $ylabel: string, text describing the Y-axis of the plot
 8930: 
 8931: =item $colors: Array ref containing the hex color codes for the data to be 
 8932: plotted in.  If undefined, default values will be used.
 8933: 
 8934: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8935: 
 8936: =item $Ydata1: The first data set
 8937: 
 8938: =item $Min1: The minimum value of the left Y-axis
 8939: 
 8940: =item $Max1: The maximum value of the left Y-axis
 8941: 
 8942: =item $Ydata2: The second data set
 8943: 
 8944: =item $Min2: The minimum value of the right Y-axis
 8945: 
 8946: =item $Max2: The maximum value of the left Y-axis
 8947: 
 8948: =item %Values: hash indicating or overriding any default values which are 
 8949: passed to graph.png.  
 8950: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8951: 
 8952: =back
 8953: 
 8954: Returns:
 8955: 
 8956: An <img> tag which references graph.png and the appropriate identifying
 8957: information for the plot.
 8958: 
 8959: =cut
 8960: 
 8961: ############################################################
 8962: ############################################################
 8963: sub DrawXYYGraph {
 8964:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8965:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8966:     #
 8967:     # Create the identifier for the graph
 8968:     my $identifier = &get_cgi_id();
 8969:     my $id = 'cgi.'.$identifier;
 8970:     #
 8971:     $Title  = '' if (! defined($Title));
 8972:     $xlabel = '' if (! defined($xlabel));
 8973:     $ylabel = '' if (! defined($ylabel));
 8974:     my %ValuesHash = 
 8975:         (
 8976:          $id.'.title'  => &escape($Title),
 8977:          $id.'.xlabel' => &escape($xlabel),
 8978:          $id.'.ylabel' => &escape($ylabel),
 8979:          $id.'.labels' => join(',',@$Xlabels),
 8980:          $id.'.PlotType' => 'XY',
 8981:          $id.'.NumSets' => 2,
 8982:          $id.'.two_axes' => 1,
 8983:          $id.'.y1_max_value' => $Max1,
 8984:          $id.'.y1_min_value' => $Min1,
 8985:          $id.'.y2_max_value' => $Max2,
 8986:          $id.'.y2_min_value' => $Min2,
 8987:          );
 8988:     #
 8989:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8990:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8991:     }
 8992:     #
 8993:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8994:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8995:         return '';
 8996:     }
 8997:     my $NumSets=1;
 8998:     foreach my $array ($Ydata1,$Ydata2){
 8999:         next if (! ref($array));
 9000:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9001:     }
 9002:     #
 9003:     # Deal with other parameters
 9004:     while (my ($key,$value) = each(%Values)) {
 9005:         $ValuesHash{$id.'.'.$key} = $value;
 9006:     }
 9007:     #
 9008:     &Apache::lonnet::appenv(\%ValuesHash);
 9009:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9010: }
 9011: 
 9012: ############################################################
 9013: ############################################################
 9014: 
 9015: =pod
 9016: 
 9017: =back 
 9018: 
 9019: =head1 Statistics helper routines?  
 9020: 
 9021: Bad place for them but what the hell.
 9022: 
 9023: =over 4
 9024: 
 9025: =item * &chartlink()
 9026: 
 9027: Returns a link to the chart for a specific student.  
 9028: 
 9029: Inputs:
 9030: 
 9031: =over 4
 9032: 
 9033: =item $linktext: The text of the link
 9034: 
 9035: =item $sname: The students username
 9036: 
 9037: =item $sdomain: The students domain
 9038: 
 9039: =back
 9040: 
 9041: =back
 9042: 
 9043: =cut
 9044: 
 9045: ############################################################
 9046: ############################################################
 9047: sub chartlink {
 9048:     my ($linktext, $sname, $sdomain) = @_;
 9049:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9050:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9051:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9052:        '">'.$linktext.'</a>';
 9053: }
 9054: 
 9055: #######################################################
 9056: #######################################################
 9057: 
 9058: =pod
 9059: 
 9060: =head1 Course Environment Routines
 9061: 
 9062: =over 4
 9063: 
 9064: =item * &restore_course_settings()
 9065: 
 9066: =item * &store_course_settings()
 9067: 
 9068: Restores/Store indicated form parameters from the course environment.
 9069: Will not overwrite existing values of the form parameters.
 9070: 
 9071: Inputs: 
 9072: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9073: 
 9074: a hash ref describing the data to be stored.  For example:
 9075:    
 9076: %Save_Parameters = ('Status' => 'scalar',
 9077:     'chartoutputmode' => 'scalar',
 9078:     'chartoutputdata' => 'scalar',
 9079:     'Section' => 'array',
 9080:     'Group' => 'array',
 9081:     'StudentData' => 'array',
 9082:     'Maps' => 'array');
 9083: 
 9084: Returns: both routines return nothing
 9085: 
 9086: =back
 9087: 
 9088: =cut
 9089: 
 9090: #######################################################
 9091: #######################################################
 9092: sub store_course_settings {
 9093:     return &store_settings($env{'request.course.id'},@_);
 9094: }
 9095: 
 9096: sub store_settings {
 9097:     # save to the environment
 9098:     # appenv the same items, just to be safe
 9099:     my $udom  = $env{'user.domain'};
 9100:     my $uname = $env{'user.name'};
 9101:     my ($context,$prefix,$Settings) = @_;
 9102:     my %SaveHash;
 9103:     my %AppHash;
 9104:     while (my ($setting,$type) = each(%$Settings)) {
 9105:         my $basename = join('.','internal',$context,$prefix,$setting);
 9106:         my $envname = 'environment.'.$basename;
 9107:         if (exists($env{'form.'.$setting})) {
 9108:             # Save this value away
 9109:             if ($type eq 'scalar' &&
 9110:                 (! exists($env{$envname}) || 
 9111:                  $env{$envname} ne $env{'form.'.$setting})) {
 9112:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9113:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9114:             } elsif ($type eq 'array') {
 9115:                 my $stored_form;
 9116:                 if (ref($env{'form.'.$setting})) {
 9117:                     $stored_form = join(',',
 9118:                                         map {
 9119:                                             &escape($_);
 9120:                                         } sort(@{$env{'form.'.$setting}}));
 9121:                 } else {
 9122:                     $stored_form = 
 9123:                         &escape($env{'form.'.$setting});
 9124:                 }
 9125:                 # Determine if the array contents are the same.
 9126:                 if ($stored_form ne $env{$envname}) {
 9127:                     $SaveHash{$basename} = $stored_form;
 9128:                     $AppHash{$envname}   = $stored_form;
 9129:                 }
 9130:             }
 9131:         }
 9132:     }
 9133:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9134:                                           $udom,$uname);
 9135:     if ($put_result !~ /^(ok|delayed)/) {
 9136:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9137:                                  'got error:'.$put_result);
 9138:     }
 9139:     # Make sure these settings stick around in this session, too
 9140:     &Apache::lonnet::appenv(\%AppHash);
 9141:     return;
 9142: }
 9143: 
 9144: sub restore_course_settings {
 9145:     return &restore_settings($env{'request.course.id'},@_);
 9146: }
 9147: 
 9148: sub restore_settings {
 9149:     my ($context,$prefix,$Settings) = @_;
 9150:     while (my ($setting,$type) = each(%$Settings)) {
 9151:         next if (exists($env{'form.'.$setting}));
 9152:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9153:             '.'.$setting;
 9154:         if (exists($env{$envname})) {
 9155:             if ($type eq 'scalar') {
 9156:                 $env{'form.'.$setting} = $env{$envname};
 9157:             } elsif ($type eq 'array') {
 9158:                 $env{'form.'.$setting} = [ 
 9159:                                            map { 
 9160:                                                &unescape($_); 
 9161:                                            } split(',',$env{$envname})
 9162:                                            ];
 9163:             }
 9164:         }
 9165:     }
 9166: }
 9167: 
 9168: #######################################################
 9169: #######################################################
 9170: 
 9171: =pod
 9172: 
 9173: =head1 Domain E-mail Routines  
 9174: 
 9175: =over 4
 9176: 
 9177: =item * &build_recipient_list()
 9178: 
 9179: Build recipient lists for four types of e-mail:
 9180: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9181: (d) Help requests, generated by
 9182: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 9183: 
 9184: Inputs:
 9185: defmail (scalar - email address of default recipient), 
 9186: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9187: defdom (domain for which to retrieve configuration settings),
 9188: origmail (scalar - email address of recipient from loncapa.conf, 
 9189: i.e., predates configuration by DC via domainprefs.pm 
 9190: 
 9191: Returns: comma separated list of addresses to which to send e-mail.
 9192: 
 9193: =back
 9194: 
 9195: =cut
 9196: 
 9197: ############################################################
 9198: ############################################################
 9199: sub build_recipient_list {
 9200:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9201:     my @recipients;
 9202:     my $otheremails;
 9203:     my %domconfig =
 9204:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9205:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9206:         if (exists($domconfig{'contacts'}{$mailing})) {
 9207:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9208:                 my @contacts = ('adminemail','supportemail');
 9209:                 foreach my $item (@contacts) {
 9210:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9211:                         my $addr = $domconfig{'contacts'}{$item}; 
 9212:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9213:                             push(@recipients,$addr);
 9214:                         }
 9215:                     }
 9216:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9217:                 }
 9218:             }
 9219:         } elsif ($origmail ne '') {
 9220:             push(@recipients,$origmail);
 9221:         }
 9222:     } elsif ($origmail ne '') {
 9223:         push(@recipients,$origmail);
 9224:     }
 9225:     if (defined($defmail)) {
 9226:         if ($defmail ne '') {
 9227:             push(@recipients,$defmail);
 9228:         }
 9229:     }
 9230:     if ($otheremails) {
 9231:         my @others;
 9232:         if ($otheremails =~ /,/) {
 9233:             @others = split(/,/,$otheremails);
 9234:         } else {
 9235:             push(@others,$otheremails);
 9236:         }
 9237:         foreach my $addr (@others) {
 9238:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9239:                 push(@recipients,$addr);
 9240:             }
 9241:         }
 9242:     }
 9243:     my $recipientlist = join(',',@recipients); 
 9244:     return $recipientlist;
 9245: }
 9246: 
 9247: ############################################################
 9248: ############################################################
 9249: 
 9250: =pod
 9251: 
 9252: =head1 Course Catalog Routines
 9253: 
 9254: =over 4
 9255: 
 9256: =item * &gather_categories()
 9257: 
 9258: Converts category definitions - keys of categories hash stored in  
 9259: coursecategories in configuration.db on the primary library server in a 
 9260: domain - to an array.  Also generates javascript and idx hash used to 
 9261: generate Domain Coordinator interface for editing Course Categories.
 9262: 
 9263: Inputs:
 9264: 
 9265: categories (reference to hash of category definitions).
 9266: 
 9267: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9268:       categories and subcategories).
 9269: 
 9270: idx (reference to hash of counters used in Domain Coordinator interface for 
 9271:       editing Course Categories).
 9272: 
 9273: jsarray (reference to array of categories used to create Javascript arrays for
 9274:          Domain Coordinator interface for editing Course Categories).
 9275: 
 9276: Returns: nothing
 9277: 
 9278: Side effects: populates cats, idx and jsarray. 
 9279: 
 9280: =cut
 9281: 
 9282: sub gather_categories {
 9283:     my ($categories,$cats,$idx,$jsarray) = @_;
 9284:     my %counters;
 9285:     my $num = 0;
 9286:     foreach my $item (keys(%{$categories})) {
 9287:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9288:         if ($container eq '' && $depth == 0) {
 9289:             $cats->[$depth][$categories->{$item}] = $cat;
 9290:         } else {
 9291:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9292:         }
 9293:         my ($escitem,$tail) = split(/:/,$item,2);
 9294:         if ($counters{$tail} eq '') {
 9295:             $counters{$tail} = $num;
 9296:             $num ++;
 9297:         }
 9298:         if (ref($idx) eq 'HASH') {
 9299:             $idx->{$item} = $counters{$tail};
 9300:         }
 9301:         if (ref($jsarray) eq 'ARRAY') {
 9302:             push(@{$jsarray->[$counters{$tail}]},$item);
 9303:         }
 9304:     }
 9305:     return;
 9306: }
 9307: 
 9308: =pod
 9309: 
 9310: =item * &extract_categories()
 9311: 
 9312: Used to generate breadcrumb trails for course categories.
 9313: 
 9314: Inputs:
 9315: 
 9316: categories (reference to hash of category definitions).
 9317: 
 9318: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9319:       categories and subcategories).
 9320: 
 9321: trails (reference to array of breacrumb trails for each category).
 9322: 
 9323: allitems (reference to hash - key is category key 
 9324:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9325: 
 9326: idx (reference to hash of counters used in Domain Coordinator interface for
 9327:       editing Course Categories).
 9328: 
 9329: jsarray (reference to array of categories used to create Javascript arrays for
 9330:          Domain Coordinator interface for editing Course Categories).
 9331: 
 9332: subcats (reference to hash of arrays containing all subcategories within each 
 9333:          category, -recursive)
 9334: 
 9335: Returns: nothing
 9336: 
 9337: Side effects: populates trails and allitems hash references.
 9338: 
 9339: =cut
 9340: 
 9341: sub extract_categories {
 9342:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9343:     if (ref($categories) eq 'HASH') {
 9344:         &gather_categories($categories,$cats,$idx,$jsarray);
 9345:         if (ref($cats->[0]) eq 'ARRAY') {
 9346:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9347:                 my $name = $cats->[0][$i];
 9348:                 my $item = &escape($name).'::0';
 9349:                 my $trailstr;
 9350:                 if ($name eq 'instcode') {
 9351:                     $trailstr = &mt('Official courses (with institutional codes)');
 9352:                 } else {
 9353:                     $trailstr = $name;
 9354:                 }
 9355:                 if ($allitems->{$item} eq '') {
 9356:                     push(@{$trails},$trailstr);
 9357:                     $allitems->{$item} = scalar(@{$trails})-1;
 9358:                 }
 9359:                 my @parents = ($name);
 9360:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9361:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9362:                         my $category = $cats->[1]{$name}[$j];
 9363:                         if (ref($subcats) eq 'HASH') {
 9364:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9365:                         }
 9366:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9367:                     }
 9368:                 } else {
 9369:                     if (ref($subcats) eq 'HASH') {
 9370:                         $subcats->{$item} = [];
 9371:                     }
 9372:                 }
 9373:             }
 9374:         }
 9375:     }
 9376:     return;
 9377: }
 9378: 
 9379: =pod
 9380: 
 9381: =item *&recurse_categories()
 9382: 
 9383: Recursively used to generate breadcrumb trails for course categories.
 9384: 
 9385: Inputs:
 9386: 
 9387: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9388:       categories and subcategories).
 9389: 
 9390: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9391: 
 9392: category (current course category, for which breadcrumb trail is being generated).
 9393: 
 9394: trails (reference to array of breadcrumb trails for each category).
 9395: 
 9396: allitems (reference to hash - key is category key
 9397:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9398: 
 9399: parents (array containing containers directories for current category, 
 9400:          back to top level). 
 9401: 
 9402: Returns: nothing
 9403: 
 9404: Side effects: populates trails and allitems hash references
 9405: 
 9406: =cut
 9407: 
 9408: sub recurse_categories {
 9409:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9410:     my $shallower = $depth - 1;
 9411:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9412:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9413:             my $name = $cats->[$depth]{$category}[$k];
 9414:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9415:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9416:             if ($allitems->{$item} eq '') {
 9417:                 push(@{$trails},$trailstr);
 9418:                 $allitems->{$item} = scalar(@{$trails})-1;
 9419:             }
 9420:             my $deeper = $depth+1;
 9421:             push(@{$parents},$category);
 9422:             if (ref($subcats) eq 'HASH') {
 9423:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9424:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9425:                     my $higher;
 9426:                     if ($j > 0) {
 9427:                         $higher = &escape($parents->[$j]).':'.
 9428:                                   &escape($parents->[$j-1]).':'.$j;
 9429:                     } else {
 9430:                         $higher = &escape($parents->[$j]).'::'.$j;
 9431:                     }
 9432:                     push(@{$subcats->{$higher}},$subcat);
 9433:                 }
 9434:             }
 9435:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9436:                                 $subcats);
 9437:             pop(@{$parents});
 9438:         }
 9439:     } else {
 9440:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9441:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9442:         if ($allitems->{$item} eq '') {
 9443:             push(@{$trails},$trailstr);
 9444:             $allitems->{$item} = scalar(@{$trails})-1;
 9445:         }
 9446:     }
 9447:     return;
 9448: }
 9449: 
 9450: =pod
 9451: 
 9452: =item *&assign_categories_table()
 9453: 
 9454: Create a datatable for display of hierarchical categories in a domain,
 9455: with checkboxes to allow a course to be categorized. 
 9456: 
 9457: Inputs:
 9458: 
 9459: cathash - reference to hash of categories defined for the domain (from
 9460:           configuration.db)
 9461: 
 9462: currcat - scalar with an & separated list of categories assigned to a course. 
 9463: 
 9464: Returns: $output (markup to be displayed) 
 9465: 
 9466: =cut
 9467: 
 9468: sub assign_categories_table {
 9469:     my ($cathash,$currcat) = @_;
 9470:     my $output;
 9471:     if (ref($cathash) eq 'HASH') {
 9472:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9473:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9474:         $maxdepth = scalar(@cats);
 9475:         if (@cats > 0) {
 9476:             my $itemcount = 0;
 9477:             if (ref($cats[0]) eq 'ARRAY') {
 9478:                 $output = &Apache::loncommon::start_data_table();
 9479:                 my @currcategories;
 9480:                 if ($currcat ne '') {
 9481:                     @currcategories = split('&',$currcat);
 9482:                 }
 9483:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9484:                     my $parent = $cats[0][$i];
 9485:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9486:                     next if ($parent eq 'instcode');
 9487:                     my $item = &escape($parent).'::0';
 9488:                     my $checked = '';
 9489:                     if (@currcategories > 0) {
 9490:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9491:                             $checked = ' checked="checked"';
 9492:                         }
 9493:                     }
 9494:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9495:                                '<input type="checkbox" name="usecategory" value="'.
 9496:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9497:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9498:                     my $depth = 1;
 9499:                     push(@path,$parent);
 9500:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9501:                     pop(@path);
 9502:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9503:                     $itemcount ++;
 9504:                 }
 9505:                 $output .= &Apache::loncommon::end_data_table();
 9506:             }
 9507:         }
 9508:     }
 9509:     return $output;
 9510: }
 9511: 
 9512: =pod
 9513: 
 9514: =item *&assign_category_rows()
 9515: 
 9516: Create a datatable row for display of nested categories in a domain,
 9517: with checkboxes to allow a course to be categorized,called recursively.
 9518: 
 9519: Inputs:
 9520: 
 9521: itemcount - track row number for alternating colors
 9522: 
 9523: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9524:       categories and subcategories.
 9525: 
 9526: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9527: 
 9528: parent - parent of current category item
 9529: 
 9530: path - Array containing all categories back up through the hierarchy from the
 9531:        current category to the top level.
 9532: 
 9533: currcategories - reference to array of current categories assigned to the course
 9534: 
 9535: Returns: $output (markup to be displayed).
 9536: 
 9537: =cut
 9538: 
 9539: sub assign_category_rows {
 9540:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9541:     my ($text,$name,$item,$chgstr);
 9542:     if (ref($cats) eq 'ARRAY') {
 9543:         my $maxdepth = scalar(@{$cats});
 9544:         if (ref($cats->[$depth]) eq 'HASH') {
 9545:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9546:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9547:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9548:                 $text .= '<td><table class="LC_datatable">';
 9549:                 for (my $j=0; $j<$numchildren; $j++) {
 9550:                     $name = $cats->[$depth]{$parent}[$j];
 9551:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9552:                     my $deeper = $depth+1;
 9553:                     my $checked = '';
 9554:                     if (ref($currcategories) eq 'ARRAY') {
 9555:                         if (@{$currcategories} > 0) {
 9556:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9557:                                 $checked = ' checked="checked"';
 9558:                             }
 9559:                         }
 9560:                     }
 9561:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9562:                              '<input type="checkbox" name="usecategory" value="'.
 9563:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9564:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9565:                              '</td><td>';
 9566:                     if (ref($path) eq 'ARRAY') {
 9567:                         push(@{$path},$name);
 9568:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9569:                         pop(@{$path});
 9570:                     }
 9571:                     $text .= '</td></tr>';
 9572:                 }
 9573:                 $text .= '</table></td>';
 9574:             }
 9575:         }
 9576:     }
 9577:     return $text;
 9578: }
 9579: 
 9580: ############################################################
 9581: ############################################################
 9582: 
 9583: 
 9584: sub commit_customrole {
 9585:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9586:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9587:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9588:                          ($end?', ending '.localtime($end):'').': <b>'.
 9589:               &Apache::lonnet::assigncustomrole(
 9590:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9591:                  '</b><br />';
 9592:     return $output;
 9593: }
 9594: 
 9595: sub commit_standardrole {
 9596:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9597:     my ($output,$logmsg,$linefeed);
 9598:     if ($context eq 'auto') {
 9599:         $linefeed = "\n";
 9600:     } else {
 9601:         $linefeed = "<br />\n";
 9602:     }  
 9603:     if ($three eq 'st') {
 9604:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9605:                                          $one,$two,$sec,$context);
 9606:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9607:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9608:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9609:         } else {
 9610:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9611:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9612:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9613:             if ($context eq 'auto') {
 9614:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9615:             } else {
 9616:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9617:                &mt('Add to classlist').': <b>ok</b>';
 9618:             }
 9619:             $output .= $linefeed;
 9620:         }
 9621:     } else {
 9622:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9623:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9624:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9625:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9626:         if ($context eq 'auto') {
 9627:             $output .= $result.$linefeed;
 9628:         } else {
 9629:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9630:         }
 9631:     }
 9632:     return $output;
 9633: }
 9634: 
 9635: sub commit_studentrole {
 9636:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9637:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9638:     if ($context eq 'auto') {
 9639:         $linefeed = "\n";
 9640:     } else {
 9641:         $linefeed = '<br />'."\n";
 9642:     }
 9643:     if (defined($one) && defined($two)) {
 9644:         my $cid=$one.'_'.$two;
 9645:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9646:         my $secchange = 0;
 9647:         my $expire_role_result;
 9648:         my $modify_section_result;
 9649:         if ($oldsec ne '-1') { 
 9650:             if ($oldsec ne $sec) {
 9651:                 $secchange = 1;
 9652:                 my $now = time;
 9653:                 my $uurl='/'.$cid;
 9654:                 $uurl=~s/\_/\//g;
 9655:                 if ($oldsec) {
 9656:                     $uurl.='/'.$oldsec;
 9657:                 }
 9658:                 $oldsecurl = $uurl;
 9659:                 $expire_role_result = 
 9660:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9661:                 if ($env{'request.course.sec'} ne '') { 
 9662:                     if ($expire_role_result eq 'refused') {
 9663:                         my @roles = ('st');
 9664:                         my @statuses = ('previous');
 9665:                         my @roledoms = ($one);
 9666:                         my $withsec = 1;
 9667:                         my %roleshash = 
 9668:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9669:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9670:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9671:                             my ($oldstart,$oldend) = 
 9672:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9673:                             if ($oldend > 0 && $oldend <= $now) {
 9674:                                 $expire_role_result = 'ok';
 9675:                             }
 9676:                         }
 9677:                     }
 9678:                 }
 9679:                 $result = $expire_role_result;
 9680:             }
 9681:         }
 9682:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9683:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9684:             if ($modify_section_result =~ /^ok/) {
 9685:                 if ($secchange == 1) {
 9686:                     if ($sec eq '') {
 9687:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9688:                     } else {
 9689:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9690:                     }
 9691:                 } elsif ($oldsec eq '-1') {
 9692:                     if ($sec eq '') {
 9693:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9694:                     } else {
 9695:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9696:                     }
 9697:                 } else {
 9698:                     if ($sec eq '') {
 9699:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9700:                     } else {
 9701:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9702:                     }
 9703:                 }
 9704:             } else {
 9705:                 if ($secchange) {       
 9706:                     $$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;
 9707:                 } else {
 9708:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9709:                 }
 9710:             }
 9711:             $result = $modify_section_result;
 9712:         } elsif ($secchange == 1) {
 9713:             if ($oldsec eq '') {
 9714:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9715:             } else {
 9716:                 $$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;
 9717:             }
 9718:             if ($expire_role_result eq 'refused') {
 9719:                 my $newsecurl = '/'.$cid;
 9720:                 $newsecurl =~ s/\_/\//g;
 9721:                 if ($sec ne '') {
 9722:                     $newsecurl.='/'.$sec;
 9723:                 }
 9724:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9725:                     if ($sec eq '') {
 9726:                         $$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;
 9727:                     } else {
 9728:                         $$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;
 9729:                     }
 9730:                 }
 9731:             }
 9732:         }
 9733:     } else {
 9734:         $$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;
 9735:         $result = "error: incomplete course id\n";
 9736:     }
 9737:     return $result;
 9738: }
 9739: 
 9740: ############################################################
 9741: ############################################################
 9742: 
 9743: sub check_clone {
 9744:     my ($args,$linefeed) = @_;
 9745:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9746:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9747:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9748:     my $clonemsg;
 9749:     my $can_clone = 0;
 9750: 
 9751:     if ($clonehome eq 'no_host') {
 9752:         $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'});     
 9753:     } else {
 9754: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9755: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9756: 	    $can_clone = 1;
 9757: 	} else {
 9758: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9759: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9760: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9761:             if (grep(/^\*$/,@cloners)) {
 9762:                 $can_clone = 1;
 9763:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9764:                 $can_clone = 1;
 9765:             } else {
 9766: 	        my %roleshash =
 9767: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9768: 					 $args->{'ccdomain'},
 9769:                                          'userroles',['active'],['cc'],
 9770: 					 [$args->{'clonedomain'}]);
 9771: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9772: 		    $can_clone = 1;
 9773: 	        } else {
 9774:                     $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'});
 9775: 	        }
 9776: 	    }
 9777:         }
 9778:     }
 9779:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9780: }
 9781: 
 9782: sub construct_course {
 9783:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9784:     my $outcome;
 9785:     my $linefeed =  '<br />'."\n";
 9786:     if ($context eq 'auto') {
 9787:         $linefeed = "\n";
 9788:     }
 9789: 
 9790: #
 9791: # Are we cloning?
 9792: #
 9793:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9794:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9795: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9796: 	if ($context ne 'auto') {
 9797:             if ($clonemsg ne '') {
 9798: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9799:             }
 9800: 	}
 9801: 	$outcome .= $clonemsg.$linefeed;
 9802: 
 9803:         if (!$can_clone) {
 9804: 	    return (0,$outcome);
 9805: 	}
 9806:     }
 9807: 
 9808: #
 9809: # Open course
 9810: #
 9811:     my $crstype = lc($args->{'crstype'});
 9812:     my %cenv=();
 9813:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9814:                                              $args->{'cdescr'},
 9815:                                              $args->{'curl'},
 9816:                                              $args->{'course_home'},
 9817:                                              $args->{'nonstandard'},
 9818:                                              $args->{'crscode'},
 9819:                                              $args->{'ccuname'}.':'.
 9820:                                              $args->{'ccdomain'},
 9821:                                              $args->{'crstype'});
 9822: 
 9823:     # Note: The testing routines depend on this being output; see 
 9824:     # Utils::Course. This needs to at least be output as a comment
 9825:     # if anyone ever decides to not show this, and Utils::Course::new
 9826:     # will need to be suitably modified.
 9827:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9828: #
 9829: # Check if created correctly
 9830: #
 9831:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9832:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9833:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9834: 
 9835: #
 9836: # Do the cloning
 9837: #   
 9838:     if ($can_clone && $cloneid) {
 9839: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9840: 	if ($context ne 'auto') {
 9841: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9842: 	}
 9843: 	$outcome .= $clonemsg.$linefeed;
 9844: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9845: # Copy all files
 9846: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9847: # Restore URL
 9848: 	$cenv{'url'}=$oldcenv{'url'};
 9849: # Restore title
 9850: 	$cenv{'description'}=$oldcenv{'description'};
 9851: # Mark as cloned
 9852: 	$cenv{'clonedfrom'}=$cloneid;
 9853: # Need to clone grading mode
 9854:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9855:         $cenv{'grading'}=$newenv{'grading'};
 9856: # Do not clone these environment entries
 9857:         &Apache::lonnet::del('environment',
 9858:                   ['default_enrollment_start_date',
 9859:                    'default_enrollment_end_date',
 9860:                    'question.email',
 9861:                    'policy.email',
 9862:                    'comment.email',
 9863:                    'pch.users.denied',
 9864:                    'plc.users.denied',
 9865:                    'hidefromcat',
 9866:                    'categories'],
 9867:                    $$crsudom,$$crsunum);
 9868:     }
 9869: 
 9870: #
 9871: # Set environment (will override cloned, if existing)
 9872: #
 9873:     my @sections = ();
 9874:     my @xlists = ();
 9875:     if ($args->{'crstype'}) {
 9876:         $cenv{'type'}=$args->{'crstype'};
 9877:     }
 9878:     if ($args->{'crsid'}) {
 9879:         $cenv{'courseid'}=$args->{'crsid'};
 9880:     }
 9881:     if ($args->{'crscode'}) {
 9882:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9883:     }
 9884:     if ($args->{'crsquota'} ne '') {
 9885:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9886:     } else {
 9887:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9888:     }
 9889:     if ($args->{'ccuname'}) {
 9890:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9891:                                         ':'.$args->{'ccdomain'};
 9892:     } else {
 9893:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9894:     }
 9895:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9896:     if ($args->{'crssections'}) {
 9897:         $cenv{'internal.sectionnums'} = '';
 9898:         if ($args->{'crssections'} =~ m/,/) {
 9899:             @sections = split/,/,$args->{'crssections'};
 9900:         } else {
 9901:             $sections[0] = $args->{'crssections'};
 9902:         }
 9903:         if (@sections > 0) {
 9904:             foreach my $item (@sections) {
 9905:                 my ($sec,$gp) = split/:/,$item;
 9906:                 my $class = $args->{'crscode'}.$sec;
 9907:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9908:                 $cenv{'internal.sectionnums'} .= $item.',';
 9909:                 unless ($addcheck eq 'ok') {
 9910:                     push @badclasses, $class;
 9911:                 }
 9912:             }
 9913:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9914:         }
 9915:     }
 9916: # do not hide course coordinator from staff listing, 
 9917: # even if privileged
 9918:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9919: # add crosslistings
 9920:     if ($args->{'crsxlist'}) {
 9921:         $cenv{'internal.crosslistings'}='';
 9922:         if ($args->{'crsxlist'} =~ m/,/) {
 9923:             @xlists = split/,/,$args->{'crsxlist'};
 9924:         } else {
 9925:             $xlists[0] = $args->{'crsxlist'};
 9926:         }
 9927:         if (@xlists > 0) {
 9928:             foreach my $item (@xlists) {
 9929:                 my ($xl,$gp) = split/:/,$item;
 9930:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9931:                 $cenv{'internal.crosslistings'} .= $item.',';
 9932:                 unless ($addcheck eq 'ok') {
 9933:                     push @badclasses, $xl;
 9934:                 }
 9935:             }
 9936:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9937:         }
 9938:     }
 9939:     if ($args->{'autoadds'}) {
 9940:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9941:     }
 9942:     if ($args->{'autodrops'}) {
 9943:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9944:     }
 9945: # check for notification of enrollment changes
 9946:     my @notified = ();
 9947:     if ($args->{'notify_owner'}) {
 9948:         if ($args->{'ccuname'} ne '') {
 9949:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9950:         }
 9951:     }
 9952:     if ($args->{'notify_dc'}) {
 9953:         if ($uname ne '') { 
 9954:             push(@notified,$uname.':'.$udom);
 9955:         }
 9956:     }
 9957:     if (@notified > 0) {
 9958:         my $notifylist;
 9959:         if (@notified > 1) {
 9960:             $notifylist = join(',',@notified);
 9961:         } else {
 9962:             $notifylist = $notified[0];
 9963:         }
 9964:         $cenv{'internal.notifylist'} = $notifylist;
 9965:     }
 9966:     if (@badclasses > 0) {
 9967:         my %lt=&Apache::lonlocal::texthash(
 9968:                 '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',
 9969:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9970:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9971:         );
 9972:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9973:                            ' ('.$lt{'adby'}.')';
 9974:         if ($context eq 'auto') {
 9975:             $outcome .= $badclass_msg.$linefeed;
 9976:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9977:             foreach my $item (@badclasses) {
 9978:                 if ($context eq 'auto') {
 9979:                     $outcome .= " - $item\n";
 9980:                 } else {
 9981:                     $outcome .= "<li>$item</li>\n";
 9982:                 }
 9983:             }
 9984:             if ($context eq 'auto') {
 9985:                 $outcome .= $linefeed;
 9986:             } else {
 9987:                 $outcome .= "</ul><br /><br /></div>\n";
 9988:             }
 9989:         } 
 9990:     }
 9991:     if ($args->{'no_end_date'}) {
 9992:         $args->{'endaccess'} = 0;
 9993:     }
 9994:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9995:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9996:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9997:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9998:     if ($args->{'showphotos'}) {
 9999:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10000:     }
10001:     $cenv{'internal.authtype'} = $args->{'authtype'};
10002:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10003:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10004:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10005:             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'); 
10006:             if ($context eq 'auto') {
10007:                 $outcome .= $krb_msg;
10008:             } else {
10009:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10010:             }
10011:             $outcome .= $linefeed;
10012:         }
10013:     }
10014:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10015:        if ($args->{'setpolicy'}) {
10016:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10017:        }
10018:        if ($args->{'setcontent'}) {
10019:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10020:        }
10021:     }
10022:     if ($args->{'reshome'}) {
10023: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10024: 	$cenv{'reshome'}=~s/\/+$/\//;
10025:     }
10026: #
10027: # course has keyed access
10028: #
10029:     if ($args->{'setkeys'}) {
10030:        $cenv{'keyaccess'}='yes';
10031:     }
10032: # if specified, key authority is not course, but user
10033: # only active if keyaccess is yes
10034:     if ($args->{'keyauth'}) {
10035: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10036: 	$user = &LONCAPA::clean_username($user);
10037: 	$domain = &LONCAPA::clean_username($domain);
10038: 	if ($user ne '' && $domain ne '') {
10039: 	    $cenv{'keyauth'}=$user.':'.$domain;
10040: 	}
10041:     }
10042: 
10043:     if ($args->{'disresdis'}) {
10044:         $cenv{'pch.roles.denied'}='st';
10045:     }
10046:     if ($args->{'disablechat'}) {
10047:         $cenv{'plc.roles.denied'}='st';
10048:     }
10049: 
10050:     # Record we've not yet viewed the Course Initialization Helper for this 
10051:     # course
10052:     $cenv{'course.helper.not.run'} = 1;
10053:     #
10054:     # Use new Randomseed
10055:     #
10056:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10057:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10058:     #
10059:     # The encryption code and receipt prefix for this course
10060:     #
10061:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10062:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10063:     #
10064:     # By default, use standard grading
10065:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10066: 
10067:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10068:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10069: #
10070: # Open all assignments
10071: #
10072:     if ($args->{'openall'}) {
10073:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10074:        my %storecontent = ($storeunder         => time,
10075:                            $storeunder.'.type' => 'date_start');
10076:        
10077:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10078:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10079:    }
10080: #
10081: # Set first page
10082: #
10083:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10084: 	    || ($cloneid)) {
10085: 	use LONCAPA::map;
10086: 	$outcome .= &mt('Setting first resource').': ';
10087: 
10088: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10089:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10090: 
10091:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10092:         my $title; my $url;
10093:         if ($args->{'firstres'} eq 'syl') {
10094: 	    $title=&mt('Syllabus');
10095:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10096:         } else {
10097:             $title=&mt('Navigate Contents');
10098:             $url='/adm/navmaps';
10099:         }
10100: 
10101:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10102: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10103: 
10104: 	if ($errtext) { $fatal=2; }
10105:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10106:     }
10107: 
10108:     return (1,$outcome);
10109: }
10110: 
10111: ############################################################
10112: ############################################################
10113: 
10114: sub course_type {
10115:     my ($cid) = @_;
10116:     if (!defined($cid)) {
10117:         $cid = $env{'request.course.id'};
10118:     }
10119:     if (defined($env{'course.'.$cid.'.type'})) {
10120:         return $env{'course.'.$cid.'.type'};
10121:     } else {
10122:         return 'Course';
10123:     }
10124: }
10125: 
10126: sub group_term {
10127:     my $crstype = &course_type();
10128:     my %names = (
10129:                   'Course' => 'group',
10130:                   'Group' => 'team',
10131:                 );
10132:     return $names{$crstype};
10133: }
10134: 
10135: sub icon {
10136:     my ($file)=@_;
10137:     my $curfext = lc((split(/\./,$file))[-1]);
10138:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10139:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10140:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10141: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10142: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10143: 	            $curfext.".gif") {
10144: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10145: 		$curfext.".gif";
10146: 	}
10147:     }
10148:     return &lonhttpdurl($iconname);
10149: } 
10150: 
10151: sub lonhttpdurl {
10152: #
10153: # Had been used for "small fry" static images on separate port 8080.
10154: # Modify here if lightweight http functionality desired again.
10155: # Currently eliminated due to increasing firewall issues.
10156: #
10157:     my ($url)=@_;
10158:     return $url;
10159: }
10160: 
10161: sub connection_aborted {
10162:     my ($r)=@_;
10163:     $r->print(" ");$r->rflush();
10164:     my $c = $r->connection;
10165:     return $c->aborted();
10166: }
10167: 
10168: #    Escapes strings that may have embedded 's that will be put into
10169: #    strings as 'strings'.
10170: sub escape_single {
10171:     my ($input) = @_;
10172:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10173:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10174:     return $input;
10175: }
10176: 
10177: #  Same as escape_single, but escape's "'s  This 
10178: #  can be used for  "strings"
10179: sub escape_double {
10180:     my ($input) = @_;
10181:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10182:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10183:     return $input;
10184: }
10185:  
10186: #   Escapes the last element of a full URL.
10187: sub escape_url {
10188:     my ($url)   = @_;
10189:     my @urlslices = split(/\//, $url,-1);
10190:     my $lastitem = &escape(pop(@urlslices));
10191:     return join('/',@urlslices).'/'.$lastitem;
10192: }
10193: 
10194: # -------------------------------------------------------- Initliaze user login
10195: sub init_user_environment {
10196:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10197:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10198: 
10199:     my $public=($username eq 'public' && $domain eq 'public');
10200: 
10201: # See if old ID present, if so, remove
10202: 
10203:     my ($filename,$cookie,$userroles);
10204:     my $now=time;
10205: 
10206:     if ($public) {
10207: 	my $max_public=100;
10208: 	my $oldest;
10209: 	my $oldest_time=0;
10210: 	for(my $next=1;$next<=$max_public;$next++) {
10211: 	    if (-e $lonids."/publicuser_$next.id") {
10212: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10213: 		if ($mtime<$oldest_time || !$oldest_time) {
10214: 		    $oldest_time=$mtime;
10215: 		    $oldest=$next;
10216: 		}
10217: 	    } else {
10218: 		$cookie="publicuser_$next";
10219: 		last;
10220: 	    }
10221: 	}
10222: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10223:     } else {
10224: 	# if this isn't a robot, kill any existing non-robot sessions
10225: 	if (!$args->{'robot'}) {
10226: 	    opendir(DIR,$lonids);
10227: 	    while ($filename=readdir(DIR)) {
10228: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10229: 		    unlink($lonids.'/'.$filename);
10230: 		}
10231: 	    }
10232: 	    closedir(DIR);
10233: 	}
10234: # Give them a new cookie
10235: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10236: 		                   : $now.$$.int(rand(10000)));
10237: 	$cookie="$username\_$id\_$domain\_$authhost";
10238:     
10239: # Initialize roles
10240: 
10241: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10242:     }
10243: # ------------------------------------ Check browser type and MathML capability
10244: 
10245:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10246:         $clientunicode,$clientos) = &decode_user_agent($r);
10247: 
10248: # -------------------------------------- Any accessibility options to remember?
10249:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
10250: 	foreach my $option ('imagesuppress','appletsuppress',
10251: 			    'embedsuppress','fontenhance','blackwhite') {
10252: 	    if ($form->{$option} eq 'true') {
10253: 		&Apache::lonnet::put('environment',{$option => 'on'},
10254: 				     $domain,$username);
10255: 	    } else {
10256: 		&Apache::lonnet::del('environment',[$option],
10257: 				     $domain,$username);
10258: 	    }
10259: 	}
10260:     }
10261: # ------------------------------------------------------------- Get environment
10262: 
10263:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10264:     my ($tmp) = keys(%userenv);
10265:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10266: 	# default remote control to off
10267: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10268:     } else {
10269: 	undef(%userenv);
10270:     }
10271:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10272: 	$form->{'interface'}=$userenv{'interface'};
10273:     }
10274:     $env{'environment.remote'}=$userenv{'remote'};
10275:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10276: 
10277: # --------------- Do not trust query string to be put directly into environment
10278:     foreach my $option ('imagesuppress','appletsuppress',
10279: 			'embedsuppress','fontenhance','blackwhite',
10280: 			'interface','localpath','localres') {
10281: 	$form->{$option}=~s/[\n\r\=]//gs;
10282:     }
10283: # --------------------------------------------------------- Write first profile
10284: 
10285:     {
10286: 	my %initial_env = 
10287: 	    ("user.name"          => $username,
10288: 	     "user.domain"        => $domain,
10289: 	     "user.home"          => $authhost,
10290: 	     "browser.type"       => $clientbrowser,
10291: 	     "browser.version"    => $clientversion,
10292: 	     "browser.mathml"     => $clientmathml,
10293: 	     "browser.unicode"    => $clientunicode,
10294: 	     "browser.os"         => $clientos,
10295: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10296: 	     "request.course.fn"  => '',
10297: 	     "request.course.uri" => '',
10298: 	     "request.course.sec" => '',
10299: 	     "request.role"       => 'cm',
10300: 	     "request.role.adv"   => $env{'user.adv'},
10301: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10302: 
10303:         if ($form->{'localpath'}) {
10304: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10305: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10306:         }
10307: 	
10308: 	if ($public) {
10309: 	    $initial_env{"environment.remote"} = "off";
10310: 	}
10311: 	if ($form->{'interface'}) {
10312: 	    $form->{'interface'}=~s/\W//gs;
10313: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10314: 	    $env{'browser.interface'}=$form->{'interface'};
10315: 	    foreach my $option ('imagesuppress','appletsuppress',
10316: 				'embedsuppress','fontenhance','blackwhite') {
10317: 		if (($form->{$option} eq 'true') ||
10318: 		    ($userenv{$option} eq 'on')) {
10319: 		    $initial_env{"browser.$option"} = "on";
10320: 		}
10321: 	    }
10322: 	}
10323: 
10324:         foreach my $tool ('aboutme','blog','portfolio') {
10325:             $userenv{'availabletools.'.$tool} = 
10326:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10327:         }
10328: 
10329:         foreach my $crstype ('official','unofficial') {
10330:             $userenv{'canrequest.'.$crstype} =
10331:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10332:                                                   'reload','requestcourses');
10333:         }
10334: 
10335: 	$env{'user.environment'} = "$lonids/$cookie.id";
10336: 	
10337: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10338: 		 &GDBM_WRCREAT(),0640)) {
10339: 	    &_add_to_env(\%disk_env,\%initial_env);
10340: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10341: 	    &_add_to_env(\%disk_env,$userroles);
10342: 	    if (ref($args->{'extra_env'})) {
10343: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10344: 	    }
10345: 	    untie(%disk_env);
10346: 	} else {
10347: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10348: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10349: 	    return 'error: '.$!;
10350: 	}
10351:     }
10352:     $env{'request.role'}='cm';
10353:     $env{'request.role.adv'}=$env{'user.adv'};
10354:     $env{'browser.type'}=$clientbrowser;
10355: 
10356:     return $cookie;
10357: 
10358: }
10359: 
10360: sub _add_to_env {
10361:     my ($idf,$env_data,$prefix) = @_;
10362:     if (ref($env_data) eq 'HASH') {
10363:         while (my ($key,$value) = each(%$env_data)) {
10364: 	    $idf->{$prefix.$key} = $value;
10365: 	    $env{$prefix.$key}   = $value;
10366:         }
10367:     }
10368: }
10369: 
10370: # --- Get the symbolic name of a problem and the url
10371: sub get_symb {
10372:     my ($request,$silent) = @_;
10373:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10374:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10375:     if ($symb eq '') {
10376:         if (!$silent) {
10377:             $request->print("Unable to handle ambiguous references:$url:.");
10378:             return ();
10379:         }
10380:     }
10381:     &Apache::lonenc::check_decrypt(\$symb);
10382:     return ($symb);
10383: }
10384: 
10385: # --------------------------------------------------------------Get annotation
10386: 
10387: sub get_annotation {
10388:     my ($symb,$enc) = @_;
10389: 
10390:     my $key = $symb;
10391:     if (!$enc) {
10392:         $key =
10393:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10394:     }
10395:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10396:     return $annotation{$key};
10397: }
10398: 
10399: sub clean_symb {
10400:     my ($symb,$delete_enc) = @_;
10401: 
10402:     &Apache::lonenc::check_decrypt(\$symb);
10403:     my $enc = $env{'request.enc'};
10404:     if ($delete_enc) {
10405:         delete($env{'request.enc'});
10406:     }
10407: 
10408:     return ($symb,$enc);
10409: }
10410: 
10411: =pod
10412: 
10413: =back
10414: 
10415: =cut
10416: 
10417: 1;
10418: __END__;
10419: 

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