File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.800: download - view: text, annotated - select for diffs
Fri May 1 01:07:55 2009 UTC (15 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
 - Scantron Uploader's upload screen.
   - Replace table tags with pick_box().
   - Link to syllabus adjacent to Course Name textbox (becomes active when a course has been chosen.
   - Javascript alert on submit if no course selected.
   - Domain select box replaced with static domain ($env{'request.role.domain'})

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.800 2009/05/01 01:07:55 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410:     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:                 } else {
  521:                     if (formname == 'rules') {
  522:                         url += '&fixeddom='+extra_element; 
  523:                     }
  524:                 }
  525:             }     
  526:         }
  527:         if (multflag !=null && multflag != '') {
  528:             url += '&multiple='+multflag;
  529:         }
  530:         if (crstype == 'Course/Group') {
  531:             if (formname == 'cu') {
  532:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  533:                 if (crstype == "") {
  534:                     alert("$crs_or_grp_alert");
  535:                     return;
  536:                 }
  537:             }
  538:         }
  539:         if (crstype !=null && crstype != '') {
  540:             url += '&type='+crstype;
  541:         }
  542:         var title = 'Course_Browser';
  543:         var options = 'scrollbars=1,resizable=1,menubar=0';
  544:         options += ',width=700,height=600';
  545:         stdeditbrowser = open(url,title,options,'1');
  546:         stdeditbrowser.focus();
  547:     }
  548: 
  549:     function getFormIdByName(formname) {
  550:         for (var i=0;i<document.forms.length;i++) {
  551:             if (document.forms[i].name == formname) {
  552:                 return i;
  553:             }
  554:         }
  555:         return -1; 
  556:     }
  557: 
  558:     function getIndexByName(formid,item) {
  559:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  560:             if (document.forms[formid].elements[i].name == item) {
  561:                 return i;
  562:             }
  563:         }
  564:         return -1;
  565:     }
  566: ENDSTDBRW
  567:     if ($sec_element ne '') {
  568:         $output .= &setsec_javascript($sec_element,$formname);
  569:     }
  570:     $output .= '
  571: </script>';
  572:     return $output;
  573: }
  574: 
  575: sub setsec_javascript {
  576:     my ($sec_element,$formname) = @_;
  577:     my $setsections = qq|
  578: function setSect(sectionlist) {
  579:     var sectionsArray = new Array();
  580:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  581:         sectionsArray = sectionlist.split(",");
  582:     }
  583:     var numSections = sectionsArray.length;
  584:     document.$formname.$sec_element.length = 0;
  585:     if (numSections == 0) {
  586:         document.$formname.$sec_element.multiple=false;
  587:         document.$formname.$sec_element.size=1;
  588:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  589:     } else {
  590:         if (numSections == 1) {
  591:             document.$formname.$sec_element.multiple=false;
  592:             document.$formname.$sec_element.size=1;
  593:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  594:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  595:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  596:         } else {
  597:             for (var i=0; i<numSections; i++) {
  598:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  599:             }
  600:             document.$formname.$sec_element.multiple=true
  601:             if (numSections < 3) {
  602:                 document.$formname.$sec_element.size=numSections;
  603:             } else {
  604:                 document.$formname.$sec_element.size=3;
  605:             }
  606:             document.$formname.$sec_element.options[0].selected = false
  607:         }
  608:     }
  609: }
  610: |;
  611:     return $setsections;
  612: }
  613: 
  614: 
  615: sub selectcourse_link {
  616:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  617:    return '<span class="LC_nobreak">'
  618:          ."<a href='"
  619:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  620:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  621:          .'","'.$multflag.'","'.$selecttype.'");'
  622:          ."'>".&mt('Select Course').'</a>'
  623:          .'</span>';
  624: }
  625: 
  626: sub selectauthor_link {
  627:    my ($form,$udom)=@_;
  628:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  629:           &mt('Select Author').'</a>';
  630: }
  631: 
  632: sub check_uncheck_jscript {
  633:     my $jscript = <<"ENDSCRT";
  634: function checkAll(field) {
  635:     if (field.length > 0) {
  636:         for (i = 0; i < field.length; i++) {
  637:             field[i].checked = true ;
  638:         }
  639:     } else {
  640:         field.checked = true
  641:     }
  642: }
  643:  
  644: function uncheckAll(field) {
  645:     if (field.length > 0) {
  646:         for (i = 0; i < field.length; i++) {
  647:             field[i].checked = false ;
  648:         }
  649:     } else {
  650:         field.checked = false ;
  651:     }
  652: }
  653: ENDSCRT
  654:     return $jscript;
  655: }
  656: 
  657: sub select_timezone {
  658:    my ($name,$selected,$onchange,$includeempty)=@_;
  659:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  660:    if ($includeempty) {
  661:        $output .= '<option value=""';
  662:        if (($selected eq '') || ($selected eq 'local')) {
  663:            $output .= ' selected="selected" ';
  664:        }
  665:        $output .= '> </option>';
  666:    }
  667:    my @timezones = DateTime::TimeZone->all_names;
  668:    foreach my $tzone (@timezones) {
  669:        $output.= '<option value="'.$tzone.'"';
  670:        if ($tzone eq $selected) {
  671:            $output.=' selected="selected"';
  672:        }
  673:        $output.=">$tzone</option>\n";
  674:    }
  675:    $output.="</select>";
  676:    return $output;
  677: }
  678: 
  679: sub select_datelocale {
  680:     my ($name,$selected,$onchange,$includeempty)=@_;
  681:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  682:     if ($includeempty) {
  683:         $output .= '<option value=""';
  684:         if ($selected eq '') {
  685:             $output .= ' selected="selected" ';
  686:         }
  687:         $output .= '> </option>';
  688:     }
  689:     my (@possibles,%locale_names);
  690:     my @locales = DateTime::Locale::Catalog::Locales;
  691:     foreach my $locale (@locales) {
  692:         if (ref($locale) eq 'HASH') {
  693:             my $id = $locale->{'id'};
  694:             if ($id ne '') {
  695:                 my $en_terr = $locale->{'en_territory'};
  696:                 my $native_terr = $locale->{'native_territory'};
  697:                 my @languages = &Apache::lonlocal::preferred_languages();
  698:                 if (grep(/^en$/,@languages) || !@languages) {
  699:                     if ($en_terr ne '') {
  700:                         $locale_names{$id} = '('.$en_terr.')';
  701:                     } elsif ($native_terr ne '') {
  702:                         $locale_names{$id} = $native_terr;
  703:                     }
  704:                 } else {
  705:                     if ($native_terr ne '') {
  706:                         $locale_names{$id} = $native_terr.' ';
  707:                     } elsif ($en_terr ne '') {
  708:                         $locale_names{$id} = '('.$en_terr.')';
  709:                     }
  710:                 }
  711:                 push (@possibles,$id);
  712:             }
  713:         }
  714:     }
  715:     foreach my $item (sort(@possibles)) {
  716:         $output.= '<option value="'.$item.'"';
  717:         if ($item eq $selected) {
  718:             $output.=' selected="selected"';
  719:         }
  720:         $output.=">$item";
  721:         if ($locale_names{$item} ne '') {
  722:             $output.="  $locale_names{$item}</option>\n";
  723:         }
  724:         $output.="</option>\n";
  725:     }
  726:     $output.="</select>";
  727:     return $output;
  728: }
  729: 
  730: sub select_language {
  731:     my ($name,$selected,$includeempty) = @_;
  732:     my %langchoices;
  733:     if ($includeempty) {
  734:         %langchoices = ('' => 'No language preference');
  735:     }
  736:     foreach my $id (&languageids()) {
  737:         my $code = &supportedlanguagecode($id);
  738:         if ($code) {
  739:             $langchoices{$code} = &plainlanguagedescription($id);
  740:         }
  741:     }
  742:     return &select_form($selected,$name,%langchoices);
  743: }
  744: 
  745: =pod
  746: 
  747: =item * &linked_select_forms(...)
  748: 
  749: linked_select_forms returns a string containing a <script></script> block
  750: and html for two <select> menus.  The select menus will be linked in that
  751: changing the value of the first menu will result in new values being placed
  752: in the second menu.  The values in the select menu will appear in alphabetical
  753: order unless a defined order is provided.
  754: 
  755: linked_select_forms takes the following ordered inputs:
  756: 
  757: =over 4
  758: 
  759: =item * $formname, the name of the <form> tag
  760: 
  761: =item * $middletext, the text which appears between the <select> tags
  762: 
  763: =item * $firstdefault, the default value for the first menu
  764: 
  765: =item * $firstselectname, the name of the first <select> tag
  766: 
  767: =item * $secondselectname, the name of the second <select> tag
  768: 
  769: =item * $hashref, a reference to a hash containing the data for the menus.
  770: 
  771: =item * $menuorder, the order of values in the first menu
  772: 
  773: =back 
  774: 
  775: Below is an example of such a hash.  Only the 'text', 'default', and 
  776: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  777: values for the first select menu.  The text that coincides with the 
  778: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  779: and text for the second menu are given in the hash pointed to by 
  780: $menu{$choice1}->{'select2'}.  
  781: 
  782:  my %menu = ( A1 => { text =>"Choice A1" ,
  783:                        default => "B3",
  784:                        select2 => { 
  785:                            B1 => "Choice B1",
  786:                            B2 => "Choice B2",
  787:                            B3 => "Choice B3",
  788:                            B4 => "Choice B4"
  789:                            },
  790:                        order => ['B4','B3','B1','B2'],
  791:                    },
  792:                A2 => { text =>"Choice A2" ,
  793:                        default => "C2",
  794:                        select2 => { 
  795:                            C1 => "Choice C1",
  796:                            C2 => "Choice C2",
  797:                            C3 => "Choice C3"
  798:                            },
  799:                        order => ['C2','C1','C3'],
  800:                    },
  801:                A3 => { text =>"Choice A3" ,
  802:                        default => "D6",
  803:                        select2 => { 
  804:                            D1 => "Choice D1",
  805:                            D2 => "Choice D2",
  806:                            D3 => "Choice D3",
  807:                            D4 => "Choice D4",
  808:                            D5 => "Choice D5",
  809:                            D6 => "Choice D6",
  810:                            D7 => "Choice D7"
  811:                            },
  812:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  813:                    }
  814:                );
  815: 
  816: =cut
  817: 
  818: sub linked_select_forms {
  819:     my ($formname,
  820:         $middletext,
  821:         $firstdefault,
  822:         $firstselectname,
  823:         $secondselectname, 
  824:         $hashref,
  825:         $menuorder,
  826:         ) = @_;
  827:     my $second = "document.$formname.$secondselectname";
  828:     my $first = "document.$formname.$firstselectname";
  829:     # output the javascript to do the changing
  830:     my $result = '';
  831:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  832:     $result.="var select2data = new Object();\n";
  833:     $" = '","';
  834:     my $debug = '';
  835:     foreach my $s1 (sort(keys(%$hashref))) {
  836:         $result.="select2data.d_$s1 = new Object();\n";        
  837:         $result.="select2data.d_$s1.def = new String('".
  838:             $hashref->{$s1}->{'default'}."');\n";
  839:         $result.="select2data.d_$s1.values = new Array(";
  840:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  841:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  842:             @s2values = @{$hashref->{$s1}->{'order'}};
  843:         }
  844:         $result.="\"@s2values\");\n";
  845:         $result.="select2data.d_$s1.texts = new Array(";        
  846:         my @s2texts;
  847:         foreach my $value (@s2values) {
  848:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  849:         }
  850:         $result.="\"@s2texts\");\n";
  851:     }
  852:     $"=' ';
  853:     $result.= <<"END";
  854: 
  855: function select1_changed() {
  856:     // Determine new choice
  857:     var newvalue = "d_" + $first.value;
  858:     // update select2
  859:     var values     = select2data[newvalue].values;
  860:     var texts      = select2data[newvalue].texts;
  861:     var select2def = select2data[newvalue].def;
  862:     var i;
  863:     // out with the old
  864:     for (i = 0; i < $second.options.length; i++) {
  865:         $second.options[i] = null;
  866:     }
  867:     // in with the nuclear
  868:     for (i=0;i<values.length; i++) {
  869:         $second.options[i] = new Option(values[i]);
  870:         $second.options[i].value = values[i];
  871:         $second.options[i].text = texts[i];
  872:         if (values[i] == select2def) {
  873:             $second.options[i].selected = true;
  874:         }
  875:     }
  876: }
  877: </script>
  878: END
  879:     # output the initial values for the selection lists
  880:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  881:     my @order = sort(keys(%{$hashref}));
  882:     if (ref($menuorder) eq 'ARRAY') {
  883:         @order = @{$menuorder};
  884:     }
  885:     foreach my $value (@order) {
  886:         $result.="    <option value=\"$value\" ";
  887:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  888:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  889:     }
  890:     $result .= "</select>\n";
  891:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  892:     $result .= $middletext;
  893:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  894:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  895:     
  896:     my @secondorder = sort(keys(%select2));
  897:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  898:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  899:     }
  900:     foreach my $value (@secondorder) {
  901:         $result.="    <option value=\"$value\" ";        
  902:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  903:         $result.=">".&mt($select2{$value})."</option>\n";
  904:     }
  905:     $result .= "</select>\n";
  906:     #    return $debug;
  907:     return $result;
  908: }   #  end of sub linked_select_forms {
  909: 
  910: =pod
  911: 
  912: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  913: 
  914: Returns a string corresponding to an HTML link to the given help
  915: $topic, where $topic corresponds to the name of a .tex file in
  916: /home/httpd/html/adm/help/tex, with underscores replaced by
  917: spaces. 
  918: 
  919: $text will optionally be linked to the same topic, allowing you to
  920: link text in addition to the graphic. If you do not want to link
  921: text, but wish to specify one of the later parameters, pass an
  922: empty string. 
  923: 
  924: $stayOnPage is a value that will be interpreted as a boolean. If true,
  925: the link will not open a new window. If false, the link will open
  926: a new window using Javascript. (Default is false.) 
  927: 
  928: $width and $height are optional numerical parameters that will
  929: override the width and height of the popped up window, which may
  930: be useful for certain help topics with big pictures included. 
  931: 
  932: =cut
  933: 
  934: sub help_open_topic {
  935:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  936:     $text = "" if (not defined $text);
  937:     $stayOnPage = 0 if (not defined $stayOnPage);
  938:     $width = 350 if (not defined $width);
  939:     $height = 400 if (not defined $height);
  940:     my $filename = $topic;
  941:     $filename =~ s/ /_/g;
  942: 
  943:     my $template = "";
  944:     my $link;
  945:     
  946:     $topic=~s/\W/\_/g;
  947: 
  948:     if (!$stayOnPage) {
  949: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  950:     } else {
  951: 	$link = "/adm/help/${filename}.hlp";
  952:     }
  953: 
  954:     # Add the text
  955:     if ($text ne "") {	
  956: 	$template.='<span class="LC_help_open_topic">'
  957:                   .'<a target="_top" href="'.$link.'">'
  958:                   .$text.'</a>';
  959:     }
  960: 
  961:     # (Always) Add the graphic
  962:     my $title = &mt('Online Help');
  963:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  964:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
  965:               .'<img src="'.$helpicon.'" border="0"'
  966:               .' alt="'.&mt('Help: [_1]',$topic).'"'
  967:               .' title="'.$title.'"' 
  968:               .' /></a>';
  969:     if ($text ne "") {	
  970:         $template.='</span>';
  971:     }
  972:     return $template;
  973: 
  974: }
  975: 
  976: # This is a quicky function for Latex cheatsheet editing, since it 
  977: # appears in at least four places
  978: sub helpLatexCheatsheet {
  979:     my ($topic,$text,$not_author) = @_;
  980:     my $out;
  981:     my $addOther = '';
  982:     if ($topic) {
  983: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
  984: 							       undef, undef, 600).
  985: 								   '</span> ';
  986:     }
  987:     $out = '<span>' # Start cheatsheet
  988: 	  .$addOther
  989:           .'<span>'
  990: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
  991: 					       undef,undef,600)
  992: 	  .'</span> <span>'
  993: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
  994: 					       undef,undef,600)
  995: 	  .'</span>';
  996:     unless ($not_author) {
  997:         $out .= ' <span>'
  998: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
  999: 	                                            undef,undef,600)
 1000: 	       .'</span>';
 1001:     }
 1002:     $out .= '</span>'; # End cheatsheet
 1003:     return $out;
 1004: }
 1005: 
 1006: sub general_help {
 1007:     my $helptopic='Student_Intro';
 1008:     if ($env{'request.role'}=~/^(ca|au)/) {
 1009: 	$helptopic='Authoring_Intro';
 1010:     } elsif ($env{'request.role'}=~/^cc/) {
 1011: 	$helptopic='Course_Coordination_Intro';
 1012:     } elsif ($env{'request.role'}=~/^dc/) {
 1013:         $helptopic='Domain_Coordination_Intro';
 1014:     }
 1015:     return $helptopic;
 1016: }
 1017: 
 1018: sub update_help_link {
 1019:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1020:     my $origurl = $ENV{'REQUEST_URI'};
 1021:     $origurl=~s|^/~|/priv/|;
 1022:     my $timestamp = time;
 1023:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1024:         $$datum = &escape($$datum);
 1025:     }
 1026: 
 1027:     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";
 1028:     my $output .= <<"ENDOUTPUT";
 1029: <script type="text/javascript">
 1030: banner_link = '$banner_link';
 1031: </script>
 1032: ENDOUTPUT
 1033:     return $output;
 1034: }
 1035: 
 1036: # now just updates the help link and generates a blue icon
 1037: sub help_open_menu {
 1038:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1039: 	= @_;    
 1040:     $stayOnPage = 0 if (not defined $stayOnPage);
 1041:     # only use pop-up help (stayOnPage == 0)
 1042:     # if environment.remote is on (using remote control UI)
 1043:     if ($env{'environment.remote'} eq 'off' ) {
 1044:         $stayOnPage=1;
 1045:     }
 1046:     my $output;
 1047:     if ($component_help) {
 1048: 	if (!$text) {
 1049: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1050: 				       $width,$height);
 1051: 	} else {
 1052: 	    my $help_text;
 1053: 	    $help_text=&unescape($topic);
 1054: 	    $output='<table><tr><td>'.
 1055: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1056: 				 $width,$height).'</td></tr></table>';
 1057: 	}
 1058:     }
 1059:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1060:     return $output.$banner_link;
 1061: }
 1062: 
 1063: sub top_nav_help {
 1064:     my ($text) = @_;
 1065:     $text = &mt($text);
 1066:     my $stay_on_page = 
 1067: 	($env{'environment.remote'} eq 'off' );
 1068:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1069: 	                     : "javascript:helpMenu('open')";
 1070:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1071: 
 1072:     my $title = &mt('Get help');
 1073: 
 1074:     return <<"END";
 1075: $banner_link
 1076:  <a href="$link" title="$title">$text</a>
 1077: END
 1078: }
 1079: 
 1080: sub help_menu_js {
 1081:     my ($text) = @_;
 1082: 
 1083:     my $stayOnPage = 
 1084: 	($env{'environment.remote'} eq 'off' );
 1085: 
 1086:     my $width = 620;
 1087:     my $height = 600;
 1088:     my $helptopic=&general_help();
 1089:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1090:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1091:     my $start_page =
 1092:         &Apache::loncommon::start_page('Help Menu', undef,
 1093: 				       {'frameset'    => 1,
 1094: 					'js_ready'    => 1,
 1095: 					'add_entries' => {
 1096: 					    'border' => '0',
 1097: 					    'rows'   => "110,*",},});
 1098:     my $end_page =
 1099:         &Apache::loncommon::end_page({'frameset' => 1,
 1100: 				      'js_ready' => 1,});
 1101: 
 1102:     my $template .= <<"ENDTEMPLATE";
 1103: <script type="text/javascript">
 1104: // <!-- BEGIN LON-CAPA Internal
 1105: // <![CDATA[
 1106: var banner_link = '';
 1107: function helpMenu(target) {
 1108:     var caller = this;
 1109:     if (target == 'open') {
 1110:         var newWindow = null;
 1111:         try {
 1112:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1113:         }
 1114:         catch(error) {
 1115:             writeHelp(caller);
 1116:             return;
 1117:         }
 1118:         if (newWindow) {
 1119:             caller = newWindow;
 1120:         }
 1121:     }
 1122:     writeHelp(caller);
 1123:     return;
 1124: }
 1125: function writeHelp(caller) {
 1126:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1127:     caller.document.close()
 1128:     caller.focus()
 1129: }
 1130: // ]]>
 1131: // END LON-CAPA Internal -->
 1132: </script>
 1133: ENDTEMPLATE
 1134:     return $template;
 1135: }
 1136: 
 1137: sub help_open_bug {
 1138:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1139:     unless ($env{'user.adv'}) { return ''; }
 1140:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1141:     $text = "" if (not defined $text);
 1142:     $stayOnPage = 0 if (not defined $stayOnPage);
 1143:     if ($env{'environment.remote'} eq 'off' ) {
 1144: 	$stayOnPage=1;
 1145:     }
 1146:     $width = 600 if (not defined $width);
 1147:     $height = 600 if (not defined $height);
 1148: 
 1149:     $topic=~s/\W+/\+/g;
 1150:     my $link='';
 1151:     my $template='';
 1152:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1153: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1154:     if (!$stayOnPage)
 1155:     {
 1156: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1157:     }
 1158:     else
 1159:     {
 1160: 	$link = $url;
 1161:     }
 1162:     # Add the text
 1163:     if ($text ne "")
 1164:     {
 1165: 	$template .= 
 1166:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1167:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1168:     }
 1169: 
 1170:     # Add the graphic
 1171:     my $title = &mt('Report a Bug');
 1172:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1173:     $template .= <<"ENDTEMPLATE";
 1174:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1175: ENDTEMPLATE
 1176:     if ($text ne '') { $template.='</td></tr></table>' };
 1177:     return $template;
 1178: 
 1179: }
 1180: 
 1181: sub help_open_faq {
 1182:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1183:     unless ($env{'user.adv'}) { return ''; }
 1184:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1185:     $text = "" if (not defined $text);
 1186:     $stayOnPage = 0 if (not defined $stayOnPage);
 1187:     if ($env{'environment.remote'} eq 'off' ) {
 1188: 	$stayOnPage=1;
 1189:     }
 1190:     $width = 350 if (not defined $width);
 1191:     $height = 400 if (not defined $height);
 1192: 
 1193:     $topic=~s/\W+/\+/g;
 1194:     my $link='';
 1195:     my $template='';
 1196:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1197:     if (!$stayOnPage)
 1198:     {
 1199: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1200:     }
 1201:     else
 1202:     {
 1203: 	$link = $url;
 1204:     }
 1205: 
 1206:     # Add the text
 1207:     if ($text ne "")
 1208:     {
 1209: 	$template .= 
 1210:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1211:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1212:     }
 1213: 
 1214:     # Add the graphic
 1215:     my $title = &mt('View the FAQ');
 1216:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1217:     $template .= <<"ENDTEMPLATE";
 1218:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1219: ENDTEMPLATE
 1220:     if ($text ne '') { $template.='</td></tr></table>' };
 1221:     return $template;
 1222: 
 1223: }
 1224: 
 1225: ###############################################################
 1226: ###############################################################
 1227: 
 1228: =pod
 1229: 
 1230: =item * &change_content_javascript():
 1231: 
 1232: This and the next function allow you to create small sections of an
 1233: otherwise static HTML page that you can update on the fly with
 1234: Javascript, even in Netscape 4.
 1235: 
 1236: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1237: must be written to the HTML page once. It will prove the Javascript
 1238: function "change(name, content)". Calling the change function with the
 1239: name of the section 
 1240: you want to update, matching the name passed to C<changable_area>, and
 1241: the new content you want to put in there, will put the content into
 1242: that area.
 1243: 
 1244: B<Note>: Netscape 4 only reserves enough space for the changable area
 1245: to contain room for the original contents. You need to "make space"
 1246: for whatever changes you wish to make, and be B<sure> to check your
 1247: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1248: it's adequate for updating a one-line status display, but little more.
 1249: This script will set the space to 100% width, so you only need to
 1250: worry about height in Netscape 4.
 1251: 
 1252: Modern browsers are much less limiting, and if you can commit to the
 1253: user not using Netscape 4, this feature may be used freely with
 1254: pretty much any HTML.
 1255: 
 1256: =cut
 1257: 
 1258: sub change_content_javascript {
 1259:     # If we're on Netscape 4, we need to use Layer-based code
 1260:     if ($env{'browser.type'} eq 'netscape' &&
 1261: 	$env{'browser.version'} =~ /^4\./) {
 1262: 	return (<<NETSCAPE4);
 1263: 	function change(name, content) {
 1264: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1265: 	    doc.open();
 1266: 	    doc.write(content);
 1267: 	    doc.close();
 1268: 	}
 1269: NETSCAPE4
 1270:     } else {
 1271: 	# Otherwise, we need to use semi-standards-compliant code
 1272: 	# (technically, "innerHTML" isn't standard but the equivalent
 1273: 	# is really scary, and every useful browser supports it
 1274: 	return (<<DOMBASED);
 1275: 	function change(name, content) {
 1276: 	    element = document.getElementById(name);
 1277: 	    element.innerHTML = content;
 1278: 	}
 1279: DOMBASED
 1280:     }
 1281: }
 1282: 
 1283: =pod
 1284: 
 1285: =item * &changable_area($name,$origContent):
 1286: 
 1287: This provides a "changable area" that can be modified on the fly via
 1288: the Javascript code provided in C<change_content_javascript>. $name is
 1289: the name you will use to reference the area later; do not repeat the
 1290: same name on a given HTML page more then once. $origContent is what
 1291: the area will originally contain, which can be left blank.
 1292: 
 1293: =cut
 1294: 
 1295: sub changable_area {
 1296:     my ($name, $origContent) = @_;
 1297: 
 1298:     if ($env{'browser.type'} eq 'netscape' &&
 1299: 	$env{'browser.version'} =~ /^4\./) {
 1300: 	# If this is netscape 4, we need to use the Layer tag
 1301: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1302:     } else {
 1303: 	return "<span id='$name'>$origContent</span>";
 1304:     }
 1305: }
 1306: 
 1307: =pod
 1308: 
 1309: =item * &viewport_geometry_js 
 1310: 
 1311: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1312: 
 1313: =cut
 1314: 
 1315: 
 1316: sub viewport_geometry_js { 
 1317:     return <<"GEOMETRY";
 1318: var Geometry = {};
 1319: function init_geometry() {
 1320:     if (Geometry.init) { return };
 1321:     Geometry.init=1;
 1322:     if (window.innerHeight) {
 1323:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1324:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1325:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1326:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1327:     }
 1328:     else if (document.documentElement && document.documentElement.clientHeight) {
 1329:         Geometry.getViewportHeight =
 1330:             function() { return document.documentElement.clientHeight; };
 1331:         Geometry.getViewportWidth =
 1332:             function() { return document.documentElement.clientWidth; };
 1333: 
 1334:         Geometry.getHorizontalScroll =
 1335:             function() { return document.documentElement.scrollLeft; };
 1336:         Geometry.getVerticalScroll =
 1337:             function() { return document.documentElement.scrollTop; };
 1338:     }
 1339:     else if (document.body.clientHeight) {
 1340:         Geometry.getViewportHeight =
 1341:             function() { return document.body.clientHeight; };
 1342:         Geometry.getViewportWidth =
 1343:             function() { return document.body.clientWidth; };
 1344:         Geometry.getHorizontalScroll =
 1345:             function() { return document.body.scrollLeft; };
 1346:         Geometry.getVerticalScroll =
 1347:             function() { return document.body.scrollTop; };
 1348:     }
 1349: }
 1350: 
 1351: GEOMETRY
 1352: }
 1353: 
 1354: =pod
 1355: 
 1356: =item * &viewport_size_js()
 1357: 
 1358: 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. 
 1359: 
 1360: =cut
 1361: 
 1362: sub viewport_size_js {
 1363:     my $geometry = &viewport_geometry_js();
 1364:     return <<"DIMS";
 1365: 
 1366: $geometry
 1367: 
 1368: function getViewportDims(width,height) {
 1369:     init_geometry();
 1370:     width.value = Geometry.getViewportWidth();
 1371:     height.value = Geometry.getViewportHeight();
 1372:     return;
 1373: }
 1374: 
 1375: DIMS
 1376: }
 1377: 
 1378: =pod
 1379: 
 1380: =item * &resize_textarea_js()
 1381: 
 1382: emits the needed javascript to resize a textarea to be as big as possible
 1383: 
 1384: creates a function resize_textrea that takes two IDs first should be
 1385: the id of the element to resize, second should be the id of a div that
 1386: surrounds everything that comes after the textarea, this routine needs
 1387: to be attached to the <body> for the onload and onresize events.
 1388: 
 1389: =back
 1390: 
 1391: =cut
 1392: 
 1393: sub resize_textarea_js {
 1394:     my $geometry = &viewport_geometry_js();
 1395:     return <<"RESIZE";
 1396:     <script type="text/javascript">
 1397: $geometry
 1398: 
 1399: function getX(element) {
 1400:     var x = 0;
 1401:     while (element) {
 1402: 	x += element.offsetLeft;
 1403: 	element = element.offsetParent;
 1404:     }
 1405:     return x;
 1406: }
 1407: function getY(element) {
 1408:     var y = 0;
 1409:     while (element) {
 1410: 	y += element.offsetTop;
 1411: 	element = element.offsetParent;
 1412:     }
 1413:     return y;
 1414: }
 1415: 
 1416: 
 1417: function resize_textarea(textarea_id,bottom_id) {
 1418:     init_geometry();
 1419:     var textarea        = document.getElementById(textarea_id);
 1420:     //alert(textarea);
 1421: 
 1422:     var textarea_top    = getY(textarea);
 1423:     var textarea_height = textarea.offsetHeight;
 1424:     var bottom          = document.getElementById(bottom_id);
 1425:     var bottom_top      = getY(bottom);
 1426:     var bottom_height   = bottom.offsetHeight;
 1427:     var window_height   = Geometry.getViewportHeight();
 1428:     var fudge           = 23;
 1429:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1430:     if (new_height < 300) {
 1431: 	new_height = 300;
 1432:     }
 1433:     textarea.style.height=new_height+'px';
 1434: }
 1435: </script>
 1436: RESIZE
 1437: 
 1438: }
 1439: 
 1440: =pod
 1441: 
 1442: =head1 Excel and CSV file utility routines
 1443: 
 1444: =over 4
 1445: 
 1446: =cut
 1447: 
 1448: ###############################################################
 1449: ###############################################################
 1450: 
 1451: =pod
 1452: 
 1453: =item * &csv_translate($text) 
 1454: 
 1455: Translate $text to allow it to be output as a 'comma separated values' 
 1456: format.
 1457: 
 1458: =cut
 1459: 
 1460: ###############################################################
 1461: ###############################################################
 1462: sub csv_translate {
 1463:     my $text = shift;
 1464:     $text =~ s/\"/\"\"/g;
 1465:     $text =~ s/\n/ /g;
 1466:     return $text;
 1467: }
 1468: 
 1469: ###############################################################
 1470: ###############################################################
 1471: 
 1472: =pod
 1473: 
 1474: =item * &define_excel_formats()
 1475: 
 1476: Define some commonly used Excel cell formats.
 1477: 
 1478: Currently supported formats:
 1479: 
 1480: =over 4
 1481: 
 1482: =item header
 1483: 
 1484: =item bold
 1485: 
 1486: =item h1
 1487: 
 1488: =item h2
 1489: 
 1490: =item h3
 1491: 
 1492: =item h4
 1493: 
 1494: =item i
 1495: 
 1496: =item date
 1497: 
 1498: =back
 1499: 
 1500: Inputs: $workbook
 1501: 
 1502: Returns: $format, a hash reference.
 1503: 
 1504: =cut
 1505: 
 1506: ###############################################################
 1507: ###############################################################
 1508: sub define_excel_formats {
 1509:     my ($workbook) = @_;
 1510:     my $format;
 1511:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1512:                                                 bottom    => 1,
 1513:                                                 align     => 'center');
 1514:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1515:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1516:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1517:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1518:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1519:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1520:     $format->{'date'} = $workbook->add_format(num_format=>
 1521:                                             'mm/dd/yyyy hh:mm:ss');
 1522:     return $format;
 1523: }
 1524: 
 1525: ###############################################################
 1526: ###############################################################
 1527: 
 1528: =pod
 1529: 
 1530: =item * &create_workbook()
 1531: 
 1532: Create an Excel worksheet.  If it fails, output message on the
 1533: request object and return undefs.
 1534: 
 1535: Inputs: Apache request object
 1536: 
 1537: Returns (undef) on failure, 
 1538:     Excel worksheet object, scalar with filename, and formats 
 1539:     from &Apache::loncommon::define_excel_formats on success
 1540: 
 1541: =cut
 1542: 
 1543: ###############################################################
 1544: ###############################################################
 1545: sub create_workbook {
 1546:     my ($r) = @_;
 1547:         #
 1548:     # Create the excel spreadsheet
 1549:     my $filename = '/prtspool/'.
 1550:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1551:         time.'_'.rand(1000000000).'.xls';
 1552:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1553:     if (! defined($workbook)) {
 1554:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1555:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1556:                             "This error has been logged.  ".
 1557:                             "Please alert your LON-CAPA administrator").
 1558:                   '</p>');
 1559:         return (undef);
 1560:     }
 1561:     #
 1562:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1563:     #
 1564:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1565:     return ($workbook,$filename,$format);
 1566: }
 1567: 
 1568: ###############################################################
 1569: ###############################################################
 1570: 
 1571: =pod
 1572: 
 1573: =item * &create_text_file()
 1574: 
 1575: Create a file to write to and eventually make available to the user.
 1576: If file creation fails, outputs an error message on the request object and 
 1577: return undefs.
 1578: 
 1579: Inputs: Apache request object, and file suffix
 1580: 
 1581: Returns (undef) on failure, 
 1582:     Filehandle and filename on success.
 1583: 
 1584: =cut
 1585: 
 1586: ###############################################################
 1587: ###############################################################
 1588: sub create_text_file {
 1589:     my ($r,$suffix) = @_;
 1590:     if (! defined($suffix)) { $suffix = 'txt'; };
 1591:     my $fh;
 1592:     my $filename = '/prtspool/'.
 1593:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1594:         time.'_'.rand(1000000000).'.'.$suffix;
 1595:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1596:     if (! defined($fh)) {
 1597:         $r->log_error("Couldn't open $filename for output $!");
 1598:         $r->print(&mt('Problems occurred in creating the output file. '
 1599:                      .'This error has been logged. '
 1600:                      .'Please alert your LON-CAPA administrator.'));
 1601:     }
 1602:     return ($fh,$filename)
 1603: }
 1604: 
 1605: 
 1606: =pod 
 1607: 
 1608: =back
 1609: 
 1610: =cut
 1611: 
 1612: ###############################################################
 1613: ##        Home server <option> list generating code          ##
 1614: ###############################################################
 1615: 
 1616: # ------------------------------------------
 1617: 
 1618: sub domain_select {
 1619:     my ($name,$value,$multiple)=@_;
 1620:     my %domains=map { 
 1621: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1622:     } &Apache::lonnet::all_domains();
 1623:     if ($multiple) {
 1624: 	$domains{''}=&mt('Any domain');
 1625: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1626: 	return &multiple_select_form($name,$value,4,\%domains);
 1627:     } else {
 1628: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1629: 	return &select_form($name,$value,%domains);
 1630:     }
 1631: }
 1632: 
 1633: #-------------------------------------------
 1634: 
 1635: =pod
 1636: 
 1637: =head1 Routines for form select boxes
 1638: 
 1639: =over 4
 1640: 
 1641: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1642: 
 1643: Returns a string containing a <select> element int multiple mode
 1644: 
 1645: 
 1646: Args:
 1647:   $name - name of the <select> element
 1648:   $value - scalar or array ref of values that should already be selected
 1649:   $size - number of rows long the select element is
 1650:   $hash - the elements should be 'option' => 'shown text'
 1651:           (shown text should already have been &mt())
 1652:   $order - (optional) array ref of the order to show the elements in
 1653: 
 1654: =cut
 1655: 
 1656: #-------------------------------------------
 1657: sub multiple_select_form {
 1658:     my ($name,$value,$size,$hash,$order)=@_;
 1659:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1660:     my $output='';
 1661:     if (! defined($size)) {
 1662:         $size = 4;
 1663:         if (scalar(keys(%$hash))<4) {
 1664:             $size = scalar(keys(%$hash));
 1665:         }
 1666:     }
 1667:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1668:     my @order;
 1669:     if (ref($order) eq 'ARRAY')  {
 1670:         @order = @{$order};
 1671:     } else {
 1672:         @order = sort(keys(%$hash));
 1673:     }
 1674:     if (exists($$hash{'select_form_order'})) {
 1675:         @order = @{$$hash{'select_form_order'}};
 1676:     }
 1677:         
 1678:     foreach my $key (@order) {
 1679:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1680:         $output.='selected="selected" ' if ($selected{$key});
 1681:         $output.='>'.$hash->{$key}."</option>\n";
 1682:     }
 1683:     $output.="</select>\n";
 1684:     return $output;
 1685: }
 1686: 
 1687: #-------------------------------------------
 1688: 
 1689: =pod
 1690: 
 1691: =item * &select_form($defdom,$name,%hash)
 1692: 
 1693: Returns a string containing a <select name='$name' size='1'> form to 
 1694: allow a user to select options from a hash option_name => displayed text.  
 1695: See lonrights.pm for an example invocation and use.
 1696: 
 1697: =cut
 1698: 
 1699: #-------------------------------------------
 1700: sub select_form {
 1701:     my ($def,$name,%hash) = @_;
 1702:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1703:     my @keys;
 1704:     if (exists($hash{'select_form_order'})) {
 1705: 	@keys=@{$hash{'select_form_order'}};
 1706:     } else {
 1707: 	@keys=sort(keys(%hash));
 1708:     }
 1709:     foreach my $key (@keys) {
 1710:         $selectform.=
 1711: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1712:             ($key eq $def ? 'selected="selected" ' : '').
 1713:                 ">".&mt($hash{$key})."</option>\n";
 1714:     }
 1715:     $selectform.="</select>";
 1716:     return $selectform;
 1717: }
 1718: 
 1719: # For display filters
 1720: 
 1721: sub display_filter {
 1722:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1723:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1724:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1725: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1726: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1727: 	   '</label></span> <span class="LC_nobreak">'.
 1728:            &mt('Filter [_1]',
 1729: 	   &select_form($env{'form.displayfilter'},
 1730: 			'displayfilter',
 1731: 			('currentfolder' => 'Current folder/page',
 1732: 			 'containing' => 'Containing phrase',
 1733: 			 'none' => 'None'))).
 1734: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1735: }
 1736: 
 1737: sub gradeleveldescription {
 1738:     my $gradelevel=shift;
 1739:     my %gradelevels=(0 => 'Not specified',
 1740: 		     1 => 'Grade 1',
 1741: 		     2 => 'Grade 2',
 1742: 		     3 => 'Grade 3',
 1743: 		     4 => 'Grade 4',
 1744: 		     5 => 'Grade 5',
 1745: 		     6 => 'Grade 6',
 1746: 		     7 => 'Grade 7',
 1747: 		     8 => 'Grade 8',
 1748: 		     9 => 'Grade 9',
 1749: 		     10 => 'Grade 10',
 1750: 		     11 => 'Grade 11',
 1751: 		     12 => 'Grade 12',
 1752: 		     13 => 'Grade 13',
 1753: 		     14 => '100 Level',
 1754: 		     15 => '200 Level',
 1755: 		     16 => '300 Level',
 1756: 		     17 => '400 Level',
 1757: 		     18 => 'Graduate Level');
 1758:     return &mt($gradelevels{$gradelevel});
 1759: }
 1760: 
 1761: sub select_level_form {
 1762:     my ($deflevel,$name)=@_;
 1763:     unless ($deflevel) { $deflevel=0; }
 1764:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1765:     for (my $i=0; $i<=18; $i++) {
 1766:         $selectform.="<option value=\"$i\" ".
 1767:             ($i==$deflevel ? 'selected="selected" ' : '').
 1768:                 ">".&gradeleveldescription($i)."</option>\n";
 1769:     }
 1770:     $selectform.="</select>";
 1771:     return $selectform;
 1772: }
 1773: 
 1774: #-------------------------------------------
 1775: 
 1776: =pod
 1777: 
 1778: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1779: 
 1780: Returns a string containing a <select name='$name' size='1'> form to 
 1781: allow a user to select the domain to preform an operation in.  
 1782: See loncreateuser.pm for an example invocation and use.
 1783: 
 1784: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1785: selected");
 1786: 
 1787: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1788: 
 1789: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.  
 1790: 
 1791: =cut
 1792: 
 1793: #-------------------------------------------
 1794: sub select_dom_form {
 1795:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1796:     my $onchange;
 1797:     if ($autosubmit) {
 1798:         $onchange = ' onchange="this.form.submit()"';
 1799:     }
 1800:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1801:     if ($includeempty) { @domains=('',@domains); }
 1802:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1803:     foreach my $dom (@domains) {
 1804:         $selectdomain.="<option value=\"$dom\" ".
 1805:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1806:         if ($showdomdesc) {
 1807:             if ($dom ne '') {
 1808:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1809:                 if ($domdesc ne '') {
 1810:                     $selectdomain .= ' ('.$domdesc.')';
 1811:                 }
 1812:             } 
 1813:         }
 1814:         $selectdomain .= "</option>\n";
 1815:     }
 1816:     $selectdomain.="</select>";
 1817:     return $selectdomain;
 1818: }
 1819: 
 1820: #-------------------------------------------
 1821: 
 1822: =pod
 1823: 
 1824: =item * &home_server_form_item($domain,$name,$defaultflag)
 1825: 
 1826: input: 4 arguments (two required, two optional) - 
 1827:     $domain - domain of new user
 1828:     $name - name of form element
 1829:     $default - Value of 'default' causes a default item to be first 
 1830:                             option, and selected by default. 
 1831:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1832:                             if 1 server found, or default, if 0 found.
 1833: output: returns 2 items: 
 1834: (a) form element which contains either:
 1835:    (i) <select name="$name">
 1836:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1837:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1838:        </select>
 1839:        form item if there are multiple library servers in $domain, or
 1840:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1841:        if there is only one library server in $domain.
 1842: 
 1843: (b) number of library servers found.
 1844: 
 1845: See loncreateuser.pm for example of use.
 1846: 
 1847: =cut
 1848: 
 1849: #-------------------------------------------
 1850: sub home_server_form_item {
 1851:     my ($domain,$name,$default,$hide) = @_;
 1852:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1853:     my $result;
 1854:     my $numlib = keys(%servers);
 1855:     if ($numlib > 1) {
 1856:         $result .= '<select name="'.$name.'" />'."\n";
 1857:         if ($default) {
 1858:             $result .= '<option value="default" selected>'.&mt('default').
 1859:                        '</option>'."\n";
 1860:         }
 1861:         foreach my $hostid (sort(keys(%servers))) {
 1862:             $result.= '<option value="'.$hostid.'">'.
 1863: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1864:         }
 1865:         $result .= '</select>'."\n";
 1866:     } elsif ($numlib == 1) {
 1867:         my $hostid;
 1868:         foreach my $item (keys(%servers)) {
 1869:             $hostid = $item;
 1870:         }
 1871:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1872:                    $hostid.'" />';
 1873:                    if (!$hide) {
 1874:                        $result .= $hostid.' '.$servers{$hostid};
 1875:                    }
 1876:                    $result .= "\n";
 1877:     } elsif ($default) {
 1878:         $result .= '<input type="hidden" name="'.$name.
 1879:                    '" value="default" />';
 1880:                    if (!$hide) {
 1881:                        $result .= &mt('default');
 1882:                    }
 1883:                    $result .= "\n";
 1884:     }
 1885:     return ($result,$numlib);
 1886: }
 1887: 
 1888: =pod
 1889: 
 1890: =back 
 1891: 
 1892: =cut
 1893: 
 1894: ###############################################################
 1895: ##                  Decoding User Agent                      ##
 1896: ###############################################################
 1897: 
 1898: =pod
 1899: 
 1900: =head1 Decoding the User Agent
 1901: 
 1902: =over 4
 1903: 
 1904: =item * &decode_user_agent()
 1905: 
 1906: Inputs: $r
 1907: 
 1908: Outputs:
 1909: 
 1910: =over 4
 1911: 
 1912: =item * $httpbrowser
 1913: 
 1914: =item * $clientbrowser
 1915: 
 1916: =item * $clientversion
 1917: 
 1918: =item * $clientmathml
 1919: 
 1920: =item * $clientunicode
 1921: 
 1922: =item * $clientos
 1923: 
 1924: =back
 1925: 
 1926: =back 
 1927: 
 1928: =cut
 1929: 
 1930: ###############################################################
 1931: ###############################################################
 1932: sub decode_user_agent {
 1933:     my ($r)=@_;
 1934:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1935:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1936:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1937:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1938:     my $clientbrowser='unknown';
 1939:     my $clientversion='0';
 1940:     my $clientmathml='';
 1941:     my $clientunicode='0';
 1942:     for (my $i=0;$i<=$#browsertype;$i++) {
 1943:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1944: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1945: 	    $clientbrowser=$bname;
 1946:             $httpbrowser=~/$vreg/i;
 1947: 	    $clientversion=$1;
 1948:             $clientmathml=($clientversion>=$minv);
 1949:             $clientunicode=($clientversion>=$univ);
 1950: 	}
 1951:     }
 1952:     my $clientos='unknown';
 1953:     if (($httpbrowser=~/linux/i) ||
 1954:         ($httpbrowser=~/unix/i) ||
 1955:         ($httpbrowser=~/ux/i) ||
 1956:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1957:     if (($httpbrowser=~/vax/i) ||
 1958:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1959:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1960:     if (($httpbrowser=~/mac/i) ||
 1961:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1962:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1963:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1964:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1965:             $clientunicode,$clientos,);
 1966: }
 1967: 
 1968: ###############################################################
 1969: ##    Authentication changing form generation subroutines    ##
 1970: ###############################################################
 1971: ##
 1972: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1973: ## hash, and have reasonable default values.
 1974: ##
 1975: ##    formname = the name given in the <form> tag.
 1976: #-------------------------------------------
 1977: 
 1978: =pod
 1979: 
 1980: =head1 Authentication Routines
 1981: 
 1982: =over 4
 1983: 
 1984: =item * &authform_xxxxxx()
 1985: 
 1986: The authform_xxxxxx subroutines provide javascript and html forms which 
 1987: handle some of the conveniences required for authentication forms.  
 1988: This is not an optimal method, but it works.  
 1989: 
 1990: =over 4
 1991: 
 1992: =item * authform_header
 1993: 
 1994: =item * authform_authorwarning
 1995: 
 1996: =item * authform_nochange
 1997: 
 1998: =item * authform_kerberos
 1999: 
 2000: =item * authform_internal
 2001: 
 2002: =item * authform_filesystem
 2003: 
 2004: =back
 2005: 
 2006: See loncreateuser.pm for invocation and use examples.
 2007: 
 2008: =cut
 2009: 
 2010: #-------------------------------------------
 2011: sub authform_header{  
 2012:     my %in = (
 2013:         formname => 'cu',
 2014:         kerb_def_dom => '',
 2015:         @_,
 2016:     );
 2017:     $in{'formname'} = 'document.' . $in{'formname'};
 2018:     my $result='';
 2019: 
 2020: #---------------------------------------------- Code for upper case translation
 2021:     my $Javascript_toUpperCase;
 2022:     unless ($in{kerb_def_dom}) {
 2023:         $Javascript_toUpperCase =<<"END";
 2024:         switch (choice) {
 2025:            case 'krb': currentform.elements[choicearg].value =
 2026:                currentform.elements[choicearg].value.toUpperCase();
 2027:                break;
 2028:            default:
 2029:         }
 2030: END
 2031:     } else {
 2032:         $Javascript_toUpperCase = "";
 2033:     }
 2034: 
 2035:     my $radioval = "'nochange'";
 2036:     if (defined($in{'curr_authtype'})) {
 2037:         if ($in{'curr_authtype'} ne '') {
 2038:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2039:         }
 2040:     }
 2041:     my $argfield = 'null';
 2042:     if (defined($in{'mode'})) {
 2043:         if ($in{'mode'} eq 'modifycourse')  {
 2044:             if (defined($in{'curr_autharg'})) {
 2045:                 if ($in{'curr_autharg'} ne '') {
 2046:                     $argfield = "'$in{'curr_autharg'}'";
 2047:                 }
 2048:             }
 2049:         }
 2050:     }
 2051: 
 2052:     $result.=<<"END";
 2053: var current = new Object();
 2054: current.radiovalue = $radioval;
 2055: current.argfield = $argfield;
 2056: 
 2057: function changed_radio(choice,currentform) {
 2058:     var choicearg = choice + 'arg';
 2059:     // If a radio button in changed, we need to change the argfield
 2060:     if (current.radiovalue != choice) {
 2061:         current.radiovalue = choice;
 2062:         if (current.argfield != null) {
 2063:             currentform.elements[current.argfield].value = '';
 2064:         }
 2065:         if (choice == 'nochange') {
 2066:             current.argfield = null;
 2067:         } else {
 2068:             current.argfield = choicearg;
 2069:             switch(choice) {
 2070:                 case 'krb': 
 2071:                     currentform.elements[current.argfield].value = 
 2072:                         "$in{'kerb_def_dom'}";
 2073:                 break;
 2074:               default:
 2075:                 break;
 2076:             }
 2077:         }
 2078:     }
 2079:     return;
 2080: }
 2081: 
 2082: function changed_text(choice,currentform) {
 2083:     var choicearg = choice + 'arg';
 2084:     if (currentform.elements[choicearg].value !='') {
 2085:         $Javascript_toUpperCase
 2086:         // clear old field
 2087:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2088:             currentform.elements[current.argfield].value = '';
 2089:         }
 2090:         current.argfield = choicearg;
 2091:     }
 2092:     set_auth_radio_buttons(choice,currentform);
 2093:     return;
 2094: }
 2095: 
 2096: function set_auth_radio_buttons(newvalue,currentform) {
 2097:     var i=0;
 2098:     while (i < currentform.login.length) {
 2099:         if (currentform.login[i].value == newvalue) { break; }
 2100:         i++;
 2101:     }
 2102:     if (i == currentform.login.length) {
 2103:         return;
 2104:     }
 2105:     current.radiovalue = newvalue;
 2106:     currentform.login[i].checked = true;
 2107:     return;
 2108: }
 2109: END
 2110:     return $result;
 2111: }
 2112: 
 2113: sub authform_authorwarning{
 2114:     my $result='';
 2115:     $result='<i>'.
 2116:         &mt('As a general rule, only authors or co-authors should be '.
 2117:             'filesystem authenticated '.
 2118:             '(which allows access to the server filesystem).')."</i>\n";
 2119:     return $result;
 2120: }
 2121: 
 2122: sub authform_nochange{  
 2123:     my %in = (
 2124:               formname => 'document.cu',
 2125:               kerb_def_dom => 'MSU.EDU',
 2126:               @_,
 2127:           );
 2128:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2129:     my $result;
 2130:     if (keys(%can_assign) == 0) {
 2131:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2132:     } else {
 2133:         $result = '<label>'.&mt('[_1] Do not change login data',
 2134:                   '<input type="radio" name="login" value="nochange" '.
 2135:                   'checked="checked" onclick="'.
 2136:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2137: 	    '</label>';
 2138:     }
 2139:     return $result;
 2140: }
 2141: 
 2142: sub authform_kerberos {
 2143:     my %in = (
 2144:               formname => 'document.cu',
 2145:               kerb_def_dom => 'MSU.EDU',
 2146:               kerb_def_auth => 'krb4',
 2147:               @_,
 2148:               );
 2149:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2150:         $autharg,$jscall);
 2151:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2152:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2153:        $check5 = ' checked="checked"';
 2154:     } else {
 2155:        $check4 = ' checked="checked"';
 2156:     }
 2157:     $krbarg = $in{'kerb_def_dom'};
 2158:     if (defined($in{'curr_authtype'})) {
 2159:         if ($in{'curr_authtype'} eq 'krb') {
 2160:             $krbcheck = ' checked="checked"';
 2161:             if (defined($in{'mode'})) {
 2162:                 if ($in{'mode'} eq 'modifyuser') {
 2163:                     $krbcheck = '';
 2164:                 }
 2165:             }
 2166:             if (defined($in{'curr_kerb_ver'})) {
 2167:                 if ($in{'curr_krb_ver'} eq '5') {
 2168:                     $check5 = ' checked="checked"';
 2169:                     $check4 = '';
 2170:                 } else {
 2171:                     $check4 = ' checked="checked"';
 2172:                     $check5 = '';
 2173:                 }
 2174:             }
 2175:             if (defined($in{'curr_autharg'})) {
 2176:                 $krbarg = $in{'curr_autharg'};
 2177:             }
 2178:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2179:                 if (defined($in{'curr_autharg'})) {
 2180:                     $result = 
 2181:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2182:         $in{'curr_autharg'},$krbver);
 2183:                 } else {
 2184:                     $result =
 2185:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2186:                 }
 2187:                 return $result; 
 2188:             }
 2189:         }
 2190:     } else {
 2191:         if ($authnum == 1) {
 2192:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2193:         }
 2194:     }
 2195:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2196:         return;
 2197:     } elsif ($authtype eq '') {
 2198:         if (defined($in{'mode'})) {
 2199:             if ($in{'mode'} eq 'modifycourse') {
 2200:                 if ($authnum == 1) {
 2201:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2202:                 }
 2203:             }
 2204:         }
 2205:     }
 2206:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2207:     if ($authtype eq '') {
 2208:         $authtype = '<input type="radio" name="login" value="krb" '.
 2209:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2210:                     $krbcheck.' />';
 2211:     }
 2212:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2213:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2214:          $in{'curr_authtype'} eq 'krb5') ||
 2215:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2216:          $in{'curr_authtype'} eq 'krb4')) {
 2217:         $result .= &mt
 2218:         ('[_1] Kerberos authenticated with domain [_2] '.
 2219:          '[_3] Version 4 [_4] Version 5 [_5]',
 2220:          '<label>'.$authtype,
 2221:          '</label><input type="text" size="10" name="krbarg" '.
 2222:              'value="'.$krbarg.'" '.
 2223:              'onchange="'.$jscall.'" />',
 2224:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2225:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2226: 	 '</label>');
 2227:     } elsif ($can_assign{'krb4'}) {
 2228:         $result .= &mt
 2229:         ('[_1] Kerberos authenticated with domain [_2] '.
 2230:          '[_3] Version 4 [_4]',
 2231:          '<label>'.$authtype,
 2232:          '</label><input type="text" size="10" name="krbarg" '.
 2233:              'value="'.$krbarg.'" '.
 2234:              'onchange="'.$jscall.'" />',
 2235:          '<label><input type="hidden" name="krbver" value="4" />',
 2236:          '</label>');
 2237:     } elsif ($can_assign{'krb5'}) {
 2238:         $result .= &mt
 2239:         ('[_1] Kerberos authenticated with domain [_2] '.
 2240:          '[_3] Version 5 [_4]',
 2241:          '<label>'.$authtype,
 2242:          '</label><input type="text" size="10" name="krbarg" '.
 2243:              'value="'.$krbarg.'" '.
 2244:              'onchange="'.$jscall.'" />',
 2245:          '<label><input type="hidden" name="krbver" value="5" />',
 2246:          '</label>');
 2247:     }
 2248:     return $result;
 2249: }
 2250: 
 2251: sub authform_internal{  
 2252:     my %in = (
 2253:                 formname => 'document.cu',
 2254:                 kerb_def_dom => 'MSU.EDU',
 2255:                 @_,
 2256:                 );
 2257:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2258:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2259:     if (defined($in{'curr_authtype'})) {
 2260:         if ($in{'curr_authtype'} eq 'int') {
 2261:             if ($can_assign{'int'}) {
 2262:                 $intcheck = 'checked="checked" ';
 2263:                 if (defined($in{'mode'})) {
 2264:                     if ($in{'mode'} eq 'modifyuser') {
 2265:                         $intcheck = '';
 2266:                     }
 2267:                 }
 2268:                 if (defined($in{'curr_autharg'})) {
 2269:                     $intarg = $in{'curr_autharg'};
 2270:                 }
 2271:             } else {
 2272:                 $result = &mt('Currently internally authenticated.');
 2273:                 return $result;
 2274:             }
 2275:         }
 2276:     } else {
 2277:         if ($authnum == 1) {
 2278:             $authtype = '<input type="hidden" name="login" value="int" />';
 2279:         }
 2280:     }
 2281:     if (!$can_assign{'int'}) {
 2282:         return;
 2283:     } elsif ($authtype eq '') {
 2284:         if (defined($in{'mode'})) {
 2285:             if ($in{'mode'} eq 'modifycourse') {
 2286:                 if ($authnum == 1) {
 2287:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2288:                 }
 2289:             }
 2290:         }
 2291:     }
 2292:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2293:     if ($authtype eq '') {
 2294:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2295:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2296:     }
 2297:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2298:                $intarg.'" onchange="'.$jscall.'" />';
 2299:     $result = &mt
 2300:         ('[_1] Internally authenticated (with initial password [_2])',
 2301:          '<label>'.$authtype,'</label>'.$autharg);
 2302:     $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>';
 2303:     return $result;
 2304: }
 2305: 
 2306: sub authform_local{  
 2307:     my %in = (
 2308:               formname => 'document.cu',
 2309:               kerb_def_dom => 'MSU.EDU',
 2310:               @_,
 2311:               );
 2312:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2313:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2314:     if (defined($in{'curr_authtype'})) {
 2315:         if ($in{'curr_authtype'} eq 'loc') {
 2316:             if ($can_assign{'loc'}) {
 2317:                 $loccheck = 'checked="checked" ';
 2318:                 if (defined($in{'mode'})) {
 2319:                     if ($in{'mode'} eq 'modifyuser') {
 2320:                         $loccheck = '';
 2321:                     }
 2322:                 }
 2323:                 if (defined($in{'curr_autharg'})) {
 2324:                     $locarg = $in{'curr_autharg'};
 2325:                 }
 2326:             } else {
 2327:                 $result = &mt('Currently using local (institutional) authentication.');
 2328:                 return $result;
 2329:             }
 2330:         }
 2331:     } else {
 2332:         if ($authnum == 1) {
 2333:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2334:         }
 2335:     }
 2336:     if (!$can_assign{'loc'}) {
 2337:         return;
 2338:     } elsif ($authtype eq '') {
 2339:         if (defined($in{'mode'})) {
 2340:             if ($in{'mode'} eq 'modifycourse') {
 2341:                 if ($authnum == 1) {
 2342:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2343:                 }
 2344:             }
 2345:         }
 2346:     }
 2347:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2348:     if ($authtype eq '') {
 2349:         $authtype = '<input type="radio" name="login" value="loc" '.
 2350:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2351:                     $jscall.'" />';
 2352:     }
 2353:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2354:                $locarg.'" onchange="'.$jscall.'" />';
 2355:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2356:                   '<label>'.$authtype,'</label>'.$autharg);
 2357:     return $result;
 2358: }
 2359: 
 2360: sub authform_filesystem{  
 2361:     my %in = (
 2362:               formname => 'document.cu',
 2363:               kerb_def_dom => 'MSU.EDU',
 2364:               @_,
 2365:               );
 2366:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2367:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2368:     if (defined($in{'curr_authtype'})) {
 2369:         if ($in{'curr_authtype'} eq 'fsys') {
 2370:             if ($can_assign{'fsys'}) {
 2371:                 $fsyscheck = 'checked="checked" ';
 2372:                 if (defined($in{'mode'})) {
 2373:                     if ($in{'mode'} eq 'modifyuser') {
 2374:                         $fsyscheck = '';
 2375:                     }
 2376:                 }
 2377:             } else {
 2378:                 $result = &mt('Currently Filesystem Authenticated.');
 2379:                 return $result;
 2380:             }           
 2381:         }
 2382:     } else {
 2383:         if ($authnum == 1) {
 2384:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2385:         }
 2386:     }
 2387:     if (!$can_assign{'fsys'}) {
 2388:         return;
 2389:     } elsif ($authtype eq '') {
 2390:         if (defined($in{'mode'})) {
 2391:             if ($in{'mode'} eq 'modifycourse') {
 2392:                 if ($authnum == 1) {
 2393:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2394:                 }
 2395:             }
 2396:         }
 2397:     }
 2398:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2399:     if ($authtype eq '') {
 2400:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2401:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2402:                     $jscall.'" />';
 2403:     }
 2404:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2405:                ' onchange="'.$jscall.'" />';
 2406:     $result = &mt
 2407:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2408:          '<label><input type="radio" name="login" value="fsys" '.
 2409:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2410:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2411:                   'onchange="'.$jscall.'" />');
 2412:     return $result;
 2413: }
 2414: 
 2415: sub get_assignable_auth {
 2416:     my ($dom) = @_;
 2417:     if ($dom eq '') {
 2418:         $dom = $env{'request.role.domain'};
 2419:     }
 2420:     my %can_assign = (
 2421:                           krb4 => 1,
 2422:                           krb5 => 1,
 2423:                           int  => 1,
 2424:                           loc  => 1,
 2425:                      );
 2426:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2427:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2428:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2429:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2430:             my $context;
 2431:             if ($env{'request.role'} =~ /^au/) {
 2432:                 $context = 'author';
 2433:             } elsif ($env{'request.role'} =~ /^dc/) {
 2434:                 $context = 'domain';
 2435:             } elsif ($env{'request.course.id'}) {
 2436:                 $context = 'course';
 2437:             }
 2438:             if ($context) {
 2439:                 if (ref($authhash->{$context}) eq 'HASH') {
 2440:                    %can_assign = %{$authhash->{$context}}; 
 2441:                 }
 2442:             }
 2443:         }
 2444:     }
 2445:     my $authnum = 0;
 2446:     foreach my $key (keys(%can_assign)) {
 2447:         if ($can_assign{$key}) {
 2448:             $authnum ++;
 2449:         }
 2450:     }
 2451:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2452:         $authnum --;
 2453:     }
 2454:     return ($authnum,%can_assign);
 2455: }
 2456: 
 2457: ###############################################################
 2458: ##    Get Kerberos Defaults for Domain                 ##
 2459: ###############################################################
 2460: ##
 2461: ## Returns default kerberos version and an associated argument
 2462: ## as listed in file domain.tab. If not listed, provides
 2463: ## appropriate default domain and kerberos version.
 2464: ##
 2465: #-------------------------------------------
 2466: 
 2467: =pod
 2468: 
 2469: =item * &get_kerberos_defaults()
 2470: 
 2471: get_kerberos_defaults($target_domain) returns the default kerberos
 2472: version and domain. If not found, it defaults to version 4 and the 
 2473: domain of the server.
 2474: 
 2475: =over 4
 2476: 
 2477: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2478: 
 2479: =back
 2480: 
 2481: =back
 2482: 
 2483: =cut
 2484: 
 2485: #-------------------------------------------
 2486: sub get_kerberos_defaults {
 2487:     my $domain=shift;
 2488:     my ($krbdef,$krbdefdom);
 2489:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2490:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2491:         $krbdef = $domdefaults{'auth_def'};
 2492:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2493:     } else {
 2494:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2495:         my $krbdefdom=$1;
 2496:         $krbdefdom=~tr/a-z/A-Z/;
 2497:         $krbdef = "krb4";
 2498:     }
 2499:     return ($krbdef,$krbdefdom);
 2500: }
 2501: 
 2502: 
 2503: ###############################################################
 2504: ##                Thesaurus Functions                        ##
 2505: ###############################################################
 2506: 
 2507: =pod
 2508: 
 2509: =head1 Thesaurus Functions
 2510: 
 2511: =over 4
 2512: 
 2513: =item * &initialize_keywords()
 2514: 
 2515: Initializes the package variable %Keywords if it is empty.  Uses the
 2516: package variable $thesaurus_db_file.
 2517: 
 2518: =cut
 2519: 
 2520: ###################################################
 2521: 
 2522: sub initialize_keywords {
 2523:     return 1 if (scalar keys(%Keywords));
 2524:     # If we are here, %Keywords is empty, so fill it up
 2525:     #   Make sure the file we need exists...
 2526:     if (! -e $thesaurus_db_file) {
 2527:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2528:                                  " failed because it does not exist");
 2529:         return 0;
 2530:     }
 2531:     #   Set up the hash as a database
 2532:     my %thesaurus_db;
 2533:     if (! tie(%thesaurus_db,'GDBM_File',
 2534:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2535:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2536:                                  $thesaurus_db_file);
 2537:         return 0;
 2538:     } 
 2539:     #  Get the average number of appearances of a word.
 2540:     my $avecount = $thesaurus_db{'average.count'};
 2541:     #  Put keywords (those that appear > average) into %Keywords
 2542:     while (my ($word,$data)=each (%thesaurus_db)) {
 2543:         my ($count,undef) = split /:/,$data;
 2544:         $Keywords{$word}++ if ($count > $avecount);
 2545:     }
 2546:     untie %thesaurus_db;
 2547:     # Remove special values from %Keywords.
 2548:     foreach my $value ('total.count','average.count') {
 2549:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2550:   }
 2551:     return 1;
 2552: }
 2553: 
 2554: ###################################################
 2555: 
 2556: =pod
 2557: 
 2558: =item * &keyword($word)
 2559: 
 2560: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2561: than the average number of times in the thesaurus database.  Calls 
 2562: &initialize_keywords
 2563: 
 2564: =cut
 2565: 
 2566: ###################################################
 2567: 
 2568: sub keyword {
 2569:     return if (!&initialize_keywords());
 2570:     my $word=lc(shift());
 2571:     $word=~s/\W//g;
 2572:     return exists($Keywords{$word});
 2573: }
 2574: 
 2575: ###############################################################
 2576: 
 2577: =pod 
 2578: 
 2579: =item * &get_related_words()
 2580: 
 2581: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2582: an array of words.  If the keyword is not in the thesaurus, an empty array
 2583: will be returned.  The order of the words returned is determined by the
 2584: database which holds them.
 2585: 
 2586: Uses global $thesaurus_db_file.
 2587: 
 2588: =cut
 2589: 
 2590: ###############################################################
 2591: sub get_related_words {
 2592:     my $keyword = shift;
 2593:     my %thesaurus_db;
 2594:     if (! -e $thesaurus_db_file) {
 2595:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2596:                                  "failed because the file does not exist");
 2597:         return ();
 2598:     }
 2599:     if (! tie(%thesaurus_db,'GDBM_File',
 2600:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2601:         return ();
 2602:     } 
 2603:     my @Words=();
 2604:     my $count=0;
 2605:     if (exists($thesaurus_db{$keyword})) {
 2606: 	# The first element is the number of times
 2607: 	# the word appears.  We do not need it now.
 2608: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2609: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2610: 	my $threshold=$mostfrequentcount/10;
 2611:         foreach my $possibleword (@RelatedWords) {
 2612:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2613:             if ($wordcount>$threshold) {
 2614: 		push(@Words,$word);
 2615:                 $count++;
 2616:                 if ($count>10) { last; }
 2617: 	    }
 2618:         }
 2619:     }
 2620:     untie %thesaurus_db;
 2621:     return @Words;
 2622: }
 2623: 
 2624: =pod
 2625: 
 2626: =back
 2627: 
 2628: =cut
 2629: 
 2630: # -------------------------------------------------------------- Plaintext name
 2631: =pod
 2632: 
 2633: =head1 User Name Functions
 2634: 
 2635: =over 4
 2636: 
 2637: =item * &plainname($uname,$udom,$first)
 2638: 
 2639: Takes a users logon name and returns it as a string in
 2640: "first middle last generation" form 
 2641: if $first is set to 'lastname' then it returns it as
 2642: 'lastname generation, firstname middlename' if their is a lastname
 2643: 
 2644: =cut
 2645: 
 2646: 
 2647: ###############################################################
 2648: sub plainname {
 2649:     my ($uname,$udom,$first)=@_;
 2650:     return if (!defined($uname) || !defined($udom));
 2651:     my %names=&getnames($uname,$udom);
 2652:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2653: 					  $names{'middlename'},
 2654: 					  $names{'lastname'},
 2655: 					  $names{'generation'},$first);
 2656:     $name=~s/^\s+//;
 2657:     $name=~s/\s+$//;
 2658:     $name=~s/\s+/ /g;
 2659:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2660:     return $name;
 2661: }
 2662: 
 2663: # -------------------------------------------------------------------- Nickname
 2664: =pod
 2665: 
 2666: =item * &nickname($uname,$udom)
 2667: 
 2668: Gets a users name and returns it as a string as
 2669: 
 2670: "&quot;nickname&quot;"
 2671: 
 2672: if the user has a nickname or
 2673: 
 2674: "first middle last generation"
 2675: 
 2676: if the user does not
 2677: 
 2678: =cut
 2679: 
 2680: sub nickname {
 2681:     my ($uname,$udom)=@_;
 2682:     return if (!defined($uname) || !defined($udom));
 2683:     my %names=&getnames($uname,$udom);
 2684:     my $name=$names{'nickname'};
 2685:     if ($name) {
 2686:        $name='&quot;'.$name.'&quot;'; 
 2687:     } else {
 2688:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2689: 	     $names{'lastname'}.' '.$names{'generation'};
 2690:        $name=~s/\s+$//;
 2691:        $name=~s/\s+/ /g;
 2692:     }
 2693:     return $name;
 2694: }
 2695: 
 2696: sub getnames {
 2697:     my ($uname,$udom)=@_;
 2698:     return if (!defined($uname) || !defined($udom));
 2699:     if ($udom eq 'public' && $uname eq 'public') {
 2700: 	return ('lastname' => &mt('Public'));
 2701:     }
 2702:     my $id=$uname.':'.$udom;
 2703:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2704:     if ($cached) {
 2705: 	return %{$names};
 2706:     } else {
 2707: 	my %loadnames=&Apache::lonnet::get('environment',
 2708:                     ['firstname','middlename','lastname','generation','nickname'],
 2709: 					 $udom,$uname);
 2710: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2711: 	return %loadnames;
 2712:     }
 2713: }
 2714: 
 2715: # -------------------------------------------------------------------- getemails
 2716: 
 2717: =pod
 2718: 
 2719: =item * &getemails($uname,$udom)
 2720: 
 2721: Gets a user's email information and returns it as a hash with keys:
 2722: notification, critnotification, permanentemail
 2723: 
 2724: For notification and critnotification, values are comma-separated lists 
 2725: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2726:  
 2727: 
 2728: =cut
 2729: 
 2730: 
 2731: sub getemails {
 2732:     my ($uname,$udom)=@_;
 2733:     if ($udom eq 'public' && $uname eq 'public') {
 2734: 	return;
 2735:     }
 2736:     if (!$udom) { $udom=$env{'user.domain'}; }
 2737:     if (!$uname) { $uname=$env{'user.name'}; }
 2738:     my $id=$uname.':'.$udom;
 2739:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2740:     if ($cached) {
 2741: 	return %{$names};
 2742:     } else {
 2743: 	my %loadnames=&Apache::lonnet::get('environment',
 2744:                     			   ['notification','critnotification',
 2745: 					    'permanentemail'],
 2746: 					   $udom,$uname);
 2747: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2748: 	return %loadnames;
 2749:     }
 2750: }
 2751: 
 2752: sub flush_email_cache {
 2753:     my ($uname,$udom)=@_;
 2754:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2755:     if (!$uname) { $uname=$env{'user.name'};   }
 2756:     return if ($udom eq 'public' && $uname eq 'public');
 2757:     my $id=$uname.':'.$udom;
 2758:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2759: }
 2760: 
 2761: # -------------------------------------------------------------------- getlangs
 2762: 
 2763: =pod
 2764: 
 2765: =item * &getlangs($uname,$udom)
 2766: 
 2767: Gets a user's language preference and returns it as a hash with key:
 2768: language.
 2769: 
 2770: =cut
 2771: 
 2772: 
 2773: sub getlangs {
 2774:     my ($uname,$udom) = @_;
 2775:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2776:     if (!$uname) { $uname=$env{'user.name'};   }
 2777:     my $id=$uname.':'.$udom;
 2778:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2779:     if ($cached) {
 2780:         return %{$langs};
 2781:     } else {
 2782:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2783:                                            $udom,$uname);
 2784:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2785:         return %loadlangs;
 2786:     }
 2787: }
 2788: 
 2789: sub flush_langs_cache {
 2790:     my ($uname,$udom)=@_;
 2791:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2792:     if (!$uname) { $uname=$env{'user.name'};   }
 2793:     return if ($udom eq 'public' && $uname eq 'public');
 2794:     my $id=$uname.':'.$udom;
 2795:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2796: }
 2797: 
 2798: # ------------------------------------------------------------------ Screenname
 2799: 
 2800: =pod
 2801: 
 2802: =item * &screenname($uname,$udom)
 2803: 
 2804: Gets a users screenname and returns it as a string
 2805: 
 2806: =cut
 2807: 
 2808: sub screenname {
 2809:     my ($uname,$udom)=@_;
 2810:     if ($uname eq $env{'user.name'} &&
 2811: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2812:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2813:     return $names{'screenname'};
 2814: }
 2815: 
 2816: 
 2817: # ------------------------------------------------------------- Message Wrapper
 2818: 
 2819: sub messagewrapper {
 2820:     my ($link,$username,$domain,$subject,$text)=@_;
 2821:     return 
 2822:         '<a href="/adm/email?compose=individual&amp;'.
 2823:         'recname='.$username.'&amp;recdom='.$domain.
 2824: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2825:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2826: }
 2827: # --------------------------------------------------------------- Notes Wrapper
 2828: 
 2829: sub noteswrapper {
 2830:     my ($link,$un,$do)=@_;
 2831:     return 
 2832: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2833: }
 2834: # ------------------------------------------------------------- Aboutme Wrapper
 2835: 
 2836: sub aboutmewrapper {
 2837:     my ($link,$username,$domain,$target)=@_;
 2838:     if (!defined($username)  && !defined($domain)) {
 2839:         return;
 2840:     }
 2841:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2842: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2843: }
 2844: 
 2845: # ------------------------------------------------------------ Syllabus Wrapper
 2846: 
 2847: 
 2848: sub syllabuswrapper {
 2849:     my ($linktext,$coursedir,$domain)=@_;
 2850:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2851: }
 2852: 
 2853: sub track_student_link {
 2854:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2855:     my $link ="/adm/trackstudent?";
 2856:     my $title = 'View recent activity';
 2857:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2858:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2859:         $link .= "selected_student=$sname:$sdom";
 2860:         $title .= ' of this student';
 2861:     } 
 2862:     if (defined($target) && $target !~ /^\s*$/) {
 2863:         $target = qq{target="$target"};
 2864:     } else {
 2865:         $target = '';
 2866:     }
 2867:     if ($start) { $link.='&amp;start='.$start; }
 2868:     $title = &mt($title);
 2869:     $linktext = &mt($linktext);
 2870:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2871: 	&help_open_topic('View_recent_activity');
 2872: }
 2873: 
 2874: sub slot_reservations_link {
 2875:     my ($linktext,$sname,$sdom,$target) = @_;
 2876:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2877:     my $title = 'View slot reservation history';
 2878:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2879:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2880:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2881:         $title .= ' of this student';
 2882:     }
 2883:     if (defined($target) && $target !~ /^\s*$/) {
 2884:         $target = qq{target="$target"};
 2885:     } else {
 2886:         $target = '';
 2887:     }
 2888:     $title = &mt($title);
 2889:     $linktext = &mt($linktext);
 2890:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2891: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2892: 
 2893: }
 2894: 
 2895: # ===================================================== Display a student photo
 2896: 
 2897: 
 2898: sub student_image_tag {
 2899:     my ($domain,$user)=@_;
 2900:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2901:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2902: 	return '<img src="'.$imgsrc.'" align="right" />';
 2903:     } else {
 2904: 	return '';
 2905:     }
 2906: }
 2907: 
 2908: =pod
 2909: 
 2910: =back
 2911: 
 2912: =head1 Access .tab File Data
 2913: 
 2914: =over 4
 2915: 
 2916: =item * &languageids() 
 2917: 
 2918: returns list of all language ids
 2919: 
 2920: =cut
 2921: 
 2922: sub languageids {
 2923:     return sort(keys(%language));
 2924: }
 2925: 
 2926: =pod
 2927: 
 2928: =item * &languagedescription() 
 2929: 
 2930: returns description of a specified language id
 2931: 
 2932: =cut
 2933: 
 2934: sub languagedescription {
 2935:     my $code=shift;
 2936:     return  ($supported_language{$code}?'* ':'').
 2937:             $language{$code}.
 2938: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2939: }
 2940: 
 2941: sub plainlanguagedescription {
 2942:     my $code=shift;
 2943:     return $language{$code};
 2944: }
 2945: 
 2946: sub supportedlanguagecode {
 2947:     my $code=shift;
 2948:     return $supported_language{$code};
 2949: }
 2950: 
 2951: =pod
 2952: 
 2953: =item * &copyrightids() 
 2954: 
 2955: returns list of all copyrights
 2956: 
 2957: =cut
 2958: 
 2959: sub copyrightids {
 2960:     return sort(keys(%cprtag));
 2961: }
 2962: 
 2963: =pod
 2964: 
 2965: =item * &copyrightdescription() 
 2966: 
 2967: returns description of a specified copyright id
 2968: 
 2969: =cut
 2970: 
 2971: sub copyrightdescription {
 2972:     return &mt($cprtag{shift(@_)});
 2973: }
 2974: 
 2975: =pod
 2976: 
 2977: =item * &source_copyrightids() 
 2978: 
 2979: returns list of all source copyrights
 2980: 
 2981: =cut
 2982: 
 2983: sub source_copyrightids {
 2984:     return sort(keys(%scprtag));
 2985: }
 2986: 
 2987: =pod
 2988: 
 2989: =item * &source_copyrightdescription() 
 2990: 
 2991: returns description of a specified source copyright id
 2992: 
 2993: =cut
 2994: 
 2995: sub source_copyrightdescription {
 2996:     return &mt($scprtag{shift(@_)});
 2997: }
 2998: 
 2999: =pod
 3000: 
 3001: =item * &filecategories() 
 3002: 
 3003: returns list of all file categories
 3004: 
 3005: =cut
 3006: 
 3007: sub filecategories {
 3008:     return sort(keys(%category_extensions));
 3009: }
 3010: 
 3011: =pod
 3012: 
 3013: =item * &filecategorytypes() 
 3014: 
 3015: returns list of file types belonging to a given file
 3016: category
 3017: 
 3018: =cut
 3019: 
 3020: sub filecategorytypes {
 3021:     my ($cat) = @_;
 3022:     return @{$category_extensions{lc($cat)}};
 3023: }
 3024: 
 3025: =pod
 3026: 
 3027: =item * &fileembstyle() 
 3028: 
 3029: returns embedding style for a specified file type
 3030: 
 3031: =cut
 3032: 
 3033: sub fileembstyle {
 3034:     return $fe{lc(shift(@_))};
 3035: }
 3036: 
 3037: sub filemimetype {
 3038:     return $fm{lc(shift(@_))};
 3039: }
 3040: 
 3041: 
 3042: sub filecategoryselect {
 3043:     my ($name,$value)=@_;
 3044:     return &select_form($value,$name,
 3045: 			'' => &mt('Any category'),
 3046: 			map { $_,$_ } sort(keys(%category_extensions)));
 3047: }
 3048: 
 3049: =pod
 3050: 
 3051: =item * &filedescription() 
 3052: 
 3053: returns description for a specified file type
 3054: 
 3055: =cut
 3056: 
 3057: sub filedescription {
 3058:     my $file_description = $fd{lc(shift())};
 3059:     $file_description =~ s:([\[\]]):~$1:g;
 3060:     return &mt($file_description);
 3061: }
 3062: 
 3063: =pod
 3064: 
 3065: =item * &filedescriptionex() 
 3066: 
 3067: returns description for a specified file type with
 3068: extra formatting
 3069: 
 3070: =cut
 3071: 
 3072: sub filedescriptionex {
 3073:     my $ex=shift;
 3074:     my $file_description = $fd{lc($ex)};
 3075:     $file_description =~ s:([\[\]]):~$1:g;
 3076:     return '.'.$ex.' '.&mt($file_description);
 3077: }
 3078: 
 3079: # End of .tab access
 3080: =pod
 3081: 
 3082: =back
 3083: 
 3084: =cut
 3085: 
 3086: # ------------------------------------------------------------------ File Types
 3087: sub fileextensions {
 3088:     return sort(keys(%fe));
 3089: }
 3090: 
 3091: # ----------------------------------------------------------- Display Languages
 3092: # returns a hash with all desired display languages
 3093: #
 3094: 
 3095: sub display_languages {
 3096:     my %languages=();
 3097:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3098: 	$languages{$lang}=1;
 3099:     }
 3100:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3101:     if ($env{'form.displaylanguage'}) {
 3102: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3103: 	    $languages{$lang}=1;
 3104:         }
 3105:     }
 3106:     return %languages;
 3107: }
 3108: 
 3109: sub languages {
 3110:     my ($possible_langs) = @_;
 3111:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3112:     if (!ref($possible_langs)) {
 3113: 	if( wantarray ) {
 3114: 	    return @preferred_langs;
 3115: 	} else {
 3116: 	    return $preferred_langs[0];
 3117: 	}
 3118:     }
 3119:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3120:     my @preferred_possibilities;
 3121:     foreach my $preferred_lang (@preferred_langs) {
 3122: 	if (exists($possibilities{$preferred_lang})) {
 3123: 	    push(@preferred_possibilities, $preferred_lang);
 3124: 	}
 3125:     }
 3126:     if( wantarray ) {
 3127: 	return @preferred_possibilities;
 3128:     }
 3129:     return $preferred_possibilities[0];
 3130: }
 3131: 
 3132: sub user_lang {
 3133:     my ($touname,$toudom,$fromcid) = @_;
 3134:     my @userlangs;
 3135:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3136:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3137:                     $env{'course.'.$fromcid.'.languages'}));
 3138:     } else {
 3139:         my %langhash = &getlangs($touname,$toudom);
 3140:         if ($langhash{'languages'} ne '') {
 3141:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3142:         } else {
 3143:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3144:             if ($domdefs{'lang_def'} ne '') {
 3145:                 @userlangs = ($domdefs{'lang_def'});
 3146:             }
 3147:         }
 3148:     }
 3149:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3150:     my $user_lh = Apache::localize->get_handle(@languages);
 3151:     return $user_lh;
 3152: }
 3153: 
 3154: 
 3155: ###############################################################
 3156: ##               Student Answer Attempts                     ##
 3157: ###############################################################
 3158: 
 3159: =pod
 3160: 
 3161: =head1 Alternate Problem Views
 3162: 
 3163: =over 4
 3164: 
 3165: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3166:     $getattempt, $regexp, $gradesub)
 3167: 
 3168: Return string with previous attempt on problem. Arguments:
 3169: 
 3170: =over 4
 3171: 
 3172: =item * $symb: Problem, including path
 3173: 
 3174: =item * $username: username of the desired student
 3175: 
 3176: =item * $domain: domain of the desired student
 3177: 
 3178: =item * $course: Course ID
 3179: 
 3180: =item * $getattempt: Leave blank for all attempts, otherwise put
 3181:     something
 3182: 
 3183: =item * $regexp: if string matches this regexp, the string will be
 3184:     sent to $gradesub
 3185: 
 3186: =item * $gradesub: routine that processes the string if it matches $regexp
 3187: 
 3188: =back
 3189: 
 3190: The output string is a table containing all desired attempts, if any.
 3191: 
 3192: =cut
 3193: 
 3194: sub get_previous_attempt {
 3195:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3196:   my $prevattempts='';
 3197:   no strict 'refs';
 3198:   if ($symb) {
 3199:     my (%returnhash)=
 3200:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3201:     if ($returnhash{'version'}) {
 3202:       my %lasthash=();
 3203:       my $version;
 3204:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3205:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3206: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3207:         }
 3208:       }
 3209:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3210:       $prevattempts.='<th>'.&mt('History').'</th>';
 3211:       foreach my $key (sort(keys(%lasthash))) {
 3212: 	my ($ign,@parts) = split(/\./,$key);
 3213: 	if ($#parts > 0) {
 3214: 	  my $data=$parts[-1];
 3215: 	  pop(@parts);
 3216: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3217: 	} else {
 3218: 	  if ($#parts == 0) {
 3219: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3220: 	  } else {
 3221: 	    $prevattempts.='<th>'.$ign.'</th>';
 3222: 	  }
 3223: 	}
 3224:       }
 3225:       $prevattempts.=&end_data_table_header_row();
 3226:       if ($getattempt eq '') {
 3227: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3228: 	  $prevattempts.=&start_data_table_row().
 3229: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3230: 	    foreach my $key (sort(keys(%lasthash))) {
 3231: 		my $value = &format_previous_attempt_value($key,
 3232: 							   $returnhash{$version.':'.$key});
 3233: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3234: 	    }
 3235: 	  $prevattempts.=&end_data_table_row();
 3236: 	 }
 3237:       }
 3238:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3239:       foreach my $key (sort(keys(%lasthash))) {
 3240: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3241: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3242: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3243:       }
 3244:       $prevattempts.= &end_data_table_row().&end_data_table();
 3245:     } else {
 3246:       $prevattempts=
 3247: 	  &start_data_table().&start_data_table_row().
 3248: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3249: 	  &end_data_table_row().&end_data_table();
 3250:     }
 3251:   } else {
 3252:     $prevattempts=
 3253: 	  &start_data_table().&start_data_table_row().
 3254: 	  '<td>'.&mt('No data.').'</td>'.
 3255: 	  &end_data_table_row().&end_data_table();
 3256:   }
 3257: }
 3258: 
 3259: sub format_previous_attempt_value {
 3260:     my ($key,$value) = @_;
 3261:     if ($key =~ /timestamp/) {
 3262: 	$value = &Apache::lonlocal::locallocaltime($value);
 3263:     } elsif (ref($value) eq 'ARRAY') {
 3264: 	$value = '('.join(', ', @{ $value }).')';
 3265:     } else {
 3266: 	$value = &unescape($value);
 3267:     }
 3268:     return $value;
 3269: }
 3270: 
 3271: 
 3272: sub relative_to_absolute {
 3273:     my ($url,$output)=@_;
 3274:     my $parser=HTML::TokeParser->new(\$output);
 3275:     my $token;
 3276:     my $thisdir=$url;
 3277:     my @rlinks=();
 3278:     while ($token=$parser->get_token) {
 3279: 	if ($token->[0] eq 'S') {
 3280: 	    if ($token->[1] eq 'a') {
 3281: 		if ($token->[2]->{'href'}) {
 3282: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3283: 		}
 3284: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3285: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3286: 	    } elsif ($token->[1] eq 'base') {
 3287: 		$thisdir=$token->[2]->{'href'};
 3288: 	    }
 3289: 	}
 3290:     }
 3291:     $thisdir=~s-/[^/]*$--;
 3292:     foreach my $link (@rlinks) {
 3293: 	unless (($link=~/^https?\:\/\//i) ||
 3294: 		($link=~/^\//) ||
 3295: 		($link=~/^javascript:/i) ||
 3296: 		($link=~/^mailto:/i) ||
 3297: 		($link=~/^\#/)) {
 3298: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3299: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3300: 	}
 3301:     }
 3302: # -------------------------------------------------- Deal with Applet codebases
 3303:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3304:     return $output;
 3305: }
 3306: 
 3307: =pod
 3308: 
 3309: =item * &get_student_view()
 3310: 
 3311: show a snapshot of what student was looking at
 3312: 
 3313: =cut
 3314: 
 3315: sub get_student_view {
 3316:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3317:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3318:   my (%form);
 3319:   my @elements=('symb','courseid','domain','username');
 3320:   foreach my $element (@elements) {
 3321:       $form{'grade_'.$element}=eval '$'.$element #'
 3322:   }
 3323:   if (defined($moreenv)) {
 3324:       %form=(%form,%{$moreenv});
 3325:   }
 3326:   if (defined($target)) { $form{'grade_target'} = $target; }
 3327:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3328:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3329:   $userview=~s/\<body[^\>]*\>//gi;
 3330:   $userview=~s/\<\/body\>//gi;
 3331:   $userview=~s/\<html\>//gi;
 3332:   $userview=~s/\<\/html\>//gi;
 3333:   $userview=~s/\<head\>//gi;
 3334:   $userview=~s/\<\/head\>//gi;
 3335:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3336:   $userview=&relative_to_absolute($feedurl,$userview);
 3337:   if (wantarray) {
 3338:      return ($userview,$response);
 3339:   } else {
 3340:      return $userview;
 3341:   }
 3342: }
 3343: 
 3344: sub get_student_view_with_retries {
 3345:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3346: 
 3347:     my $ok = 0;                 # True if we got a good response.
 3348:     my $content;
 3349:     my $response;
 3350: 
 3351:     # Try to get the student_view done. within the retries count:
 3352:     
 3353:     do {
 3354:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3355:          $ok      = $response->is_success;
 3356:          if (!$ok) {
 3357:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3358:          }
 3359:          $retries--;
 3360:     } while (!$ok && ($retries > 0));
 3361:     
 3362:     if (!$ok) {
 3363:        $content = '';          # On error return an empty content.
 3364:     }
 3365:     if (wantarray) {
 3366:        return ($content, $response);
 3367:     } else {
 3368:        return $content;
 3369:     }
 3370: }
 3371: 
 3372: =pod
 3373: 
 3374: =item * &get_student_answers() 
 3375: 
 3376: show a snapshot of how student was answering problem
 3377: 
 3378: =cut
 3379: 
 3380: sub get_student_answers {
 3381:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3382:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3383:   my (%moreenv);
 3384:   my @elements=('symb','courseid','domain','username');
 3385:   foreach my $element (@elements) {
 3386:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3387:   }
 3388:   $moreenv{'grade_target'}='answer';
 3389:   %moreenv=(%form,%moreenv);
 3390:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3391:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3392:   return $userview;
 3393: }
 3394: 
 3395: =pod
 3396: 
 3397: =item * &submlink()
 3398: 
 3399: Inputs: $text $uname $udom $symb $target
 3400: 
 3401: Returns: A link to grades.pm such as to see the SUBM view of a student
 3402: 
 3403: =cut
 3404: 
 3405: ###############################################
 3406: sub submlink {
 3407:     my ($text,$uname,$udom,$symb,$target)=@_;
 3408:     if (!($uname && $udom)) {
 3409: 	(my $cursymb, my $courseid,$udom,$uname)=
 3410: 	    &Apache::lonnet::whichuser($symb);
 3411: 	if (!$symb) { $symb=$cursymb; }
 3412:     }
 3413:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3414:     $symb=&escape($symb);
 3415:     if ($target) { $target="target=\"$target\""; }
 3416:     return '<a href="/adm/grades?&command=submission&'.
 3417: 	'symb='.$symb.'&student='.$uname.
 3418: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3419: }
 3420: ##############################################
 3421: 
 3422: =pod
 3423: 
 3424: =item * &pgrdlink()
 3425: 
 3426: Inputs: $text $uname $udom $symb $target
 3427: 
 3428: Returns: A link to grades.pm such as to see the PGRD view of a student
 3429: 
 3430: =cut
 3431: 
 3432: ###############################################
 3433: sub pgrdlink {
 3434:     my $link=&submlink(@_);
 3435:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3436:     return $link;
 3437: }
 3438: ##############################################
 3439: 
 3440: =pod
 3441: 
 3442: =item * &pprmlink()
 3443: 
 3444: Inputs: $text $uname $udom $symb $target
 3445: 
 3446: Returns: A link to parmset.pm such as to see the PPRM view of a
 3447: student and a specific resource
 3448: 
 3449: =cut
 3450: 
 3451: ###############################################
 3452: sub pprmlink {
 3453:     my ($text,$uname,$udom,$symb,$target)=@_;
 3454:     if (!($uname && $udom)) {
 3455: 	(my $cursymb, my $courseid,$udom,$uname)=
 3456: 	    &Apache::lonnet::whichuser($symb);
 3457: 	if (!$symb) { $symb=$cursymb; }
 3458:     }
 3459:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3460:     $symb=&escape($symb);
 3461:     if ($target) { $target="target=\"$target\""; }
 3462:     return '<a href="/adm/parmset?command=set&amp;'.
 3463: 	'symb='.$symb.'&amp;uname='.$uname.
 3464: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3465: }
 3466: ##############################################
 3467: 
 3468: =pod
 3469: 
 3470: =back
 3471: 
 3472: =cut
 3473: 
 3474: ###############################################
 3475: 
 3476: 
 3477: sub timehash {
 3478:     my ($thistime) = @_;
 3479:     my $timezone = &Apache::lonlocal::gettimezone();
 3480:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3481:                      ->set_time_zone($timezone);
 3482:     my $wday = $dt->day_of_week();
 3483:     if ($wday == 7) { $wday = 0; }
 3484:     return ( 'second' => $dt->second(),
 3485:              'minute' => $dt->minute(),
 3486:              'hour'   => $dt->hour(),
 3487:              'day'     => $dt->day_of_month(),
 3488:              'month'   => $dt->month(),
 3489:              'year'    => $dt->year(),
 3490:              'weekday' => $wday,
 3491:              'dayyear' => $dt->day_of_year(),
 3492:              'dlsav'   => $dt->is_dst() );
 3493: }
 3494: 
 3495: sub utc_string {
 3496:     my ($date)=@_;
 3497:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3498: }
 3499: 
 3500: sub maketime {
 3501:     my %th=@_;
 3502:     my ($epoch_time,$timezone,$dt);
 3503:     $timezone = &Apache::lonlocal::gettimezone();
 3504:     eval {
 3505:         $dt = DateTime->new( year   => $th{'year'},
 3506:                              month  => $th{'month'},
 3507:                              day    => $th{'day'},
 3508:                              hour   => $th{'hour'},
 3509:                              minute => $th{'minute'},
 3510:                              second => $th{'second'},
 3511:                              time_zone => $timezone,
 3512:                          );
 3513:     };
 3514:     if (!$@) {
 3515:         $epoch_time = $dt->epoch;
 3516:         if ($epoch_time) {
 3517:             return $epoch_time;
 3518:         }
 3519:     }
 3520:     return POSIX::mktime(
 3521:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3522:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3523: }
 3524: 
 3525: #########################################
 3526: 
 3527: sub findallcourses {
 3528:     my ($roles,$uname,$udom) = @_;
 3529:     my %roles;
 3530:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3531:     my %courses;
 3532:     my $now=time;
 3533:     if (!defined($uname)) {
 3534:         $uname = $env{'user.name'};
 3535:     }
 3536:     if (!defined($udom)) {
 3537:         $udom = $env{'user.domain'};
 3538:     }
 3539:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3540:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3541:         if (!%roles) {
 3542:             %roles = (
 3543:                        cc => 1,
 3544:                        in => 1,
 3545:                        ep => 1,
 3546:                        ta => 1,
 3547:                        cr => 1,
 3548:                        st => 1,
 3549:              );
 3550:         }
 3551:         foreach my $entry (keys(%roleshash)) {
 3552:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3553:             if ($trole =~ /^cr/) { 
 3554:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3555:             } else {
 3556:                 next if (!exists($roles{$trole}));
 3557:             }
 3558:             if ($tend) {
 3559:                 next if ($tend < $now);
 3560:             }
 3561:             if ($tstart) {
 3562:                 next if ($tstart > $now);
 3563:             }
 3564:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3565:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3566:             if ($secpart eq '') {
 3567:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3568:                 $sec = 'none';
 3569:                 $realsec = '';
 3570:             } else {
 3571:                 $cnum = $cnumpart;
 3572:                 ($sec,$role) = split(/_/,$secpart);
 3573:                 $realsec = $sec;
 3574:             }
 3575:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3576:         }
 3577:     } else {
 3578:         foreach my $key (keys(%env)) {
 3579: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3580:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3581: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3582: 	        next if ($role eq 'ca' || $role eq 'aa');
 3583: 	        next if (%roles && !exists($roles{$role}));
 3584: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3585:                 my $active=1;
 3586:                 if ($starttime) {
 3587: 		    if ($now<$starttime) { $active=0; }
 3588:                 }
 3589:                 if ($endtime) {
 3590:                     if ($now>$endtime) { $active=0; }
 3591:                 }
 3592:                 if ($active) {
 3593:                     if ($sec eq '') {
 3594:                         $sec = 'none';
 3595:                     }
 3596:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3597:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3598:                 }
 3599:             }
 3600:         }
 3601:     }
 3602:     return %courses;
 3603: }
 3604: 
 3605: ###############################################
 3606: 
 3607: sub blockcheck {
 3608:     my ($setters,$activity,$uname,$udom) = @_;
 3609: 
 3610:     if (!defined($udom)) {
 3611:         $udom = $env{'user.domain'};
 3612:     }
 3613:     if (!defined($uname)) {
 3614:         $uname = $env{'user.name'};
 3615:     }
 3616: 
 3617:     # If uname and udom are for a course, check for blocks in the course.
 3618: 
 3619:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3620:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3621:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3622:         return ($startblock,$endblock);
 3623:     }
 3624: 
 3625:     my $startblock = 0;
 3626:     my $endblock = 0;
 3627:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3628: 
 3629:     # If uname is for a user, and activity is course-specific, i.e.,
 3630:     # boards, chat or groups, check for blocking in current course only.
 3631: 
 3632:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3633:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3634:         foreach my $key (keys(%live_courses)) {
 3635:             if ($key ne $env{'request.course.id'}) {
 3636:                 delete($live_courses{$key});
 3637:             }
 3638:         }
 3639:     }
 3640: 
 3641:     my $otheruser = 0;
 3642:     my %own_courses;
 3643:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3644:         # Resource belongs to user other than current user.
 3645:         $otheruser = 1;
 3646:         # Gather courses for current user
 3647:         %own_courses = 
 3648:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3649:     }
 3650: 
 3651:     # Gather active course roles - course coordinator, instructor, 
 3652:     # exam proctor, ta, student, or custom role.
 3653: 
 3654:     foreach my $course (keys(%live_courses)) {
 3655:         my ($cdom,$cnum);
 3656:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3657:             $cdom = $env{'course.'.$course.'.domain'};
 3658:             $cnum = $env{'course.'.$course.'.num'};
 3659:         } else {
 3660:             ($cdom,$cnum) = split(/_/,$course); 
 3661:         }
 3662:         my $no_ownblock = 0;
 3663:         my $no_userblock = 0;
 3664:         if ($otheruser && $activity ne 'com') {
 3665:             # Check if current user has 'evb' priv for this
 3666:             if (defined($own_courses{$course})) {
 3667:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3668:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3669:                     if ($sec ne 'none') {
 3670:                         $checkrole .= '/'.$sec;
 3671:                     }
 3672:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3673:                         $no_ownblock = 1;
 3674:                         last;
 3675:                     }
 3676:                 }
 3677:             }
 3678:             # if they have 'evb' priv and are currently not playing student
 3679:             next if (($no_ownblock) &&
 3680:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3681:         }
 3682:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3683:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3684:             if ($sec ne 'none') {
 3685:                 $checkrole .= '/'.$sec;
 3686:             }
 3687:             if ($otheruser) {
 3688:                 # Resource belongs to user other than current user.
 3689:                 # Assemble privs for that user, and check for 'evb' priv.
 3690:                 my ($trole,$tdom,$tnum,$tsec);
 3691:                 my $entry = $live_courses{$course}{$sec};
 3692:                 if ($entry =~ /^cr/) {
 3693:                     ($trole,$tdom,$tnum,$tsec) = 
 3694:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3695:                 } else {
 3696:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3697:                 }
 3698:                 my ($spec,$area,$trest,%allroles,%userroles);
 3699:                 $area = '/'.$tdom.'/'.$tnum;
 3700:                 $trest = $tnum;
 3701:                 if ($tsec ne '') {
 3702:                     $area .= '/'.$tsec;
 3703:                     $trest .= '/'.$tsec;
 3704:                 }
 3705:                 $spec = $trole.'.'.$area;
 3706:                 if ($trole =~ /^cr/) {
 3707:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3708:                                                       $tdom,$spec,$trest,$area);
 3709:                 } else {
 3710:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3711:                                                        $tdom,$spec,$trest,$area);
 3712:                 }
 3713:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3714:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3715:                     if ($1) {
 3716:                         $no_userblock = 1;
 3717:                         last;
 3718:                     }
 3719:                 }
 3720:             } else {
 3721:                 # Resource belongs to current user
 3722:                 # Check for 'evb' priv via lonnet::allowed().
 3723:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3724:                     $no_ownblock = 1;
 3725:                     last;
 3726:                 }
 3727:             }
 3728:         }
 3729:         # if they have the evb priv and are currently not playing student
 3730:         next if (($no_ownblock) &&
 3731:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3732:         next if ($no_userblock);
 3733: 
 3734:         # Retrieve blocking times and identity of blocker for course
 3735:         # of specified user, unless user has 'evb' privilege.
 3736:         
 3737:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3738:         if (($start != 0) && 
 3739:             (($startblock == 0) || ($startblock > $start))) {
 3740:             $startblock = $start;
 3741:         }
 3742:         if (($end != 0)  &&
 3743:             (($endblock == 0) || ($endblock < $end))) {
 3744:             $endblock = $end;
 3745:         }
 3746:     }
 3747:     return ($startblock,$endblock);
 3748: }
 3749: 
 3750: sub get_blocks {
 3751:     my ($setters,$activity,$cdom,$cnum) = @_;
 3752:     my $startblock = 0;
 3753:     my $endblock = 0;
 3754:     my $course = $cdom.'_'.$cnum;
 3755:     $setters->{$course} = {};
 3756:     $setters->{$course}{'staff'} = [];
 3757:     $setters->{$course}{'times'} = [];
 3758:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3759:     foreach my $record (keys(%records)) {
 3760:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3761:         if ($start <= time && $end >= time) {
 3762:             my ($staff_name,$staff_dom,$title,$blocks) =
 3763:                 &parse_block_record($records{$record});
 3764:             if ($blocks->{$activity} eq 'on') {
 3765:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3766:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3767:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3768:                     $startblock = $start;
 3769:                 }
 3770:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3771:                     $endblock = $end;
 3772:                 }
 3773:             }
 3774:         }
 3775:     }
 3776:     return ($startblock,$endblock);
 3777: }
 3778: 
 3779: sub parse_block_record {
 3780:     my ($record) = @_;
 3781:     my ($setuname,$setudom,$title,$blocks);
 3782:     if (ref($record) eq 'HASH') {
 3783:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3784:         $title = &unescape($record->{'event'});
 3785:         $blocks = $record->{'blocks'};
 3786:     } else {
 3787:         my @data = split(/:/,$record,3);
 3788:         if (scalar(@data) eq 2) {
 3789:             $title = $data[1];
 3790:             ($setuname,$setudom) = split(/@/,$data[0]);
 3791:         } else {
 3792:             ($setuname,$setudom,$title) = @data;
 3793:         }
 3794:         $blocks = { 'com' => 'on' };
 3795:     }
 3796:     return ($setuname,$setudom,$title,$blocks);
 3797: }
 3798: 
 3799: sub build_block_table {
 3800:     my ($startblock,$endblock,$setters) = @_;
 3801:     my %lt = &Apache::lonlocal::texthash(
 3802:         'cacb' => 'Currently active communication blocks',
 3803:         'cour' => 'Course',
 3804:         'dura' => 'Duration',
 3805:         'blse' => 'Block set by'
 3806:     );
 3807:     my $output;
 3808:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3809:     $output .= &start_data_table();
 3810:     $output .= '
 3811: <tr>
 3812:  <th>'.$lt{'cour'}.'</th>
 3813:  <th>'.$lt{'dura'}.'</th>
 3814:  <th>'.$lt{'blse'}.'</th>
 3815: </tr>
 3816: ';
 3817:     foreach my $course (keys(%{$setters})) {
 3818:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3819:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3820:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3821:             my $fullname = &plainname($uname,$udom);
 3822:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3823:                 && $env{'user.name'} ne 'public' 
 3824:                 && $env{'user.domain'} ne 'public') {
 3825:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3826:             }
 3827:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3828:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3829:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3830:             $output .= &Apache::loncommon::start_data_table_row().
 3831:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3832:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3833:                        '<td>'.$fullname.'</td>'.
 3834:                         &Apache::loncommon::end_data_table_row();
 3835:         }
 3836:     }
 3837:     $output .= &end_data_table();
 3838: }
 3839: 
 3840: sub blocking_status {
 3841:     my ($activity,$uname,$udom) = @_;
 3842:     my %setters;
 3843:     my ($blocked,$output,$ownitem,$is_course);
 3844:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3845:     if ($startblock && $endblock) {
 3846:         $blocked = 1;
 3847:         if (wantarray) {
 3848:             my $category;
 3849:             if ($activity eq 'boards') {
 3850:                 $category = 'Discussion posts in this course';
 3851:             } elsif ($activity eq 'blogs') {
 3852:                 $category = 'Blogs';
 3853:             } elsif ($activity eq 'port') {
 3854:                 if (defined($uname) && defined($udom)) {
 3855:                     if ($uname eq $env{'user.name'} &&
 3856:                         $udom eq $env{'user.domain'}) {
 3857:                         $ownitem = 1;
 3858:                     }
 3859:                 }
 3860:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3861:                 if ($ownitem) { 
 3862:                     $category = 'Your portfolio files';  
 3863:                 } elsif ($is_course) {
 3864:                     my $coursedesc;
 3865:                     foreach my $course (keys(%setters)) {
 3866:                         my %courseinfo =
 3867:                              &Apache::lonnet::coursedescription($course);
 3868:                         $coursedesc = $courseinfo{'description'};
 3869:                     }
 3870:                     $category = "Group portfolio in the course '$coursedesc'";
 3871:                 } else {
 3872:                     $category = 'Portfolio files belonging to ';
 3873:                     if ($env{'user.name'} eq 'public' && 
 3874:                         $env{'user.domain'} eq 'public') {
 3875:                         $category .= &plainname($uname,$udom);
 3876:                     } else {
 3877:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3878:                     }
 3879:                 }
 3880:             } elsif ($activity eq 'groups') {
 3881:                 $category = 'Groups in this course';
 3882:             }
 3883:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3884:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3885:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3886:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3887:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3888:             }
 3889:         }
 3890:     }
 3891:     if (wantarray) {
 3892:         return ($blocked,$output);
 3893:     } else {
 3894:         return $blocked;
 3895:     }
 3896: }
 3897: 
 3898: ###############################################
 3899: 
 3900: sub check_ip_acc {
 3901:     my ($acc)=@_;
 3902:     &Apache::lonxml::debug("acc is $acc");
 3903:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3904:         return 1;
 3905:     }
 3906:     my $allowed=0;
 3907:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3908: 
 3909:     my $name;
 3910:     foreach my $pattern (split(',',$acc)) {
 3911:         $pattern =~ s/^\s*//;
 3912:         $pattern =~ s/\s*$//;
 3913:         if ($pattern =~ /\*$/) {
 3914:             #35.8.*
 3915:             $pattern=~s/\*//;
 3916:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3917:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3918:             #35.8.3.[34-56]
 3919:             my $low=$2;
 3920:             my $high=$3;
 3921:             $pattern=$1;
 3922:             if ($ip =~ /^\Q$pattern\E/) {
 3923:                 my $last=(split(/\./,$ip))[3];
 3924:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3925:             }
 3926:         } elsif ($pattern =~ /^\*/) {
 3927:             #*.msu.edu
 3928:             $pattern=~s/\*//;
 3929:             if (!defined($name)) {
 3930:                 use Socket;
 3931:                 my $netaddr=inet_aton($ip);
 3932:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3933:             }
 3934:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3935:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3936:             #127.0.0.1
 3937:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3938:         } else {
 3939:             #some.name.com
 3940:             if (!defined($name)) {
 3941:                 use Socket;
 3942:                 my $netaddr=inet_aton($ip);
 3943:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3944:             }
 3945:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3946:         }
 3947:         if ($allowed) { last; }
 3948:     }
 3949:     return $allowed;
 3950: }
 3951: 
 3952: ###############################################
 3953: 
 3954: =pod
 3955: 
 3956: =head1 Domain Template Functions
 3957: 
 3958: =over 4
 3959: 
 3960: =item * &determinedomain()
 3961: 
 3962: Inputs: $domain (usually will be undef)
 3963: 
 3964: Returns: Determines which domain should be used for designs
 3965: 
 3966: =cut
 3967: 
 3968: ###############################################
 3969: sub determinedomain {
 3970:     my $domain=shift;
 3971:     if (! $domain) {
 3972:         # Determine domain if we have not been given one
 3973:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3974:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3975:         if ($env{'request.role.domain'}) { 
 3976:             $domain=$env{'request.role.domain'}; 
 3977:         }
 3978:     }
 3979:     return $domain;
 3980: }
 3981: ###############################################
 3982: 
 3983: sub devalidate_domconfig_cache {
 3984:     my ($udom)=@_;
 3985:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3986: }
 3987: 
 3988: # ---------------------- Get domain configuration for a domain
 3989: sub get_domainconf {
 3990:     my ($udom) = @_;
 3991:     my $cachetime=1800;
 3992:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3993:     if (defined($cached)) { return %{$result}; }
 3994: 
 3995:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3996: 					     ['login','rolecolors'],$udom);
 3997:     my (%designhash,%legacy);
 3998:     if (keys(%domconfig) > 0) {
 3999:         if (ref($domconfig{'login'}) eq 'HASH') {
 4000:             if (keys(%{$domconfig{'login'}})) {
 4001:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4002:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4003:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4004:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4005:                                 $domconfig{'login'}{$key}{$img};
 4006:                         }
 4007:                     } else {
 4008:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4009:                     }
 4010:                 }
 4011:             } else {
 4012:                 $legacy{'login'} = 1;
 4013:             }
 4014:         } else {
 4015:             $legacy{'login'} = 1;
 4016:         }
 4017:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4018:             if (keys(%{$domconfig{'rolecolors'}})) {
 4019:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4020:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4021:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4022:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4023:                         }
 4024:                     }
 4025:                 }
 4026:             } else {
 4027:                 $legacy{'rolecolors'} = 1;
 4028:             }
 4029:         } else {
 4030:             $legacy{'rolecolors'} = 1;
 4031:         }
 4032:         if (keys(%legacy) > 0) {
 4033:             my %legacyhash = &get_legacy_domconf($udom);
 4034:             foreach my $item (keys(%legacyhash)) {
 4035:                 if ($item =~ /^\Q$udom\E\.login/) {
 4036:                     if ($legacy{'login'}) { 
 4037:                         $designhash{$item} = $legacyhash{$item};
 4038:                     }
 4039:                 } else {
 4040:                     if ($legacy{'rolecolors'}) {
 4041:                         $designhash{$item} = $legacyhash{$item};
 4042:                     }
 4043:                 }
 4044:             }
 4045:         }
 4046:     } else {
 4047:         %designhash = &get_legacy_domconf($udom); 
 4048:     }
 4049:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4050: 				  $cachetime);
 4051:     return %designhash;
 4052: }
 4053: 
 4054: sub get_legacy_domconf {
 4055:     my ($udom) = @_;
 4056:     my %legacyhash;
 4057:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4058:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4059:     if (-e $designfile) {
 4060:         if ( open (my $fh,"<$designfile") ) {
 4061:             while (my $line = <$fh>) {
 4062:                 next if ($line =~ /^\#/);
 4063:                 chomp($line);
 4064:                 my ($key,$val)=(split(/\=/,$line));
 4065:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4066:             }
 4067:             close($fh);
 4068:         }
 4069:     }
 4070:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4071:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4072:     }
 4073:     return %legacyhash;
 4074: }
 4075: 
 4076: =pod
 4077: 
 4078: =item * &domainlogo()
 4079: 
 4080: Inputs: $domain (usually will be undef)
 4081: 
 4082: Returns: A link to a domain logo, if the domain logo exists.
 4083: If the domain logo does not exist, a description of the domain.
 4084: 
 4085: =cut
 4086: 
 4087: ###############################################
 4088: sub domainlogo {
 4089:     my $domain = &determinedomain(shift);
 4090:     my %designhash = &get_domainconf($domain);    
 4091:     # See if there is a logo
 4092:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4093:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4094:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4095: 	    if ($imgsrc =~ m{^/res/}) {
 4096: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4097: 		&Apache::lonnet::repcopy($local_name);
 4098: 	    }
 4099: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4100:         } 
 4101:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4102:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4103:         return &Apache::lonnet::domain($domain,'description');
 4104:     } else {
 4105:         return '';
 4106:     }
 4107: }
 4108: ##############################################
 4109: 
 4110: =pod
 4111: 
 4112: =item * &designparm()
 4113: 
 4114: Inputs: $which parameter; $domain (usually will be undef)
 4115: 
 4116: Returns: value of designparamter $which
 4117: 
 4118: =cut
 4119: 
 4120: 
 4121: ##############################################
 4122: sub designparm {
 4123:     my ($which,$domain)=@_;
 4124:     if ($env{'browser.blackwhite'} eq 'on') {
 4125: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4126: 	    return '#000000';
 4127: 	}
 4128: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4129: 	    return '#FFFFFF';
 4130: 	}
 4131: 	if ($which=~/\.tabbg$/) {
 4132: 	    return '#CCCCCC';
 4133: 	}
 4134:     }
 4135:     if (exists($env{'environment.color.'.$which})) {
 4136: 	return $env{'environment.color.'.$which};
 4137:     }
 4138:     $domain=&determinedomain($domain);
 4139:     my %domdesign = &get_domainconf($domain);
 4140:     my $output;
 4141:     if ($domdesign{$domain.'.'.$which} ne '') {
 4142: 	$output = $domdesign{$domain.'.'.$which};
 4143:     } else {
 4144:         $output = $defaultdesign{$which};
 4145:     }
 4146:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4147:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4148:         if ($output =~ m{^/(adm|res)/}) {
 4149: 	    if ($output =~ m{^/res/}) {
 4150: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4151: 		&Apache::lonnet::repcopy($local_name);
 4152: 	    }
 4153:             $output = &lonhttpdurl($output);
 4154:         }
 4155:     }
 4156:     return $output;
 4157: }
 4158: 
 4159: ###############################################
 4160: ###############################################
 4161: 
 4162: =pod
 4163: 
 4164: =back
 4165: 
 4166: =head1 HTML Helpers
 4167: 
 4168: =over 4
 4169: 
 4170: =item * &bodytag()
 4171: 
 4172: Returns a uniform header for LON-CAPA web pages.
 4173: 
 4174: Inputs: 
 4175: 
 4176: =over 4
 4177: 
 4178: =item * $title, A title to be displayed on the page.
 4179: 
 4180: =item * $function, the current role (can be undef).
 4181: 
 4182: =item * $addentries, extra parameters for the <body> tag.
 4183: 
 4184: =item * $bodyonly, if defined, only return the <body> tag.
 4185: 
 4186: =item * $domain, if defined, force a given domain.
 4187: 
 4188: =item * $forcereg, if page should register as content page (relevant for 
 4189:             text interface only)
 4190: 
 4191: =item * $customtitle, alternate text to use instead of $title
 4192:                       in the title box that appears, this text
 4193:                       is not auto translated like the $title is
 4194: 
 4195: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4196:                    navigational links
 4197: 
 4198: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4199: 
 4200: =item * $notitle, if true keep the nav controls, but remove the title bar
 4201: 
 4202: =item * $no_inline_link, if true and in remote mode, don't show the 
 4203:          'Switch To Inline Menu' link
 4204: 
 4205: =item * $args, optional argument valid values are
 4206:             no_auto_mt_title -> prevents &mt()ing the title arg
 4207:             inherit_jsmath -> when creating popup window in a page,
 4208:                               should it have jsmath forced on by the
 4209:                               current page
 4210: 
 4211: =back
 4212: 
 4213: Returns: A uniform header for LON-CAPA web pages.  
 4214: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4215: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4216: other decorations will be returned.
 4217: 
 4218: =cut
 4219: 
 4220: sub bodytag {
 4221:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4222: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4223: 
 4224:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4225: 
 4226:     $function = &get_users_function() if (!$function);
 4227:     my $img =    &designparm($function.'.img',$domain);
 4228:     my $font =   &designparm($function.'.font',$domain);
 4229:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4230: 
 4231:     my %design = ( 'style'   => 'margin-top: 0px',
 4232: 		   'bgcolor' => $pgbg,
 4233: 		   'text'    => $font,
 4234:                    'alink'   => &designparm($function.'.alink',$domain),
 4235: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4236: 		   'link'    => &designparm($function.'.link',$domain),);
 4237:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4238: 
 4239:  # role and realm
 4240:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4241:     if ($role  eq 'ca') {
 4242:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4243:         $realm = &plainname($rname,$rdom);
 4244:     } 
 4245: # realm
 4246:     if ($env{'request.course.id'}) {
 4247:         if ($env{'request.role'} !~ /^cr/) {
 4248:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4249:         }
 4250: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4251:     } else {
 4252:         $role = &Apache::lonnet::plaintext($role);
 4253:     }
 4254: 
 4255:     if (!$realm) { $realm='&nbsp;'; }
 4256: # Set messages
 4257:     my $messages=&domainlogo($domain);
 4258: 
 4259:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4260: 
 4261: # construct main body tag
 4262:     my $bodytag = "<body $extra_body_attr>".
 4263: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4264: 
 4265:     if ($bodyonly) {
 4266:         return $bodytag;
 4267:     } 
 4268: 
 4269:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4270:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4271: 	undef($role);
 4272:     } else {
 4273: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4274:     }
 4275:     
 4276:     my $roleinfo=(<<ENDROLE);
 4277: <td class="LC_title_bar_who">
 4278: <div class="LC_title_bar_name">
 4279:     $name
 4280:     &nbsp;
 4281: </div>
 4282: <div class="LC_title_bar_role">
 4283: $role&nbsp;
 4284: </div>
 4285: <div class="LC_title_bar_realm">
 4286: $realm&nbsp;
 4287: </div>
 4288: </td>
 4289: ENDROLE
 4290: 
 4291:     my $titleinfo = '<h1>'.$title.'</h1>';
 4292:     if ($customtitle) {
 4293:         $titleinfo = $customtitle;
 4294:     }
 4295:     #
 4296:     # Extra info if you are the DC
 4297:     my $dc_info = '';
 4298:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4299:                         $env{'course.'.$env{'request.course.id'}.
 4300:                                  '.domain'}.'/'})) {
 4301:         my $cid = $env{'request.course.id'};
 4302:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4303:         $dc_info =~ s/\s+$//;
 4304:         $dc_info = '('.$dc_info.')';
 4305:     }
 4306: 
 4307:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4308:         # No Remote
 4309: 	if ($env{'request.state'} eq 'construct') {
 4310: 	    $forcereg=1;
 4311: 	}
 4312: 
 4313: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4314: 	    # this is for resources; directories have customtitle, and crumbs
 4315:             # and select recent are created in lonpubdir.pm  
 4316: 	    my ($uname,$thisdisfn)=
 4317: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4318: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4319: 	    $formaction=~s/\/+/\//g;
 4320: 
 4321: 	    my $parentpath = '';
 4322: 	    my $lastitem = '';
 4323: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4324: 		$parentpath = $1;
 4325: 		$lastitem = $2;
 4326: 	    } else {
 4327: 		$lastitem = $thisdisfn;
 4328: 	    }
 4329: 	    $titleinfo = 
 4330: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4331: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4332: 		.'<form name="dirs" method="post" action="'.$formaction
 4333: 		.'" target="_top"><tt><b>'
 4334: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
 4335: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4336: 		.'</form>'
 4337: 		.&Apache::lonmenu::constspaceform();
 4338:         }
 4339: 
 4340:         my $titletable;
 4341: 	if (!$notitle) {
 4342: 	    $titletable =
 4343: 		'<table id="LC_title_bar">'.
 4344:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4345: 			 '</tr></table>';
 4346: 	}
 4347: 	if ($notopbar) {
 4348: 	    $bodytag .= $titletable;
 4349: 	} else {
 4350: 	    if ($env{'request.state'} eq 'construct') {
 4351:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4352: 							  $titletable);
 4353:             } else {
 4354:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4355: 		    $titletable;
 4356:             }
 4357:         }
 4358:         return $bodytag;
 4359:     }
 4360: 
 4361: #
 4362: # Top frame rendering, Remote is up
 4363: #
 4364: 
 4365:     my $imgsrc = $img;
 4366:     if ($img =~ /^\/adm/) {
 4367:         $imgsrc = &lonhttpdurl($img);
 4368:     }
 4369:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4370: 
 4371:     # Explicit link to get inline menu
 4372:     my $menu= ($no_inline_link?''
 4373: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4374:     #
 4375:     if ($notitle) {
 4376: 	return $bodytag;
 4377:     }
 4378:     return(<<ENDBODY);
 4379: $bodytag
 4380: <table id="LC_title_bar" class="LC_with_remote">
 4381: <tr><td>$upperleft</td>
 4382:     <td>$messages&nbsp;</td>
 4383: </tr>
 4384: <tr><td>$titleinfo $dc_info $menu</td>
 4385: $roleinfo
 4386: </tr>
 4387: </table>
 4388: ENDBODY
 4389: }
 4390: 
 4391: sub make_attr_string {
 4392:     my ($register,$attr_ref) = @_;
 4393: 
 4394:     if ($attr_ref && !ref($attr_ref)) {
 4395: 	die("addentries Must be a hash ref ".
 4396: 	    join(':',caller(1))." ".
 4397: 	    join(':',caller(0))." ");
 4398:     }
 4399: 
 4400:     if ($register) {
 4401: 	my ($on_load,$on_unload);
 4402: 	foreach my $key (keys(%{$attr_ref})) {
 4403: 	    if      (lc($key) eq 'onload') {
 4404: 		$on_load.=$attr_ref->{$key}.';';
 4405: 		delete($attr_ref->{$key});
 4406: 
 4407: 	    } elsif (lc($key) eq 'onunload') {
 4408: 		$on_unload.=$attr_ref->{$key}.';';
 4409: 		delete($attr_ref->{$key});
 4410: 	    }
 4411: 	}
 4412: 	$attr_ref->{'onload'}  =
 4413: 	    &Apache::lonmenu::loadevents().  $on_load;
 4414: 	$attr_ref->{'onunload'}=
 4415: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4416:     }
 4417: 
 4418: # Accessibility font enhance
 4419:     if ($env{'browser.fontenhance'} eq 'on') {
 4420: 	my $style;
 4421: 	foreach my $key (keys(%{$attr_ref})) {
 4422: 	    if (lc($key) eq 'style') {
 4423: 		$style.=$attr_ref->{$key}.';';
 4424: 		delete($attr_ref->{$key});
 4425: 	    }
 4426: 	}
 4427: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4428:     }
 4429: 
 4430:     if ($env{'browser.blackwhite'} eq 'on') {
 4431: 	delete($attr_ref->{'font'});
 4432: 	delete($attr_ref->{'link'});
 4433: 	delete($attr_ref->{'alink'});
 4434: 	delete($attr_ref->{'vlink'});
 4435: 	delete($attr_ref->{'bgcolor'});
 4436: 	delete($attr_ref->{'background'});
 4437:     }
 4438: 
 4439:     my $attr_string;
 4440:     foreach my $attr (keys(%$attr_ref)) {
 4441: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4442:     }
 4443:     return $attr_string;
 4444: }
 4445: 
 4446: 
 4447: ###############################################
 4448: ###############################################
 4449: 
 4450: =pod
 4451: 
 4452: =item * &endbodytag()
 4453: 
 4454: Returns a uniform footer for LON-CAPA web pages.
 4455: 
 4456: Inputs: 1 - optional reference to an args hash
 4457: If in the hash, key for noredirectlink has a value which evaluates to true,
 4458: a 'Continue' link is not displayed if the page contains an
 4459: internal redirect in the <head></head> section,
 4460: i.e., $env{'internal.head.redirect'} exists   
 4461: 
 4462: =cut
 4463: 
 4464: sub endbodytag {
 4465:     my ($args) = @_;
 4466:     my $endbodytag='</body>';
 4467:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4468:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4469:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4470: 	    $endbodytag=
 4471: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4472: 	        &mt('Continue').'</a>'.
 4473: 	        $endbodytag;
 4474:         }
 4475:     }
 4476:     return $endbodytag;
 4477: }
 4478: 
 4479: =pod
 4480: 
 4481: =item * &standard_css()
 4482: 
 4483: Returns a style sheet
 4484: 
 4485: Inputs: (all optional)
 4486:             domain         -> force to color decorate a page for a specific
 4487:                                domain
 4488:             function       -> force usage of a specific rolish color scheme
 4489:             bgcolor        -> override the default page bgcolor
 4490: 
 4491: =cut
 4492: 
 4493: sub standard_css {
 4494:     my ($function,$domain,$bgcolor) = @_;
 4495:     $function  = &get_users_function() if (!$function);
 4496:     my $img    = &designparm($function.'.img',   $domain);
 4497:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4498:     my $font   = &designparm($function.'.font',  $domain);
 4499: #second colour for later usage
 4500:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4501:     my $pgbg_or_bgcolor =
 4502: 	         $bgcolor ||
 4503: 	         &designparm($function.'.pgbg',  $domain);
 4504:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4505:     my $alink  = &designparm($function.'.alink', $domain);
 4506:     my $vlink  = &designparm($function.'.vlink', $domain);
 4507:     my $link   = &designparm($function.'.link',  $domain);
 4508: 
 4509:     my $loginbg = &designparm('login.sidebg',$domain);
 4510:     my $bgcol = &designparm('login.bgcol',$domain);
 4511:     my $textcol = &designparm('login.textcol',$domain);
 4512: 
 4513:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4514:     my $mono                 = 'monospace';
 4515:     my $data_table_head      = $tabbg;
 4516:     my $data_table_light     = '#EEEEEE';
 4517:     my $data_table_dark      = '#DDDDDD';
 4518:     my $data_table_darker    = '#CCCCCC';
 4519:     my $data_table_highlight = '#FFFF00';
 4520:     my $mail_new             = '#FFBB77';
 4521:     my $mail_new_hover       = '#DD9955';
 4522:     my $mail_read            = '#BBBB77';
 4523:     my $mail_read_hover      = '#999944';
 4524:     my $mail_replied         = '#AAAA88';
 4525:     my $mail_replied_hover   = '#888855';
 4526:     my $mail_other           = '#99BBBB';
 4527:     my $mail_other_hover     = '#669999';
 4528:     my $table_header         = '#DDDDDD';
 4529:     my $feedback_link_bg     = '#BBBBBB';
 4530:     my $lg_border_color	     = '#C8C8C8';
 4531: 
 4532:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4533: 		  $env{'browser.type'} eq 'safari'     ) ? '0px 2px 0px 2px'
 4534: 	                                                 : '0px 3px 0px 4px';
 4535: 
 4536: 
 4537:     return <<END;
 4538: body {
 4539:    font-family: $sans;
 4540:    line-height:130%;
 4541:    font-size:0.83em;
 4542:    color:$font;
 4543: }
 4544: 
 4545: a:link, a:visited { 
 4546:   font-size:100%; 
 4547: }
 4548: 
 4549: a:focus { 
 4550:   color: red;
 4551:   background: yellow 
 4552: }
 4553: 
 4554: table.thinborder,
 4555: table.thinborder tr th {
 4556:   border-style: solid;
 4557:   border-width: 1px;
 4558:   border-color: $lg_border_color;
 4559:   background: $tabbg;
 4560: }
 4561: 
 4562: table.thinborder tr td {
 4563:   border-style: solid;
 4564:   border-width: 1px;
 4565:   border-color: $lg_border_color;
 4566: }
 4567: 
 4568: form, .inline { 
 4569:    display: inline; 
 4570: }
 4571: 
 4572: .LC_right {
 4573:    text-align:right;
 4574: }
 4575: 
 4576: .LC_middle {
 4577:    vertical-align:middle;
 4578: }
 4579: 
 4580: /* just for tests */
 4581: .LC_400Box {width:400px; }
 4582: /* end */
 4583: 
 4584: .LC_filename {
 4585:   font-family: $mono;
 4586:   white-space:pre;
 4587: }
 4588: 
 4589: .LC_fileicon {
 4590:   border: none;
 4591:   height: 1.3em;
 4592:   vertical-align: text-bottom;
 4593:   margin-right: 0.3em;
 4594:   text-decoration:none;
 4595: }
 4596: 
 4597: .LC_error {
 4598:   color: red;
 4599:   font-size: larger;
 4600: }
 4601: 
 4602: .LC_warning,
 4603: .LC_diff_removed {
 4604:   color: red;
 4605: }
 4606: 
 4607: .LC_info,
 4608: .LC_success,
 4609: .LC_diff_added {
 4610:   color: green;
 4611: }
 4612: 
 4613: .LC_unknown {
 4614:   color: yellow;
 4615: }
 4616: 
 4617: .LC_icon {
 4618:   border: none;
 4619:   vertical-align: middle;
 4620: }
 4621: 
 4622: .LC_indexer_icon {
 4623:   border: 0px;
 4624:   height: 22px;
 4625: }
 4626: 
 4627: .LC_docs_spacer {
 4628:   width: 25px;
 4629:   height: 1px;
 4630:   border: none;
 4631: }
 4632: 
 4633: .LC_internal_info {
 4634:   color: #999999;
 4635: }
 4636: 
 4637: .LC_discussion {
 4638:    background: $tabbg;
 4639:    border: 1px solid black;
 4640:    margin: 2px;
 4641: }
 4642: 
 4643: .LC_disc_action_links_bar {
 4644:    background: $tabbg;
 4645:    font-family: $sans;
 4646:    border: 0px;
 4647:    margin: 4px;
 4648: }
 4649: 
 4650: .LC_disc_action_left {
 4651:    text-align: left;
 4652: }
 4653: 
 4654: .LC_disc_action_right {
 4655:    text-align: right;
 4656: }
 4657: 
 4658: .LC_disc_new_item {
 4659:    background: white;
 4660:    border: 2px solid red;
 4661:    margin: 2px;
 4662: }
 4663: 
 4664: .LC_disc_old_item {
 4665:    background: white;
 4666:    border: 1px solid black;
 4667:    margin: 2px;
 4668: }
 4669: 
 4670: table.LC_pastsubmission {
 4671:   border: 1px solid black;
 4672:   margin: 2px;
 4673: }
 4674: 
 4675: table#LC_top_nav,
 4676: table#LC_menubuttons,
 4677: table#LC_nav_location {
 4678:   width: 100%;
 4679:   background: $pgbg;
 4680:   border: 2px;
 4681:   border-collapse: separate;
 4682:   padding: 0px;
 4683: }
 4684: 
 4685: table#LC_title_bar,
 4686: table.LC_breadcrumbs,
 4687: table#LC_title_bar.LC_with_remote {
 4688:   width: 100%;
 4689:   border-color: $pgbg;
 4690:   border-style: solid;
 4691:   border-width: $border;
 4692:   background: $pgbg;
 4693:   font-family: $sans;
 4694:   border-collapse: collapse;
 4695:   padding: 0px;
 4696: }
 4697: 
 4698: table.LC_docs_path {
 4699:   width: 100%;
 4700:   border: 0;
 4701:   background: $pgbg;
 4702:   font-family: $sans;
 4703:   border-collapse: collapse;
 4704:   padding: 0px;
 4705: }
 4706: 
 4707: table#LC_title_bar td {
 4708:   background: $tabbg;
 4709: }
 4710: 
 4711: table#LC_title_bar .LC_title_bar_who {
 4712:   background: $tabbg;
 4713:   color: $font;
 4714:   font: small $sans;
 4715:   text-align: right;
 4716:   margin: 0px;
 4717: }
 4718: 
 4719: table#LC_title_bar .LC_title_bar_name {
 4720:   margin: 0px;
 4721: }
 4722: 
 4723: table#LC_title_bar .LC_title_bar_role {
 4724:   margin: 0px;
 4725: }
 4726: 
 4727: table#LC_title_bar .LC_title_bar_realm {
 4728:   margin: 0px;
 4729: }
 4730: 
 4731: span.LC_metadata {
 4732:   font-family: $sans;
 4733: }
 4734: 
 4735: table#LC_menubuttons img{
 4736:   border: 0px;
 4737: }
 4738: 
 4739: table#LC_top_nav td {
 4740:   background: $tabbg;
 4741:   border: 0px;
 4742:   font-size: small;
 4743:   vertical-align:top;
 4744:   padding:2px 5px 2px 5px;
 4745: }
 4746: 
 4747: table#LC_top_nav td a,
 4748: div#LC_top_nav a {
 4749:   color: $font;
 4750:   font-family: $sans;
 4751: }
 4752: 
 4753: table#LC_top_nav td.LC_top_nav_logo {
 4754:   background: $tabbg;
 4755:   text-align: left;
 4756:   white-space: nowrap;
 4757:   width: 31px;
 4758: }
 4759: 
 4760: table#LC_top_nav td.LC_top_nav_logo img {
 4761:   border: 0px;
 4762:   vertical-align: bottom;
 4763: }
 4764: 
 4765: table#LC_top_nav td.LC_top_nav_exit,
 4766: table#LC_top_nav td.LC_top_nav_help {
 4767:   width: 2.0em;
 4768: }
 4769: 
 4770: table#LC_top_nav td.LC_top_nav_login {
 4771:   width: 4.0em;
 4772:   text-align: center;
 4773: }
 4774: 
 4775: table.LC_breadcrumbs td,
 4776: table.LC_docs_path td  {
 4777:   background: $tabbg;
 4778:   color: $font;
 4779:   font-family: $sans;
 4780:   font-size: smaller;
 4781: }
 4782: 
 4783: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4784: table.LC_docs_path td.LC_docs_path_component {
 4785:   background: $tabbg;
 4786:   color: $font;
 4787:   font-family: $sans;
 4788:   font-size: larger;
 4789:   text-align: right;
 4790: }
 4791: 
 4792: td.LC_table_cell_checkbox {
 4793:   text-align: center;
 4794: }
 4795: 
 4796: table#LC_mainmenu td.LC_mainmenu_column {
 4797:     vertical-align: top;
 4798: }
 4799: 
 4800: .LC_fontsize_small {
 4801:  font-size: 70%;
 4802: }
 4803: 
 4804: .LC_fontsize_medium {
 4805:  font-size: 85%;
 4806: }
 4807: 
 4808: .LC_fontsize_large {
 4809:  font-size: 120%;
 4810: }
 4811: 
 4812: .LC_menubuttons_inline_text {
 4813:   color: $font;
 4814:   font-family: $sans;
 4815:   font-size: 90%;
 4816:   padding-left:3px;
 4817: }
 4818: 
 4819: .LC_menubuttons_link {
 4820:   text-decoration: none;
 4821: }
 4822: 
 4823: .LC_menubuttons_category {
 4824:   color: $font;
 4825:   background: $pgbg;
 4826:   font-family: $sans;
 4827:   font-size: larger;
 4828:   font-weight: bold;
 4829: }
 4830: 
 4831: td.LC_menubuttons_text {
 4832:  	color: $font;
 4833: }
 4834: 
 4835: .LC_current_location {
 4836:   font-family: $sans;
 4837:   background: $tabbg;
 4838: }
 4839: 
 4840: .LC_new_mail {
 4841:   font-family: $sans;
 4842:   background: $tabbg;
 4843:   font-weight: bold;
 4844: }
 4845: 
 4846: .LC_dropadd_labeltext {
 4847:   font-family: $sans;
 4848:   text-align: right;
 4849: }
 4850: 
 4851: .LC_preferences_labeltext {
 4852:   font-family: $sans;
 4853:   text-align: right;
 4854: }
 4855: 
 4856: .LC_roleslog_note {
 4857:   font-size: small;
 4858: }
 4859: 
 4860: .LC_mail_functions {
 4861:     font-weight: bold;
 4862: }
 4863: 
 4864: table.LC_aboutme_port {
 4865:   border: 0px;
 4866:   border-collapse: collapse;
 4867:   border-spacing: 0px;
 4868: }
 4869: 
 4870: table.LC_data_table,
 4871: table.LC_mail_list {
 4872:   border: 1px solid #000000;
 4873:   border-collapse: separate;
 4874:   border-spacing: 1px;
 4875:   background: $pgbg;
 4876: }
 4877: 
 4878: .LC_data_table_dense {
 4879:   font-size: small;
 4880: }
 4881: 
 4882: table.LC_nested_outer {
 4883:   border: 1px solid #000000;
 4884:   border-collapse: collapse;
 4885:   border-spacing: 0px;
 4886:   width: 100%;
 4887: }
 4888: 
 4889: table.LC_nested {
 4890:   border: 0px;
 4891:   border-collapse: collapse;
 4892:   border-spacing: 0px;
 4893:   width: 100%;
 4894: }
 4895: 
 4896: table.LC_data_table tr th, 
 4897: table.LC_calendar tr th, 
 4898: table.LC_mail_list tr th,
 4899: table.LC_prior_tries tr th {
 4900:   font-weight: bold;
 4901:   background-color: $data_table_head;
 4902:   font-size:90%;
 4903: }
 4904: 
 4905: table.LC_data_table tr.LC_info_row > td {
 4906:   background-color: #CCCCCC;
 4907:   font-weight: bold;
 4908:   text-align: left;
 4909: }
 4910: 
 4911: table.LC_data_table tr.LC_odd_row > td,
 4912: table.LC_pick_box tr > td.LC_odd_row,
 4913: table.LC_aboutme_port tr td {
 4914:   background-color: $data_table_light;
 4915:   padding: 2px;
 4916: }
 4917: 
 4918: table.LC_data_table tr.LC_even_row > td,
 4919: table.LC_pick_box tr > td.LC_even_row,
 4920: table.LC_aboutme_port tr.LC_even_row td {
 4921:   background-color: $data_table_dark;
 4922:   padding: 2px;
 4923: }
 4924: 
 4925: table.LC_data_table tr.LC_data_table_highlight td {
 4926:   background-color: $data_table_darker;
 4927: }
 4928: 
 4929: table.LC_data_table tr td.LC_leftcol_header {
 4930:   background-color: $data_table_head;
 4931:   font-weight: bold;
 4932: }
 4933: 
 4934: table.LC_data_table tr.LC_empty_row td,
 4935: table.LC_nested tr.LC_empty_row td {
 4936:   background-color: #FFFFFF;
 4937:   font-weight: bold;
 4938:   font-style: italic;
 4939:   text-align: center;
 4940:   padding: 8px;
 4941: }
 4942: 
 4943: table.LC_nested tr.LC_empty_row td {
 4944:   padding: 4ex
 4945: }
 4946: 
 4947: table.LC_nested_outer tr th {
 4948:   font-weight: bold;
 4949:   background-color: $data_table_head;
 4950:   font-size: small;
 4951:   border-bottom: 1px solid #000000;
 4952: }
 4953: 
 4954: table.LC_nested_outer tr td.LC_subheader {
 4955:   background-color: $data_table_head;
 4956:   font-weight: bold;
 4957:   font-size: small;
 4958:   border-bottom: 1px solid #000000;
 4959:   text-align: right;
 4960: }
 4961: 
 4962: table.LC_nested tr.LC_info_row td {
 4963:   background-color: #CCCCCC;
 4964:   font-weight: bold;
 4965:   font-size: small;
 4966:   text-align: center;
 4967: }
 4968: 
 4969: table.LC_nested tr.LC_info_row td.LC_left_item,
 4970: table.LC_nested_outer tr th.LC_left_item {
 4971:   text-align: left;
 4972: }
 4973: 
 4974: table.LC_nested td {
 4975:   background-color: #FFFFFF;
 4976:   font-size: small;
 4977: }
 4978: 
 4979: table.LC_nested_outer tr th.LC_right_item,
 4980: table.LC_nested tr.LC_info_row td.LC_right_item,
 4981: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4982: table.LC_nested tr td.LC_right_item {
 4983:   text-align: right;
 4984: }
 4985: 
 4986: table.LC_nested tr.LC_odd_row td {
 4987:   background-color: #EEEEEE;
 4988: }
 4989: 
 4990: table.LC_createuser {
 4991: }
 4992: 
 4993: table.LC_createuser tr.LC_section_row td {
 4994:   font-size: small;
 4995: }
 4996: 
 4997: table.LC_createuser tr.LC_info_row td  {
 4998:   background-color: #CCCCCC;
 4999:   font-weight: bold;
 5000:   text-align: center;
 5001: }
 5002: 
 5003: table.LC_calendar {
 5004:   border: 1px solid #000000;
 5005:   border-collapse: collapse;
 5006: }
 5007: 
 5008: table.LC_calendar_pickdate {
 5009:   font-size: xx-small;
 5010: }
 5011: 
 5012: table.LC_calendar tr td {
 5013:   border: 1px solid #000000;
 5014:   vertical-align: top;
 5015: }
 5016: 
 5017: table.LC_calendar tr td.LC_calendar_day_empty {
 5018:   background-color: $data_table_dark;
 5019: }
 5020: 
 5021: table.LC_calendar tr td.LC_calendar_day_current {
 5022:   background-color: $data_table_highlight;
 5023: }
 5024: 
 5025: table.LC_mail_list tr.LC_mail_new {
 5026:   background-color: $mail_new;
 5027: }
 5028: 
 5029: table.LC_mail_list tr.LC_mail_new:hover {
 5030:   background-color: $mail_new_hover;
 5031: }
 5032: 
 5033: table.LC_mail_list tr.LC_mail_even {
 5034: }
 5035: 
 5036: table.LC_mail_list tr.LC_mail_odd {
 5037: }
 5038: 
 5039: table.LC_mail_list tr.LC_mail_read {
 5040:   background-color: $mail_read;
 5041: }
 5042: 
 5043: table.LC_mail_list tr.LC_mail_read:hover {
 5044:   background-color: $mail_read_hover;
 5045: }
 5046: 
 5047: table.LC_mail_list tr.LC_mail_replied {
 5048:   background-color: $mail_replied;
 5049: }
 5050: 
 5051: table.LC_mail_list tr.LC_mail_replied:hover {
 5052:   background-color: $mail_replied_hover;
 5053: }
 5054: 
 5055: table.LC_mail_list tr.LC_mail_other {
 5056:   background-color: $mail_other;
 5057: }
 5058: 
 5059: table.LC_mail_list tr.LC_mail_other:hover {
 5060:   background-color: $mail_other_hover;
 5061: }
 5062: 
 5063: table.LC_data_table tr > td.LC_browser_file,
 5064: table.LC_data_table tr > td.LC_browser_file_published {
 5065:   background: #CCFF88;
 5066: }
 5067: 
 5068: table.LC_data_table tr > td.LC_browser_file_locked,
 5069: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5070:   background: #FFAA99;
 5071: }
 5072: 
 5073: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5074:   background: #AAAAAA;
 5075: }
 5076: 
 5077: table.LC_data_table tr > td.LC_browser_file_modified,
 5078: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5079:   background: #FFFF77;
 5080: }
 5081: 
 5082: table.LC_data_table tr.LC_browser_folder > td {
 5083:   background: #CCCCFF;
 5084: }
 5085: 
 5086: table.LC_data_table tr > td.LC_roles_is {
 5087: /*  background: #77FF77; */
 5088: }
 5089: 
 5090: table.LC_data_table tr > td.LC_roles_future {
 5091:   background: #FFFF77;
 5092: }
 5093: 
 5094: table.LC_data_table tr > td.LC_roles_will {
 5095:   background: #FFAA77;
 5096: }
 5097: 
 5098: table.LC_data_table tr > td.LC_roles_expired {
 5099:   background: #FF7777;
 5100: }
 5101: 
 5102: table.LC_data_table tr > td.LC_roles_will_not {
 5103:   background: #AAFF77;
 5104: }
 5105: 
 5106: table.LC_data_table tr > td.LC_roles_selected {
 5107:   background: #11CC55;
 5108: }
 5109: 
 5110: span.LC_current_location {
 5111:   font-size:larger;
 5112:   background: $pgbg;
 5113: }
 5114: 
 5115: span.LC_parm_menu_item {
 5116:   font-size: larger;
 5117:   font-family: $sans;
 5118: }
 5119: 
 5120: span.LC_parm_scope_all {
 5121:   color: red;
 5122: }
 5123: 
 5124: span.LC_parm_scope_folder {
 5125:   color: green;
 5126: }
 5127: 
 5128: span.LC_parm_scope_resource {
 5129:   color: orange;
 5130: }
 5131: 
 5132: span.LC_parm_part {
 5133:   color: blue;
 5134: }
 5135: 
 5136: span.LC_parm_folder, span.LC_parm_symb {
 5137:   font-size: x-small;
 5138:   font-family: $mono;
 5139:   color: #AAAAAA;
 5140: }
 5141: 
 5142: td.LC_parm_overview_level_menu,
 5143: td.LC_parm_overview_map_menu,
 5144: td.LC_parm_overview_parm_selectors,
 5145: td.LC_parm_overview_restrictions  {
 5146:   border: 1px solid black;
 5147:   border-collapse: collapse;
 5148: }
 5149: 
 5150: table.LC_parm_overview_restrictions td {
 5151:   border-width: 1px 4px 1px 4px;
 5152:   border-style: solid;
 5153:   border-color: $pgbg;
 5154:   text-align: center;
 5155: }
 5156: 
 5157: table.LC_parm_overview_restrictions th {
 5158:   background: $tabbg;
 5159:   border-width: 1px 4px 1px 4px;
 5160:   border-style: solid;
 5161:   border-color: $pgbg;
 5162: }
 5163: 
 5164: table#LC_helpmenu {
 5165:   border: 0px;
 5166:   height: 55px;
 5167:   border-spacing: 0px;
 5168: }
 5169: 
 5170: table#LC_helpmenu fieldset legend {
 5171:   font-size: larger;
 5172:   font-weight: bold;
 5173: }
 5174: 
 5175: table#LC_helpmenu_links {
 5176:   width: 100%;
 5177:   border: 1px solid black;
 5178:   background: $pgbg;
 5179:   padding: 0px;
 5180:   border-spacing: 1px;
 5181: }
 5182: 
 5183: table#LC_helpmenu_links tr td {
 5184:   padding: 1px;
 5185:   background: $tabbg;
 5186:   text-align: center;
 5187:   font-weight: bold;
 5188: }
 5189: 
 5190: table#LC_helpmenu_links a:link,
 5191: table#LC_helpmenu_links a:visited,
 5192: table#LC_helpmenu_links a:active {
 5193:   text-decoration: none;
 5194:   color: $font;
 5195: }
 5196: 
 5197: table#LC_helpmenu_links a:hover {
 5198:   text-decoration: underline;
 5199:   color: $vlink;
 5200: }
 5201: 
 5202: .LC_chrt_popup_exists {
 5203:   border: 1px solid #339933;
 5204:   margin: -1px;
 5205: }
 5206: 
 5207: .LC_chrt_popup_up {
 5208:   border: 1px solid yellow;
 5209:   margin: -1px;
 5210: }
 5211: 
 5212: .LC_chrt_popup {
 5213:   border: 1px solid #8888FF;
 5214:   background: #CCCCFF;
 5215: }
 5216: 
 5217: table.LC_pick_box {
 5218:   border-collapse: separate;
 5219:   background: white;
 5220:   border: 1px solid black;
 5221:   border-spacing: 1px;
 5222: }
 5223: 
 5224: table.LC_pick_box td.LC_pick_box_title {
 5225:   background: $tabbg;
 5226:   font-weight: bold;
 5227:   text-align: right;
 5228:   vertical-align: top;
 5229:   width: 184px;
 5230:   padding: 8px;
 5231: }
 5232: 
 5233: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5234:   background: $tabbg;
 5235:   font-weight: bold;
 5236:   text-align: right;
 5237:   width: 350px;
 5238:   padding: 8px;
 5239: }
 5240: 
 5241: table.LC_pick_box td.LC_pick_box_value {
 5242:   text-align: left;
 5243:   padding: 8px;
 5244: }
 5245: 
 5246: table.LC_pick_box td.LC_pick_box_select {
 5247:   text-align: left;
 5248:   padding: 8px;
 5249: }
 5250: 
 5251: table.LC_pick_box td.LC_pick_box_separator {
 5252:   padding: 0px;
 5253:   height: 1px;
 5254:   background: black;
 5255: }
 5256: 
 5257: table.LC_pick_box td.LC_pick_box_submit {
 5258:   text-align: right;
 5259: }
 5260: 
 5261: table.LC_pick_box td.LC_evenrow_value {
 5262:   text-align: left;
 5263:   padding: 8px;
 5264:   background-color: $data_table_light;
 5265: }
 5266: 
 5267: table.LC_pick_box td.LC_oddrow_value {
 5268:   text-align: left;
 5269:   padding: 8px;
 5270:   background-color: $data_table_light;
 5271: }
 5272: 
 5273: table.LC_helpform_receipt {
 5274:   width: 620px;
 5275:   border-collapse: separate;
 5276:   background: white;
 5277:   border: 1px solid black;
 5278:   border-spacing: 1px;
 5279: }
 5280: 
 5281: table.LC_helpform_receipt td.LC_pick_box_title {
 5282:   background: $tabbg;
 5283:   font-weight: bold;
 5284:   text-align: right;
 5285:   width: 184px;
 5286:   padding: 8px;
 5287: }
 5288: 
 5289: table.LC_helpform_receipt td.LC_evenrow_value {
 5290:   text-align: left;
 5291:   padding: 8px;
 5292:   background-color: $data_table_light;
 5293: }
 5294: 
 5295: table.LC_helpform_receipt td.LC_oddrow_value {
 5296:   text-align: left;
 5297:   padding: 8px;
 5298:   background-color: $data_table_light;
 5299: }
 5300: 
 5301: table.LC_helpform_receipt td.LC_pick_box_separator {
 5302:   padding: 0px;
 5303:   height: 1px;
 5304:   background: black;
 5305: }
 5306: 
 5307: span.LC_helpform_receipt_cat {
 5308:   font-weight: bold;
 5309: }
 5310: 
 5311: table.LC_group_priv_box {
 5312:   background: white;
 5313:   border: 1px solid black;
 5314:   border-spacing: 1px;
 5315: }
 5316: 
 5317: table.LC_group_priv_box td.LC_pick_box_title {
 5318:   background: $tabbg;
 5319:   font-weight: bold;
 5320:   text-align: right;
 5321:   width: 184px;
 5322: }
 5323: 
 5324: table.LC_group_priv_box td.LC_groups_fixed {
 5325:   background: $data_table_light;
 5326:   text-align: center;
 5327: }
 5328: 
 5329: table.LC_group_priv_box td.LC_groups_optional {
 5330:   background: $data_table_dark;
 5331:   text-align: center;
 5332: }
 5333: 
 5334: table.LC_group_priv_box td.LC_groups_functionality {
 5335:   background: $data_table_darker;
 5336:   text-align: center;
 5337:   font-weight: bold;
 5338: }
 5339: 
 5340: table.LC_group_priv td {
 5341:   text-align: left;
 5342:   padding: 0px;
 5343: }
 5344: 
 5345: table.LC_notify_front_page {
 5346:   background: white;
 5347:   border: 1px solid black;
 5348:   padding: 8px;
 5349: }
 5350: 
 5351: table.LC_notify_front_page td {
 5352:   padding: 8px;
 5353: }
 5354: 
 5355: .LC_navbuttons {
 5356:   margin: 2ex 0ex 2ex 0ex;
 5357: }
 5358: 
 5359: .LC_topic_bar {
 5360:   font-family: $sans;
 5361:   font-weight: bold;
 5362:   width: 100%;
 5363:   background: $tabbg;
 5364:   vertical-align: middle;
 5365:   margin: 2ex 0ex 2ex 0ex;
 5366: }
 5367: 
 5368: .LC_topic_bar span {
 5369:   vertical-align: middle;
 5370: }
 5371: 
 5372: .LC_topic_bar img {
 5373:   vertical-align: bottom;
 5374: }
 5375: 
 5376: table.LC_course_group_status {
 5377:   margin: 20px;
 5378: }
 5379: 
 5380: table.LC_status_selector td {
 5381:   vertical-align: top;
 5382:   text-align: center;
 5383:   padding: 4px;
 5384: }
 5385: 
 5386: table.LC_descriptive_input td.LC_description {
 5387:   vertical-align: top;
 5388:   text-align: right;
 5389:   font-weight: bold;
 5390: }
 5391: 
 5392: div.LC_feedback_link {
 5393:   clear: both;
 5394:   background: white;
 5395:   width: 100%;
 5396: }
 5397: 
 5398: span.LC_feedback_link {
 5399:   background: $feedback_link_bg;
 5400:   font-size: larger;
 5401: }
 5402: 
 5403: span.LC_message_link {
 5404:   background: $feedback_link_bg;
 5405:   font-size: larger;
 5406:   position: absolute;
 5407:   right: 1em;
 5408: }
 5409: 
 5410: table.LC_prior_tries {
 5411:   border: 1px solid #000000;
 5412:   border-collapse: separate;
 5413:   border-spacing: 1px;
 5414: }
 5415: 
 5416: table.LC_prior_tries td {
 5417:   padding: 2px;
 5418: }
 5419: 
 5420: .LC_answer_correct {
 5421:   background: lightgreen;
 5422:   font-family: $sans;
 5423:   color: darkgreen;
 5424:   padding: 6px;
 5425: }
 5426: 
 5427: .LC_answer_charged_try {
 5428:   background: #FFAAAA;
 5429:   font-family: $sans;
 5430:   color: darkred;
 5431:   padding: 6px;
 5432: }
 5433: 
 5434: .LC_answer_not_charged_try,
 5435: .LC_answer_no_grade,
 5436: .LC_answer_late {
 5437:   background: lightyellow;
 5438:   font-family: $sans;
 5439:   color: black;
 5440:   padding: 6px;
 5441: }
 5442: 
 5443: .LC_answer_previous {
 5444:   background: lightblue;
 5445:   font-family: $sans;
 5446:   color: darkblue;
 5447:   padding: 6px;
 5448: }
 5449: 
 5450: .LC_answer_no_message {
 5451:   background: #FFFFFF;
 5452:   font-family: $sans;
 5453:   color: black;
 5454:   padding: 6px;
 5455: }
 5456: 
 5457: .LC_answer_unknown {
 5458:   background: orange;
 5459:   font-family: $sans;
 5460:   color: black;
 5461:   padding: 6px;
 5462: }
 5463: 
 5464: span.LC_prior_numerical,
 5465: span.LC_prior_string,
 5466: span.LC_prior_custom,
 5467: span.LC_prior_reaction,
 5468: span.LC_prior_math {
 5469:   font-family: monospace;
 5470:   white-space: pre;
 5471: }
 5472: 
 5473: span.LC_prior_string {
 5474:   font-family: monospace;
 5475:   white-space: pre;
 5476: }
 5477: 
 5478: table.LC_prior_option {
 5479:   width: 100%;
 5480:   border-collapse: collapse;
 5481: }
 5482: 
 5483: table.LC_prior_rank, 
 5484: table.LC_prior_match {
 5485:   border-collapse: collapse;
 5486: }
 5487: 
 5488: table.LC_prior_option tr td,
 5489: table.LC_prior_rank tr td,
 5490: table.LC_prior_match tr td {
 5491:   border: 1px solid #000000;
 5492: }
 5493: 
 5494: td.LC_nobreak,
 5495: span.LC_nobreak {
 5496:   white-space: nowrap;
 5497: }
 5498: 
 5499: span.LC_cusr_emph {
 5500:   font-style: italic;
 5501: }
 5502: 
 5503: span.LC_cusr_subheading {
 5504:   font-weight: normal;
 5505:   font-size: 85%;
 5506: }
 5507: 
 5508: table.LC_docs_documents {
 5509:   background: #BBBBBB;
 5510:   border-width: 0px;
 5511:   border-collapse: collapse;
 5512: }
 5513: 
 5514: table.LC_docs_documents td.LC_docs_document {
 5515:   border: 2px solid black;
 5516:   padding: 4px;
 5517: }
 5518: 
 5519: .LC_docs_entry_move {
 5520:   border: 0px;
 5521:   border-collapse: collapse;
 5522: }
 5523: 
 5524: .LC_docs_entry_move td {
 5525:   border: 2px solid #BBBBBB;
 5526:   background: #DDDDDD;
 5527: }
 5528: 
 5529: .LC_docs_editor td.LC_docs_entry_commands {
 5530:   background: #DDDDDD;
 5531:   font-size: x-small;
 5532: }
 5533: 
 5534: .LC_docs_copy {
 5535:   color: #000099;
 5536: }
 5537: 
 5538: .LC_docs_cut {
 5539:   color: #550044;
 5540: }
 5541: 
 5542: .LC_docs_rename {
 5543:   color: #009900;
 5544: }
 5545: 
 5546: .LC_docs_remove {
 5547:   color: #990000;
 5548: }
 5549: 
 5550: .LC_docs_reinit_warn,
 5551: .LC_docs_ext_edit {
 5552:   font-size: x-small;
 5553: }
 5554: 
 5555: .LC_docs_editor td.LC_docs_entry_title,
 5556: .LC_docs_editor td.LC_docs_entry_icon {
 5557:   background: #FFFFBB;
 5558: }
 5559: 
 5560: .LC_docs_editor td.LC_docs_entry_parameter {
 5561:   background: #BBBBFF;
 5562:   font-size: x-small;
 5563:   white-space: nowrap;
 5564: }
 5565: 
 5566: table.LC_docs_adddocs td,
 5567: table.LC_docs_adddocs th {
 5568:   border: 1px solid #BBBBBB;
 5569:   padding: 4px;
 5570:   background: #DDDDDD;
 5571: }
 5572: 
 5573: table.LC_sty_begin {
 5574:   background: #BBFFBB;
 5575: }
 5576: 
 5577: table.LC_sty_end {
 5578:   background: #FFBBBB;
 5579: }
 5580: 
 5581: table.LC_double_column {
 5582:   border-width: 0px;
 5583:   border-collapse: collapse;
 5584:   width: 100%;
 5585:   padding: 2px;
 5586: }
 5587: 
 5588: table.LC_double_column tr td.LC_left_col {
 5589:   top: 2px;
 5590:   left: 2px;
 5591:   width: 47%;
 5592:   vertical-align: top;
 5593: }
 5594: 
 5595: table.LC_double_column tr td.LC_right_col {
 5596:   top: 2px;
 5597:   right: 2px;
 5598:   width: 47%;
 5599:   vertical-align: top;
 5600: }
 5601: 
 5602: span.LC_role_level {
 5603:   font-weight: bold;
 5604: }
 5605: 
 5606: div.LC_left_float {
 5607:   float: left;
 5608:   padding-right: 5%;
 5609:   padding-bottom: 4px;
 5610: }
 5611: 
 5612: div.LC_clear_float_header {
 5613:   padding-bottom: 2px;
 5614: }
 5615: 
 5616: div.LC_clear_float_footer {
 5617:   padding-top: 10px;
 5618:   clear: both;
 5619: }
 5620: 
 5621: div.LC_grade_show_user {
 5622:   margin-top: 20px;
 5623:   border: 1px solid black;
 5624: }
 5625: 
 5626: div.LC_grade_user_name {
 5627:   background: #DDDDEE;
 5628:   border-bottom: 1px solid black;
 5629:   font-weight: bold;
 5630:   font-size: large;
 5631: }
 5632: 
 5633: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5634:   background: #DDEEDD;
 5635: }
 5636: 
 5637: div.LC_grade_show_problem,
 5638: div.LC_grade_submissions,
 5639: div.LC_grade_message_center,
 5640: div.LC_grade_info_links,
 5641: div.LC_grade_assign {
 5642:   margin: 5px;
 5643:   width: 99%;
 5644:   background: #FFFFFF;
 5645: }
 5646: 
 5647: div.LC_grade_show_problem_header,
 5648: div.LC_grade_submissions_header,
 5649: div.LC_grade_message_center_header,
 5650: div.LC_grade_assign_header {
 5651:   font-weight: bold;
 5652:   font-size: large;
 5653: }
 5654: 
 5655: div.LC_grade_show_problem_problem,
 5656: div.LC_grade_submissions_body,
 5657: div.LC_grade_message_center_body,
 5658: div.LC_grade_assign_body {
 5659:   border: 1px solid black;
 5660:   width: 99%;
 5661:   background: #FFFFFF;
 5662: }
 5663: 
 5664: span.LC_grade_check_note {
 5665:   font-weight: normal;
 5666:   font-size: medium;
 5667:   display: inline;
 5668:   position: absolute;
 5669:   right: 1em;
 5670: }
 5671: 
 5672: table.LC_scantron_action {
 5673:   width: 100%;
 5674: }
 5675: 
 5676: table.LC_scantron_action tr th {
 5677:   font-weight:bold;
 5678:   font-style:normal;
 5679: }
 5680: 
 5681: .LC_edit_problem_header,
 5682: div.LC_edit_problem_footer {
 5683:   font-weight: normal;
 5684:   font-size:  medium;
 5685:   margin: 2px;
 5686: }
 5687: 
 5688: div.LC_edit_problem_header,
 5689: div.LC_edit_problem_header div,
 5690: div.LC_edit_problem_footer,
 5691: div.LC_edit_problem_footer div,
 5692: div.LC_edit_problem_editxml_header,
 5693: div.LC_edit_problem_editxml_header div {
 5694:   margin-top: 5px;
 5695: }
 5696: 
 5697: div.LC_edit_problem_header_edit_row {
 5698:   background: $tabbg;
 5699:   padding: 3px;
 5700:   margin-bottom: 5px;
 5701: }
 5702: 
 5703: div.LC_edit_problem_header_title {
 5704:   font-weight: bold;
 5705:   font-size: larger;
 5706:   background: $tabbg;
 5707:   padding: 3px;
 5708: }
 5709: 
 5710: table.LC_edit_problem_header_title {
 5711:   font-size: larger;
 5712:   font-weight:  bold;
 5713:   width: 100%;
 5714:   border-color: $pgbg;
 5715:   border-style: solid;
 5716:   border-width: $border;
 5717:   background: $tabbg;
 5718:   border-collapse: collapse;
 5719:   padding: 0px
 5720: }
 5721: 
 5722: div.LC_edit_problem_discards {
 5723:   float: left;
 5724:   padding-bottom: 5px;
 5725: }
 5726: 
 5727: div.LC_edit_problem_saves {
 5728:   float: right;
 5729:   padding-bottom: 5px;
 5730: }
 5731: 
 5732: hr.LC_edit_problem_divide {
 5733:   clear: both;
 5734:   color: $tabbg;
 5735:   background-color: $tabbg;
 5736:   height: 3px;
 5737:   border: 0px;
 5738: }
 5739: 
 5740: img.stift{
 5741:   border-width:0;
 5742:   vertical-align:middle;
 5743: }
 5744: 
 5745: table#LC_mainmenu{
 5746:  margin-top:10px;
 5747:  width:80%;
 5748: }
 5749: 
 5750: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5751:   vertical-align: top;
 5752:   width: 45%;
 5753: }
 5754: 
 5755: .LC_mainmenu_fieldset_category {
 5756:   color: $font;
 5757:   background: $pgbg;
 5758:   font-family: $sans;
 5759:   font-size: small;
 5760:   font-weight: bold;
 5761: }
 5762: 
 5763: div.LC_createcourse {
 5764:     margin: 10px 10px 10px 10px;
 5765: }
 5766: 
 5767: /* ---- Remove when done ----
 5768: # The following styles is part of the redesign of LON-CAPA and are
 5769: # subject to change during this project.
 5770: # Don't rely on their current functionality as they might be 
 5771: # changed or removed.
 5772: # --------------------------*/
 5773: 
 5774: a:hover,
 5775: ol.LC_smallMenu a:hover,
 5776: ol#LC_MenuBreadcrumbs a:hover,
 5777: ol#LC_PathBreadcrumbs a:hover,
 5778: ul#LC_TabMainMenuContent a:hover,
 5779: .LC_FormSectionClearButton input:hover
 5780: ul.LC_TabContent   li:hover a {
 5781: 	color:#BF2317;
 5782:         text-decoration:none;
 5783: }
 5784: 
 5785: h1 {
 5786: 	padding:5px 10px 5px 20px;
 5787: 	line-height:130%;
 5788: }
 5789: 
 5790: h2,h3,h4,h5,h6 {
 5791: 	margin:5px 0px 5px 0px;
 5792: 	padding:0px;
 5793: 	line-height:130%;
 5794: }
 5795: 
 5796: .LC_hcell {
 5797:         padding:3px 15px 3px 15px;
 5798:         margin:0px;
 5799: 	background-color:$tabbg;
 5800: 	border-bottom:solid 1px $lg_border_color;
 5801: }
 5802: 
 5803: .LC_noBorder {
 5804:         border:0px;
 5805: }
 5806: 
 5807: 
 5808: /* Main Header with discription of Person, Course, etc. */
 5809: 
 5810: .LC_Right {
 5811:         float: right;
 5812:         margin: 0px;
 5813:         padding: 0px;
 5814: }
 5815: 
 5816: .LC_FormSectionClearButton input {
 5817:         background-color:transparent;
 5818:         border:0px;
 5819:         cursor:pointer;
 5820:         text-decoration:underline;
 5821: }
 5822: 
 5823: .LC_help_open_topic {
 5824:         color: #FFFFFF;
 5825:         background-color: #EEEEFF;
 5826:         margin: 1px;
 5827:         padding: 4px;
 5828:         border: 1px solid #000033;
 5829:         white-space: nowrap;
 5830: /*		vertical-align: middle; */
 5831: }
 5832: 
 5833: dl,ul,div,fieldset {
 5834: 	margin: 10px 10px 10px 0px;
 5835: 	overflow:hidden;
 5836: }
 5837: 
 5838: ol.LC_smallMenu, ol#LC_PathBreadcrumbs {
 5839: 	margin: 0px;
 5840: }
 5841: 
 5842: ol.LC_smallMenu li {
 5843: 	display: inline;
 5844: 	padding: 5px 5px 0px 10px;
 5845: 	vertical-align: top;
 5846: }
 5847: 
 5848: ol.LC_smallMenu li img {
 5849: 	vertical-align: bottom;
 5850: }
 5851: 
 5852: ol.LC_smallMenu a {
 5853: 	font-size: 90%;
 5854: 	color: RGB(80, 80, 80);
 5855: 	text-decoration: none;
 5856: }
 5857: 
 5858: ol#LC_TabMainMenuContent, 
 5859: ul.LC_TabContent ,
 5860: ul.LC_TabContentBigger {
 5861: 	display:block;
 5862: 	list-style:none;
 5863: 	margin: 0px;
 5864: 	padding: 0px;
 5865: }
 5866: 
 5867: ol#LC_TabMainMenuContent li,
 5868: ul.LC_TabContent li,
 5869: ul.LC_TabContentBigger li {
 5870: 	display: inline;
 5871: 	border-right: solid 1px $lg_border_color;
 5872: 	float:left;
 5873: 	line-height:140%;
 5874: 	white-space:nowrap;
 5875: }
 5876: 
 5877: ol#LC_TabMainMenuContent li {
 5878: 	vertical-align: bottom;
 5879: 	border-bottom: solid 1px RGB(175, 175, 175);
 5880: 	padding: 5px 10px 5px 10px;
 5881: 	margin-right:5px;
 5882: 	margin-bottom:3px;
 5883: 	font-weight: bold;
 5884: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5885: }
 5886: 
 5887: ol#LC_TabMainMenuContent li a {
 5888: 	color: RGB(47, 47, 47);
 5889: 	text-decoration: none;
 5890: }
 5891: 
 5892: ul.LC_TabContent {
 5893: 	min-height:1.6em;
 5894: }
 5895: 
 5896: ul.LC_TabContent li {
 5897: 	vertical-align:middle;
 5898: 	padding:0px 10px 0px 10px;
 5899: 	background-color:$tabbg;
 5900: 	border-bottom:solid 1px $lg_border_color;
 5901: }
 5902: 
 5903: ul.LC_TabContent li a, ul.LC_TabContent li {
 5904: 	color:rgb(47,47,47);
 5905: 	text-decoration:none;
 5906: 	font-size:95%;
 5907: 	font-weight:bold;
 5908: 	padding-right: 16px;
 5909: }
 5910: 
 5911: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
 5912:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 5913: 	border-bottom:solid 1px #FFFFFF;
 5914: 	padding-right: 16px;
 5915: }
 5916: 
 5917: ul.LC_TabContentBigger li {
 5918: 	vertical-align:bottom;
 5919: 	border-top:solid 1px $lg_border_color;
 5920: 	border-left:solid 1px $lg_border_color;
 5921: 	padding:5px 10px 5px 10px;
 5922: 	margin-left:2px;
 5923: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5924: }
 5925: 
 5926: ul.LC_TabContentBigger li:hover, 
 5927: ul.LC_TabContentBigger li.active {
 5928: 	background:url(/adm/lonIcons/lightGreyBG.png) repeat-x right bottom;
 5929: }
 5930: 
 5931: ul.LC_TabContentBigger li, 
 5932: ul.LC_TabContentBigger li a {
 5933: 	font-size:110%;
 5934: 	font-weight:bold;
 5935: }
 5936: 
 5937: ol#LC_MenuBreadcrumbs, 
 5938: ol#LC_PathBreadcrumbs, 
 5939: ul.LC_CourseBreadcrumbs {
 5940: 	border-top: solid 1px RGB(255, 255, 255);
 5941: 	height: 20px;
 5942: 	line-height: 20px;
 5943: 	vertical-align: bottom;
 5944: 	margin: 0px 0px 30px 0px;
 5945: 	padding-left: 10px;
 5946: 	list-style-position: inside;
 5947: 	background: url(/adm/lonIcons/lightGreyBG.png) repeat-x left top;
 5948: }
 5949: 
 5950: ol#LC_MenuBreadcrumbs li, 
 5951: ol#LC_PathBreadcrumbs li, 
 5952: ul.LC_CourseBreadcrumbs li {
 5953: /*
 5954: 	background: url(/adm/lonIcons/arrow_white.png) no-repeat left center;
 5955: */
 5956: 	display: inline;
 5957: 	padding: 0px 0px 0px 10px;
 5958: /*	vertical-align: bottom; */
 5959: 	overflow:hidden;
 5960: }
 5961: 
 5962: ol#LC_MenuBreadcrumbs li a, ul.LC_CourseBreadcrumbs li a {
 5963: 	text-decoration: none;
 5964: 	font-size:90%;
 5965: }
 5966: 
 5967: ol#LC_PathBreadcrumbs li a {
 5968: 	text-decoration:none;
 5969: 	font-size:100%;
 5970: 	font-weight:bold;
 5971: }
 5972: 
 5973: .LC_BoxPadding {
 5974: 	padding: 10px;
 5975: }
 5976: 
 5977: .LC_ContentBoxSpecial {
 5978: 	border: solid 1px $lg_border_color;
 5979: }
 5980: 
 5981: .LC_ContentBoxSpecialContactInfo {
 5982: 	border: solid 1px $lg_border_color;
 5983: 	max-width:25%;
 5984: 	min-width:25%;
 5985: }
 5986: 
 5987: .LC_AboutMe_Image {
 5988: 	float:left;
 5989: 	margin-right:10px;
 5990: }
 5991: 
 5992: .LC_Clear_AboutMe_Image {
 5993: 	clear:left;
 5994: }
 5995: 
 5996: dl.LC_ListStyleClean dt {
 5997: 	padding-right: 5px;
 5998: 	display: table-header-group;
 5999: }
 6000: 
 6001: dl.LC_ListStyleClean dd {
 6002: 	display: table-row;
 6003: }
 6004: 
 6005: .LC_ListStyleClean,
 6006: .LC_ListStyleSimple,
 6007: .LC_ListStyleNormal,
 6008: .LC_ListStyle_Border,
 6009: .LC_ListStyleSpecial {
 6010: 	/*display:block;	*/
 6011: 	list-style-position: inside;
 6012: 	list-style-type: none;
 6013: 	overflow: hidden;
 6014: 	padding: 0px;
 6015: }
 6016: 
 6017: .LC_ListStyleSimple li,
 6018: .LC_ListStyleSimple dd,
 6019: .LC_ListStyleNormal li,
 6020: .LC_ListStyleNormal dd,
 6021: .LC_ListStyleSpecial li,
 6022: .LC_ListStyleSpecial dd {
 6023: 	margin: 0px;
 6024: 	padding: 5px 5px 5px 10px;
 6025: 	clear: both;
 6026: }
 6027: 
 6028: .LC_ListStyleClean li,
 6029: .LC_ListStyleClean dd {
 6030: 	padding-top: 0px;
 6031: 	padding-bottom: 0px;
 6032: }
 6033: 
 6034: .LC_ListStyleSimple dd,
 6035: .LC_ListStyleSimple li {
 6036: 	border-bottom: solid 1px $lg_border_color;
 6037: }
 6038: 
 6039: .LC_ListStyleSpecial li,
 6040: .LC_ListStyleSpecial dd {
 6041: 	list-style-type: none;
 6042: 	background-color: RGB(220, 220, 220);
 6043: 	margin-bottom: 4px;
 6044: }
 6045: 
 6046: table.LC_SimpleTable {
 6047: 	margin:5px;
 6048: 	border:solid 1px $lg_border_color;
 6049: }
 6050: 
 6051: table.LC_SimpleTable tr {
 6052: 	padding:0px;
 6053: 	border:solid 1px $lg_border_color;
 6054: }
 6055: 
 6056: table.LC_SimpleTable thead {
 6057: 	 background:rgb(220,220,220);
 6058: }
 6059: 
 6060: div.LC_columnSection {
 6061: 	display: block;
 6062: 	clear: both;
 6063: 	overflow: hidden;
 6064: 	margin:0px;
 6065: }
 6066: 
 6067: div.LC_columnSection>* {
 6068: 	float: left;
 6069: 	margin: 10px 20px 10px 0px;
 6070: 	overflow:hidden;
 6071: }
 6072: 
 6073: .ContentBoxSpecialTemplate {
 6074:         border: solid 1px $lg_border_color;
 6075: }
 6076: 
 6077: .ContentBoxTemplate {
 6078:         padding:10px;
 6079: }
 6080: 
 6081: div.LC_columnSection > .ContentBoxTemplate,
 6082: div.LC_columnSection > .ContentBoxSpecialTemplate {
 6083:         width: 600px;
 6084: }
 6085: 
 6086: .clear {
 6087: 	clear: both;
 6088: 	line-height: 0px;
 6089: 	font-size: 0px;
 6090: 	height: 0px;
 6091: }
 6092: 
 6093: .LC_loginpage_container {
 6094: 	text-align:left;
 6095: 	margin : 0 auto;
 6096: 	width:90%;
 6097: 	padding: 10px;
 6098: 	height: auto;
 6099: 	background-color:#FFFFFF;
 6100: 	border:1px solid #CCCCCC;
 6101: }
 6102: 
 6103: 
 6104: .LC_loginpage_loginContainer {
 6105: 	float:left;
 6106: 	width: 182px;
 6107: 	padding: 2px;
 6108: 	border:1px solid #CCCCCC;
 6109: 	background-color:$loginbg;
 6110: }
 6111: 
 6112: .LC_loginpage_loginContainer h2 {
 6113: 	margin-top:0;
 6114: 	display:block;
 6115: 	background:$bgcol;
 6116: 	color:$textcol;
 6117: 	padding-left:5px;
 6118: }
 6119: 
 6120: .LC_loginpage_loginInfo {
 6121: 	float:left;
 6122: 	width:182px;
 6123: 	border:1px solid #CCCCCC;
 6124: 	padding:2px;
 6125: }
 6126: 
 6127: .LC_loginpage_space {
 6128: 	clear: both;
 6129: 	margin-bottom: 20px;
 6130: 	border-bottom: 1px solid #CCCCCC;
 6131: }
 6132: 
 6133: .LC_loginpage_floatLeft {
 6134: 	float: left;
 6135: 	width: 200px;
 6136: 	margin: 0;
 6137: }
 6138: 
 6139: table em {
 6140: 	font-weight: bold;
 6141: 	font-style: normal;
 6142: }
 6143: 
 6144: table.LC_tableBrowseRes,
 6145: table.LC_tableOfContent {
 6146:         border:none;
 6147: 	border-spacing: 1;
 6148: 	padding: 3px;
 6149: 	background-color: #FFFFFF;
 6150: 	font-size: 90%;
 6151: }
 6152: 
 6153: table.LC_tableOfContent{
 6154:     border-collapse: collapse;
 6155: }
 6156: 
 6157: table.LC_tableBrowseRes a,
 6158: table.LC_tableOfContent a {
 6159:         background-color: transparent;
 6160: 	text-decoration: none;
 6161: }
 6162: 
 6163: table.LC_tableBrowseRes tr.LC_trOdd,
 6164: table.LC_tableOfContent tr.LC_trOdd{
 6165: 	background-color: #EEEEEE;
 6166: }
 6167: 
 6168: table.LC_tableOfContent img {
 6169: 	border: none;
 6170: 	height: 1.3em;
 6171: 	vertical-align: text-bottom;
 6172: 	margin-right: 0.3em;
 6173: }
 6174: 
 6175: a#LC_content_toolbar_firsthomework {
 6176: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 6177: }
 6178: 
 6179: a#LC_content_toolbar_launchnav {
 6180: 	background-image:url(/res/adm/pages/start-navigation.gif);
 6181: }
 6182: 
 6183: a#LC_content_toolbar_closenav {
 6184: 	background-image:url(/res/adm/pages/close-navigation.gif);
 6185: }
 6186: 
 6187: a#LC_content_toolbar_everything {
 6188: 	background-image:url(/res/adm/pages/show-all.gif);
 6189: }
 6190: 
 6191: a#LC_content_toolbar_uncompleted {
 6192: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6193: }
 6194: 
 6195: #LC_content_toolbar_clearbubbles {
 6196: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6197: }
 6198: 
 6199: a#LC_content_toolbar_changefolder {
 6200: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6201: }
 6202: 
 6203: a#LC_content_toolbar_changefolder_toggled {
 6204: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 6205: }
 6206: 
 6207: ul#LC_toolbar li a:hover {
 6208: 	background-position: bottom center;
 6209: }
 6210: 
 6211: ul#LC_toolbar {
 6212: 	padding:0;
 6213: 	margin: 2px;
 6214: 	list-style:none;
 6215: 	position:relative;
 6216: 	background-color:white;
 6217: }
 6218: 
 6219: ul#LC_toolbar li {
 6220: 	border:1px solid white;
 6221: 	padding:0;
 6222: 	margin: 0;
 6223:         float: left;
 6224: 	display:inline;
 6225: 	vertical-align:middle;
 6226: } 
 6227: 
 6228: 
 6229: a.LC_toolbarItem {
 6230: 	display:block;
 6231: 	padding:0;
 6232: 	margin:0;
 6233: 	height: 32px;
 6234: 	width: 32px;
 6235: 	color:white;
 6236: 	border:0 none;
 6237: 	background-repeat:no-repeat;
 6238: 	background-color:transparent;
 6239: }
 6240: 
 6241: ul.LC_functionslist li {
 6242:   float: left;
 6243:   white-space: nowrap;
 6244:   height: 35px; /* at least as high as heighest list item */
 6245:   margin: 0px 15px 15px 10px;
 6246: }
 6247: 
 6248: 
 6249: END
 6250: }
 6251: 
 6252: =pod
 6253: 
 6254: =item * &headtag()
 6255: 
 6256: Returns a uniform footer for LON-CAPA web pages.
 6257: 
 6258: Inputs: $title - optional title for the head
 6259:         $head_extra - optional extra HTML to put inside the <head>
 6260:         $args - optional arguments
 6261:             force_register - if is true call registerurl so the remote is 
 6262:                              informed
 6263:             redirect       -> array ref of
 6264:                                    1- seconds before redirect occurs
 6265:                                    2- url to redirect to
 6266:                                    3- whether the side effect should occur
 6267:                            (side effect of setting 
 6268:                                $env{'internal.head.redirect'} to the url 
 6269:                                redirected too)
 6270:             domain         -> force to color decorate a page for a specific
 6271:                                domain
 6272:             function       -> force usage of a specific rolish color scheme
 6273:             bgcolor        -> override the default page bgcolor
 6274:             no_auto_mt_title
 6275:                            -> prevent &mt()ing the title arg
 6276: 
 6277: =cut
 6278: 
 6279: sub headtag {
 6280:     my ($title,$head_extra,$args) = @_;
 6281:     
 6282:     my $function = $args->{'function'} || &get_users_function();
 6283:     my $domain   = $args->{'domain'}   || &determinedomain();
 6284:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6285:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6286: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6287: 		   #time(),
 6288: 		   $env{'environment.color.timestamp'},
 6289: 		   $function,$domain,$bgcolor);
 6290: 
 6291:     $url = '/adm/css/'.&escape($url).'.css';
 6292: 
 6293:     my $result =
 6294: 	'<head>'.
 6295: 	&font_settings();
 6296: 
 6297:     if (!$args->{'frameset'}) {
 6298: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6299:     }
 6300:     if ($args->{'force_register'}) {
 6301: 	$result .= &Apache::lonmenu::registerurl(1);
 6302:     }
 6303:     if (!$args->{'no_nav_bar'} 
 6304: 	&& !$args->{'only_body'}
 6305: 	&& !$args->{'frameset'}) {
 6306: 	$result .= &help_menu_js();
 6307:     }
 6308: 
 6309:     if (ref($args->{'redirect'})) {
 6310: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6311: 	$url = &Apache::lonenc::check_encrypt($url);
 6312: 	if (!$inhibit_continue) {
 6313: 	    $env{'internal.head.redirect'} = $url;
 6314: 	}
 6315: 	$result.=<<ADDMETA
 6316: <meta http-equiv="pragma" content="no-cache" />
 6317: <meta http-equiv="Refresh" content="$time; url=$url" />
 6318: ADDMETA
 6319:     }
 6320:     if (!defined($title)) {
 6321: 	$title = 'The LearningOnline Network with CAPA';
 6322:     }
 6323:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6324:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6325: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6326: 	.$head_extra;
 6327:     return $result;
 6328: }
 6329: 
 6330: =pod
 6331: 
 6332: =item * &font_settings()
 6333: 
 6334: Returns neccessary <meta> to set the proper encoding
 6335: 
 6336: Inputs: none
 6337: 
 6338: =cut
 6339: 
 6340: sub font_settings {
 6341:     my $headerstring='';
 6342:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6343: 	$headerstring.=
 6344: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6345:     }
 6346:     return $headerstring;
 6347: }
 6348: 
 6349: =pod
 6350: 
 6351: =item * &xml_begin()
 6352: 
 6353: Returns the needed doctype and <html>
 6354: 
 6355: Inputs: none
 6356: 
 6357: =cut
 6358: 
 6359: sub xml_begin {
 6360:     my $output='';
 6361: 
 6362:     if ($env{'internal.start_page'}==1) {
 6363: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6364:     }
 6365: 
 6366:     if ($env{'browser.mathml'}) {
 6367: 	$output='<?xml version="1.0"?>'
 6368:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6369: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6370:             
 6371: #	    .'<!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">] >'
 6372: 	    .'<!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">'
 6373:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6374: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6375:     } else {
 6376: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 6377:     }
 6378:     return $output;
 6379: }
 6380: 
 6381: =pod
 6382: 
 6383: =item * &endheadtag()
 6384: 
 6385: Returns a uniform </head> for LON-CAPA web pages.
 6386: 
 6387: Inputs: none
 6388: 
 6389: =cut
 6390: 
 6391: sub endheadtag {
 6392:     return '</head>';
 6393: }
 6394: 
 6395: =pod
 6396: 
 6397: =item * &head()
 6398: 
 6399: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6400: 
 6401: Inputs:
 6402: 
 6403: =over 4
 6404: 
 6405: $title - optional title for the page
 6406: 
 6407: $head_extra - optional extra HTML to put inside the <head>
 6408: 
 6409: =back
 6410: 
 6411: =cut
 6412: 
 6413: sub head {
 6414:     my ($title,$head_extra,$args) = @_;
 6415:     return &headtag($title,$head_extra,$args).&endheadtag();
 6416: }
 6417: 
 6418: =pod
 6419: 
 6420: =item * &start_page()
 6421: 
 6422: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6423: 
 6424: Inputs:
 6425: 
 6426: =over 4
 6427: 
 6428: $title - optional title for the page
 6429: 
 6430: $head_extra - optional extra HTML to incude inside the <head>
 6431: 
 6432: $args - additional optional args supported are:
 6433: 
 6434: =over 8
 6435: 
 6436:              only_body      -> is true will set &bodytag() onlybodytag
 6437:                                     arg on
 6438:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 6439:              add_entries    -> additional attributes to add to the  <body>
 6440:              domain         -> force to color decorate a page for a 
 6441:                                     specific domain
 6442:              function       -> force usage of a specific rolish color
 6443:                                     scheme
 6444:              redirect       -> see &headtag()
 6445:              bgcolor        -> override the default page bg color
 6446:              js_ready       -> return a string ready for being used in 
 6447:                                     a javascript writeln
 6448:              html_encode    -> return a string ready for being used in 
 6449:                                     a html attribute
 6450:              force_register -> if is true will turn on the &bodytag()
 6451:                                     $forcereg arg
 6452:              body_title     -> alternate text to use instead of $title
 6453:                                     in the title box that appears, this text
 6454:                                     is not auto translated like the $title is
 6455:              frameset       -> if true will start with a <frameset>
 6456:                                     rather than <body>
 6457:              no_title       -> if true the title bar won't be shown
 6458:              skip_phases    -> hash ref of 
 6459:                                     head -> skip the <html><head> generation
 6460:                                     body -> skip all <body> generation
 6461:              no_inline_link -> if true and in remote mode, don't show the 
 6462:                                     'Switch To Inline Menu' link
 6463:              no_auto_mt_title -> prevent &mt()ing the title arg
 6464:              inherit_jsmath -> when creating popup window in a page,
 6465:                                     should it have jsmath forced on by the
 6466:                                     current page
 6467: 
 6468: =back
 6469: 
 6470: =back
 6471: 
 6472: =cut
 6473: 
 6474: sub start_page {
 6475:     my ($title,$head_extra,$args) = @_;
 6476:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6477:     my %head_args;
 6478:     foreach my $arg ('redirect','force_register','domain','function',
 6479: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6480: 		     'no_auto_mt_title') {
 6481: 	if (defined($args->{$arg})) {
 6482: 	    $head_args{$arg} = $args->{$arg};
 6483: 	}
 6484:     }
 6485: 
 6486:     $env{'internal.start_page'}++;
 6487:     my $result;
 6488:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6489: 	$result.=
 6490: 	    &xml_begin().
 6491: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6492:     }
 6493:     
 6494:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6495: 	if ($args->{'frameset'}) {
 6496: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6497: 						$args->{'add_entries'});
 6498: 	    $result .= "\n<frameset $attr_string>\n";
 6499: 	} else {
 6500: 	    $result .=
 6501: 		&bodytag($title, 
 6502: 			 $args->{'function'},       $args->{'add_entries'},
 6503: 			 $args->{'only_body'},      $args->{'domain'},
 6504: 			 $args->{'force_register'}, $args->{'body_title'},
 6505: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6506: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6507: 			 $args);
 6508: 	}
 6509:     }
 6510: 
 6511:     if ($args->{'js_ready'}) {
 6512: 		$result = &js_ready($result);
 6513:     }
 6514:     if ($args->{'html_encode'}) {
 6515: 		$result = &html_encode($result);
 6516:     }
 6517: 
 6518: 	#Breadcrumbs
 6519:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6520: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6521: 		#if any br links exists, add them to the breadcrumbs
 6522: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6523: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6524: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6525: 			}
 6526: 		}
 6527: 
 6528: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6529: 		if(exists($args->{'bread_crumbs_component'})){
 6530: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6531: 		}else{
 6532: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6533: 		}
 6534:     }
 6535:     return $result;
 6536: }
 6537: 
 6538: 
 6539: =pod
 6540: 
 6541: =item * &head()
 6542: 
 6543: Returns a complete </body></html> section for LON-CAPA web pages.
 6544: 
 6545: Inputs:         $args - additional optional args supported are:
 6546:                  js_ready     -> return a string ready for being used in 
 6547:                                  a javascript writeln
 6548:                  html_encode  -> return a string ready for being used in 
 6549:                                  a html attribute
 6550:                  frameset     -> if true will start with a <frameset>
 6551:                                  rather than <body>
 6552:                  dicsussion   -> if true will get discussion from
 6553:                                   lonxml::xmlend
 6554:                                  (you can pass the target and parser arguments
 6555:                                   through optional 'target' and 'parser' args
 6556:                                   to this routine)
 6557: 
 6558: =cut
 6559: 
 6560: sub end_page {
 6561:     my ($args) = @_;
 6562:     $env{'internal.end_page'}++;
 6563:     my $result;
 6564:     if ($args->{'discussion'}) {
 6565: 	my ($target,$parser);
 6566: 	if (ref($args->{'discussion'})) {
 6567: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6568: 				$args->{'discussion'}{'parser'});
 6569: 	}
 6570: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6571:     }
 6572: 
 6573:     if ($args->{'frameset'}) {
 6574: 	$result .= '</frameset>';
 6575:     } else {
 6576: 	$result .= &endbodytag($args);
 6577:     }
 6578:     $result .= "\n</html>";
 6579: 
 6580:     if ($args->{'js_ready'}) {
 6581: 	$result = &js_ready($result);
 6582:     }
 6583: 
 6584:     if ($args->{'html_encode'}) {
 6585: 	$result = &html_encode($result);
 6586:     }
 6587: 
 6588:     return $result;
 6589: }
 6590: 
 6591: sub html_encode {
 6592:     my ($result) = @_;
 6593: 
 6594:     $result = &HTML::Entities::encode($result,'<>&"');
 6595:     
 6596:     return $result;
 6597: }
 6598: sub js_ready {
 6599:     my ($result) = @_;
 6600: 
 6601:     $result =~ s/[\n\r]/ /xmsg;
 6602:     $result =~ s/\\/\\\\/xmsg;
 6603:     $result =~ s/'/\\'/xmsg;
 6604:     $result =~ s{</}{<\\/}xmsg;
 6605:     
 6606:     return $result;
 6607: }
 6608: 
 6609: sub validate_page {
 6610:     if (  exists($env{'internal.start_page'})
 6611: 	  &&     $env{'internal.start_page'} > 1) {
 6612: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6613: 				 $env{'internal.start_page'}.' '.
 6614: 				 $ENV{'request.filename'});
 6615:     }
 6616:     if (  exists($env{'internal.end_page'})
 6617: 	  &&     $env{'internal.end_page'} > 1) {
 6618: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6619: 				 $env{'internal.end_page'}.' '.
 6620: 				 $env{'request.filename'});
 6621:     }
 6622:     if (     exists($env{'internal.start_page'})
 6623: 	&& ! exists($env{'internal.end_page'})) {
 6624: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6625: 				 $env{'request.filename'});
 6626:     }
 6627:     if (   ! exists($env{'internal.start_page'})
 6628: 	&&   exists($env{'internal.end_page'})) {
 6629: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6630: 				 $env{'request.filename'});
 6631:     }
 6632: }
 6633: 
 6634: sub simple_error_page {
 6635:     my ($r,$title,$msg) = @_;
 6636:     my $page =
 6637: 	&Apache::loncommon::start_page($title).
 6638: 	&mt($msg).
 6639: 	&Apache::loncommon::end_page();
 6640:     if (ref($r)) {
 6641: 	$r->print($page);
 6642: 	return;
 6643:     }
 6644:     return $page;
 6645: }
 6646: 
 6647: {
 6648:     my @row_count;
 6649:     sub start_data_table {
 6650: 	my ($add_class) = @_;
 6651: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6652: 	unshift(@row_count,0);
 6653: 	return '<table class="'.$css_class.'">'."\n";
 6654:     }
 6655: 
 6656:     sub end_data_table {
 6657: 	shift(@row_count);
 6658: 	return '</table>'."\n";;
 6659:     }
 6660: 
 6661:     sub start_data_table_row {
 6662: 	my ($add_class) = @_;
 6663: 	$row_count[0]++;
 6664: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6665: 	$css_class = (join(' ',$css_class,$add_class));
 6666: 	return  '<tr class="'.$css_class.'">'."\n";;
 6667:     }
 6668:     
 6669:     sub continue_data_table_row {
 6670: 	my ($add_class) = @_;
 6671: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6672: 	$css_class = (join(' ',$css_class,$add_class));
 6673: 	return  '<tr class="'.$css_class.'">'."\n";;
 6674:     }
 6675: 
 6676:     sub end_data_table_row {
 6677: 	return '</tr>'."\n";;
 6678:     }
 6679: 
 6680:     sub start_data_table_empty_row {
 6681: #	$row_count[0]++;
 6682: 	return  '<tr class="LC_empty_row" >'."\n";;
 6683:     }
 6684: 
 6685:     sub end_data_table_empty_row {
 6686: 	return '</tr>'."\n";;
 6687:     }
 6688: 
 6689:     sub start_data_table_header_row {
 6690: 	return  '<tr class="LC_header_row">'."\n";;
 6691:     }
 6692: 
 6693:     sub end_data_table_header_row {
 6694: 	return '</tr>'."\n";;
 6695:     }
 6696: }
 6697: 
 6698: =pod
 6699: 
 6700: =item * &inhibit_menu_check($arg)
 6701: 
 6702: Checks for a inhibitmenu state and generates output to preserve it
 6703: 
 6704: Inputs:         $arg - can be any of
 6705:                      - undef - in which case the return value is a string 
 6706:                                to add  into arguments list of a uri
 6707:                      - 'input' - in which case the return value is a HTML
 6708:                                  <form> <input> field of type hidden to
 6709:                                  preserve the value
 6710:                      - a url - in which case the return value is the url with
 6711:                                the neccesary cgi args added to preserve the
 6712:                                inhibitmenu state
 6713:                      - a ref to a url - no return value, but the string is
 6714:                                         updated to include the neccessary cgi
 6715:                                         args to preserve the inhibitmenu state
 6716: 
 6717: =cut
 6718: 
 6719: sub inhibit_menu_check {
 6720:     my ($arg) = @_;
 6721:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6722:     if ($arg eq 'input') {
 6723: 	if ($env{'form.inhibitmenu'}) {
 6724: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6725: 	} else {
 6726: 	    return
 6727: 	}
 6728:     }
 6729:     if ($env{'form.inhibitmenu'}) {
 6730: 	if (ref($arg)) {
 6731: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6732: 	} elsif ($arg eq '') {
 6733: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6734: 	} else {
 6735: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6736: 	}
 6737:     }
 6738:     if (!ref($arg)) {
 6739: 	return $arg;
 6740:     }
 6741: }
 6742: 
 6743: ###############################################
 6744: 
 6745: =pod
 6746: 
 6747: =back
 6748: 
 6749: =head1 User Information Routines
 6750: 
 6751: =over 4
 6752: 
 6753: =item * &get_users_function()
 6754: 
 6755: Used by &bodytag to determine the current users primary role.
 6756: Returns either 'student','coordinator','admin', or 'author'.
 6757: 
 6758: =cut
 6759: 
 6760: ###############################################
 6761: sub get_users_function {
 6762:     my $function = 'student';
 6763:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6764:         $function='coordinator';
 6765:     }
 6766:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6767:         $function='admin';
 6768:     }
 6769:     if (($env{'request.role'}=~/^(au|ca)/) ||
 6770:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6771:         $function='author';
 6772:     }
 6773:     return $function;
 6774: }
 6775: 
 6776: ###############################################
 6777: 
 6778: =pod
 6779: 
 6780: =item * &check_user_status()
 6781: 
 6782: Determines current status of supplied role for a
 6783: specific user. Roles can be active, previous or future.
 6784: 
 6785: Inputs: 
 6786: user's domain, user's username, course's domain,
 6787: course's number, optional section ID.
 6788: 
 6789: Outputs:
 6790: role status: active, previous or future. 
 6791: 
 6792: =cut
 6793: 
 6794: sub check_user_status {
 6795:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6796:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6797:     my @uroles = keys %userinfo;
 6798:     my $srchstr;
 6799:     my $active_chk = 'none';
 6800:     my $now = time;
 6801:     if (@uroles > 0) {
 6802:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6803:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6804:         } else {
 6805:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6806:         }
 6807:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6808:             my $role_end = 0;
 6809:             my $role_start = 0;
 6810:             $active_chk = 'active';
 6811:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6812:                 $role_end = $1;
 6813:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6814:                     $role_start = $1;
 6815:                 }
 6816:             }
 6817:             if ($role_start > 0) {
 6818:                 if ($now < $role_start) {
 6819:                     $active_chk = 'future';
 6820:                 }
 6821:             }
 6822:             if ($role_end > 0) {
 6823:                 if ($now > $role_end) {
 6824:                     $active_chk = 'previous';
 6825:                 }
 6826:             }
 6827:         }
 6828:     }
 6829:     return $active_chk;
 6830: }
 6831: 
 6832: ###############################################
 6833: 
 6834: =pod
 6835: 
 6836: =item * &get_sections()
 6837: 
 6838: Determines all the sections for a course including
 6839: sections with students and sections containing other roles.
 6840: Incoming parameters: 
 6841: 
 6842: 1. domain
 6843: 2. course number 
 6844: 3. reference to array containing roles for which sections should 
 6845: be gathered (optional).
 6846: 4. reference to array containing status types for which sections 
 6847: should be gathered (optional).
 6848: 
 6849: If the third argument is undefined, sections are gathered for any role. 
 6850: If the fourth argument is undefined, sections are gathered for any status.
 6851: Permissible values are 'active' or 'future' or 'previous'.
 6852:  
 6853: Returns section hash (keys are section IDs, values are
 6854: number of users in each section), subject to the
 6855: optional roles filter, optional status filter 
 6856: 
 6857: =cut
 6858: 
 6859: ###############################################
 6860: sub get_sections {
 6861:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6862:     if (!defined($cdom) || !defined($cnum)) {
 6863:         my $cid =  $env{'request.course.id'};
 6864: 
 6865: 	return if (!defined($cid));
 6866: 
 6867:         $cdom = $env{'course.'.$cid.'.domain'};
 6868:         $cnum = $env{'course.'.$cid.'.num'};
 6869:     }
 6870: 
 6871:     my %sectioncount;
 6872:     my $now = time;
 6873: 
 6874:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6875: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6876: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6877: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6878:         my $start_index = &Apache::loncoursedata::CL_START();
 6879:         my $end_index = &Apache::loncoursedata::CL_END();
 6880:         my $status;
 6881: 	while (my ($student,$data) = each(%$classlist)) {
 6882: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6883: 				                     $data->[$status_index],
 6884:                                                      $data->[$start_index],
 6885:                                                      $data->[$end_index]);
 6886:             if ($stu_status eq 'Active') {
 6887:                 $status = 'active';
 6888:             } elsif ($end < $now) {
 6889:                 $status = 'previous';
 6890:             } elsif ($start > $now) {
 6891:                 $status = 'future';
 6892:             } 
 6893: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6894:                 if ((!defined($possible_status)) || (($status ne '') && 
 6895:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6896: 		    $sectioncount{$section}++;
 6897:                 }
 6898: 	    }
 6899: 	}
 6900:     }
 6901:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6902:     foreach my $user (sort(keys(%courseroles))) {
 6903: 	if ($user !~ /^(\w{2})/) { next; }
 6904: 	my ($role) = ($user =~ /^(\w{2})/);
 6905: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6906: 	my ($section,$status);
 6907: 	if ($role eq 'cr' &&
 6908: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6909: 	    $section=$1;
 6910: 	}
 6911: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6912: 	if (!defined($section) || $section eq '-1') { next; }
 6913:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6914:         if ($end == -1 && $start == -1) {
 6915:             next; #deleted role
 6916:         }
 6917:         if (!defined($possible_status)) { 
 6918:             $sectioncount{$section}++;
 6919:         } else {
 6920:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6921:                 $status = 'active';
 6922:             } elsif ($end < $now) {
 6923:                 $status = 'future';
 6924:             } elsif ($start > $now) {
 6925:                 $status = 'previous';
 6926:             }
 6927:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6928:                 $sectioncount{$section}++;
 6929:             }
 6930:         }
 6931:     }
 6932:     return %sectioncount;
 6933: }
 6934: 
 6935: ###############################################
 6936: 
 6937: =pod
 6938: 
 6939: =item * &get_course_users()
 6940: 
 6941: Retrieves usernames:domains for users in the specified course
 6942: with specific role(s), and access status. 
 6943: 
 6944: Incoming parameters:
 6945: 1. course domain
 6946: 2. course number
 6947: 3. access status: users must have - either active, 
 6948: previous, future, or all.
 6949: 4. reference to array of permissible roles
 6950: 5. reference to array of section restrictions (optional)
 6951: 6. reference to results object (hash of hashes).
 6952: 7. reference to optional userdata hash
 6953: 8. reference to optional statushash
 6954: 9. flag if privileged users (except those set to unhide in
 6955:    course settings) should be excluded    
 6956: Keys of top level results hash are roles.
 6957: Keys of inner hashes are username:domain, with 
 6958: values set to access type.
 6959: Optional userdata hash returns an array with arguments in the 
 6960: same order as loncoursedata::get_classlist() for student data.
 6961: 
 6962: Optional statushash returns
 6963: 
 6964: Entries for end, start, section and status are blank because
 6965: of the possibility of multiple values for non-student roles.
 6966: 
 6967: =cut
 6968: 
 6969: ###############################################
 6970: 
 6971: sub get_course_users {
 6972:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6973:     my %idx = ();
 6974:     my %seclists;
 6975: 
 6976:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6977:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6978:     $idx{end} = &Apache::loncoursedata::CL_END();
 6979:     $idx{start} = &Apache::loncoursedata::CL_START();
 6980:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6981:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6982:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6983:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6984: 
 6985:     if (grep(/^st$/,@{$roles})) {
 6986:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6987:         my $now = time;
 6988:         foreach my $student (keys(%{$classlist})) {
 6989:             my $match = 0;
 6990:             my $secmatch = 0;
 6991:             my $section = $$classlist{$student}[$idx{section}];
 6992:             my $status = $$classlist{$student}[$idx{status}];
 6993:             if ($section eq '') {
 6994:                 $section = 'none';
 6995:             }
 6996:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6997:                 if (grep(/^all$/,@{$sections})) {
 6998:                     $secmatch = 1;
 6999:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7000:                     if (grep(/^none$/,@{$sections})) {
 7001:                         $secmatch = 1;
 7002:                     }
 7003:                 } else {  
 7004: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7005: 		        $secmatch = 1;
 7006:                     }
 7007: 		}
 7008:                 if (!$secmatch) {
 7009:                     next;
 7010:                 }
 7011:             }
 7012:             if (defined($$types{'active'})) {
 7013:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7014:                     push(@{$$users{st}{$student}},'active');
 7015:                     $match = 1;
 7016:                 }
 7017:             }
 7018:             if (defined($$types{'previous'})) {
 7019:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7020:                     push(@{$$users{st}{$student}},'previous');
 7021:                     $match = 1;
 7022:                 }
 7023:             }
 7024:             if (defined($$types{'future'})) {
 7025:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7026:                     push(@{$$users{st}{$student}},'future');
 7027:                     $match = 1;
 7028:                 }
 7029:             }
 7030:             if ($match) {
 7031:                 push(@{$seclists{$student}},$section);
 7032:                 if (ref($userdata) eq 'HASH') {
 7033:                     $$userdata{$student} = $$classlist{$student};
 7034:                 }
 7035:                 if (ref($statushash) eq 'HASH') {
 7036:                     $statushash->{$student}{'st'}{$section} = $status;
 7037:                 }
 7038:             }
 7039:         }
 7040:     }
 7041:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7042:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7043:         my $now = time;
 7044:         my %displaystatus = ( previous => 'Expired',
 7045:                               active   => 'Active',
 7046:                               future   => 'Future',
 7047:                             );
 7048:         my %nothide;
 7049:         if ($hidepriv) {
 7050:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7051:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7052:                 if ($user !~ /:/) {
 7053:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7054:                 } else {
 7055:                     $nothide{$user} = 1;
 7056:                 }
 7057:             }
 7058:         }
 7059:         foreach my $person (sort(keys(%coursepersonnel))) {
 7060:             my $match = 0;
 7061:             my $secmatch = 0;
 7062:             my $status;
 7063:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7064:             $user =~ s/:$//;
 7065:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7066:             if ($end == -1 || $start == -1) {
 7067:                 next;
 7068:             }
 7069:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7070:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7071:                 my ($uname,$udom) = split(/:/,$user);
 7072:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7073:                     if (grep(/^all$/,@{$sections})) {
 7074:                         $secmatch = 1;
 7075:                     } elsif ($usec eq '') {
 7076:                         if (grep(/^none$/,@{$sections})) {
 7077:                             $secmatch = 1;
 7078:                         }
 7079:                     } else {
 7080:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7081:                             $secmatch = 1;
 7082:                         }
 7083:                     }
 7084:                     if (!$secmatch) {
 7085:                         next;
 7086:                     }
 7087:                 }
 7088:                 if ($usec eq '') {
 7089:                     $usec = 'none';
 7090:                 }
 7091:                 if ($uname ne '' && $udom ne '') {
 7092:                     if ($hidepriv) {
 7093:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7094:                             (!$nothide{$uname.':'.$udom})) {
 7095:                             next;
 7096:                         }
 7097:                     }
 7098:                     if ($end > 0 && $end < $now) {
 7099:                         $status = 'previous';
 7100:                     } elsif ($start > $now) {
 7101:                         $status = 'future';
 7102:                     } else {
 7103:                         $status = 'active';
 7104:                     }
 7105:                     foreach my $type (keys(%{$types})) { 
 7106:                         if ($status eq $type) {
 7107:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7108:                                 push(@{$$users{$role}{$user}},$type);
 7109:                             }
 7110:                             $match = 1;
 7111:                         }
 7112:                     }
 7113:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7114:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7115: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7116:                         }
 7117:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7118:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7119:                         }
 7120:                         if (ref($statushash) eq 'HASH') {
 7121:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7122:                         }
 7123:                     }
 7124:                 }
 7125:             }
 7126:         }
 7127:         if (grep(/^ow$/,@{$roles})) {
 7128:             if ((defined($cdom)) && (defined($cnum))) {
 7129:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7130:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7131:                     my $owner = $csettings{'internal.courseowner'};
 7132:                     next if ($owner eq '');
 7133:                     my ($ownername,$ownerdom);
 7134:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7135:                         $ownername = $1;
 7136:                         $ownerdom = $2;
 7137:                     } else {
 7138:                         $ownername = $owner;
 7139:                         $ownerdom = $cdom;
 7140:                         $owner = $ownername.':'.$ownerdom;
 7141:                     }
 7142:                     @{$$users{'ow'}{$owner}} = 'any';
 7143:                     if (defined($userdata) && 
 7144: 			!exists($$userdata{$owner})) {
 7145: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7146:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7147:                             push(@{$seclists{$owner}},'none');
 7148:                         }
 7149:                         if (ref($statushash) eq 'HASH') {
 7150:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7151:                         }
 7152: 		    }
 7153:                 }
 7154:             }
 7155:         }
 7156:         foreach my $user (keys(%seclists)) {
 7157:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7158:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7159:         }
 7160:     }
 7161:     return;
 7162: }
 7163: 
 7164: sub get_user_info {
 7165:     my ($udom,$uname,$idx,$userdata) = @_;
 7166:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7167: 	&plainname($uname,$udom,'lastname');
 7168:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7169:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7170:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7171:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7172:     return;
 7173: }
 7174: 
 7175: ###############################################
 7176: 
 7177: =pod
 7178: 
 7179: =item * &get_user_quota()
 7180: 
 7181: Retrieves quota assigned for storage of portfolio files for a user  
 7182: 
 7183: Incoming parameters:
 7184: 1. user's username
 7185: 2. user's domain
 7186: 
 7187: Returns:
 7188: 1. Disk quota (in Mb) assigned to student.
 7189: 2. (Optional) Type of setting: custom or default
 7190:    (individually assigned or default for user's 
 7191:    institutional status).
 7192: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7193:    or student - types as defined in localenroll::inst_usertypes 
 7194:    for user's domain, which determines default quota for user.
 7195: 4. (Optional) - Default quota which would apply to the user.
 7196: 
 7197: If a value has been stored in the user's environment, 
 7198: it will return that, otherwise it returns the maximal default
 7199: defined for the user's instituional status(es) in the domain.
 7200: 
 7201: =cut
 7202: 
 7203: ###############################################
 7204: 
 7205: 
 7206: sub get_user_quota {
 7207:     my ($uname,$udom) = @_;
 7208:     my ($quota,$quotatype,$settingstatus,$defquota);
 7209:     if (!defined($udom)) {
 7210:         $udom = $env{'user.domain'};
 7211:     }
 7212:     if (!defined($uname)) {
 7213:         $uname = $env{'user.name'};
 7214:     }
 7215:     if (($udom eq '' || $uname eq '') ||
 7216:         ($udom eq 'public') && ($uname eq 'public')) {
 7217:         $quota = 0;
 7218:         $quotatype = 'default';
 7219:         $defquota = 0; 
 7220:     } else {
 7221:         my $inststatus;
 7222:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7223:             $quota = $env{'environment.portfolioquota'};
 7224:             $inststatus = $env{'environment.inststatus'};
 7225:         } else {
 7226:             my %userenv = 
 7227:                 &Apache::lonnet::get('environment',['portfolioquota',
 7228:                                      'inststatus'],$udom,$uname);
 7229:             my ($tmp) = keys(%userenv);
 7230:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7231:                 $quota = $userenv{'portfolioquota'};
 7232:                 $inststatus = $userenv{'inststatus'};
 7233:             } else {
 7234:                 undef(%userenv);
 7235:             }
 7236:         }
 7237:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7238:         if ($quota eq '') {
 7239:             $quota = $defquota;
 7240:             $quotatype = 'default';
 7241:         } else {
 7242:             $quotatype = 'custom';
 7243:         }
 7244:     }
 7245:     if (wantarray) {
 7246:         return ($quota,$quotatype,$settingstatus,$defquota);
 7247:     } else {
 7248:         return $quota;
 7249:     }
 7250: }
 7251: 
 7252: ###############################################
 7253: 
 7254: =pod
 7255: 
 7256: =item * &default_quota()
 7257: 
 7258: Retrieves default quota assigned for storage of user portfolio files,
 7259: given an (optional) user's institutional status.
 7260: 
 7261: Incoming parameters:
 7262: 1. domain
 7263: 2. (Optional) institutional status(es).  This is a : separated list of 
 7264:    status types (e.g., faculty, staff, student etc.)
 7265:    which apply to the user for whom the default is being retrieved.
 7266:    If the institutional status string in undefined, the domain
 7267:    default quota will be returned. 
 7268: 
 7269: Returns:
 7270: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7271: 2. (Optional) institutional type which determined the value of the
 7272:    default quota.
 7273: 
 7274: If a value has been stored in the domain's configuration db,
 7275: it will return that, otherwise it returns 20 (for backwards 
 7276: compatibility with domains which have not set up a configuration
 7277: db file; the original statically defined portfolio quota was 20 Mb). 
 7278: 
 7279: If the user's status includes multiple types (e.g., staff and student),
 7280: the largest default quota which applies to the user determines the
 7281: default quota returned.
 7282: 
 7283: =back
 7284: 
 7285: =cut
 7286: 
 7287: ###############################################
 7288: 
 7289: 
 7290: sub default_quota {
 7291:     my ($udom,$inststatus) = @_;
 7292:     my ($defquota,$settingstatus);
 7293:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7294:                                             ['quotas'],$udom);
 7295:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7296:         if ($inststatus ne '') {
 7297:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7298:             foreach my $item (@statuses) {
 7299:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7300:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7301:                         if ($defquota eq '') {
 7302:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7303:                             $settingstatus = $item;
 7304:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7305:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7306:                             $settingstatus = $item;
 7307:                         }
 7308:                     }
 7309:                 } else {
 7310:                     if ($quotahash{'quotas'}{$item} ne '') {
 7311:                         if ($defquota eq '') {
 7312:                             $defquota = $quotahash{'quotas'}{$item};
 7313:                             $settingstatus = $item;
 7314:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7315:                             $defquota = $quotahash{'quotas'}{$item};
 7316:                             $settingstatus = $item;
 7317:                         }
 7318:                     }
 7319:                 }
 7320:             }
 7321:         }
 7322:         if ($defquota eq '') {
 7323:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7324:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7325:             } else {
 7326:                 $defquota = $quotahash{'quotas'}{'default'};
 7327:             }
 7328:             $settingstatus = 'default';
 7329:         }
 7330:     } else {
 7331:         $settingstatus = 'default';
 7332:         $defquota = 20;
 7333:     }
 7334:     if (wantarray) {
 7335:         return ($defquota,$settingstatus);
 7336:     } else {
 7337:         return $defquota;
 7338:     }
 7339: }
 7340: 
 7341: sub get_secgrprole_info {
 7342:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7343:     my %sections_count = &get_sections($cdom,$cnum);
 7344:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7345:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7346:     my @groups = sort(keys(%curr_groups));
 7347:     my $allroles = [];
 7348:     my $rolehash;
 7349:     my $accesshash = {
 7350:                      active => 'Currently has access',
 7351:                      future => 'Will have future access',
 7352:                      previous => 'Previously had access',
 7353:                   };
 7354:     if ($needroles) {
 7355:         $rolehash = {'all' => 'all'};
 7356:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7357: 	if (&Apache::lonnet::error(%user_roles)) {
 7358: 	    undef(%user_roles);
 7359: 	}
 7360:         foreach my $item (keys(%user_roles)) {
 7361:             my ($role)=split(/\:/,$item,2);
 7362:             if ($role eq 'cr') { next; }
 7363:             if ($role =~ /^cr/) {
 7364:                 $$rolehash{$role} = (split('/',$role))[3];
 7365:             } else {
 7366:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7367:             }
 7368:         }
 7369:         foreach my $key (sort(keys(%{$rolehash}))) {
 7370:             push(@{$allroles},$key);
 7371:         }
 7372:         push (@{$allroles},'st');
 7373:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7374:     }
 7375:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7376: }
 7377: 
 7378: sub user_picker {
 7379:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7380:     my $currdom = $dom;
 7381:     my %curr_selected = (
 7382:                         srchin => 'dom',
 7383:                         srchby => 'lastname',
 7384:                       );
 7385:     my $srchterm;
 7386:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7387:         if ($srch->{'srchby'} ne '') {
 7388:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7389:         }
 7390:         if ($srch->{'srchin'} ne '') {
 7391:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7392:         }
 7393:         if ($srch->{'srchtype'} ne '') {
 7394:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7395:         }
 7396:         if ($srch->{'srchdomain'} ne '') {
 7397:             $currdom = $srch->{'srchdomain'};
 7398:         }
 7399:         $srchterm = $srch->{'srchterm'};
 7400:     }
 7401:     my %lt=&Apache::lonlocal::texthash(
 7402:                     'usr'       => 'Search criteria',
 7403:                     'doma'      => 'Domain/institution to search',
 7404:                     'uname'     => 'username',
 7405:                     'lastname'  => 'last name',
 7406:                     'lastfirst' => 'last name, first name',
 7407:                     'crs'       => 'in this course',
 7408:                     'dom'       => 'in selected LON-CAPA domain', 
 7409:                     'alc'       => 'all LON-CAPA',
 7410:                     'instd'     => 'in institutional directory for selected domain',
 7411:                     'exact'     => 'is',
 7412:                     'contains'  => 'contains',
 7413:                     'begins'    => 'begins with',
 7414:                     'youm'      => "You must include some text to search for.",
 7415:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7416:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7417:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7418:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7419:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7420:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7421:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7422:                                        );
 7423:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7424:     my $srchinsel = ' <select name="srchin">';
 7425: 
 7426:     my @srchins = ('crs','dom','alc','instd');
 7427: 
 7428:     foreach my $option (@srchins) {
 7429:         # FIXME 'alc' option unavailable until 
 7430:         #       loncreateuser::print_user_query_page()
 7431:         #       has been completed.
 7432:         next if ($option eq 'alc');
 7433:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7434:         if ($curr_selected{'srchin'} eq $option) {
 7435:             $srchinsel .= ' 
 7436:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7437:         } else {
 7438:             $srchinsel .= '
 7439:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7440:         }
 7441:     }
 7442:     $srchinsel .= "\n  </select>\n";
 7443: 
 7444:     my $srchbysel =  ' <select name="srchby">';
 7445:     foreach my $option ('lastname','lastfirst','uname') {
 7446:         if ($curr_selected{'srchby'} eq $option) {
 7447:             $srchbysel .= '
 7448:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7449:         } else {
 7450:             $srchbysel .= '
 7451:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7452:          }
 7453:     }
 7454:     $srchbysel .= "\n  </select>\n";
 7455: 
 7456:     my $srchtypesel = ' <select name="srchtype">';
 7457:     foreach my $option ('begins','contains','exact') {
 7458:         if ($curr_selected{'srchtype'} eq $option) {
 7459:             $srchtypesel .= '
 7460:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7461:         } else {
 7462:             $srchtypesel .= '
 7463:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7464:         }
 7465:     }
 7466:     $srchtypesel .= "\n  </select>\n";
 7467: 
 7468:     my ($newuserscript,$new_user_create);
 7469: 
 7470:     if ($forcenewuser) {
 7471:         if (ref($srch) eq 'HASH') {
 7472:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7473:                 if ($cancreate) {
 7474:                     $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>';
 7475:                 } else {
 7476:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7477:                     my %usertypetext = (
 7478:                         official   => 'institutional',
 7479:                         unofficial => 'non-institutional',
 7480:                     );
 7481:                     $new_user_create = '<p class="LC_warning">'
 7482:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7483:                                       .' '
 7484:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7485:                                           ,'<a href="'.$helplink.'">','</a>')
 7486:                                       .'</p><br />';
 7487:                 }
 7488:             }
 7489:         }
 7490: 
 7491:         $newuserscript = <<"ENDSCRIPT";
 7492: 
 7493: function setSearch(createnew,callingForm) {
 7494:     if (createnew == 1) {
 7495:         for (var i=0; i<callingForm.srchby.length; i++) {
 7496:             if (callingForm.srchby.options[i].value == 'uname') {
 7497:                 callingForm.srchby.selectedIndex = i;
 7498:             }
 7499:         }
 7500:         for (var i=0; i<callingForm.srchin.length; i++) {
 7501:             if ( callingForm.srchin.options[i].value == 'dom') {
 7502: 		callingForm.srchin.selectedIndex = i;
 7503:             }
 7504:         }
 7505:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7506:             if (callingForm.srchtype.options[i].value == 'exact') {
 7507:                 callingForm.srchtype.selectedIndex = i;
 7508:             }
 7509:         }
 7510:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7511:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7512:                 callingForm.srchdomain.selectedIndex = i;
 7513:             }
 7514:         }
 7515:     }
 7516: }
 7517: ENDSCRIPT
 7518: 
 7519:     }
 7520: 
 7521:     my $output = <<"END_BLOCK";
 7522: <script type="text/javascript">
 7523: function validateEntry(callingForm) {
 7524: 
 7525:     var checkok = 1;
 7526:     var srchin;
 7527:     for (var i=0; i<callingForm.srchin.length; i++) {
 7528: 	if ( callingForm.srchin[i].checked ) {
 7529: 	    srchin = callingForm.srchin[i].value;
 7530: 	}
 7531:     }
 7532: 
 7533:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7534:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7535:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7536:     var srchterm =  callingForm.srchterm.value;
 7537:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7538:     var msg = "";
 7539: 
 7540:     if (srchterm == "") {
 7541:         checkok = 0;
 7542:         msg += "$lt{'youm'}\\n";
 7543:     }
 7544: 
 7545:     if (srchtype== 'begins') {
 7546:         if (srchterm.length < 2) {
 7547:             checkok = 0;
 7548:             msg += "$lt{'thte'}\\n";
 7549:         }
 7550:     }
 7551: 
 7552:     if (srchtype== 'contains') {
 7553:         if (srchterm.length < 3) {
 7554:             checkok = 0;
 7555:             msg += "$lt{'thet'}\\n";
 7556:         }
 7557:     }
 7558:     if (srchin == 'instd') {
 7559:         if (srchdomain == '') {
 7560:             checkok = 0;
 7561:             msg += "$lt{'yomc'}\\n";
 7562:         }
 7563:     }
 7564:     if (srchin == 'dom') {
 7565:         if (srchdomain == '') {
 7566:             checkok = 0;
 7567:             msg += "$lt{'ymcd'}\\n";
 7568:         }
 7569:     }
 7570:     if (srchby == 'lastfirst') {
 7571:         if (srchterm.indexOf(",") == -1) {
 7572:             checkok = 0;
 7573:             msg += "$lt{'whus'}\\n";
 7574:         }
 7575:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7576:             checkok = 0;
 7577:             msg += "$lt{'whse'}\\n";
 7578:         }
 7579:     }
 7580:     if (checkok == 0) {
 7581:         alert("$lt{'thfo'}\\n"+msg);
 7582:         return;
 7583:     }
 7584:     if (checkok == 1) {
 7585:         callingForm.submit();
 7586:     }
 7587: }
 7588: 
 7589: $newuserscript
 7590: 
 7591: </script>
 7592: 
 7593: $new_user_create
 7594: 
 7595: <table>
 7596:  <tr>
 7597:   <td>$lt{'doma'}:</td>
 7598:   <td>$domform</td>
 7599:   </td>
 7600:  </tr>
 7601:  <tr>
 7602:   <td>$lt{'usr'}:</td>
 7603:   <td>$srchbysel
 7604:       $srchtypesel 
 7605:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7606:       $srchinsel 
 7607:   </td>
 7608:  </tr>
 7609: </table>
 7610: <br />
 7611: END_BLOCK
 7612: 
 7613:     return $output;
 7614: }
 7615: 
 7616: sub user_rule_check {
 7617:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7618:     my $response;
 7619:     if (ref($usershash) eq 'HASH') {
 7620:         foreach my $user (keys(%{$usershash})) {
 7621:             my ($uname,$udom) = split(/:/,$user);
 7622:             next if ($udom eq '' || $uname eq '');
 7623:             my ($id,$newuser);
 7624:             if (ref($usershash->{$user}) eq 'HASH') {
 7625:                 $newuser = $usershash->{$user}->{'newuser'};
 7626:                 $id = $usershash->{$user}->{'id'};
 7627:             }
 7628:             my $inst_response;
 7629:             if (ref($checks) eq 'HASH') {
 7630:                 if (defined($checks->{'username'})) {
 7631:                     ($inst_response,%{$inst_results->{$user}}) = 
 7632:                         &Apache::lonnet::get_instuser($udom,$uname);
 7633:                 } elsif (defined($checks->{'id'})) {
 7634:                     ($inst_response,%{$inst_results->{$user}}) =
 7635:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7636:                 }
 7637:             } else {
 7638:                 ($inst_response,%{$inst_results->{$user}}) =
 7639:                     &Apache::lonnet::get_instuser($udom,$uname);
 7640:                 return;
 7641:             }
 7642:             if (!$got_rules->{$udom}) {
 7643:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7644:                                                   ['usercreation'],$udom);
 7645:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7646:                     foreach my $item ('username','id') {
 7647:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7648:                             $$curr_rules{$udom}{$item} = 
 7649:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7650:                         }
 7651:                     }
 7652:                 }
 7653:                 $got_rules->{$udom} = 1;  
 7654:             }
 7655:             foreach my $item (keys(%{$checks})) {
 7656:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7657:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7658:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7659:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7660:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7661:                                 if ($rule_check{$rule}) {
 7662:                                     $$rulematch{$user}{$item} = $rule;
 7663:                                     if ($inst_response eq 'ok') {
 7664:                                         if (ref($inst_results) eq 'HASH') {
 7665:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7666:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7667:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7668:                                                 }
 7669:                                             }
 7670:                                         }
 7671:                                     }
 7672:                                     last;
 7673:                                 }
 7674:                             }
 7675:                         }
 7676:                     }
 7677:                 }
 7678:             }
 7679:         }
 7680:     }
 7681:     return;
 7682: }
 7683: 
 7684: sub user_rule_formats {
 7685:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7686:     my %text = ( 
 7687:                  'username' => 'Usernames',
 7688:                  'id'       => 'IDs',
 7689:                );
 7690:     my $output;
 7691:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7692:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7693:         if (@{$ruleorder} > 0) {
 7694:             $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>';
 7695:             foreach my $rule (@{$ruleorder}) {
 7696:                 if (ref($curr_rules) eq 'ARRAY') {
 7697:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7698:                         if (ref($rules->{$rule}) eq 'HASH') {
 7699:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7700:                                         $rules->{$rule}{'desc'}.'</li>';
 7701:                         }
 7702:                     }
 7703:                 }
 7704:             }
 7705:             $output .= '</ul>';
 7706:         }
 7707:     }
 7708:     return $output;
 7709: }
 7710: 
 7711: sub instrule_disallow_msg {
 7712:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7713:     my $response;
 7714:     my %text = (
 7715:                   item   => 'username',
 7716:                   items  => 'usernames',
 7717:                   match  => 'matches',
 7718:                   do     => 'does',
 7719:                   action => 'a username',
 7720:                   one    => 'one',
 7721:                );
 7722:     if ($count > 1) {
 7723:         $text{'item'} = 'usernames';
 7724:         $text{'match'} ='match';
 7725:         $text{'do'} = 'do';
 7726:         $text{'action'} = 'usernames',
 7727:         $text{'one'} = 'ones';
 7728:     }
 7729:     if ($checkitem eq 'id') {
 7730:         $text{'items'} = 'IDs';
 7731:         $text{'item'} = 'ID';
 7732:         $text{'action'} = 'an ID';
 7733:         if ($count > 1) {
 7734:             $text{'item'} = 'IDs';
 7735:             $text{'action'} = 'IDs';
 7736:         }
 7737:     }
 7738:     $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 />';
 7739:     if ($mode eq 'upload') {
 7740:         if ($checkitem eq 'username') {
 7741:             $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'}.");
 7742:         } elsif ($checkitem eq 'id') {
 7743:             $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.");
 7744:         }
 7745:     } elsif ($mode eq 'selfcreate') {
 7746:         if ($checkitem eq 'id') {
 7747:             $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.");
 7748:         }
 7749:     } else {
 7750:         if ($checkitem eq 'username') {
 7751:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7752:         } elsif ($checkitem eq 'id') {
 7753:             $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.");
 7754:         }
 7755:     }
 7756:     return $response;
 7757: }
 7758: 
 7759: sub personal_data_fieldtitles {
 7760:     my %fieldtitles = &Apache::lonlocal::texthash (
 7761:                         id => 'Student/Employee ID',
 7762:                         permanentemail => 'E-mail address',
 7763:                         lastname => 'Last Name',
 7764:                         firstname => 'First Name',
 7765:                         middlename => 'Middle Name',
 7766:                         generation => 'Generation',
 7767:                         gen => 'Generation',
 7768:                         inststatus => 'Affiliation',
 7769:                    );
 7770:     return %fieldtitles;
 7771: }
 7772: 
 7773: sub sorted_inst_types {
 7774:     my ($dom) = @_;
 7775:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7776:     my $othertitle = &mt('All users');
 7777:     if ($env{'request.course.id'}) {
 7778:         $othertitle  = &mt('Any users');
 7779:     }
 7780:     my @types;
 7781:     if (ref($order) eq 'ARRAY') {
 7782:         @types = @{$order};
 7783:     }
 7784:     if (@types == 0) {
 7785:         if (ref($usertypes) eq 'HASH') {
 7786:             @types = sort(keys(%{$usertypes}));
 7787:         }
 7788:     }
 7789:     if (keys(%{$usertypes}) > 0) {
 7790:         $othertitle = &mt('Other users');
 7791:     }
 7792:     return ($othertitle,$usertypes,\@types);
 7793: }
 7794: 
 7795: sub get_institutional_codes {
 7796:     my ($settings,$allcourses,$LC_code) = @_;
 7797: # Get complete list of course sections to update
 7798:     my @currsections = ();
 7799:     my @currxlists = ();
 7800:     my $coursecode = $$settings{'internal.coursecode'};
 7801: 
 7802:     if ($$settings{'internal.sectionnums'} ne '') {
 7803:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7804:     }
 7805: 
 7806:     if ($$settings{'internal.crosslistings'} ne '') {
 7807:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7808:     }
 7809: 
 7810:     if (@currxlists > 0) {
 7811:         foreach (@currxlists) {
 7812:             if (m/^([^:]+):(\w*)$/) {
 7813:                 unless (grep/^$1$/,@{$allcourses}) {
 7814:                     push @{$allcourses},$1;
 7815:                     $$LC_code{$1} = $2;
 7816:                 }
 7817:             }
 7818:         }
 7819:     }
 7820:  
 7821:     if (@currsections > 0) {
 7822:         foreach (@currsections) {
 7823:             if (m/^(\w+):(\w*)$/) {
 7824:                 my $sec = $coursecode.$1;
 7825:                 my $lc_sec = $2;
 7826:                 unless (grep/^$sec$/,@{$allcourses}) {
 7827:                     push @{$allcourses},$sec;
 7828:                     $$LC_code{$sec} = $lc_sec;
 7829:                 }
 7830:             }
 7831:         }
 7832:     }
 7833:     return;
 7834: }
 7835: 
 7836: =pod
 7837: 
 7838: =head1 Slot Helpers
 7839: 
 7840: =over 4
 7841: 
 7842: =item * sorted_slots()
 7843: 
 7844: Sorts an array of slot names in order of slot start time (earliest first). 
 7845: 
 7846: Inputs:
 7847: 
 7848: =over 4
 7849: 
 7850: slotsarr  - Reference to array of unsorted slot names.
 7851: 
 7852: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7853: 
 7854: =back
 7855: 
 7856: Returns:
 7857: 
 7858: =over 4
 7859: 
 7860: sorted   - An array of slot names sorted by the start time of the slot.
 7861: 
 7862: =back
 7863: 
 7864: =back
 7865: 
 7866: =cut
 7867: 
 7868: 
 7869: sub sorted_slots {
 7870:     my ($slotsarr,$slots) = @_;
 7871:     my @sorted;
 7872:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7873:         @sorted =
 7874:             sort {
 7875:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7876:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7877:                      }
 7878:                      if (ref($slots->{$a})) { return -1;}
 7879:                      if (ref($slots->{$b})) { return 1;}
 7880:                      return 0;
 7881:                  } @{$slotsarr};
 7882:     }
 7883:     return @sorted;
 7884: }
 7885: 
 7886: 
 7887: =pod
 7888: 
 7889: =head1 HTTP Helpers
 7890: 
 7891: =over 4
 7892: 
 7893: =item * &get_unprocessed_cgi($query,$possible_names)
 7894: 
 7895: Modify the %env hash to contain unprocessed CGI form parameters held in
 7896: $query.  The parameters listed in $possible_names (an array reference),
 7897: will be set in $env{'form.name'} if they do not already exist.
 7898: 
 7899: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7900: $possible_names is an ref to an array of form element names.  As an example:
 7901: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7902: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7903: 
 7904: =cut
 7905: 
 7906: sub get_unprocessed_cgi {
 7907:   my ($query,$possible_names)= @_;
 7908:   # $Apache::lonxml::debug=1;
 7909:   foreach my $pair (split(/&/,$query)) {
 7910:     my ($name, $value) = split(/=/,$pair);
 7911:     $name = &unescape($name);
 7912:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7913:       $value =~ tr/+/ /;
 7914:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7915:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7916:     }
 7917:   }
 7918: }
 7919: 
 7920: =pod
 7921: 
 7922: =item * &cacheheader() 
 7923: 
 7924: returns cache-controlling header code
 7925: 
 7926: =cut
 7927: 
 7928: sub cacheheader {
 7929:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7930:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7931:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7932:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7933:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7934:     return $output;
 7935: }
 7936: 
 7937: =pod
 7938: 
 7939: =item * &no_cache($r) 
 7940: 
 7941: specifies header code to not have cache
 7942: 
 7943: =cut
 7944: 
 7945: sub no_cache {
 7946:     my ($r) = @_;
 7947:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7948: 	$env{'request.method'} ne 'GET') { return ''; }
 7949:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7950:     $r->no_cache(1);
 7951:     $r->header_out("Expires" => $date);
 7952:     $r->header_out("Pragma" => "no-cache");
 7953: }
 7954: 
 7955: sub content_type {
 7956:     my ($r,$type,$charset) = @_;
 7957:     if ($r) {
 7958: 	#  Note that printout.pl calls this with undef for $r.
 7959: 	&no_cache($r);
 7960:     }
 7961:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7962:     unless ($charset) {
 7963: 	$charset=&Apache::lonlocal::current_encoding;
 7964:     }
 7965:     if ($charset) { $type.='; charset='.$charset; }
 7966:     if ($r) {
 7967: 	$r->content_type($type);
 7968:     } else {
 7969: 	print("Content-type: $type\n\n");
 7970:     }
 7971: }
 7972: 
 7973: =pod
 7974: 
 7975: =item * &add_to_env($name,$value) 
 7976: 
 7977: adds $name to the %env hash with value
 7978: $value, if $name already exists, the entry is converted to an array
 7979: reference and $value is added to the array.
 7980: 
 7981: =cut
 7982: 
 7983: sub add_to_env {
 7984:   my ($name,$value)=@_;
 7985:   if (defined($env{$name})) {
 7986:     if (ref($env{$name})) {
 7987:       #already have multiple values
 7988:       push(@{ $env{$name} },$value);
 7989:     } else {
 7990:       #first time seeing multiple values, convert hash entry to an arrayref
 7991:       my $first=$env{$name};
 7992:       undef($env{$name});
 7993:       push(@{ $env{$name} },$first,$value);
 7994:     }
 7995:   } else {
 7996:     $env{$name}=$value;
 7997:   }
 7998: }
 7999: 
 8000: =pod
 8001: 
 8002: =item * &get_env_multiple($name) 
 8003: 
 8004: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8005: values may be defined and end up as an array ref.
 8006: 
 8007: returns an array of values
 8008: 
 8009: =cut
 8010: 
 8011: sub get_env_multiple {
 8012:     my ($name) = @_;
 8013:     my @values;
 8014:     if (defined($env{$name})) {
 8015:         # exists is it an array
 8016:         if (ref($env{$name})) {
 8017:             @values=@{ $env{$name} };
 8018:         } else {
 8019:             $values[0]=$env{$name};
 8020:         }
 8021:     }
 8022:     return(@values);
 8023: }
 8024: 
 8025: sub ask_for_embedded_content {
 8026:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8027:     my $upload_output = '
 8028:    <form name="upload_embedded" action="'.$actionurl.'"
 8029:                   method="post" enctype="multipart/form-data">';
 8030:     $upload_output .= $state;
 8031:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8032: 
 8033:     my $num = 0;
 8034:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8035:         $upload_output .= &start_data_table_row().
 8036:             '<td>'.$embed_file.'</td><td>';
 8037:         if ($args->{'ignore_remote_references'}
 8038:             && $embed_file =~ m{^\w+://}) {
 8039:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8040:         } elsif ($args->{'error_on_invalid_names'}
 8041:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8042: 
 8043:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8044: 
 8045:         } else {
 8046:             $upload_output .='
 8047:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8048:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8049:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8050:             $upload_output .=
 8051:                 "\n\t\t".
 8052:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8053:                 $attrib.'" />';
 8054:             if (exists($$codebase{$embed_file})) {
 8055:                 $upload_output .=
 8056:                     "\n\t\t".
 8057:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8058:                     &escape($$codebase{$embed_file}).'" />';
 8059:             }
 8060:         }
 8061:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8062:         $num++;
 8063:     }
 8064:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8065:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8066:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8067:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8068:    </form>';
 8069:     return $upload_output;
 8070: }
 8071: 
 8072: sub upload_embedded {
 8073:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8074:         $current_disk_usage) = @_;
 8075:     my $output;
 8076:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8077:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8078:         my $orig_uploaded_filename =
 8079:             $env{'form.embedded_item_'.$i.'.filename'};
 8080: 
 8081:         $env{'form.embedded_orig_'.$i} =
 8082:             &unescape($env{'form.embedded_orig_'.$i});
 8083:         my ($path,$fname) =
 8084:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8085:         # no path, whole string is fname
 8086:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8087: 
 8088:         $path = $env{'form.currentpath'}.$path;
 8089:         $fname = &Apache::lonnet::clean_filename($fname);
 8090:         # See if there is anything left
 8091:         next if ($fname eq '');
 8092: 
 8093:         # Check if file already exists as a file or directory.
 8094:         my ($state,$msg);
 8095:         if ($context eq 'portfolio') {
 8096:             my $port_path = $dirpath;
 8097:             if ($group ne '') {
 8098:                 $port_path = "groups/$group/$port_path";
 8099:             }
 8100:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8101:                                               $dir_root,$port_path,$disk_quota,
 8102:                                               $current_disk_usage,$uname,$udom);
 8103:             if ($state eq 'will_exceed_quota'
 8104:                 || $state eq 'file_locked'
 8105:                 || $state eq 'file_exists' ) {
 8106:                 $output .= $msg;
 8107:                 next;
 8108:             }
 8109:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8110:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8111:             if ($state eq 'exists') {
 8112:                 $output .= $msg;
 8113:                 next;
 8114:             }
 8115:         }
 8116:         # Check if extension is valid
 8117:         if (($fname =~ /\.(\w+)$/) &&
 8118:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8119:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8120:             next;
 8121:         } elsif (($fname =~ /\.(\w+)$/) &&
 8122:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8123:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8124:             next;
 8125:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8126:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8127:             next;
 8128:         }
 8129: 
 8130:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8131:         if ($context eq 'portfolio') {
 8132:             my $result=
 8133:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8134:                                                 $dirpath.$path);
 8135:             if ($result !~ m|^/uploaded/|) {
 8136:                 $output .= '<span class="LC_error">'
 8137:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8138:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8139:                       .'</span><br />';
 8140:                 next;
 8141:             } else {
 8142:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8143:                            $path.$fname.'</span>').'</p>';     
 8144:             }
 8145:         } else {
 8146: # Save the file
 8147:             my $target = $env{'form.embedded_item_'.$i};
 8148:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8149:             my $dest = $fullpath.$fname;
 8150:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8151:             my @parts=split(/\//,$fullpath);
 8152:             my $count;
 8153:             my $filepath = $dir_root;
 8154:             for ($count=4;$count<=$#parts;$count++) {
 8155:                 $filepath .= "/$parts[$count]";
 8156:                 if ((-e $filepath)!=1) {
 8157:                     mkdir($filepath,0770);
 8158:                 }
 8159:             }
 8160:             my $fh;
 8161:             if (!open($fh,'>'.$dest)) {
 8162:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8163:                 $output .= '<span class="LC_error">'.
 8164:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8165:                            '</span><br />';
 8166:             } else {
 8167:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8168:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8169:                     $output .= '<span class="LC_error">'.
 8170:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8171:                               '</span><br />';
 8172:                 } else {
 8173:                     if ($context eq 'testbank') {
 8174:                         $output .= &mt('Embedded file uploaded successfully:').
 8175:                                    '&nbsp;<a href="'.$url.'">'.
 8176:                                    $orig_uploaded_filename.'</a><br />';
 8177:                     } else {
 8178:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8179:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8180:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8181:                     }
 8182:                 }
 8183:                 close($fh);
 8184:             }
 8185:         }
 8186:     }
 8187:     return $output;
 8188: }
 8189: 
 8190: sub check_for_existing {
 8191:     my ($path,$fname,$element) = @_;
 8192:     my ($state,$msg);
 8193:     if (-d $path.'/'.$fname) {
 8194:         $state = 'exists';
 8195:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8196:     } elsif (-e $path.'/'.$fname) {
 8197:         $state = 'exists';
 8198:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8199:     }
 8200:     if ($state eq 'exists') {
 8201:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8202:     }
 8203:     return ($state,$msg);
 8204: }
 8205: 
 8206: sub check_for_upload {
 8207:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8208:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8209:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8210:     my $getpropath = 1;
 8211:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8212:                                             $getpropath);
 8213:     my $found_file = 0;
 8214:     my $locked_file = 0;
 8215:     foreach my $line (@dir_list) {
 8216:         my ($file_name)=split(/\&/,$line,2);
 8217:         if ($file_name eq $fname){
 8218:             $file_name = $path.$file_name;
 8219:             if ($group ne '') {
 8220:                 $file_name = $group.$file_name;
 8221:             }
 8222:             $found_file = 1;
 8223:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8224:                 $locked_file = 1;
 8225:             }
 8226:         }
 8227:     }
 8228:     if (($current_disk_usage + $filesize) > $disk_quota){
 8229:         my $msg = '<span class="LC_error">'.
 8230:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8231:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8232:         return ('will_exceed_quota',$msg);
 8233:     } elsif ($found_file) {
 8234:         if ($locked_file) {
 8235:             my $msg = '<span class="LC_error">';
 8236:             $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>');
 8237:             $msg .= '</span><br />';
 8238:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8239:             return ('file_locked',$msg);
 8240:         } else {
 8241:             my $msg = '<span class="LC_error">';
 8242:             $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'});
 8243:             $msg .= '</span>';
 8244:             $msg .= '<br />';
 8245:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8246:             return ('file_exists',$msg);
 8247:         }
 8248:     }
 8249: }
 8250: 
 8251: 
 8252: =pod
 8253: 
 8254: =back
 8255: 
 8256: =head1 CSV Upload/Handling functions
 8257: 
 8258: =over 4
 8259: 
 8260: =item * &upfile_store($r)
 8261: 
 8262: Store uploaded file, $r should be the HTTP Request object,
 8263: needs $env{'form.upfile'}
 8264: returns $datatoken to be put into hidden field
 8265: 
 8266: =cut
 8267: 
 8268: sub upfile_store {
 8269:     my $r=shift;
 8270:     $env{'form.upfile'}=~s/\r/\n/gs;
 8271:     $env{'form.upfile'}=~s/\f/\n/gs;
 8272:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8273:     $env{'form.upfile'}=~s/\n+$//gs;
 8274: 
 8275:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8276: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8277:     {
 8278:         my $datafile = $r->dir_config('lonDaemons').
 8279:                            '/tmp/'.$datatoken.'.tmp';
 8280:         if ( open(my $fh,">$datafile") ) {
 8281:             print $fh $env{'form.upfile'};
 8282:             close($fh);
 8283:         }
 8284:     }
 8285:     return $datatoken;
 8286: }
 8287: 
 8288: =pod
 8289: 
 8290: =item * &load_tmp_file($r)
 8291: 
 8292: Load uploaded file from tmp, $r should be the HTTP Request object,
 8293: needs $env{'form.datatoken'},
 8294: sets $env{'form.upfile'} to the contents of the file
 8295: 
 8296: =cut
 8297: 
 8298: sub load_tmp_file {
 8299:     my $r=shift;
 8300:     my @studentdata=();
 8301:     {
 8302:         my $studentfile = $r->dir_config('lonDaemons').
 8303:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8304:         if ( open(my $fh,"<$studentfile") ) {
 8305:             @studentdata=<$fh>;
 8306:             close($fh);
 8307:         }
 8308:     }
 8309:     $env{'form.upfile'}=join('',@studentdata);
 8310: }
 8311: 
 8312: =pod
 8313: 
 8314: =item * &upfile_record_sep()
 8315: 
 8316: Separate uploaded file into records
 8317: returns array of records,
 8318: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8319: 
 8320: =cut
 8321: 
 8322: sub upfile_record_sep {
 8323:     if ($env{'form.upfiletype'} eq 'xml') {
 8324:     } else {
 8325: 	my @records;
 8326: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8327: 	    if ($line=~/^\s*$/) { next; }
 8328: 	    push(@records,$line);
 8329: 	}
 8330: 	return @records;
 8331:     }
 8332: }
 8333: 
 8334: =pod
 8335: 
 8336: =item * &record_sep($record)
 8337: 
 8338: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8339: 
 8340: =cut
 8341: 
 8342: sub takeleft {
 8343:     my $index=shift;
 8344:     return substr('0000'.$index,-4,4);
 8345: }
 8346: 
 8347: sub record_sep {
 8348:     my $record=shift;
 8349:     my %components=();
 8350:     if ($env{'form.upfiletype'} eq 'xml') {
 8351:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8352:         my $i=0;
 8353:         foreach my $field (split(/\s+/,$record)) {
 8354:             $field=~s/^(\"|\')//;
 8355:             $field=~s/(\"|\')$//;
 8356:             $components{&takeleft($i)}=$field;
 8357:             $i++;
 8358:         }
 8359:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8360:         my $i=0;
 8361:         foreach my $field (split(/\t/,$record)) {
 8362:             $field=~s/^(\"|\')//;
 8363:             $field=~s/(\"|\')$//;
 8364:             $components{&takeleft($i)}=$field;
 8365:             $i++;
 8366:         }
 8367:     } else {
 8368:         my $separator=',';
 8369:         if ($env{'form.upfiletype'} eq 'semisv') {
 8370:             $separator=';';
 8371:         }
 8372:         my $i=0;
 8373: # the character we are looking for to indicate the end of a quote or a record 
 8374:         my $looking_for=$separator;
 8375: # do not add the characters to the fields
 8376:         my $ignore=0;
 8377: # we just encountered a separator (or the beginning of the record)
 8378:         my $just_found_separator=1;
 8379: # store the field we are working on here
 8380:         my $field='';
 8381: # work our way through all characters in record
 8382:         foreach my $character ($record=~/(.)/g) {
 8383:             if ($character eq $looking_for) {
 8384:                if ($character ne $separator) {
 8385: # Found the end of a quote, again looking for separator
 8386:                   $looking_for=$separator;
 8387:                   $ignore=1;
 8388:                } else {
 8389: # Found a separator, store away what we got
 8390:                   $components{&takeleft($i)}=$field;
 8391: 	          $i++;
 8392:                   $just_found_separator=1;
 8393:                   $ignore=0;
 8394:                   $field='';
 8395:                }
 8396:                next;
 8397:             }
 8398: # single or double quotation marks after a separator indicate beginning of a quote
 8399: # we are now looking for the end of the quote and need to ignore separators
 8400:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8401:                $looking_for=$character;
 8402:                next;
 8403:             }
 8404: # ignore would be true after we reached the end of a quote
 8405:             if ($ignore) { next; }
 8406:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8407:             $field.=$character;
 8408:             $just_found_separator=0; 
 8409:         }
 8410: # catch the very last entry, since we never encountered the separator
 8411:         $components{&takeleft($i)}=$field;
 8412:     }
 8413:     return %components;
 8414: }
 8415: 
 8416: ######################################################
 8417: ######################################################
 8418: 
 8419: =pod
 8420: 
 8421: =item * &upfile_select_html()
 8422: 
 8423: Return HTML code to select a file from the users machine and specify 
 8424: the file type.
 8425: 
 8426: =cut
 8427: 
 8428: ######################################################
 8429: ######################################################
 8430: sub upfile_select_html {
 8431:     my %Types = (
 8432:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8433:                  semisv => &mt('Semicolon separated values'),
 8434:                  space => &mt('Space separated'),
 8435:                  tab   => &mt('Tabulator separated'),
 8436: #                 xml   => &mt('HTML/XML'),
 8437:                  );
 8438:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8439:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8440:     foreach my $type (sort(keys(%Types))) {
 8441:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8442:     }
 8443:     $Str .= "</select>\n";
 8444:     return $Str;
 8445: }
 8446: 
 8447: sub get_samples {
 8448:     my ($records,$toget) = @_;
 8449:     my @samples=({});
 8450:     my $got=0;
 8451:     foreach my $rec (@$records) {
 8452: 	my %temp = &record_sep($rec);
 8453: 	if (! grep(/\S/, values(%temp))) { next; }
 8454: 	if (%temp) {
 8455: 	    $samples[$got]=\%temp;
 8456: 	    $got++;
 8457: 	    if ($got == $toget) { last; }
 8458: 	}
 8459:     }
 8460:     return \@samples;
 8461: }
 8462: 
 8463: ######################################################
 8464: ######################################################
 8465: 
 8466: =pod
 8467: 
 8468: =item * &csv_print_samples($r,$records)
 8469: 
 8470: Prints a table of sample values from each column uploaded $r is an
 8471: Apache Request ref, $records is an arrayref from
 8472: &Apache::loncommon::upfile_record_sep
 8473: 
 8474: =cut
 8475: 
 8476: ######################################################
 8477: ######################################################
 8478: sub csv_print_samples {
 8479:     my ($r,$records) = @_;
 8480:     my $samples = &get_samples($records,5);
 8481: 
 8482:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8483:               &start_data_table_header_row());
 8484:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8485:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 8486:     $r->print(&end_data_table_header_row());
 8487:     foreach my $hash (@$samples) {
 8488: 	$r->print(&start_data_table_row());
 8489: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8490: 	    $r->print('<td>');
 8491: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8492: 	    $r->print('</td>');
 8493: 	}
 8494: 	$r->print(&end_data_table_row());
 8495:     }
 8496:     $r->print(&end_data_table().'<br />'."\n");
 8497: }
 8498: 
 8499: ######################################################
 8500: ######################################################
 8501: 
 8502: =pod
 8503: 
 8504: =item * &csv_print_select_table($r,$records,$d)
 8505: 
 8506: Prints a table to create associations between values and table columns.
 8507: 
 8508: $r is an Apache Request ref,
 8509: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8510: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8511: 
 8512: =cut
 8513: 
 8514: ######################################################
 8515: ######################################################
 8516: sub csv_print_select_table {
 8517:     my ($r,$records,$d) = @_;
 8518:     my $i=0;
 8519:     my $samples = &get_samples($records,1);
 8520:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8521: 	      &start_data_table().&start_data_table_header_row().
 8522:               '<th>'.&mt('Attribute').'</th>'.
 8523:               '<th>'.&mt('Column').'</th>'.
 8524:               &end_data_table_header_row()."\n");
 8525:     foreach my $array_ref (@$d) {
 8526: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8527: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8528: 
 8529: 	$r->print('<td><select name=f'.$i.
 8530: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8531: 	$r->print('<option value="none"></option>');
 8532: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8533: 	    $r->print('<option value="'.$sample.'"'.
 8534:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8535:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8536: 	}
 8537: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8538: 	$i++;
 8539:     }
 8540:     $r->print(&end_data_table());
 8541:     $i--;
 8542:     return $i;
 8543: }
 8544: 
 8545: ######################################################
 8546: ######################################################
 8547: 
 8548: =pod
 8549: 
 8550: =item * &csv_samples_select_table($r,$records,$d)
 8551: 
 8552: Prints a table of sample values from the upload and can make associate samples to internal names.
 8553: 
 8554: $r is an Apache Request ref,
 8555: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8556: $d is an array of 2 element arrays (internal name, displayed name)
 8557: 
 8558: =cut
 8559: 
 8560: ######################################################
 8561: ######################################################
 8562: sub csv_samples_select_table {
 8563:     my ($r,$records,$d) = @_;
 8564:     my $i=0;
 8565:     #
 8566:     my $max_samples = 5;
 8567:     my $samples = &get_samples($records,$max_samples);
 8568:     $r->print(&start_data_table().
 8569:               &start_data_table_header_row().'<th>'.
 8570:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8571:               &end_data_table_header_row());
 8572: 
 8573:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8574: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8575: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8576: 	foreach my $option (@$d) {
 8577: 	    my ($value,$display,$defaultcol)=@{ $option };
 8578: 	    $r->print('<option value="'.$value.'"'.
 8579:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8580:                       $display.'</option>');
 8581: 	}
 8582: 	$r->print('</select></td><td>');
 8583: 	foreach my $line (0..($max_samples-1)) {
 8584: 	    if (defined($samples->[$line]{$key})) { 
 8585: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8586: 	    }
 8587: 	}
 8588: 	$r->print('</td>'.&end_data_table_row());
 8589: 	$i++;
 8590:     }
 8591:     $r->print(&end_data_table());
 8592:     $i--;
 8593:     return($i);
 8594: }
 8595: 
 8596: ######################################################
 8597: ######################################################
 8598: 
 8599: =pod
 8600: 
 8601: =item * &clean_excel_name($name)
 8602: 
 8603: Returns a replacement for $name which does not contain any illegal characters.
 8604: 
 8605: =cut
 8606: 
 8607: ######################################################
 8608: ######################################################
 8609: sub clean_excel_name {
 8610:     my ($name) = @_;
 8611:     $name =~ s/[:\*\?\/\\]//g;
 8612:     if (length($name) > 31) {
 8613:         $name = substr($name,0,31);
 8614:     }
 8615:     return $name;
 8616: }
 8617: 
 8618: =pod
 8619: 
 8620: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8621: 
 8622: Returns either 1 or undef
 8623: 
 8624: 1 if the part is to be hidden, undef if it is to be shown
 8625: 
 8626: Arguments are:
 8627: 
 8628: $id the id of the part to be checked
 8629: $symb, optional the symb of the resource to check
 8630: $udom, optional the domain of the user to check for
 8631: $uname, optional the username of the user to check for
 8632: 
 8633: =cut
 8634: 
 8635: sub check_if_partid_hidden {
 8636:     my ($id,$symb,$udom,$uname) = @_;
 8637:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8638: 					 $symb,$udom,$uname);
 8639:     my $truth=1;
 8640:     #if the string starts with !, then the list is the list to show not hide
 8641:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8642:     my @hiddenlist=split(/,/,$hiddenparts);
 8643:     foreach my $checkid (@hiddenlist) {
 8644: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8645:     }
 8646:     return !$truth;
 8647: }
 8648: 
 8649: 
 8650: ############################################################
 8651: ############################################################
 8652: 
 8653: =pod
 8654: 
 8655: =back 
 8656: 
 8657: =head1 cgi-bin script and graphing routines
 8658: 
 8659: =over 4
 8660: 
 8661: =item * &get_cgi_id()
 8662: 
 8663: Inputs: none
 8664: 
 8665: Returns an id which can be used to pass environment variables
 8666: to various cgi-bin scripts.  These environment variables will
 8667: be removed from the users environment after a given time by
 8668: the routine &Apache::lonnet::transfer_profile_to_env.
 8669: 
 8670: =cut
 8671: 
 8672: ############################################################
 8673: ############################################################
 8674: my $uniq=0;
 8675: sub get_cgi_id {
 8676:     $uniq=($uniq+1)%100000;
 8677:     return (time.'_'.$$.'_'.$uniq);
 8678: }
 8679: 
 8680: ############################################################
 8681: ############################################################
 8682: 
 8683: =pod
 8684: 
 8685: =item * &DrawBarGraph()
 8686: 
 8687: Facilitates the plotting of data in a (stacked) bar graph.
 8688: Puts plot definition data into the users environment in order for 
 8689: graph.png to plot it.  Returns an <img> tag for the plot.
 8690: The bars on the plot are labeled '1','2',...,'n'.
 8691: 
 8692: Inputs:
 8693: 
 8694: =over 4
 8695: 
 8696: =item $Title: string, the title of the plot
 8697: 
 8698: =item $xlabel: string, text describing the X-axis of the plot
 8699: 
 8700: =item $ylabel: string, text describing the Y-axis of the plot
 8701: 
 8702: =item $Max: scalar, the maximum Y value to use in the plot
 8703: If $Max is < any data point, the graph will not be rendered.
 8704: 
 8705: =item $colors: array ref holding the colors to be used for the data sets when
 8706: they are plotted.  If undefined, default values will be used.
 8707: 
 8708: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8709: 
 8710: =item @Values: An array of array references.  Each array reference holds data
 8711: to be plotted in a stacked bar chart.
 8712: 
 8713: =item If the final element of @Values is a hash reference the key/value
 8714: pairs will be added to the graph definition.
 8715: 
 8716: =back
 8717: 
 8718: Returns:
 8719: 
 8720: An <img> tag which references graph.png and the appropriate identifying
 8721: information for the plot.
 8722: 
 8723: =cut
 8724: 
 8725: ############################################################
 8726: ############################################################
 8727: sub DrawBarGraph {
 8728:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8729:     #
 8730:     if (! defined($colors)) {
 8731:         $colors = ['#33ff00', 
 8732:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8733:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8734:                   ]; 
 8735:     }
 8736:     my $extra_settings = {};
 8737:     if (ref($Values[-1]) eq 'HASH') {
 8738:         $extra_settings = pop(@Values);
 8739:     }
 8740:     #
 8741:     my $identifier = &get_cgi_id();
 8742:     my $id = 'cgi.'.$identifier;        
 8743:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8744:         return '';
 8745:     }
 8746:     #
 8747:     my @Labels;
 8748:     if (defined($labels)) {
 8749:         @Labels = @$labels;
 8750:     } else {
 8751:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8752:             push (@Labels,$i+1);
 8753:         }
 8754:     }
 8755:     #
 8756:     my $NumBars = scalar(@{$Values[0]});
 8757:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8758:     my %ValuesHash;
 8759:     my $NumSets=1;
 8760:     foreach my $array (@Values) {
 8761:         next if (! ref($array));
 8762:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8763:             join(',',@$array);
 8764:     }
 8765:     #
 8766:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8767:     if ($NumBars < 3) {
 8768:         $width = 120+$NumBars*32;
 8769:         $xskip = 1;
 8770:         $bar_width = 30;
 8771:     } elsif ($NumBars < 5) {
 8772:         $width = 120+$NumBars*20;
 8773:         $xskip = 1;
 8774:         $bar_width = 20;
 8775:     } elsif ($NumBars < 10) {
 8776:         $width = 120+$NumBars*15;
 8777:         $xskip = 1;
 8778:         $bar_width = 15;
 8779:     } elsif ($NumBars <= 25) {
 8780:         $width = 120+$NumBars*11;
 8781:         $xskip = 5;
 8782:         $bar_width = 8;
 8783:     } elsif ($NumBars <= 50) {
 8784:         $width = 120+$NumBars*8;
 8785:         $xskip = 5;
 8786:         $bar_width = 4;
 8787:     } else {
 8788:         $width = 120+$NumBars*8;
 8789:         $xskip = 5;
 8790:         $bar_width = 4;
 8791:     }
 8792:     #
 8793:     $Max = 1 if ($Max < 1);
 8794:     if ( int($Max) < $Max ) {
 8795:         $Max++;
 8796:         $Max = int($Max);
 8797:     }
 8798:     $Title  = '' if (! defined($Title));
 8799:     $xlabel = '' if (! defined($xlabel));
 8800:     $ylabel = '' if (! defined($ylabel));
 8801:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8802:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8803:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8804:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8805:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8806:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8807:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8808:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8809:     $ValuesHash{$id.'.height'}   = $height;
 8810:     $ValuesHash{$id.'.width'}    = $width;
 8811:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8812:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8813:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8814:     #
 8815:     # Deal with other parameters
 8816:     while (my ($key,$value) = each(%$extra_settings)) {
 8817:         $ValuesHash{$id.'.'.$key} = $value;
 8818:     }
 8819:     #
 8820:     &Apache::lonnet::appenv(\%ValuesHash);
 8821:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8822: }
 8823: 
 8824: ############################################################
 8825: ############################################################
 8826: 
 8827: =pod
 8828: 
 8829: =item * &DrawXYGraph()
 8830: 
 8831: Facilitates the plotting of data in an XY graph.
 8832: Puts plot definition data into the users environment in order for 
 8833: graph.png to plot it.  Returns an <img> tag for the plot.
 8834: 
 8835: Inputs:
 8836: 
 8837: =over 4
 8838: 
 8839: =item $Title: string, the title of the plot
 8840: 
 8841: =item $xlabel: string, text describing the X-axis of the plot
 8842: 
 8843: =item $ylabel: string, text describing the Y-axis of the plot
 8844: 
 8845: =item $Max: scalar, the maximum Y value to use in the plot
 8846: If $Max is < any data point, the graph will not be rendered.
 8847: 
 8848: =item $colors: Array ref containing the hex color codes for the data to be 
 8849: plotted in.  If undefined, default values will be used.
 8850: 
 8851: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8852: 
 8853: =item $Ydata: Array ref containing Array refs.  
 8854: Each of the contained arrays will be plotted as a separate curve.
 8855: 
 8856: =item %Values: hash indicating or overriding any default values which are 
 8857: passed to graph.png.  
 8858: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8859: 
 8860: =back
 8861: 
 8862: Returns:
 8863: 
 8864: An <img> tag which references graph.png and the appropriate identifying
 8865: information for the plot.
 8866: 
 8867: =cut
 8868: 
 8869: ############################################################
 8870: ############################################################
 8871: sub DrawXYGraph {
 8872:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8873:     #
 8874:     # Create the identifier for the graph
 8875:     my $identifier = &get_cgi_id();
 8876:     my $id = 'cgi.'.$identifier;
 8877:     #
 8878:     $Title  = '' if (! defined($Title));
 8879:     $xlabel = '' if (! defined($xlabel));
 8880:     $ylabel = '' if (! defined($ylabel));
 8881:     my %ValuesHash = 
 8882:         (
 8883:          $id.'.title'  => &escape($Title),
 8884:          $id.'.xlabel' => &escape($xlabel),
 8885:          $id.'.ylabel' => &escape($ylabel),
 8886:          $id.'.y_max_value'=> $Max,
 8887:          $id.'.labels'     => join(',',@$Xlabels),
 8888:          $id.'.PlotType'   => 'XY',
 8889:          );
 8890:     #
 8891:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8892:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8893:     }
 8894:     #
 8895:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8896:         return '';
 8897:     }
 8898:     my $NumSets=1;
 8899:     foreach my $array (@{$Ydata}){
 8900:         next if (! ref($array));
 8901:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8902:     }
 8903:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8904:     #
 8905:     # Deal with other parameters
 8906:     while (my ($key,$value) = each(%Values)) {
 8907:         $ValuesHash{$id.'.'.$key} = $value;
 8908:     }
 8909:     #
 8910:     &Apache::lonnet::appenv(\%ValuesHash);
 8911:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8912: }
 8913: 
 8914: ############################################################
 8915: ############################################################
 8916: 
 8917: =pod
 8918: 
 8919: =item * &DrawXYYGraph()
 8920: 
 8921: Facilitates the plotting of data in an XY graph with two Y axes.
 8922: Puts plot definition data into the users environment in order for 
 8923: graph.png to plot it.  Returns an <img> tag for the plot.
 8924: 
 8925: Inputs:
 8926: 
 8927: =over 4
 8928: 
 8929: =item $Title: string, the title of the plot
 8930: 
 8931: =item $xlabel: string, text describing the X-axis of the plot
 8932: 
 8933: =item $ylabel: string, text describing the Y-axis of the plot
 8934: 
 8935: =item $colors: Array ref containing the hex color codes for the data to be 
 8936: plotted in.  If undefined, default values will be used.
 8937: 
 8938: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8939: 
 8940: =item $Ydata1: The first data set
 8941: 
 8942: =item $Min1: The minimum value of the left Y-axis
 8943: 
 8944: =item $Max1: The maximum value of the left Y-axis
 8945: 
 8946: =item $Ydata2: The second data set
 8947: 
 8948: =item $Min2: The minimum value of the right Y-axis
 8949: 
 8950: =item $Max2: The maximum value of the left Y-axis
 8951: 
 8952: =item %Values: hash indicating or overriding any default values which are 
 8953: passed to graph.png.  
 8954: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8955: 
 8956: =back
 8957: 
 8958: Returns:
 8959: 
 8960: An <img> tag which references graph.png and the appropriate identifying
 8961: information for the plot.
 8962: 
 8963: =cut
 8964: 
 8965: ############################################################
 8966: ############################################################
 8967: sub DrawXYYGraph {
 8968:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8969:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8970:     #
 8971:     # Create the identifier for the graph
 8972:     my $identifier = &get_cgi_id();
 8973:     my $id = 'cgi.'.$identifier;
 8974:     #
 8975:     $Title  = '' if (! defined($Title));
 8976:     $xlabel = '' if (! defined($xlabel));
 8977:     $ylabel = '' if (! defined($ylabel));
 8978:     my %ValuesHash = 
 8979:         (
 8980:          $id.'.title'  => &escape($Title),
 8981:          $id.'.xlabel' => &escape($xlabel),
 8982:          $id.'.ylabel' => &escape($ylabel),
 8983:          $id.'.labels' => join(',',@$Xlabels),
 8984:          $id.'.PlotType' => 'XY',
 8985:          $id.'.NumSets' => 2,
 8986:          $id.'.two_axes' => 1,
 8987:          $id.'.y1_max_value' => $Max1,
 8988:          $id.'.y1_min_value' => $Min1,
 8989:          $id.'.y2_max_value' => $Max2,
 8990:          $id.'.y2_min_value' => $Min2,
 8991:          );
 8992:     #
 8993:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8994:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8995:     }
 8996:     #
 8997:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8998:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8999:         return '';
 9000:     }
 9001:     my $NumSets=1;
 9002:     foreach my $array ($Ydata1,$Ydata2){
 9003:         next if (! ref($array));
 9004:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9005:     }
 9006:     #
 9007:     # Deal with other parameters
 9008:     while (my ($key,$value) = each(%Values)) {
 9009:         $ValuesHash{$id.'.'.$key} = $value;
 9010:     }
 9011:     #
 9012:     &Apache::lonnet::appenv(\%ValuesHash);
 9013:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9014: }
 9015: 
 9016: ############################################################
 9017: ############################################################
 9018: 
 9019: =pod
 9020: 
 9021: =back 
 9022: 
 9023: =head1 Statistics helper routines?  
 9024: 
 9025: Bad place for them but what the hell.
 9026: 
 9027: =over 4
 9028: 
 9029: =item * &chartlink()
 9030: 
 9031: Returns a link to the chart for a specific student.  
 9032: 
 9033: Inputs:
 9034: 
 9035: =over 4
 9036: 
 9037: =item $linktext: The text of the link
 9038: 
 9039: =item $sname: The students username
 9040: 
 9041: =item $sdomain: The students domain
 9042: 
 9043: =back
 9044: 
 9045: =back
 9046: 
 9047: =cut
 9048: 
 9049: ############################################################
 9050: ############################################################
 9051: sub chartlink {
 9052:     my ($linktext, $sname, $sdomain) = @_;
 9053:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9054:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9055:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9056:        '">'.$linktext.'</a>';
 9057: }
 9058: 
 9059: #######################################################
 9060: #######################################################
 9061: 
 9062: =pod
 9063: 
 9064: =head1 Course Environment Routines
 9065: 
 9066: =over 4
 9067: 
 9068: =item * &restore_course_settings()
 9069: 
 9070: =item * &store_course_settings()
 9071: 
 9072: Restores/Store indicated form parameters from the course environment.
 9073: Will not overwrite existing values of the form parameters.
 9074: 
 9075: Inputs: 
 9076: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9077: 
 9078: a hash ref describing the data to be stored.  For example:
 9079:    
 9080: %Save_Parameters = ('Status' => 'scalar',
 9081:     'chartoutputmode' => 'scalar',
 9082:     'chartoutputdata' => 'scalar',
 9083:     'Section' => 'array',
 9084:     'Group' => 'array',
 9085:     'StudentData' => 'array',
 9086:     'Maps' => 'array');
 9087: 
 9088: Returns: both routines return nothing
 9089: 
 9090: =back
 9091: 
 9092: =cut
 9093: 
 9094: #######################################################
 9095: #######################################################
 9096: sub store_course_settings {
 9097:     return &store_settings($env{'request.course.id'},@_);
 9098: }
 9099: 
 9100: sub store_settings {
 9101:     # save to the environment
 9102:     # appenv the same items, just to be safe
 9103:     my $udom  = $env{'user.domain'};
 9104:     my $uname = $env{'user.name'};
 9105:     my ($context,$prefix,$Settings) = @_;
 9106:     my %SaveHash;
 9107:     my %AppHash;
 9108:     while (my ($setting,$type) = each(%$Settings)) {
 9109:         my $basename = join('.','internal',$context,$prefix,$setting);
 9110:         my $envname = 'environment.'.$basename;
 9111:         if (exists($env{'form.'.$setting})) {
 9112:             # Save this value away
 9113:             if ($type eq 'scalar' &&
 9114:                 (! exists($env{$envname}) || 
 9115:                  $env{$envname} ne $env{'form.'.$setting})) {
 9116:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9117:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9118:             } elsif ($type eq 'array') {
 9119:                 my $stored_form;
 9120:                 if (ref($env{'form.'.$setting})) {
 9121:                     $stored_form = join(',',
 9122:                                         map {
 9123:                                             &escape($_);
 9124:                                         } sort(@{$env{'form.'.$setting}}));
 9125:                 } else {
 9126:                     $stored_form = 
 9127:                         &escape($env{'form.'.$setting});
 9128:                 }
 9129:                 # Determine if the array contents are the same.
 9130:                 if ($stored_form ne $env{$envname}) {
 9131:                     $SaveHash{$basename} = $stored_form;
 9132:                     $AppHash{$envname}   = $stored_form;
 9133:                 }
 9134:             }
 9135:         }
 9136:     }
 9137:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9138:                                           $udom,$uname);
 9139:     if ($put_result !~ /^(ok|delayed)/) {
 9140:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9141:                                  'got error:'.$put_result);
 9142:     }
 9143:     # Make sure these settings stick around in this session, too
 9144:     &Apache::lonnet::appenv(\%AppHash);
 9145:     return;
 9146: }
 9147: 
 9148: sub restore_course_settings {
 9149:     return &restore_settings($env{'request.course.id'},@_);
 9150: }
 9151: 
 9152: sub restore_settings {
 9153:     my ($context,$prefix,$Settings) = @_;
 9154:     while (my ($setting,$type) = each(%$Settings)) {
 9155:         next if (exists($env{'form.'.$setting}));
 9156:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9157:             '.'.$setting;
 9158:         if (exists($env{$envname})) {
 9159:             if ($type eq 'scalar') {
 9160:                 $env{'form.'.$setting} = $env{$envname};
 9161:             } elsif ($type eq 'array') {
 9162:                 $env{'form.'.$setting} = [ 
 9163:                                            map { 
 9164:                                                &unescape($_); 
 9165:                                            } split(',',$env{$envname})
 9166:                                            ];
 9167:             }
 9168:         }
 9169:     }
 9170: }
 9171: 
 9172: #######################################################
 9173: #######################################################
 9174: 
 9175: =pod
 9176: 
 9177: =head1 Domain E-mail Routines  
 9178: 
 9179: =over 4
 9180: 
 9181: =item * &build_recipient_list()
 9182: 
 9183: Build recipient lists for four types of e-mail:
 9184: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9185: (d) Help requests, generated by
 9186: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 9187: 
 9188: Inputs:
 9189: defmail (scalar - email address of default recipient), 
 9190: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9191: defdom (domain for which to retrieve configuration settings),
 9192: origmail (scalar - email address of recipient from loncapa.conf, 
 9193: i.e., predates configuration by DC via domainprefs.pm 
 9194: 
 9195: Returns: comma separated list of addresses to which to send e-mail.
 9196: 
 9197: =back
 9198: 
 9199: =cut
 9200: 
 9201: ############################################################
 9202: ############################################################
 9203: sub build_recipient_list {
 9204:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9205:     my @recipients;
 9206:     my $otheremails;
 9207:     my %domconfig =
 9208:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9209:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9210:         if (exists($domconfig{'contacts'}{$mailing})) {
 9211:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9212:                 my @contacts = ('adminemail','supportemail');
 9213:                 foreach my $item (@contacts) {
 9214:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9215:                         my $addr = $domconfig{'contacts'}{$item}; 
 9216:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9217:                             push(@recipients,$addr);
 9218:                         }
 9219:                     }
 9220:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9221:                 }
 9222:             }
 9223:         } elsif ($origmail ne '') {
 9224:             push(@recipients,$origmail);
 9225:         }
 9226:     } elsif ($origmail ne '') {
 9227:         push(@recipients,$origmail);
 9228:     }
 9229:     if (defined($defmail)) {
 9230:         if ($defmail ne '') {
 9231:             push(@recipients,$defmail);
 9232:         }
 9233:     }
 9234:     if ($otheremails) {
 9235:         my @others;
 9236:         if ($otheremails =~ /,/) {
 9237:             @others = split(/,/,$otheremails);
 9238:         } else {
 9239:             push(@others,$otheremails);
 9240:         }
 9241:         foreach my $addr (@others) {
 9242:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9243:                 push(@recipients,$addr);
 9244:             }
 9245:         }
 9246:     }
 9247:     my $recipientlist = join(',',@recipients); 
 9248:     return $recipientlist;
 9249: }
 9250: 
 9251: ############################################################
 9252: ############################################################
 9253: 
 9254: =pod
 9255: 
 9256: =head1 Course Catalog Routines
 9257: 
 9258: =over 4
 9259: 
 9260: =item * &gather_categories()
 9261: 
 9262: Converts category definitions - keys of categories hash stored in  
 9263: coursecategories in configuration.db on the primary library server in a 
 9264: domain - to an array.  Also generates javascript and idx hash used to 
 9265: generate Domain Coordinator interface for editing Course Categories.
 9266: 
 9267: Inputs:
 9268: 
 9269: categories (reference to hash of category definitions).
 9270: 
 9271: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9272:       categories and subcategories).
 9273: 
 9274: idx (reference to hash of counters used in Domain Coordinator interface for 
 9275:       editing Course Categories).
 9276: 
 9277: jsarray (reference to array of categories used to create Javascript arrays for
 9278:          Domain Coordinator interface for editing Course Categories).
 9279: 
 9280: Returns: nothing
 9281: 
 9282: Side effects: populates cats, idx and jsarray. 
 9283: 
 9284: =cut
 9285: 
 9286: sub gather_categories {
 9287:     my ($categories,$cats,$idx,$jsarray) = @_;
 9288:     my %counters;
 9289:     my $num = 0;
 9290:     foreach my $item (keys(%{$categories})) {
 9291:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9292:         if ($container eq '' && $depth == 0) {
 9293:             $cats->[$depth][$categories->{$item}] = $cat;
 9294:         } else {
 9295:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9296:         }
 9297:         my ($escitem,$tail) = split(/:/,$item,2);
 9298:         if ($counters{$tail} eq '') {
 9299:             $counters{$tail} = $num;
 9300:             $num ++;
 9301:         }
 9302:         if (ref($idx) eq 'HASH') {
 9303:             $idx->{$item} = $counters{$tail};
 9304:         }
 9305:         if (ref($jsarray) eq 'ARRAY') {
 9306:             push(@{$jsarray->[$counters{$tail}]},$item);
 9307:         }
 9308:     }
 9309:     return;
 9310: }
 9311: 
 9312: =pod
 9313: 
 9314: =item * &extract_categories()
 9315: 
 9316: Used to generate breadcrumb trails for course categories.
 9317: 
 9318: Inputs:
 9319: 
 9320: categories (reference to hash of category definitions).
 9321: 
 9322: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9323:       categories and subcategories).
 9324: 
 9325: trails (reference to array of breacrumb trails for each category).
 9326: 
 9327: allitems (reference to hash - key is category key 
 9328:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9329: 
 9330: idx (reference to hash of counters used in Domain Coordinator interface for
 9331:       editing Course Categories).
 9332: 
 9333: jsarray (reference to array of categories used to create Javascript arrays for
 9334:          Domain Coordinator interface for editing Course Categories).
 9335: 
 9336: subcats (reference to hash of arrays containing all subcategories within each 
 9337:          category, -recursive)
 9338: 
 9339: Returns: nothing
 9340: 
 9341: Side effects: populates trails and allitems hash references.
 9342: 
 9343: =cut
 9344: 
 9345: sub extract_categories {
 9346:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9347:     if (ref($categories) eq 'HASH') {
 9348:         &gather_categories($categories,$cats,$idx,$jsarray);
 9349:         if (ref($cats->[0]) eq 'ARRAY') {
 9350:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9351:                 my $name = $cats->[0][$i];
 9352:                 my $item = &escape($name).'::0';
 9353:                 my $trailstr;
 9354:                 if ($name eq 'instcode') {
 9355:                     $trailstr = &mt('Official courses (with institutional codes)');
 9356:                 } else {
 9357:                     $trailstr = $name;
 9358:                 }
 9359:                 if ($allitems->{$item} eq '') {
 9360:                     push(@{$trails},$trailstr);
 9361:                     $allitems->{$item} = scalar(@{$trails})-1;
 9362:                 }
 9363:                 my @parents = ($name);
 9364:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9365:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9366:                         my $category = $cats->[1]{$name}[$j];
 9367:                         if (ref($subcats) eq 'HASH') {
 9368:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9369:                         }
 9370:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9371:                     }
 9372:                 } else {
 9373:                     if (ref($subcats) eq 'HASH') {
 9374:                         $subcats->{$item} = [];
 9375:                     }
 9376:                 }
 9377:             }
 9378:         }
 9379:     }
 9380:     return;
 9381: }
 9382: 
 9383: =pod
 9384: 
 9385: =item *&recurse_categories()
 9386: 
 9387: Recursively used to generate breadcrumb trails for course categories.
 9388: 
 9389: Inputs:
 9390: 
 9391: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9392:       categories and subcategories).
 9393: 
 9394: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9395: 
 9396: category (current course category, for which breadcrumb trail is being generated).
 9397: 
 9398: trails (reference to array of breadcrumb trails for each category).
 9399: 
 9400: allitems (reference to hash - key is category key
 9401:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9402: 
 9403: parents (array containing containers directories for current category, 
 9404:          back to top level). 
 9405: 
 9406: Returns: nothing
 9407: 
 9408: Side effects: populates trails and allitems hash references
 9409: 
 9410: =cut
 9411: 
 9412: sub recurse_categories {
 9413:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9414:     my $shallower = $depth - 1;
 9415:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9416:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9417:             my $name = $cats->[$depth]{$category}[$k];
 9418:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9419:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9420:             if ($allitems->{$item} eq '') {
 9421:                 push(@{$trails},$trailstr);
 9422:                 $allitems->{$item} = scalar(@{$trails})-1;
 9423:             }
 9424:             my $deeper = $depth+1;
 9425:             push(@{$parents},$category);
 9426:             if (ref($subcats) eq 'HASH') {
 9427:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9428:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9429:                     my $higher;
 9430:                     if ($j > 0) {
 9431:                         $higher = &escape($parents->[$j]).':'.
 9432:                                   &escape($parents->[$j-1]).':'.$j;
 9433:                     } else {
 9434:                         $higher = &escape($parents->[$j]).'::'.$j;
 9435:                     }
 9436:                     push(@{$subcats->{$higher}},$subcat);
 9437:                 }
 9438:             }
 9439:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9440:                                 $subcats);
 9441:             pop(@{$parents});
 9442:         }
 9443:     } else {
 9444:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9445:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9446:         if ($allitems->{$item} eq '') {
 9447:             push(@{$trails},$trailstr);
 9448:             $allitems->{$item} = scalar(@{$trails})-1;
 9449:         }
 9450:     }
 9451:     return;
 9452: }
 9453: 
 9454: =pod
 9455: 
 9456: =item *&assign_categories_table()
 9457: 
 9458: Create a datatable for display of hierarchical categories in a domain,
 9459: with checkboxes to allow a course to be categorized. 
 9460: 
 9461: Inputs:
 9462: 
 9463: cathash - reference to hash of categories defined for the domain (from
 9464:           configuration.db)
 9465: 
 9466: currcat - scalar with an & separated list of categories assigned to a course. 
 9467: 
 9468: Returns: $output (markup to be displayed) 
 9469: 
 9470: =cut
 9471: 
 9472: sub assign_categories_table {
 9473:     my ($cathash,$currcat) = @_;
 9474:     my $output;
 9475:     if (ref($cathash) eq 'HASH') {
 9476:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9477:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9478:         $maxdepth = scalar(@cats);
 9479:         if (@cats > 0) {
 9480:             my $itemcount = 0;
 9481:             if (ref($cats[0]) eq 'ARRAY') {
 9482:                 $output = &Apache::loncommon::start_data_table();
 9483:                 my @currcategories;
 9484:                 if ($currcat ne '') {
 9485:                     @currcategories = split('&',$currcat);
 9486:                 }
 9487:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9488:                     my $parent = $cats[0][$i];
 9489:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9490:                     next if ($parent eq 'instcode');
 9491:                     my $item = &escape($parent).'::0';
 9492:                     my $checked = '';
 9493:                     if (@currcategories > 0) {
 9494:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9495:                             $checked = ' checked="checked"';
 9496:                         }
 9497:                     }
 9498:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9499:                                '<input type="checkbox" name="usecategory" value="'.
 9500:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9501:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9502:                     my $depth = 1;
 9503:                     push(@path,$parent);
 9504:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9505:                     pop(@path);
 9506:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9507:                     $itemcount ++;
 9508:                 }
 9509:                 $output .= &Apache::loncommon::end_data_table();
 9510:             }
 9511:         }
 9512:     }
 9513:     return $output;
 9514: }
 9515: 
 9516: =pod
 9517: 
 9518: =item *&assign_category_rows()
 9519: 
 9520: Create a datatable row for display of nested categories in a domain,
 9521: with checkboxes to allow a course to be categorized,called recursively.
 9522: 
 9523: Inputs:
 9524: 
 9525: itemcount - track row number for alternating colors
 9526: 
 9527: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9528:       categories and subcategories.
 9529: 
 9530: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9531: 
 9532: parent - parent of current category item
 9533: 
 9534: path - Array containing all categories back up through the hierarchy from the
 9535:        current category to the top level.
 9536: 
 9537: currcategories - reference to array of current categories assigned to the course
 9538: 
 9539: Returns: $output (markup to be displayed).
 9540: 
 9541: =cut
 9542: 
 9543: sub assign_category_rows {
 9544:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9545:     my ($text,$name,$item,$chgstr);
 9546:     if (ref($cats) eq 'ARRAY') {
 9547:         my $maxdepth = scalar(@{$cats});
 9548:         if (ref($cats->[$depth]) eq 'HASH') {
 9549:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9550:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9551:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9552:                 $text .= '<td><table class="LC_datatable">';
 9553:                 for (my $j=0; $j<$numchildren; $j++) {
 9554:                     $name = $cats->[$depth]{$parent}[$j];
 9555:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9556:                     my $deeper = $depth+1;
 9557:                     my $checked = '';
 9558:                     if (ref($currcategories) eq 'ARRAY') {
 9559:                         if (@{$currcategories} > 0) {
 9560:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9561:                                 $checked = ' checked="checked"';
 9562:                             }
 9563:                         }
 9564:                     }
 9565:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9566:                              '<input type="checkbox" name="usecategory" value="'.
 9567:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9568:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9569:                              '</td><td>';
 9570:                     if (ref($path) eq 'ARRAY') {
 9571:                         push(@{$path},$name);
 9572:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9573:                         pop(@{$path});
 9574:                     }
 9575:                     $text .= '</td></tr>';
 9576:                 }
 9577:                 $text .= '</table></td>';
 9578:             }
 9579:         }
 9580:     }
 9581:     return $text;
 9582: }
 9583: 
 9584: ############################################################
 9585: ############################################################
 9586: 
 9587: 
 9588: sub commit_customrole {
 9589:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9590:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9591:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9592:                          ($end?', ending '.localtime($end):'').': <b>'.
 9593:               &Apache::lonnet::assigncustomrole(
 9594:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9595:                  '</b><br />';
 9596:     return $output;
 9597: }
 9598: 
 9599: sub commit_standardrole {
 9600:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9601:     my ($output,$logmsg,$linefeed);
 9602:     if ($context eq 'auto') {
 9603:         $linefeed = "\n";
 9604:     } else {
 9605:         $linefeed = "<br />\n";
 9606:     }  
 9607:     if ($three eq 'st') {
 9608:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9609:                                          $one,$two,$sec,$context);
 9610:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9611:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9612:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9613:         } else {
 9614:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9615:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9616:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9617:             if ($context eq 'auto') {
 9618:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9619:             } else {
 9620:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9621:                &mt('Add to classlist').': <b>ok</b>';
 9622:             }
 9623:             $output .= $linefeed;
 9624:         }
 9625:     } else {
 9626:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9627:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9628:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9629:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9630:         if ($context eq 'auto') {
 9631:             $output .= $result.$linefeed;
 9632:         } else {
 9633:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9634:         }
 9635:     }
 9636:     return $output;
 9637: }
 9638: 
 9639: sub commit_studentrole {
 9640:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9641:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9642:     if ($context eq 'auto') {
 9643:         $linefeed = "\n";
 9644:     } else {
 9645:         $linefeed = '<br />'."\n";
 9646:     }
 9647:     if (defined($one) && defined($two)) {
 9648:         my $cid=$one.'_'.$two;
 9649:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9650:         my $secchange = 0;
 9651:         my $expire_role_result;
 9652:         my $modify_section_result;
 9653:         if ($oldsec ne '-1') { 
 9654:             if ($oldsec ne $sec) {
 9655:                 $secchange = 1;
 9656:                 my $now = time;
 9657:                 my $uurl='/'.$cid;
 9658:                 $uurl=~s/\_/\//g;
 9659:                 if ($oldsec) {
 9660:                     $uurl.='/'.$oldsec;
 9661:                 }
 9662:                 $oldsecurl = $uurl;
 9663:                 $expire_role_result = 
 9664:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9665:                 if ($env{'request.course.sec'} ne '') { 
 9666:                     if ($expire_role_result eq 'refused') {
 9667:                         my @roles = ('st');
 9668:                         my @statuses = ('previous');
 9669:                         my @roledoms = ($one);
 9670:                         my $withsec = 1;
 9671:                         my %roleshash = 
 9672:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9673:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9674:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9675:                             my ($oldstart,$oldend) = 
 9676:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9677:                             if ($oldend > 0 && $oldend <= $now) {
 9678:                                 $expire_role_result = 'ok';
 9679:                             }
 9680:                         }
 9681:                     }
 9682:                 }
 9683:                 $result = $expire_role_result;
 9684:             }
 9685:         }
 9686:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9687:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9688:             if ($modify_section_result =~ /^ok/) {
 9689:                 if ($secchange == 1) {
 9690:                     if ($sec eq '') {
 9691:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9692:                     } else {
 9693:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9694:                     }
 9695:                 } elsif ($oldsec eq '-1') {
 9696:                     if ($sec eq '') {
 9697:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9698:                     } else {
 9699:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9700:                     }
 9701:                 } else {
 9702:                     if ($sec eq '') {
 9703:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9704:                     } else {
 9705:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9706:                     }
 9707:                 }
 9708:             } else {
 9709:                 if ($secchange) {       
 9710:                     $$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;
 9711:                 } else {
 9712:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9713:                 }
 9714:             }
 9715:             $result = $modify_section_result;
 9716:         } elsif ($secchange == 1) {
 9717:             if ($oldsec eq '') {
 9718:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9719:             } else {
 9720:                 $$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;
 9721:             }
 9722:             if ($expire_role_result eq 'refused') {
 9723:                 my $newsecurl = '/'.$cid;
 9724:                 $newsecurl =~ s/\_/\//g;
 9725:                 if ($sec ne '') {
 9726:                     $newsecurl.='/'.$sec;
 9727:                 }
 9728:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9729:                     if ($sec eq '') {
 9730:                         $$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;
 9731:                     } else {
 9732:                         $$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;
 9733:                     }
 9734:                 }
 9735:             }
 9736:         }
 9737:     } else {
 9738:         $$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;
 9739:         $result = "error: incomplete course id\n";
 9740:     }
 9741:     return $result;
 9742: }
 9743: 
 9744: ############################################################
 9745: ############################################################
 9746: 
 9747: sub check_clone {
 9748:     my ($args,$linefeed) = @_;
 9749:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9750:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9751:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9752:     my $clonemsg;
 9753:     my $can_clone = 0;
 9754: 
 9755:     if ($clonehome eq 'no_host') {
 9756:         $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'});     
 9757:     } else {
 9758: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9759: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9760: 	    $can_clone = 1;
 9761: 	} else {
 9762: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9763: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9764: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9765:             if (grep(/^\*$/,@cloners)) {
 9766:                 $can_clone = 1;
 9767:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9768:                 $can_clone = 1;
 9769:             } else {
 9770: 	        my %roleshash =
 9771: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9772: 					 $args->{'ccdomain'},
 9773:                                          'userroles',['active'],['cc'],
 9774: 					 [$args->{'clonedomain'}]);
 9775: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9776: 		    $can_clone = 1;
 9777: 	        } else {
 9778:                     $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'});
 9779: 	        }
 9780: 	    }
 9781:         }
 9782:     }
 9783:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9784: }
 9785: 
 9786: sub construct_course {
 9787:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9788:     my $outcome;
 9789:     my $linefeed =  '<br />'."\n";
 9790:     if ($context eq 'auto') {
 9791:         $linefeed = "\n";
 9792:     }
 9793: 
 9794: #
 9795: # Are we cloning?
 9796: #
 9797:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9798:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9799: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9800: 	if ($context ne 'auto') {
 9801:             if ($clonemsg ne '') {
 9802: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9803:             }
 9804: 	}
 9805: 	$outcome .= $clonemsg.$linefeed;
 9806: 
 9807:         if (!$can_clone) {
 9808: 	    return (0,$outcome);
 9809: 	}
 9810:     }
 9811: 
 9812: #
 9813: # Open course
 9814: #
 9815:     my $crstype = lc($args->{'crstype'});
 9816:     my %cenv=();
 9817:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9818:                                              $args->{'cdescr'},
 9819:                                              $args->{'curl'},
 9820:                                              $args->{'course_home'},
 9821:                                              $args->{'nonstandard'},
 9822:                                              $args->{'crscode'},
 9823:                                              $args->{'ccuname'}.':'.
 9824:                                              $args->{'ccdomain'},
 9825:                                              $args->{'crstype'});
 9826: 
 9827:     # Note: The testing routines depend on this being output; see 
 9828:     # Utils::Course. This needs to at least be output as a comment
 9829:     # if anyone ever decides to not show this, and Utils::Course::new
 9830:     # will need to be suitably modified.
 9831:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9832: #
 9833: # Check if created correctly
 9834: #
 9835:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9836:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9837:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9838: 
 9839: #
 9840: # Do the cloning
 9841: #   
 9842:     if ($can_clone && $cloneid) {
 9843: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9844: 	if ($context ne 'auto') {
 9845: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9846: 	}
 9847: 	$outcome .= $clonemsg.$linefeed;
 9848: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9849: # Copy all files
 9850: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9851: # Restore URL
 9852: 	$cenv{'url'}=$oldcenv{'url'};
 9853: # Restore title
 9854: 	$cenv{'description'}=$oldcenv{'description'};
 9855: # Mark as cloned
 9856: 	$cenv{'clonedfrom'}=$cloneid;
 9857: # Need to clone grading mode
 9858:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9859:         $cenv{'grading'}=$newenv{'grading'};
 9860: # Do not clone these environment entries
 9861:         &Apache::lonnet::del('environment',
 9862:                   ['default_enrollment_start_date',
 9863:                    'default_enrollment_end_date',
 9864:                    'question.email',
 9865:                    'policy.email',
 9866:                    'comment.email',
 9867:                    'pch.users.denied',
 9868:                    'plc.users.denied',
 9869:                    'hidefromcat',
 9870:                    'categories'],
 9871:                    $$crsudom,$$crsunum);
 9872:     }
 9873: 
 9874: #
 9875: # Set environment (will override cloned, if existing)
 9876: #
 9877:     my @sections = ();
 9878:     my @xlists = ();
 9879:     if ($args->{'crstype'}) {
 9880:         $cenv{'type'}=$args->{'crstype'};
 9881:     }
 9882:     if ($args->{'crsid'}) {
 9883:         $cenv{'courseid'}=$args->{'crsid'};
 9884:     }
 9885:     if ($args->{'crscode'}) {
 9886:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9887:     }
 9888:     if ($args->{'crsquota'} ne '') {
 9889:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9890:     } else {
 9891:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9892:     }
 9893:     if ($args->{'ccuname'}) {
 9894:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9895:                                         ':'.$args->{'ccdomain'};
 9896:     } else {
 9897:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9898:     }
 9899:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9900:     if ($args->{'crssections'}) {
 9901:         $cenv{'internal.sectionnums'} = '';
 9902:         if ($args->{'crssections'} =~ m/,/) {
 9903:             @sections = split/,/,$args->{'crssections'};
 9904:         } else {
 9905:             $sections[0] = $args->{'crssections'};
 9906:         }
 9907:         if (@sections > 0) {
 9908:             foreach my $item (@sections) {
 9909:                 my ($sec,$gp) = split/:/,$item;
 9910:                 my $class = $args->{'crscode'}.$sec;
 9911:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9912:                 $cenv{'internal.sectionnums'} .= $item.',';
 9913:                 unless ($addcheck eq 'ok') {
 9914:                     push @badclasses, $class;
 9915:                 }
 9916:             }
 9917:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9918:         }
 9919:     }
 9920: # do not hide course coordinator from staff listing, 
 9921: # even if privileged
 9922:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9923: # add crosslistings
 9924:     if ($args->{'crsxlist'}) {
 9925:         $cenv{'internal.crosslistings'}='';
 9926:         if ($args->{'crsxlist'} =~ m/,/) {
 9927:             @xlists = split/,/,$args->{'crsxlist'};
 9928:         } else {
 9929:             $xlists[0] = $args->{'crsxlist'};
 9930:         }
 9931:         if (@xlists > 0) {
 9932:             foreach my $item (@xlists) {
 9933:                 my ($xl,$gp) = split/:/,$item;
 9934:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9935:                 $cenv{'internal.crosslistings'} .= $item.',';
 9936:                 unless ($addcheck eq 'ok') {
 9937:                     push @badclasses, $xl;
 9938:                 }
 9939:             }
 9940:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9941:         }
 9942:     }
 9943:     if ($args->{'autoadds'}) {
 9944:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9945:     }
 9946:     if ($args->{'autodrops'}) {
 9947:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9948:     }
 9949: # check for notification of enrollment changes
 9950:     my @notified = ();
 9951:     if ($args->{'notify_owner'}) {
 9952:         if ($args->{'ccuname'} ne '') {
 9953:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9954:         }
 9955:     }
 9956:     if ($args->{'notify_dc'}) {
 9957:         if ($uname ne '') { 
 9958:             push(@notified,$uname.':'.$udom);
 9959:         }
 9960:     }
 9961:     if (@notified > 0) {
 9962:         my $notifylist;
 9963:         if (@notified > 1) {
 9964:             $notifylist = join(',',@notified);
 9965:         } else {
 9966:             $notifylist = $notified[0];
 9967:         }
 9968:         $cenv{'internal.notifylist'} = $notifylist;
 9969:     }
 9970:     if (@badclasses > 0) {
 9971:         my %lt=&Apache::lonlocal::texthash(
 9972:                 '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',
 9973:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9974:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9975:         );
 9976:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9977:                            ' ('.$lt{'adby'}.')';
 9978:         if ($context eq 'auto') {
 9979:             $outcome .= $badclass_msg.$linefeed;
 9980:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9981:             foreach my $item (@badclasses) {
 9982:                 if ($context eq 'auto') {
 9983:                     $outcome .= " - $item\n";
 9984:                 } else {
 9985:                     $outcome .= "<li>$item</li>\n";
 9986:                 }
 9987:             }
 9988:             if ($context eq 'auto') {
 9989:                 $outcome .= $linefeed;
 9990:             } else {
 9991:                 $outcome .= "</ul><br /><br /></div>\n";
 9992:             }
 9993:         } 
 9994:     }
 9995:     if ($args->{'no_end_date'}) {
 9996:         $args->{'endaccess'} = 0;
 9997:     }
 9998:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9999:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10000:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10001:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10002:     if ($args->{'showphotos'}) {
10003:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10004:     }
10005:     $cenv{'internal.authtype'} = $args->{'authtype'};
10006:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10007:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10008:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10009:             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'); 
10010:             if ($context eq 'auto') {
10011:                 $outcome .= $krb_msg;
10012:             } else {
10013:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10014:             }
10015:             $outcome .= $linefeed;
10016:         }
10017:     }
10018:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10019:        if ($args->{'setpolicy'}) {
10020:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10021:        }
10022:        if ($args->{'setcontent'}) {
10023:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10024:        }
10025:     }
10026:     if ($args->{'reshome'}) {
10027: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10028: 	$cenv{'reshome'}=~s/\/+$/\//;
10029:     }
10030: #
10031: # course has keyed access
10032: #
10033:     if ($args->{'setkeys'}) {
10034:        $cenv{'keyaccess'}='yes';
10035:     }
10036: # if specified, key authority is not course, but user
10037: # only active if keyaccess is yes
10038:     if ($args->{'keyauth'}) {
10039: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10040: 	$user = &LONCAPA::clean_username($user);
10041: 	$domain = &LONCAPA::clean_username($domain);
10042: 	if ($user ne '' && $domain ne '') {
10043: 	    $cenv{'keyauth'}=$user.':'.$domain;
10044: 	}
10045:     }
10046: 
10047:     if ($args->{'disresdis'}) {
10048:         $cenv{'pch.roles.denied'}='st';
10049:     }
10050:     if ($args->{'disablechat'}) {
10051:         $cenv{'plc.roles.denied'}='st';
10052:     }
10053: 
10054:     # Record we've not yet viewed the Course Initialization Helper for this 
10055:     # course
10056:     $cenv{'course.helper.not.run'} = 1;
10057:     #
10058:     # Use new Randomseed
10059:     #
10060:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10061:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10062:     #
10063:     # The encryption code and receipt prefix for this course
10064:     #
10065:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10066:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10067:     #
10068:     # By default, use standard grading
10069:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10070: 
10071:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10072:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10073: #
10074: # Open all assignments
10075: #
10076:     if ($args->{'openall'}) {
10077:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10078:        my %storecontent = ($storeunder         => time,
10079:                            $storeunder.'.type' => 'date_start');
10080:        
10081:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10082:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10083:    }
10084: #
10085: # Set first page
10086: #
10087:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10088: 	    || ($cloneid)) {
10089: 	use LONCAPA::map;
10090: 	$outcome .= &mt('Setting first resource').': ';
10091: 
10092: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10093:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10094: 
10095:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10096:         my $title; my $url;
10097:         if ($args->{'firstres'} eq 'syl') {
10098: 	    $title=&mt('Syllabus');
10099:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10100:         } else {
10101:             $title=&mt('Navigate Contents');
10102:             $url='/adm/navmaps';
10103:         }
10104: 
10105:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10106: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10107: 
10108: 	if ($errtext) { $fatal=2; }
10109:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10110:     }
10111: 
10112:     return (1,$outcome);
10113: }
10114: 
10115: ############################################################
10116: ############################################################
10117: 
10118: sub course_type {
10119:     my ($cid) = @_;
10120:     if (!defined($cid)) {
10121:         $cid = $env{'request.course.id'};
10122:     }
10123:     if (defined($env{'course.'.$cid.'.type'})) {
10124:         return $env{'course.'.$cid.'.type'};
10125:     } else {
10126:         return 'Course';
10127:     }
10128: }
10129: 
10130: sub group_term {
10131:     my $crstype = &course_type();
10132:     my %names = (
10133:                   'Course' => 'group',
10134:                   'Group' => 'team',
10135:                 );
10136:     return $names{$crstype};
10137: }
10138: 
10139: sub icon {
10140:     my ($file)=@_;
10141:     my $curfext = lc((split(/\./,$file))[-1]);
10142:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10143:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10144:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10145: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10146: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10147: 	            $curfext.".gif") {
10148: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10149: 		$curfext.".gif";
10150: 	}
10151:     }
10152:     return &lonhttpdurl($iconname);
10153: } 
10154: 
10155: sub lonhttpdurl {
10156: #
10157: # Had been used for "small fry" static images on separate port 8080.
10158: # Modify here if lightweight http functionality desired again.
10159: # Currently eliminated due to increasing firewall issues.
10160: #
10161:     my ($url)=@_;
10162:     return $url;
10163: }
10164: 
10165: sub connection_aborted {
10166:     my ($r)=@_;
10167:     $r->print(" ");$r->rflush();
10168:     my $c = $r->connection;
10169:     return $c->aborted();
10170: }
10171: 
10172: #    Escapes strings that may have embedded 's that will be put into
10173: #    strings as 'strings'.
10174: sub escape_single {
10175:     my ($input) = @_;
10176:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10177:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10178:     return $input;
10179: }
10180: 
10181: #  Same as escape_single, but escape's "'s  This 
10182: #  can be used for  "strings"
10183: sub escape_double {
10184:     my ($input) = @_;
10185:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10186:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10187:     return $input;
10188: }
10189:  
10190: #   Escapes the last element of a full URL.
10191: sub escape_url {
10192:     my ($url)   = @_;
10193:     my @urlslices = split(/\//, $url,-1);
10194:     my $lastitem = &escape(pop(@urlslices));
10195:     return join('/',@urlslices).'/'.$lastitem;
10196: }
10197: 
10198: # -------------------------------------------------------- Initliaze user login
10199: sub init_user_environment {
10200:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10201:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10202: 
10203:     my $public=($username eq 'public' && $domain eq 'public');
10204: 
10205: # See if old ID present, if so, remove
10206: 
10207:     my ($filename,$cookie,$userroles);
10208:     my $now=time;
10209: 
10210:     if ($public) {
10211: 	my $max_public=100;
10212: 	my $oldest;
10213: 	my $oldest_time=0;
10214: 	for(my $next=1;$next<=$max_public;$next++) {
10215: 	    if (-e $lonids."/publicuser_$next.id") {
10216: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10217: 		if ($mtime<$oldest_time || !$oldest_time) {
10218: 		    $oldest_time=$mtime;
10219: 		    $oldest=$next;
10220: 		}
10221: 	    } else {
10222: 		$cookie="publicuser_$next";
10223: 		last;
10224: 	    }
10225: 	}
10226: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10227:     } else {
10228: 	# if this isn't a robot, kill any existing non-robot sessions
10229: 	if (!$args->{'robot'}) {
10230: 	    opendir(DIR,$lonids);
10231: 	    while ($filename=readdir(DIR)) {
10232: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10233: 		    unlink($lonids.'/'.$filename);
10234: 		}
10235: 	    }
10236: 	    closedir(DIR);
10237: 	}
10238: # Give them a new cookie
10239: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10240: 		                   : $now.$$.int(rand(10000)));
10241: 	$cookie="$username\_$id\_$domain\_$authhost";
10242:     
10243: # Initialize roles
10244: 
10245: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10246:     }
10247: # ------------------------------------ Check browser type and MathML capability
10248: 
10249:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10250:         $clientunicode,$clientos) = &decode_user_agent($r);
10251: 
10252: # -------------------------------------- Any accessibility options to remember?
10253:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
10254: 	foreach my $option ('imagesuppress','appletsuppress',
10255: 			    'embedsuppress','fontenhance','blackwhite') {
10256: 	    if ($form->{$option} eq 'true') {
10257: 		&Apache::lonnet::put('environment',{$option => 'on'},
10258: 				     $domain,$username);
10259: 	    } else {
10260: 		&Apache::lonnet::del('environment',[$option],
10261: 				     $domain,$username);
10262: 	    }
10263: 	}
10264:     }
10265: # ------------------------------------------------------------- Get environment
10266: 
10267:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10268:     my ($tmp) = keys(%userenv);
10269:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10270: 	# default remote control to off
10271: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10272:     } else {
10273: 	undef(%userenv);
10274:     }
10275:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10276: 	$form->{'interface'}=$userenv{'interface'};
10277:     }
10278:     $env{'environment.remote'}=$userenv{'remote'};
10279:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10280: 
10281: # --------------- Do not trust query string to be put directly into environment
10282:     foreach my $option ('imagesuppress','appletsuppress',
10283: 			'embedsuppress','fontenhance','blackwhite',
10284: 			'interface','localpath','localres') {
10285: 	$form->{$option}=~s/[\n\r\=]//gs;
10286:     }
10287: # --------------------------------------------------------- Write first profile
10288: 
10289:     {
10290: 	my %initial_env = 
10291: 	    ("user.name"          => $username,
10292: 	     "user.domain"        => $domain,
10293: 	     "user.home"          => $authhost,
10294: 	     "browser.type"       => $clientbrowser,
10295: 	     "browser.version"    => $clientversion,
10296: 	     "browser.mathml"     => $clientmathml,
10297: 	     "browser.unicode"    => $clientunicode,
10298: 	     "browser.os"         => $clientos,
10299: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10300: 	     "request.course.fn"  => '',
10301: 	     "request.course.uri" => '',
10302: 	     "request.course.sec" => '',
10303: 	     "request.role"       => 'cm',
10304: 	     "request.role.adv"   => $env{'user.adv'},
10305: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10306: 
10307:         if ($form->{'localpath'}) {
10308: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10309: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10310:         }
10311: 	
10312: 	if ($public) {
10313: 	    $initial_env{"environment.remote"} = "off";
10314: 	}
10315: 	if ($form->{'interface'}) {
10316: 	    $form->{'interface'}=~s/\W//gs;
10317: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10318: 	    $env{'browser.interface'}=$form->{'interface'};
10319: 	    foreach my $option ('imagesuppress','appletsuppress',
10320: 				'embedsuppress','fontenhance','blackwhite') {
10321: 		if (($form->{$option} eq 'true') ||
10322: 		    ($userenv{$option} eq 'on')) {
10323: 		    $initial_env{"browser.$option"} = "on";
10324: 		}
10325: 	    }
10326: 	}
10327: 
10328:         foreach my $tool ('aboutme','blog','portfolio') {
10329:             $userenv{'availabletools.'.$tool} = 
10330:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10331:         }
10332: 
10333:         foreach my $crstype ('official','unofficial') {
10334:             $userenv{'canrequest.'.$crstype} =
10335:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10336:                                                   'reload','requestcourses');
10337:         }
10338: 
10339: 	$env{'user.environment'} = "$lonids/$cookie.id";
10340: 	
10341: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10342: 		 &GDBM_WRCREAT(),0640)) {
10343: 	    &_add_to_env(\%disk_env,\%initial_env);
10344: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10345: 	    &_add_to_env(\%disk_env,$userroles);
10346: 	    if (ref($args->{'extra_env'})) {
10347: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10348: 	    }
10349: 	    untie(%disk_env);
10350: 	} else {
10351: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10352: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10353: 	    return 'error: '.$!;
10354: 	}
10355:     }
10356:     $env{'request.role'}='cm';
10357:     $env{'request.role.adv'}=$env{'user.adv'};
10358:     $env{'browser.type'}=$clientbrowser;
10359: 
10360:     return $cookie;
10361: 
10362: }
10363: 
10364: sub _add_to_env {
10365:     my ($idf,$env_data,$prefix) = @_;
10366:     if (ref($env_data) eq 'HASH') {
10367:         while (my ($key,$value) = each(%$env_data)) {
10368: 	    $idf->{$prefix.$key} = $value;
10369: 	    $env{$prefix.$key}   = $value;
10370:         }
10371:     }
10372: }
10373: 
10374: # --- Get the symbolic name of a problem and the url
10375: sub get_symb {
10376:     my ($request,$silent) = @_;
10377:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10378:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10379:     if ($symb eq '') {
10380:         if (!$silent) {
10381:             $request->print("Unable to handle ambiguous references:$url:.");
10382:             return ();
10383:         }
10384:     }
10385:     &Apache::lonenc::check_decrypt(\$symb);
10386:     return ($symb);
10387: }
10388: 
10389: # --------------------------------------------------------------Get annotation
10390: 
10391: sub get_annotation {
10392:     my ($symb,$enc) = @_;
10393: 
10394:     my $key = $symb;
10395:     if (!$enc) {
10396:         $key =
10397:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10398:     }
10399:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10400:     return $annotation{$key};
10401: }
10402: 
10403: sub clean_symb {
10404:     my ($symb,$delete_enc) = @_;
10405: 
10406:     &Apache::lonenc::check_decrypt(\$symb);
10407:     my $enc = $env{'request.enc'};
10408:     if ($delete_enc) {
10409:         delete($env{'request.enc'});
10410:     }
10411: 
10412:     return ($symb,$enc);
10413: }
10414: 
10415: =pod
10416: 
10417: =back
10418: 
10419: =cut
10420: 
10421: 1;
10422: __END__;
10423: 

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