File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.948: download - view: text, annotated - select for diffs
Mon Mar 8 14:51:14 2010 UTC (14 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_X, HEAD
- Changes to &get_domainconf().
  - Sanity checking that $domconfig{'login'}{'loginvia'}{$hostname} is a
    reference to a hash for lonHostID: $hostname.
  - Include setting for co-owners in autoenroll domain config in domain
    config items cached from %designhash.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.948 2010/03/08 14:51:14 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom;
  425: 	if (roleflag) { url+="&roles=1"; }
  426:         if (courseadvonly) { url+="&courseadvonly=1"; }
  427:         var title = 'Student_Browser';
  428:         var options = 'scrollbars=1,resizable=1,menubar=0';
  429:         options += ',width=700,height=600';
  430:         stdeditbrowser = open(url,title,options,'1');
  431:         stdeditbrowser.focus();
  432:     }
  433: // ]]>
  434: </script>
  435: ENDSTDBRW
  436: }
  437: 
  438: sub selectstudent_link {
  439:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  440:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  441:    if ($env{'request.course.id'}) {  
  442:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  443: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  444: 					'/'.$env{'request.course.sec'})) {
  445: 	   return '';
  446:        }
  447:        if ($courseadvonly)  {
  448:            $callargs .= ",'',1,1";
  449:        }
  450:        return '<span class="LC_nobreak">'.
  451:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  452:               &mt('Select User').'</a></span>';
  453:    }
  454:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  455:        $callargs .= ",1"; 
  456:        return '<span class="LC_nobreak">'.
  457:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  458:               &mt('Select User').'</a></span>';
  459:    }
  460:    return '';
  461: }
  462: 
  463: sub authorbrowser_javascript {
  464:     return <<"ENDAUTHORBRW";
  465: <script type="text/javascript" language="JavaScript">
  466: // <![CDATA[
  467: var stdeditbrowser;
  468: 
  469: function openauthorbrowser(formname,udom) {
  470:     var url = '/adm/pickauthor?';
  471:     url += 'form='+formname+'&roledom='+udom;
  472:     var title = 'Author_Browser';
  473:     var options = 'scrollbars=1,resizable=1,menubar=0';
  474:     options += ',width=700,height=600';
  475:     stdeditbrowser = open(url,title,options,'1');
  476:     stdeditbrowser.focus();
  477: }
  478: 
  479: // ]]>
  480: </script>
  481: ENDAUTHORBRW
  482: }
  483: 
  484: sub coursebrowser_javascript {
  485:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  486:     my $wintitle = 'Course_Browser';
  487:     if ($crstype eq 'Community') {
  488:         $wintitle = 'Community_Browser';
  489:     }
  490:     my $id_functions = &javascript_index_functions();
  491:     my $output = '
  492: <script type="text/javascript" language="JavaScript">
  493: // <![CDATA[
  494:     var stdeditbrowser;'."\n";
  495: 
  496:     $output .= <<"ENDSTDBRW";
  497:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  498:         var url = '/adm/pickcourse?';
  499:         var formid = getFormIdByName(formname);
  500:         var domainfilter = getDomainFromSelectbox(formname,udom);
  501:         if (domainfilter != null) {
  502:            if (domainfilter != '') {
  503:                url += 'domainfilter='+domainfilter+'&';
  504: 	   }
  505:         }
  506:         url += 'form=' + formname + '&cnumelement='+uname+
  507: 	                            '&cdomelement='+udom+
  508:                                     '&cnameelement='+desc;
  509:         if (extra_element !=null && extra_element != '') {
  510:             if (formname == 'rolechoice' || formname == 'studentform') {
  511:                 url += '&roleelement='+extra_element;
  512:                 if (domainfilter == null || domainfilter == '') {
  513:                     url += '&domainfilter='+extra_element;
  514:                 }
  515:             }
  516:             else {
  517:                 if (formname == 'portform') {
  518:                     url += '&setroles='+extra_element;
  519:                 } else {
  520:                     if (formname == 'rules') {
  521:                         url += '&fixeddom='+extra_element; 
  522:                     }
  523:                 }
  524:             }     
  525:         }
  526:         if (type != null && type != '') {
  527:             url += '&type='+type;
  528:         }
  529:         if (type_elem != null && type_elem != '') {
  530:             url += '&typeelement='+type_elem;
  531:         }
  532:         if (formname == 'ccrs') {
  533:             var ownername = document.forms[formid].ccuname.value;
  534:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  535:             url += '&cloner='+ownername+':'+ownerdom;
  536:         }
  537:         if (multflag !=null && multflag != '') {
  538:             url += '&multiple='+multflag;
  539:         }
  540:         var title = '$wintitle';
  541:         var options = 'scrollbars=1,resizable=1,menubar=0';
  542:         options += ',width=700,height=600';
  543:         stdeditbrowser = open(url,title,options,'1');
  544:         stdeditbrowser.focus();
  545:     }
  546: $id_functions
  547: ENDSTDBRW
  548:     if (($sec_element ne '') || ($role_element ne '')) {
  549:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  550:     }
  551:     $output .= '
  552: // ]]>
  553: </script>';
  554:     return $output;
  555: }
  556: 
  557: sub javascript_index_functions {
  558:     return <<"ENDJS";
  559: 
  560: function getFormIdByName(formname) {
  561:     for (var i=0;i<document.forms.length;i++) {
  562:         if (document.forms[i].name == formname) {
  563:             return i;
  564:         }
  565:     }
  566:     return -1;
  567: }
  568: 
  569: function getIndexByName(formid,item) {
  570:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  571:         if (document.forms[formid].elements[i].name == item) {
  572:             return i;
  573:         }
  574:     }
  575:     return -1;
  576: }
  577: 
  578: function getDomainFromSelectbox(formname,udom) {
  579:     var userdom;
  580:     var formid = getFormIdByName(formname);
  581:     if (formid > -1) {
  582:         var domid = getIndexByName(formid,udom);
  583:         if (domid > -1) {
  584:             if (document.forms[formid].elements[domid].type == 'select-one') {
  585:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  586:             }
  587:             if (document.forms[formid].elements[domid].type == 'hidden') {
  588:                 userdom=document.forms[formid].elements[domid].value;
  589:             }
  590:         }
  591:     }
  592:     return userdom;
  593: }
  594: 
  595: ENDJS
  596: 
  597: }
  598: 
  599: sub userbrowser_javascript {
  600:     my $id_functions = &javascript_index_functions();
  601:     return <<"ENDUSERBRW";
  602: 
  603: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  604:     var url = '/adm/pickuser?';
  605:     var userdom = getDomainFromSelectbox(formname,udom);
  606:     if (userdom != null) {
  607:        if (userdom != '') {
  608:            url += 'srchdom='+userdom+'&';
  609:        }
  610:     }
  611:     url += 'form=' + formname + '&unameelement='+uname+
  612:                                 '&udomelement='+udom+
  613:                                 '&ulastelement='+ulast+
  614:                                 '&ufirstelement='+ufirst+
  615:                                 '&uemailelement='+uemail+
  616:                                 '&hideudomelement='+hideudom+
  617:                                 '&coursedom='+crsdom;
  618:     if ((caller != null) && (caller != undefined)) {
  619:         url += '&caller='+caller;
  620:     }
  621:     var title = 'User_Browser';
  622:     var options = 'scrollbars=1,resizable=1,menubar=0';
  623:     options += ',width=700,height=600';
  624:     var stdeditbrowser = open(url,title,options,'1');
  625:     stdeditbrowser.focus();
  626: }
  627: 
  628: function fix_domain (formname,udom,origdom,uname) {
  629:     var formid = getFormIdByName(formname);
  630:     if (formid > -1) {
  631:         var unameid = getIndexByName(formid,uname);
  632:         var domid = getIndexByName(formid,udom);
  633:         var hidedomid = getIndexByName(formid,origdom);
  634:         if (hidedomid > -1) {
  635:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  636:             var unameval = document.forms[formid].elements[unameid].value;
  637:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  638:                 if (domid > -1) {
  639:                     var slct = document.forms[formid].elements[domid];
  640:                     if (slct.type == 'select-one') {
  641:                         var i;
  642:                         for (i=0;i<slct.length;i++) {
  643:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  644:                         }
  645:                     }
  646:                     if (slct.type == 'hidden') {
  647:                         slct.value = fixeddom;
  648:                     }
  649:                 }
  650:             }
  651:         }
  652:     }
  653:     return;
  654: }
  655: 
  656: $id_functions
  657: ENDUSERBRW
  658: }
  659: 
  660: sub setsec_javascript {
  661:     my ($sec_element,$formname,$role_element) = @_;
  662:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  663:         $communityrolestr);
  664:     if ($role_element ne '') {
  665:         my @allroles = ('st','ta','ep','in','ad');
  666:         foreach my $crstype ('Course','Community') {
  667:             if ($crstype eq 'Community') {
  668:                 foreach my $role (@allroles) {
  669:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  670:                 }
  671:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  672:             } else {
  673:                 foreach my $role (@allroles) {
  674:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  675:                 }
  676:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  677:             }
  678:         }
  679:         $rolestr = '"'.join('","',@allroles).'"';
  680:         $courserolestr = '"'.join('","',@courserolenames).'"';
  681:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  682:     }
  683:     my $setsections = qq|
  684: function setSect(sectionlist) {
  685:     var sectionsArray = new Array();
  686:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  687:         sectionsArray = sectionlist.split(",");
  688:     }
  689:     var numSections = sectionsArray.length;
  690:     document.$formname.$sec_element.length = 0;
  691:     if (numSections == 0) {
  692:         document.$formname.$sec_element.multiple=false;
  693:         document.$formname.$sec_element.size=1;
  694:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  695:     } else {
  696:         if (numSections == 1) {
  697:             document.$formname.$sec_element.multiple=false;
  698:             document.$formname.$sec_element.size=1;
  699:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  700:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  701:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  702:         } else {
  703:             for (var i=0; i<numSections; i++) {
  704:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  705:             }
  706:             document.$formname.$sec_element.multiple=true
  707:             if (numSections < 3) {
  708:                 document.$formname.$sec_element.size=numSections;
  709:             } else {
  710:                 document.$formname.$sec_element.size=3;
  711:             }
  712:             document.$formname.$sec_element.options[0].selected = false
  713:         }
  714:     }
  715: }
  716: 
  717: function setRole(crstype) {
  718: |;
  719:     if ($role_element eq '') {
  720:         $setsections .= '    return;
  721: }
  722: ';
  723:     } else {
  724:         $setsections .= qq|
  725:     var elementLength = document.$formname.$role_element.length;
  726:     var allroles = Array($rolestr);
  727:     var courserolenames = Array($courserolestr);
  728:     var communityrolenames = Array($communityrolestr);
  729:     if (elementLength != undefined) {
  730:         if (document.$formname.$role_element.options[5].value == 'cc') {
  731:             if (crstype == 'Course') {
  732:                 return;
  733:             } else {
  734:                 allroles[5] = 'co';
  735:                 for (var i=0; i<6; i++) {
  736:                     document.$formname.$role_element.options[i].value = allroles[i];
  737:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  738:                 }
  739:             }
  740:         } else {
  741:             if (crstype == 'Community') {
  742:                 return;
  743:             } else {
  744:                 allroles[5] = 'cc';
  745:                 for (var i=0; i<6; i++) {
  746:                     document.$formname.$role_element.options[i].value = allroles[i];
  747:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  748:                 }
  749:             }
  750:         }
  751:     }
  752:     return;
  753: }
  754: |;
  755:     }
  756:     return $setsections;
  757: }
  758: 
  759: sub selectcourse_link {
  760:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  761:        $typeelement) = @_;
  762:    my $type = $selecttype;
  763:    my $linktext = &mt('Select Course');
  764:    if ($selecttype eq 'Community') {
  765:        $linktext = &mt('Select Community');
  766:    } elsif ($selecttype eq 'Course/Community') {
  767:        $linktext = &mt('Select Course/Community');
  768:        $type = '';
  769:    }
  770:    return '<span class="LC_nobreak">'
  771:          ."<a href='"
  772:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  773:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  774:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  775:          ."'>".$linktext.'</a>'
  776:          .'</span>';
  777: }
  778: 
  779: sub selectauthor_link {
  780:    my ($form,$udom)=@_;
  781:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  782:           &mt('Select Author').'</a>';
  783: }
  784: 
  785: sub selectuser_link {
  786:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  787:         $coursedom,$linktext,$caller) = @_;
  788:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  789:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  790:            ');">'.$linktext.'</a>';
  791: }
  792: 
  793: sub check_uncheck_jscript {
  794:     my $jscript = <<"ENDSCRT";
  795: function checkAll(field) {
  796:     if (field.length > 0) {
  797:         for (i = 0; i < field.length; i++) {
  798:             field[i].checked = true ;
  799:         }
  800:     } else {
  801:         field.checked = true
  802:     }
  803: }
  804:  
  805: function uncheckAll(field) {
  806:     if (field.length > 0) {
  807:         for (i = 0; i < field.length; i++) {
  808:             field[i].checked = false ;
  809:         }
  810:     } else {
  811:         field.checked = false ;
  812:     }
  813: }
  814: ENDSCRT
  815:     return $jscript;
  816: }
  817: 
  818: sub select_timezone {
  819:    my ($name,$selected,$onchange,$includeempty)=@_;
  820:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  821:    if ($includeempty) {
  822:        $output .= '<option value=""';
  823:        if (($selected eq '') || ($selected eq 'local')) {
  824:            $output .= ' selected="selected" ';
  825:        }
  826:        $output .= '> </option>';
  827:    }
  828:    my @timezones = DateTime::TimeZone->all_names;
  829:    foreach my $tzone (@timezones) {
  830:        $output.= '<option value="'.$tzone.'"';
  831:        if ($tzone eq $selected) {
  832:            $output.=' selected="selected"';
  833:        }
  834:        $output.=">$tzone</option>\n";
  835:    }
  836:    $output.="</select>";
  837:    return $output;
  838: }
  839: 
  840: sub select_datelocale {
  841:     my ($name,$selected,$onchange,$includeempty)=@_;
  842:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  843:     if ($includeempty) {
  844:         $output .= '<option value=""';
  845:         if ($selected eq '') {
  846:             $output .= ' selected="selected" ';
  847:         }
  848:         $output .= '> </option>';
  849:     }
  850:     my (@possibles,%locale_names);
  851:     my @locales = DateTime::Locale::Catalog::Locales;
  852:     foreach my $locale (@locales) {
  853:         if (ref($locale) eq 'HASH') {
  854:             my $id = $locale->{'id'};
  855:             if ($id ne '') {
  856:                 my $en_terr = $locale->{'en_territory'};
  857:                 my $native_terr = $locale->{'native_territory'};
  858:                 my @languages = &Apache::lonlocal::preferred_languages();
  859:                 if (grep(/^en$/,@languages) || !@languages) {
  860:                     if ($en_terr ne '') {
  861:                         $locale_names{$id} = '('.$en_terr.')';
  862:                     } elsif ($native_terr ne '') {
  863:                         $locale_names{$id} = $native_terr;
  864:                     }
  865:                 } else {
  866:                     if ($native_terr ne '') {
  867:                         $locale_names{$id} = $native_terr.' ';
  868:                     } elsif ($en_terr ne '') {
  869:                         $locale_names{$id} = '('.$en_terr.')';
  870:                     }
  871:                 }
  872:                 push (@possibles,$id);
  873:             }
  874:         }
  875:     }
  876:     foreach my $item (sort(@possibles)) {
  877:         $output.= '<option value="'.$item.'"';
  878:         if ($item eq $selected) {
  879:             $output.=' selected="selected"';
  880:         }
  881:         $output.=">$item";
  882:         if ($locale_names{$item} ne '') {
  883:             $output.="  $locale_names{$item}</option>\n";
  884:         }
  885:         $output.="</option>\n";
  886:     }
  887:     $output.="</select>";
  888:     return $output;
  889: }
  890: 
  891: sub select_language {
  892:     my ($name,$selected,$includeempty) = @_;
  893:     my %langchoices;
  894:     if ($includeempty) {
  895:         %langchoices = ('' => 'No language preference');
  896:     }
  897:     foreach my $id (&languageids()) {
  898:         my $code = &supportedlanguagecode($id);
  899:         if ($code) {
  900:             $langchoices{$code} = &plainlanguagedescription($id);
  901:         }
  902:     }
  903:     return &select_form($selected,$name,%langchoices);
  904: }
  905: 
  906: =pod
  907: 
  908: =item * &linked_select_forms(...)
  909: 
  910: linked_select_forms returns a string containing a <script></script> block
  911: and html for two <select> menus.  The select menus will be linked in that
  912: changing the value of the first menu will result in new values being placed
  913: in the second menu.  The values in the select menu will appear in alphabetical
  914: order unless a defined order is provided.
  915: 
  916: linked_select_forms takes the following ordered inputs:
  917: 
  918: =over 4
  919: 
  920: =item * $formname, the name of the <form> tag
  921: 
  922: =item * $middletext, the text which appears between the <select> tags
  923: 
  924: =item * $firstdefault, the default value for the first menu
  925: 
  926: =item * $firstselectname, the name of the first <select> tag
  927: 
  928: =item * $secondselectname, the name of the second <select> tag
  929: 
  930: =item * $hashref, a reference to a hash containing the data for the menus.
  931: 
  932: =item * $menuorder, the order of values in the first menu
  933: 
  934: =back 
  935: 
  936: Below is an example of such a hash.  Only the 'text', 'default', and 
  937: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  938: values for the first select menu.  The text that coincides with the 
  939: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  940: and text for the second menu are given in the hash pointed to by 
  941: $menu{$choice1}->{'select2'}.  
  942: 
  943:  my %menu = ( A1 => { text =>"Choice A1" ,
  944:                        default => "B3",
  945:                        select2 => { 
  946:                            B1 => "Choice B1",
  947:                            B2 => "Choice B2",
  948:                            B3 => "Choice B3",
  949:                            B4 => "Choice B4"
  950:                            },
  951:                        order => ['B4','B3','B1','B2'],
  952:                    },
  953:                A2 => { text =>"Choice A2" ,
  954:                        default => "C2",
  955:                        select2 => { 
  956:                            C1 => "Choice C1",
  957:                            C2 => "Choice C2",
  958:                            C3 => "Choice C3"
  959:                            },
  960:                        order => ['C2','C1','C3'],
  961:                    },
  962:                A3 => { text =>"Choice A3" ,
  963:                        default => "D6",
  964:                        select2 => { 
  965:                            D1 => "Choice D1",
  966:                            D2 => "Choice D2",
  967:                            D3 => "Choice D3",
  968:                            D4 => "Choice D4",
  969:                            D5 => "Choice D5",
  970:                            D6 => "Choice D6",
  971:                            D7 => "Choice D7"
  972:                            },
  973:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  974:                    }
  975:                );
  976: 
  977: =cut
  978: 
  979: sub linked_select_forms {
  980:     my ($formname,
  981:         $middletext,
  982:         $firstdefault,
  983:         $firstselectname,
  984:         $secondselectname, 
  985:         $hashref,
  986:         $menuorder,
  987:         ) = @_;
  988:     my $second = "document.$formname.$secondselectname";
  989:     my $first = "document.$formname.$firstselectname";
  990:     # output the javascript to do the changing
  991:     my $result = '';
  992:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  993:     $result.="// <![CDATA[\n";
  994:     $result.="var select2data = new Object();\n";
  995:     $" = '","';
  996:     my $debug = '';
  997:     foreach my $s1 (sort(keys(%$hashref))) {
  998:         $result.="select2data.d_$s1 = new Object();\n";        
  999:         $result.="select2data.d_$s1.def = new String('".
 1000:             $hashref->{$s1}->{'default'}."');\n";
 1001:         $result.="select2data.d_$s1.values = new Array(";
 1002:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1003:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1004:             @s2values = @{$hashref->{$s1}->{'order'}};
 1005:         }
 1006:         $result.="\"@s2values\");\n";
 1007:         $result.="select2data.d_$s1.texts = new Array(";        
 1008:         my @s2texts;
 1009:         foreach my $value (@s2values) {
 1010:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1011:         }
 1012:         $result.="\"@s2texts\");\n";
 1013:     }
 1014:     $"=' ';
 1015:     $result.= <<"END";
 1016: 
 1017: function select1_changed() {
 1018:     // Determine new choice
 1019:     var newvalue = "d_" + $first.value;
 1020:     // update select2
 1021:     var values     = select2data[newvalue].values;
 1022:     var texts      = select2data[newvalue].texts;
 1023:     var select2def = select2data[newvalue].def;
 1024:     var i;
 1025:     // out with the old
 1026:     for (i = 0; i < $second.options.length; i++) {
 1027:         $second.options[i] = null;
 1028:     }
 1029:     // in with the nuclear
 1030:     for (i=0;i<values.length; i++) {
 1031:         $second.options[i] = new Option(values[i]);
 1032:         $second.options[i].value = values[i];
 1033:         $second.options[i].text = texts[i];
 1034:         if (values[i] == select2def) {
 1035:             $second.options[i].selected = true;
 1036:         }
 1037:     }
 1038: }
 1039: // ]]>
 1040: </script>
 1041: END
 1042:     # output the initial values for the selection lists
 1043:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1044:     my @order = sort(keys(%{$hashref}));
 1045:     if (ref($menuorder) eq 'ARRAY') {
 1046:         @order = @{$menuorder};
 1047:     }
 1048:     foreach my $value (@order) {
 1049:         $result.="    <option value=\"$value\" ";
 1050:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1051:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1052:     }
 1053:     $result .= "</select>\n";
 1054:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1055:     $result .= $middletext;
 1056:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1057:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1058:     
 1059:     my @secondorder = sort(keys(%select2));
 1060:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1061:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1062:     }
 1063:     foreach my $value (@secondorder) {
 1064:         $result.="    <option value=\"$value\" ";        
 1065:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1066:         $result.=">".&mt($select2{$value})."</option>\n";
 1067:     }
 1068:     $result .= "</select>\n";
 1069:     #    return $debug;
 1070:     return $result;
 1071: }   #  end of sub linked_select_forms {
 1072: 
 1073: =pod
 1074: 
 1075: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
 1076: 
 1077: Returns a string corresponding to an HTML link to the given help
 1078: $topic, where $topic corresponds to the name of a .tex file in
 1079: /home/httpd/html/adm/help/tex, with underscores replaced by
 1080: spaces. 
 1081: 
 1082: $text will optionally be linked to the same topic, allowing you to
 1083: link text in addition to the graphic. If you do not want to link
 1084: text, but wish to specify one of the later parameters, pass an
 1085: empty string. 
 1086: 
 1087: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1088: the link will not open a new window. If false, the link will open
 1089: a new window using Javascript. (Default is false.) 
 1090: 
 1091: $width and $height are optional numerical parameters that will
 1092: override the width and height of the popped up window, which may
 1093: be useful for certain help topics with big pictures included. 
 1094: 
 1095: =cut
 1096: 
 1097: sub help_open_topic {
 1098:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1099:     $text = "" if (not defined $text);
 1100:     $stayOnPage = 0 if (not defined $stayOnPage);
 1101:     $width = 350 if (not defined $width);
 1102:     $height = 400 if (not defined $height);
 1103:     my $filename = $topic;
 1104:     $filename =~ s/ /_/g;
 1105: 
 1106:     my $template = "";
 1107:     my $link;
 1108:     
 1109:     $topic=~s/\W/\_/g;
 1110: 
 1111:     if (!$stayOnPage) {
 1112: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1113:     } else {
 1114: 	$link = "/adm/help/${filename}.hlp";
 1115:     }
 1116: 
 1117:     # Add the text
 1118:     if ($text ne "") {	
 1119: 	$template.='<span class="LC_help_open_topic">'
 1120:                   .'<a target="_top" href="'.$link.'">'
 1121:                   .$text.'</a>';
 1122:     }
 1123: 
 1124:     # (Always) Add the graphic
 1125:     my $title = &mt('Online Help');
 1126:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1127:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1128:               .'<img src="'.$helpicon.'" border="0"'
 1129:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1130:               .' title="'.$title.'" style="vertical-align:middle;"' 
 1131:               .' /></a>';
 1132:     if ($text ne "") {	
 1133:         $template.='</span>';
 1134:     }
 1135:     return $template;
 1136: 
 1137: }
 1138: 
 1139: # This is a quicky function for Latex cheatsheet editing, since it 
 1140: # appears in at least four places
 1141: sub helpLatexCheatsheet {
 1142:     my ($topic,$text,$not_author) = @_;
 1143:     my $out;
 1144:     my $addOther = '';
 1145:     if ($topic) {
 1146: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1147: 							       undef, undef, 600).
 1148: 								   '</span> ';
 1149:     }
 1150:     $out = '<span>' # Start cheatsheet
 1151: 	  .$addOther
 1152:           .'<span>'
 1153: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1154: 					       undef,undef,600)
 1155: 	  .'</span> <span>'
 1156: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1157: 					       undef,undef,600)
 1158: 	  .'</span>';
 1159:     unless ($not_author) {
 1160:         $out .= ' <span>'
 1161: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1162: 	                                            undef,undef,600)
 1163: 	       .'</span>';
 1164:     }
 1165:     $out .= '</span>'; # End cheatsheet
 1166:     return $out;
 1167: }
 1168: 
 1169: sub general_help {
 1170:     my $helptopic='Student_Intro';
 1171:     if ($env{'request.role'}=~/^(ca|au)/) {
 1172: 	$helptopic='Authoring_Intro';
 1173:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1174: 	$helptopic='Course_Coordination_Intro';
 1175:     } elsif ($env{'request.role'}=~/^dc/) {
 1176:         $helptopic='Domain_Coordination_Intro';
 1177:     }
 1178:     return $helptopic;
 1179: }
 1180: 
 1181: sub update_help_link {
 1182:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1183:     my $origurl = $ENV{'REQUEST_URI'};
 1184:     $origurl=~s|^/~|/priv/|;
 1185:     my $timestamp = time;
 1186:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1187:         $$datum = &escape($$datum);
 1188:     }
 1189: 
 1190:     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";
 1191:     my $output .= <<"ENDOUTPUT";
 1192: <script type="text/javascript">
 1193: // <![CDATA[
 1194: banner_link = '$banner_link';
 1195: // ]]>
 1196: </script>
 1197: ENDOUTPUT
 1198:     return $output;
 1199: }
 1200: 
 1201: # now just updates the help link and generates a blue icon
 1202: sub help_open_menu {
 1203:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1204: 	= @_;    
 1205:     $stayOnPage = 0 if (not defined $stayOnPage);
 1206:     # only use pop-up help (stayOnPage == 0)
 1207:     # if environment.remote is on (using remote control UI)
 1208:     if ($env{'environment.remote'} eq 'off' ) {
 1209:         $stayOnPage=1;
 1210:     }
 1211:     my $output;
 1212:     if ($component_help) {
 1213: 	if (!$text) {
 1214: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1215: 				       $width,$height);
 1216: 	} else {
 1217: 	    my $help_text;
 1218: 	    $help_text=&unescape($topic);
 1219: 	    $output='<table><tr><td>'.
 1220: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1221: 				 $width,$height).'</td></tr></table>';
 1222: 	}
 1223:     }
 1224:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1225:     return $output.$banner_link;
 1226: }
 1227: 
 1228: sub top_nav_help {
 1229:     my ($text) = @_;
 1230:     $text = &mt($text);
 1231:     my $stay_on_page = 
 1232: 	($env{'environment.remote'} eq 'off' );
 1233:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1234: 	                     : "javascript:helpMenu('open')";
 1235:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1236: 
 1237:     my $title = &mt('Get help');
 1238: 
 1239:     return <<"END";
 1240: $banner_link
 1241:  <a href="$link" title="$title">$text</a>
 1242: END
 1243: }
 1244: 
 1245: sub help_menu_js {
 1246:     my ($text) = @_;
 1247: 
 1248:     my $stayOnPage = 
 1249: 	($env{'environment.remote'} eq 'off' );
 1250: 
 1251:     my $width = 620;
 1252:     my $height = 600;
 1253:     my $helptopic=&general_help();
 1254:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1255:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1256:     my $start_page =
 1257:         &Apache::loncommon::start_page('Help Menu', undef,
 1258: 				       {'frameset'    => 1,
 1259: 					'js_ready'    => 1,
 1260: 					'add_entries' => {
 1261: 					    'border' => '0',
 1262: 					    'rows'   => "110,*",},});
 1263:     my $end_page =
 1264:         &Apache::loncommon::end_page({'frameset' => 1,
 1265: 				      'js_ready' => 1,});
 1266: 
 1267:     my $template .= <<"ENDTEMPLATE";
 1268: <script type="text/javascript">
 1269: // <![CDATA[
 1270: // <!-- BEGIN LON-CAPA Internal
 1271: var banner_link = '';
 1272: function helpMenu(target) {
 1273:     var caller = this;
 1274:     if (target == 'open') {
 1275:         var newWindow = null;
 1276:         try {
 1277:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1278:         }
 1279:         catch(error) {
 1280:             writeHelp(caller);
 1281:             return;
 1282:         }
 1283:         if (newWindow) {
 1284:             caller = newWindow;
 1285:         }
 1286:     }
 1287:     writeHelp(caller);
 1288:     return;
 1289: }
 1290: function writeHelp(caller) {
 1291:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1292:     caller.document.close()
 1293:     caller.focus()
 1294: }
 1295: // END LON-CAPA Internal -->
 1296: // ]]>
 1297: </script>
 1298: ENDTEMPLATE
 1299:     return $template;
 1300: }
 1301: 
 1302: sub help_open_bug {
 1303:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1304:     unless ($env{'user.adv'}) { return ''; }
 1305:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1306:     $text = "" if (not defined $text);
 1307:     $stayOnPage = 0 if (not defined $stayOnPage);
 1308:     if ($env{'environment.remote'} eq 'off' ) {
 1309: 	$stayOnPage=1;
 1310:     }
 1311:     $width = 600 if (not defined $width);
 1312:     $height = 600 if (not defined $height);
 1313: 
 1314:     $topic=~s/\W+/\+/g;
 1315:     my $link='';
 1316:     my $template='';
 1317:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1318: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1319:     if (!$stayOnPage)
 1320:     {
 1321: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1322:     }
 1323:     else
 1324:     {
 1325: 	$link = $url;
 1326:     }
 1327:     # Add the text
 1328:     if ($text ne "")
 1329:     {
 1330: 	$template .= 
 1331:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1332:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1333:     }
 1334: 
 1335:     # Add the graphic
 1336:     my $title = &mt('Report a Bug');
 1337:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1338:     $template .= <<"ENDTEMPLATE";
 1339:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1340: ENDTEMPLATE
 1341:     if ($text ne '') { $template.='</td></tr></table>' };
 1342:     return $template;
 1343: 
 1344: }
 1345: 
 1346: sub help_open_faq {
 1347:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1348:     unless ($env{'user.adv'}) { return ''; }
 1349:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1350:     $text = "" if (not defined $text);
 1351:     $stayOnPage = 0 if (not defined $stayOnPage);
 1352:     if ($env{'environment.remote'} eq 'off' ) {
 1353: 	$stayOnPage=1;
 1354:     }
 1355:     $width = 350 if (not defined $width);
 1356:     $height = 400 if (not defined $height);
 1357: 
 1358:     $topic=~s/\W+/\+/g;
 1359:     my $link='';
 1360:     my $template='';
 1361:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1362:     if (!$stayOnPage)
 1363:     {
 1364: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1365:     }
 1366:     else
 1367:     {
 1368: 	$link = $url;
 1369:     }
 1370: 
 1371:     # Add the text
 1372:     if ($text ne "")
 1373:     {
 1374: 	$template .= 
 1375:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1376:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1377:     }
 1378: 
 1379:     # Add the graphic
 1380:     my $title = &mt('View the FAQ');
 1381:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1382:     $template .= <<"ENDTEMPLATE";
 1383:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1384: ENDTEMPLATE
 1385:     if ($text ne '') { $template.='</td></tr></table>' };
 1386:     return $template;
 1387: 
 1388: }
 1389: 
 1390: ###############################################################
 1391: ###############################################################
 1392: 
 1393: =pod
 1394: 
 1395: =item * &change_content_javascript():
 1396: 
 1397: This and the next function allow you to create small sections of an
 1398: otherwise static HTML page that you can update on the fly with
 1399: Javascript, even in Netscape 4.
 1400: 
 1401: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1402: must be written to the HTML page once. It will prove the Javascript
 1403: function "change(name, content)". Calling the change function with the
 1404: name of the section 
 1405: you want to update, matching the name passed to C<changable_area>, and
 1406: the new content you want to put in there, will put the content into
 1407: that area.
 1408: 
 1409: B<Note>: Netscape 4 only reserves enough space for the changable area
 1410: to contain room for the original contents. You need to "make space"
 1411: for whatever changes you wish to make, and be B<sure> to check your
 1412: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1413: it's adequate for updating a one-line status display, but little more.
 1414: This script will set the space to 100% width, so you only need to
 1415: worry about height in Netscape 4.
 1416: 
 1417: Modern browsers are much less limiting, and if you can commit to the
 1418: user not using Netscape 4, this feature may be used freely with
 1419: pretty much any HTML.
 1420: 
 1421: =cut
 1422: 
 1423: sub change_content_javascript {
 1424:     # If we're on Netscape 4, we need to use Layer-based code
 1425:     if ($env{'browser.type'} eq 'netscape' &&
 1426: 	$env{'browser.version'} =~ /^4\./) {
 1427: 	return (<<NETSCAPE4);
 1428: 	function change(name, content) {
 1429: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1430: 	    doc.open();
 1431: 	    doc.write(content);
 1432: 	    doc.close();
 1433: 	}
 1434: NETSCAPE4
 1435:     } else {
 1436: 	# Otherwise, we need to use semi-standards-compliant code
 1437: 	# (technically, "innerHTML" isn't standard but the equivalent
 1438: 	# is really scary, and every useful browser supports it
 1439: 	return (<<DOMBASED);
 1440: 	function change(name, content) {
 1441: 	    element = document.getElementById(name);
 1442: 	    element.innerHTML = content;
 1443: 	}
 1444: DOMBASED
 1445:     }
 1446: }
 1447: 
 1448: =pod
 1449: 
 1450: =item * &changable_area($name,$origContent):
 1451: 
 1452: This provides a "changable area" that can be modified on the fly via
 1453: the Javascript code provided in C<change_content_javascript>. $name is
 1454: the name you will use to reference the area later; do not repeat the
 1455: same name on a given HTML page more then once. $origContent is what
 1456: the area will originally contain, which can be left blank.
 1457: 
 1458: =cut
 1459: 
 1460: sub changable_area {
 1461:     my ($name, $origContent) = @_;
 1462: 
 1463:     if ($env{'browser.type'} eq 'netscape' &&
 1464: 	$env{'browser.version'} =~ /^4\./) {
 1465: 	# If this is netscape 4, we need to use the Layer tag
 1466: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1467:     } else {
 1468: 	return "<span id='$name'>$origContent</span>";
 1469:     }
 1470: }
 1471: 
 1472: =pod
 1473: 
 1474: =item * &viewport_geometry_js 
 1475: 
 1476: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1477: 
 1478: =cut
 1479: 
 1480: 
 1481: sub viewport_geometry_js { 
 1482:     return <<"GEOMETRY";
 1483: var Geometry = {};
 1484: function init_geometry() {
 1485:     if (Geometry.init) { return };
 1486:     Geometry.init=1;
 1487:     if (window.innerHeight) {
 1488:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1489:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1490:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1491:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1492:     }
 1493:     else if (document.documentElement && document.documentElement.clientHeight) {
 1494:         Geometry.getViewportHeight =
 1495:             function() { return document.documentElement.clientHeight; };
 1496:         Geometry.getViewportWidth =
 1497:             function() { return document.documentElement.clientWidth; };
 1498: 
 1499:         Geometry.getHorizontalScroll =
 1500:             function() { return document.documentElement.scrollLeft; };
 1501:         Geometry.getVerticalScroll =
 1502:             function() { return document.documentElement.scrollTop; };
 1503:     }
 1504:     else if (document.body.clientHeight) {
 1505:         Geometry.getViewportHeight =
 1506:             function() { return document.body.clientHeight; };
 1507:         Geometry.getViewportWidth =
 1508:             function() { return document.body.clientWidth; };
 1509:         Geometry.getHorizontalScroll =
 1510:             function() { return document.body.scrollLeft; };
 1511:         Geometry.getVerticalScroll =
 1512:             function() { return document.body.scrollTop; };
 1513:     }
 1514: }
 1515: 
 1516: GEOMETRY
 1517: }
 1518: 
 1519: =pod
 1520: 
 1521: =item * &viewport_size_js()
 1522: 
 1523: 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. 
 1524: 
 1525: =cut
 1526: 
 1527: sub viewport_size_js {
 1528:     my $geometry = &viewport_geometry_js();
 1529:     return <<"DIMS";
 1530: 
 1531: $geometry
 1532: 
 1533: function getViewportDims(width,height) {
 1534:     init_geometry();
 1535:     width.value = Geometry.getViewportWidth();
 1536:     height.value = Geometry.getViewportHeight();
 1537:     return;
 1538: }
 1539: 
 1540: DIMS
 1541: }
 1542: 
 1543: =pod
 1544: 
 1545: =item * &resize_textarea_js()
 1546: 
 1547: emits the needed javascript to resize a textarea to be as big as possible
 1548: 
 1549: creates a function resize_textrea that takes two IDs first should be
 1550: the id of the element to resize, second should be the id of a div that
 1551: surrounds everything that comes after the textarea, this routine needs
 1552: to be attached to the <body> for the onload and onresize events.
 1553: 
 1554: =back
 1555: 
 1556: =cut
 1557: 
 1558: sub resize_textarea_js {
 1559:     my $geometry = &viewport_geometry_js();
 1560:     return <<"RESIZE";
 1561:     <script type="text/javascript">
 1562: // <![CDATA[
 1563: $geometry
 1564: 
 1565: function getX(element) {
 1566:     var x = 0;
 1567:     while (element) {
 1568: 	x += element.offsetLeft;
 1569: 	element = element.offsetParent;
 1570:     }
 1571:     return x;
 1572: }
 1573: function getY(element) {
 1574:     var y = 0;
 1575:     while (element) {
 1576: 	y += element.offsetTop;
 1577: 	element = element.offsetParent;
 1578:     }
 1579:     return y;
 1580: }
 1581: 
 1582: 
 1583: function resize_textarea(textarea_id,bottom_id) {
 1584:     init_geometry();
 1585:     var textarea        = document.getElementById(textarea_id);
 1586:     //alert(textarea);
 1587: 
 1588:     var textarea_top    = getY(textarea);
 1589:     var textarea_height = textarea.offsetHeight;
 1590:     var bottom          = document.getElementById(bottom_id);
 1591:     var bottom_top      = getY(bottom);
 1592:     var bottom_height   = bottom.offsetHeight;
 1593:     var window_height   = Geometry.getViewportHeight();
 1594:     var fudge           = 23;
 1595:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1596:     if (new_height < 300) {
 1597: 	new_height = 300;
 1598:     }
 1599:     textarea.style.height=new_height+'px';
 1600: }
 1601: // ]]>
 1602: </script>
 1603: RESIZE
 1604: 
 1605: }
 1606: 
 1607: =pod
 1608: 
 1609: =head1 Excel and CSV file utility routines
 1610: 
 1611: =over 4
 1612: 
 1613: =cut
 1614: 
 1615: ###############################################################
 1616: ###############################################################
 1617: 
 1618: =pod
 1619: 
 1620: =item * &csv_translate($text) 
 1621: 
 1622: Translate $text to allow it to be output as a 'comma separated values' 
 1623: format.
 1624: 
 1625: =cut
 1626: 
 1627: ###############################################################
 1628: ###############################################################
 1629: sub csv_translate {
 1630:     my $text = shift;
 1631:     $text =~ s/\"/\"\"/g;
 1632:     $text =~ s/\n/ /g;
 1633:     return $text;
 1634: }
 1635: 
 1636: ###############################################################
 1637: ###############################################################
 1638: 
 1639: =pod
 1640: 
 1641: =item * &define_excel_formats()
 1642: 
 1643: Define some commonly used Excel cell formats.
 1644: 
 1645: Currently supported formats:
 1646: 
 1647: =over 4
 1648: 
 1649: =item header
 1650: 
 1651: =item bold
 1652: 
 1653: =item h1
 1654: 
 1655: =item h2
 1656: 
 1657: =item h3
 1658: 
 1659: =item h4
 1660: 
 1661: =item i
 1662: 
 1663: =item date
 1664: 
 1665: =back
 1666: 
 1667: Inputs: $workbook
 1668: 
 1669: Returns: $format, a hash reference.
 1670: 
 1671: =cut
 1672: 
 1673: ###############################################################
 1674: ###############################################################
 1675: sub define_excel_formats {
 1676:     my ($workbook) = @_;
 1677:     my $format;
 1678:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1679:                                                 bottom    => 1,
 1680:                                                 align     => 'center');
 1681:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1682:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1683:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1684:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1685:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1686:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1687:     $format->{'date'} = $workbook->add_format(num_format=>
 1688:                                             'mm/dd/yyyy hh:mm:ss');
 1689:     return $format;
 1690: }
 1691: 
 1692: ###############################################################
 1693: ###############################################################
 1694: 
 1695: =pod
 1696: 
 1697: =item * &create_workbook()
 1698: 
 1699: Create an Excel worksheet.  If it fails, output message on the
 1700: request object and return undefs.
 1701: 
 1702: Inputs: Apache request object
 1703: 
 1704: Returns (undef) on failure, 
 1705:     Excel worksheet object, scalar with filename, and formats 
 1706:     from &Apache::loncommon::define_excel_formats on success
 1707: 
 1708: =cut
 1709: 
 1710: ###############################################################
 1711: ###############################################################
 1712: sub create_workbook {
 1713:     my ($r) = @_;
 1714:         #
 1715:     # Create the excel spreadsheet
 1716:     my $filename = '/prtspool/'.
 1717:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1718:         time.'_'.rand(1000000000).'.xls';
 1719:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1720:     if (! defined($workbook)) {
 1721:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1722:         $r->print(
 1723:             '<p class="LC_error">'
 1724:            .&mt('Problems occurred in creating the new Excel file.')
 1725:            .' '.&mt('This error has been logged.')
 1726:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1727:            .'</p>'
 1728:         );
 1729:         return (undef);
 1730:     }
 1731:     #
 1732:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1733:     #
 1734:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1735:     return ($workbook,$filename,$format);
 1736: }
 1737: 
 1738: ###############################################################
 1739: ###############################################################
 1740: 
 1741: =pod
 1742: 
 1743: =item * &create_text_file()
 1744: 
 1745: Create a file to write to and eventually make available to the user.
 1746: If file creation fails, outputs an error message on the request object and 
 1747: return undefs.
 1748: 
 1749: Inputs: Apache request object, and file suffix
 1750: 
 1751: Returns (undef) on failure, 
 1752:     Filehandle and filename on success.
 1753: 
 1754: =cut
 1755: 
 1756: ###############################################################
 1757: ###############################################################
 1758: sub create_text_file {
 1759:     my ($r,$suffix) = @_;
 1760:     if (! defined($suffix)) { $suffix = 'txt'; };
 1761:     my $fh;
 1762:     my $filename = '/prtspool/'.
 1763:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1764:         time.'_'.rand(1000000000).'.'.$suffix;
 1765:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1766:     if (! defined($fh)) {
 1767:         $r->log_error("Couldn't open $filename for output $!");
 1768:         $r->print(
 1769:             '<p class="LC_error">'
 1770:            .&mt('Problems occurred in creating the output file.')
 1771:            .' '.&mt('This error has been logged.')
 1772:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1773:            .'</p>'
 1774:         );
 1775:     }
 1776:     return ($fh,$filename)
 1777: }
 1778: 
 1779: 
 1780: =pod 
 1781: 
 1782: =back
 1783: 
 1784: =cut
 1785: 
 1786: ###############################################################
 1787: ##        Home server <option> list generating code          ##
 1788: ###############################################################
 1789: 
 1790: # ------------------------------------------
 1791: 
 1792: sub domain_select {
 1793:     my ($name,$value,$multiple)=@_;
 1794:     my %domains=map { 
 1795: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1796:     } &Apache::lonnet::all_domains();
 1797:     if ($multiple) {
 1798: 	$domains{''}=&mt('Any domain');
 1799: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1800: 	return &multiple_select_form($name,$value,4,\%domains);
 1801:     } else {
 1802: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1803: 	return &select_form($name,$value,%domains);
 1804:     }
 1805: }
 1806: 
 1807: #-------------------------------------------
 1808: 
 1809: =pod
 1810: 
 1811: =head1 Routines for form select boxes
 1812: 
 1813: =over 4
 1814: 
 1815: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1816: 
 1817: Returns a string containing a <select> element int multiple mode
 1818: 
 1819: 
 1820: Args:
 1821:   $name - name of the <select> element
 1822:   $value - scalar or array ref of values that should already be selected
 1823:   $size - number of rows long the select element is
 1824:   $hash - the elements should be 'option' => 'shown text'
 1825:           (shown text should already have been &mt())
 1826:   $order - (optional) array ref of the order to show the elements in
 1827: 
 1828: =cut
 1829: 
 1830: #-------------------------------------------
 1831: sub multiple_select_form {
 1832:     my ($name,$value,$size,$hash,$order)=@_;
 1833:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1834:     my $output='';
 1835:     if (! defined($size)) {
 1836:         $size = 4;
 1837:         if (scalar(keys(%$hash))<4) {
 1838:             $size = scalar(keys(%$hash));
 1839:         }
 1840:     }
 1841:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1842:     my @order;
 1843:     if (ref($order) eq 'ARRAY')  {
 1844:         @order = @{$order};
 1845:     } else {
 1846:         @order = sort(keys(%$hash));
 1847:     }
 1848:     if (exists($$hash{'select_form_order'})) {
 1849:         @order = @{$$hash{'select_form_order'}};
 1850:     }
 1851:         
 1852:     foreach my $key (@order) {
 1853:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1854:         $output.='selected="selected" ' if ($selected{$key});
 1855:         $output.='>'.$hash->{$key}."</option>\n";
 1856:     }
 1857:     $output.="</select>\n";
 1858:     return $output;
 1859: }
 1860: 
 1861: #-------------------------------------------
 1862: 
 1863: =pod
 1864: 
 1865: =item * &select_form($defdom,$name,%hash)
 1866: 
 1867: Returns a string containing a <select name='$name' size='1'> form to 
 1868: allow a user to select options from a hash option_name => displayed text.  
 1869: See lonrights.pm for an example invocation and use.
 1870: 
 1871: =cut
 1872: 
 1873: #-------------------------------------------
 1874: sub select_form {
 1875:     my ($def,$name,%hash) = @_;
 1876:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1877:     my @keys;
 1878:     if (exists($hash{'select_form_order'})) {
 1879: 	@keys=@{$hash{'select_form_order'}};
 1880:     } else {
 1881: 	@keys=sort(keys(%hash));
 1882:     }
 1883:     foreach my $key (@keys) {
 1884:         $selectform.=
 1885: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1886:             ($key eq $def ? 'selected="selected" ' : '').
 1887:                 ">".$hash{$key}."</option>\n";
 1888:     }
 1889:     $selectform.="</select>";
 1890:     return $selectform;
 1891: }
 1892: 
 1893: # For display filters
 1894: 
 1895: sub display_filter {
 1896:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1897:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1898:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1899: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1900: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1901: 	   '</label></span> <span class="LC_nobreak">'.
 1902:            &mt('Filter [_1]',
 1903: 	   &select_form($env{'form.displayfilter'},
 1904: 			'displayfilter',
 1905: 			('currentfolder' => 'Current folder/page',
 1906: 			 'containing' => 'Containing phrase',
 1907: 			 'none' => 'None'))).
 1908: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1909: }
 1910: 
 1911: sub gradeleveldescription {
 1912:     my $gradelevel=shift;
 1913:     my %gradelevels=(0 => 'Not specified',
 1914: 		     1 => 'Grade 1',
 1915: 		     2 => 'Grade 2',
 1916: 		     3 => 'Grade 3',
 1917: 		     4 => 'Grade 4',
 1918: 		     5 => 'Grade 5',
 1919: 		     6 => 'Grade 6',
 1920: 		     7 => 'Grade 7',
 1921: 		     8 => 'Grade 8',
 1922: 		     9 => 'Grade 9',
 1923: 		     10 => 'Grade 10',
 1924: 		     11 => 'Grade 11',
 1925: 		     12 => 'Grade 12',
 1926: 		     13 => 'Grade 13',
 1927: 		     14 => '100 Level',
 1928: 		     15 => '200 Level',
 1929: 		     16 => '300 Level',
 1930: 		     17 => '400 Level',
 1931: 		     18 => 'Graduate Level');
 1932:     return &mt($gradelevels{$gradelevel});
 1933: }
 1934: 
 1935: sub select_level_form {
 1936:     my ($deflevel,$name)=@_;
 1937:     unless ($deflevel) { $deflevel=0; }
 1938:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1939:     for (my $i=0; $i<=18; $i++) {
 1940:         $selectform.="<option value=\"$i\" ".
 1941:             ($i==$deflevel ? 'selected="selected" ' : '').
 1942:                 ">".&gradeleveldescription($i)."</option>\n";
 1943:     }
 1944:     $selectform.="</select>";
 1945:     return $selectform;
 1946: }
 1947: 
 1948: #-------------------------------------------
 1949: 
 1950: =pod
 1951: 
 1952: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 1953: 
 1954: Returns a string containing a <select name='$name' size='1'> form to 
 1955: allow a user to select the domain to preform an operation in.  
 1956: See loncreateuser.pm for an example invocation and use.
 1957: 
 1958: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1959: selected");
 1960: 
 1961: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1962: 
 1963: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 1964: 
 1965: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 1966: 
 1967: =cut
 1968: 
 1969: #-------------------------------------------
 1970: sub select_dom_form {
 1971:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 1972:     if ($onchange) {
 1973:         $onchange = ' onchange="'.$onchange.'"';
 1974:     }
 1975:     my @domains;
 1976:     if (ref($incdoms) eq 'ARRAY') {
 1977:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 1978:     } else {
 1979:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1980:     }
 1981:     if ($includeempty) { @domains=('',@domains); }
 1982:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1983:     foreach my $dom (@domains) {
 1984:         $selectdomain.="<option value=\"$dom\" ".
 1985:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1986:         if ($showdomdesc) {
 1987:             if ($dom ne '') {
 1988:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1989:                 if ($domdesc ne '') {
 1990:                     $selectdomain .= ' ('.$domdesc.')';
 1991:                 }
 1992:             } 
 1993:         }
 1994:         $selectdomain .= "</option>\n";
 1995:     }
 1996:     $selectdomain.="</select>";
 1997:     return $selectdomain;
 1998: }
 1999: 
 2000: #-------------------------------------------
 2001: 
 2002: =pod
 2003: 
 2004: =item * &home_server_form_item($domain,$name,$defaultflag)
 2005: 
 2006: input: 4 arguments (two required, two optional) - 
 2007:     $domain - domain of new user
 2008:     $name - name of form element
 2009:     $default - Value of 'default' causes a default item to be first 
 2010:                             option, and selected by default. 
 2011:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2012:                             if 1 server found, or default, if 0 found.
 2013: output: returns 2 items: 
 2014: (a) form element which contains either:
 2015:    (i) <select name="$name">
 2016:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2017:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2018:        </select>
 2019:        form item if there are multiple library servers in $domain, or
 2020:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2021:        if there is only one library server in $domain.
 2022: 
 2023: (b) number of library servers found.
 2024: 
 2025: See loncreateuser.pm for example of use.
 2026: 
 2027: =cut
 2028: 
 2029: #-------------------------------------------
 2030: sub home_server_form_item {
 2031:     my ($domain,$name,$default,$hide) = @_;
 2032:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2033:     my $result;
 2034:     my $numlib = keys(%servers);
 2035:     if ($numlib > 1) {
 2036:         $result .= '<select name="'.$name.'" />'."\n";
 2037:         if ($default) {
 2038:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2039:                        '</option>'."\n";
 2040:         }
 2041:         foreach my $hostid (sort(keys(%servers))) {
 2042:             $result.= '<option value="'.$hostid.'">'.
 2043: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2044:         }
 2045:         $result .= '</select>'."\n";
 2046:     } elsif ($numlib == 1) {
 2047:         my $hostid;
 2048:         foreach my $item (keys(%servers)) {
 2049:             $hostid = $item;
 2050:         }
 2051:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2052:                    $hostid.'" />';
 2053:                    if (!$hide) {
 2054:                        $result .= $hostid.' '.$servers{$hostid};
 2055:                    }
 2056:                    $result .= "\n";
 2057:     } elsif ($default) {
 2058:         $result .= '<input type="hidden" name="'.$name.
 2059:                    '" value="default" />';
 2060:                    if (!$hide) {
 2061:                        $result .= &mt('default');
 2062:                    }
 2063:                    $result .= "\n";
 2064:     }
 2065:     return ($result,$numlib);
 2066: }
 2067: 
 2068: =pod
 2069: 
 2070: =back 
 2071: 
 2072: =cut
 2073: 
 2074: ###############################################################
 2075: ##                  Decoding User Agent                      ##
 2076: ###############################################################
 2077: 
 2078: =pod
 2079: 
 2080: =head1 Decoding the User Agent
 2081: 
 2082: =over 4
 2083: 
 2084: =item * &decode_user_agent()
 2085: 
 2086: Inputs: $r
 2087: 
 2088: Outputs:
 2089: 
 2090: =over 4
 2091: 
 2092: =item * $httpbrowser
 2093: 
 2094: =item * $clientbrowser
 2095: 
 2096: =item * $clientversion
 2097: 
 2098: =item * $clientmathml
 2099: 
 2100: =item * $clientunicode
 2101: 
 2102: =item * $clientos
 2103: 
 2104: =back
 2105: 
 2106: =back 
 2107: 
 2108: =cut
 2109: 
 2110: ###############################################################
 2111: ###############################################################
 2112: sub decode_user_agent {
 2113:     my ($r)=@_;
 2114:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2115:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2116:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2117:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2118:     my $clientbrowser='unknown';
 2119:     my $clientversion='0';
 2120:     my $clientmathml='';
 2121:     my $clientunicode='0';
 2122:     for (my $i=0;$i<=$#browsertype;$i++) {
 2123:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2124: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2125: 	    $clientbrowser=$bname;
 2126:             $httpbrowser=~/$vreg/i;
 2127: 	    $clientversion=$1;
 2128:             $clientmathml=($clientversion>=$minv);
 2129:             $clientunicode=($clientversion>=$univ);
 2130: 	}
 2131:     }
 2132:     my $clientos='unknown';
 2133:     if (($httpbrowser=~/linux/i) ||
 2134:         ($httpbrowser=~/unix/i) ||
 2135:         ($httpbrowser=~/ux/i) ||
 2136:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2137:     if (($httpbrowser=~/vax/i) ||
 2138:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2139:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2140:     if (($httpbrowser=~/mac/i) ||
 2141:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2142:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2143:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2144:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2145:             $clientunicode,$clientos,);
 2146: }
 2147: 
 2148: ###############################################################
 2149: ##    Authentication changing form generation subroutines    ##
 2150: ###############################################################
 2151: ##
 2152: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2153: ## hash, and have reasonable default values.
 2154: ##
 2155: ##    formname = the name given in the <form> tag.
 2156: #-------------------------------------------
 2157: 
 2158: =pod
 2159: 
 2160: =head1 Authentication Routines
 2161: 
 2162: =over 4
 2163: 
 2164: =item * &authform_xxxxxx()
 2165: 
 2166: The authform_xxxxxx subroutines provide javascript and html forms which 
 2167: handle some of the conveniences required for authentication forms.  
 2168: This is not an optimal method, but it works.  
 2169: 
 2170: =over 4
 2171: 
 2172: =item * authform_header
 2173: 
 2174: =item * authform_authorwarning
 2175: 
 2176: =item * authform_nochange
 2177: 
 2178: =item * authform_kerberos
 2179: 
 2180: =item * authform_internal
 2181: 
 2182: =item * authform_filesystem
 2183: 
 2184: =back
 2185: 
 2186: See loncreateuser.pm for invocation and use examples.
 2187: 
 2188: =cut
 2189: 
 2190: #-------------------------------------------
 2191: sub authform_header{  
 2192:     my %in = (
 2193:         formname => 'cu',
 2194:         kerb_def_dom => '',
 2195:         @_,
 2196:     );
 2197:     $in{'formname'} = 'document.' . $in{'formname'};
 2198:     my $result='';
 2199: 
 2200: #---------------------------------------------- Code for upper case translation
 2201:     my $Javascript_toUpperCase;
 2202:     unless ($in{kerb_def_dom}) {
 2203:         $Javascript_toUpperCase =<<"END";
 2204:         switch (choice) {
 2205:            case 'krb': currentform.elements[choicearg].value =
 2206:                currentform.elements[choicearg].value.toUpperCase();
 2207:                break;
 2208:            default:
 2209:         }
 2210: END
 2211:     } else {
 2212:         $Javascript_toUpperCase = "";
 2213:     }
 2214: 
 2215:     my $radioval = "'nochange'";
 2216:     if (defined($in{'curr_authtype'})) {
 2217:         if ($in{'curr_authtype'} ne '') {
 2218:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2219:         }
 2220:     }
 2221:     my $argfield = 'null';
 2222:     if (defined($in{'mode'})) {
 2223:         if ($in{'mode'} eq 'modifycourse')  {
 2224:             if (defined($in{'curr_autharg'})) {
 2225:                 if ($in{'curr_autharg'} ne '') {
 2226:                     $argfield = "'$in{'curr_autharg'}'";
 2227:                 }
 2228:             }
 2229:         }
 2230:     }
 2231: 
 2232:     $result.=<<"END";
 2233: var current = new Object();
 2234: current.radiovalue = $radioval;
 2235: current.argfield = $argfield;
 2236: 
 2237: function changed_radio(choice,currentform) {
 2238:     var choicearg = choice + 'arg';
 2239:     // If a radio button in changed, we need to change the argfield
 2240:     if (current.radiovalue != choice) {
 2241:         current.radiovalue = choice;
 2242:         if (current.argfield != null) {
 2243:             currentform.elements[current.argfield].value = '';
 2244:         }
 2245:         if (choice == 'nochange') {
 2246:             current.argfield = null;
 2247:         } else {
 2248:             current.argfield = choicearg;
 2249:             switch(choice) {
 2250:                 case 'krb': 
 2251:                     currentform.elements[current.argfield].value = 
 2252:                         "$in{'kerb_def_dom'}";
 2253:                 break;
 2254:               default:
 2255:                 break;
 2256:             }
 2257:         }
 2258:     }
 2259:     return;
 2260: }
 2261: 
 2262: function changed_text(choice,currentform) {
 2263:     var choicearg = choice + 'arg';
 2264:     if (currentform.elements[choicearg].value !='') {
 2265:         $Javascript_toUpperCase
 2266:         // clear old field
 2267:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2268:             currentform.elements[current.argfield].value = '';
 2269:         }
 2270:         current.argfield = choicearg;
 2271:     }
 2272:     set_auth_radio_buttons(choice,currentform);
 2273:     return;
 2274: }
 2275: 
 2276: function set_auth_radio_buttons(newvalue,currentform) {
 2277:     var i=0;
 2278:     while (i < currentform.login.length) {
 2279:         if (currentform.login[i].value == newvalue) { break; }
 2280:         i++;
 2281:     }
 2282:     if (i == currentform.login.length) {
 2283:         return;
 2284:     }
 2285:     current.radiovalue = newvalue;
 2286:     currentform.login[i].checked = true;
 2287:     return;
 2288: }
 2289: END
 2290:     return $result;
 2291: }
 2292: 
 2293: sub authform_authorwarning{
 2294:     my $result='';
 2295:     $result='<i>'.
 2296:         &mt('As a general rule, only authors or co-authors should be '.
 2297:             'filesystem authenticated '.
 2298:             '(which allows access to the server filesystem).')."</i>\n";
 2299:     return $result;
 2300: }
 2301: 
 2302: sub authform_nochange{  
 2303:     my %in = (
 2304:               formname => 'document.cu',
 2305:               kerb_def_dom => 'MSU.EDU',
 2306:               @_,
 2307:           );
 2308:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2309:     my $result;
 2310:     if (keys(%can_assign) == 0) {
 2311:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2312:     } else {
 2313:         $result = '<label>'.&mt('[_1] Do not change login data',
 2314:                   '<input type="radio" name="login" value="nochange" '.
 2315:                   'checked="checked" onclick="'.
 2316:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2317: 	    '</label>';
 2318:     }
 2319:     return $result;
 2320: }
 2321: 
 2322: sub authform_kerberos {
 2323:     my %in = (
 2324:               formname => 'document.cu',
 2325:               kerb_def_dom => 'MSU.EDU',
 2326:               kerb_def_auth => 'krb4',
 2327:               @_,
 2328:               );
 2329:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2330:         $autharg,$jscall);
 2331:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2332:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2333:        $check5 = ' checked="checked"';
 2334:     } else {
 2335:        $check4 = ' checked="checked"';
 2336:     }
 2337:     $krbarg = $in{'kerb_def_dom'};
 2338:     if (defined($in{'curr_authtype'})) {
 2339:         if ($in{'curr_authtype'} eq 'krb') {
 2340:             $krbcheck = ' checked="checked"';
 2341:             if (defined($in{'mode'})) {
 2342:                 if ($in{'mode'} eq 'modifyuser') {
 2343:                     $krbcheck = '';
 2344:                 }
 2345:             }
 2346:             if (defined($in{'curr_kerb_ver'})) {
 2347:                 if ($in{'curr_krb_ver'} eq '5') {
 2348:                     $check5 = ' checked="checked"';
 2349:                     $check4 = '';
 2350:                 } else {
 2351:                     $check4 = ' checked="checked"';
 2352:                     $check5 = '';
 2353:                 }
 2354:             }
 2355:             if (defined($in{'curr_autharg'})) {
 2356:                 $krbarg = $in{'curr_autharg'};
 2357:             }
 2358:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2359:                 if (defined($in{'curr_autharg'})) {
 2360:                     $result = 
 2361:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2362:         $in{'curr_autharg'},$krbver);
 2363:                 } else {
 2364:                     $result =
 2365:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2366:                 }
 2367:                 return $result; 
 2368:             }
 2369:         }
 2370:     } else {
 2371:         if ($authnum == 1) {
 2372:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2373:         }
 2374:     }
 2375:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2376:         return;
 2377:     } elsif ($authtype eq '') {
 2378:         if (defined($in{'mode'})) {
 2379:             if ($in{'mode'} eq 'modifycourse') {
 2380:                 if ($authnum == 1) {
 2381:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2387:     if ($authtype eq '') {
 2388:         $authtype = '<input type="radio" name="login" value="krb" '.
 2389:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2390:                     $krbcheck.' />';
 2391:     }
 2392:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2393:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2394:          $in{'curr_authtype'} eq 'krb5') ||
 2395:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2396:          $in{'curr_authtype'} eq 'krb4')) {
 2397:         $result .= &mt
 2398:         ('[_1] Kerberos authenticated with domain [_2] '.
 2399:          '[_3] Version 4 [_4] Version 5 [_5]',
 2400:          '<label>'.$authtype,
 2401:          '</label><input type="text" size="10" name="krbarg" '.
 2402:              'value="'.$krbarg.'" '.
 2403:              'onchange="'.$jscall.'" />',
 2404:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2405:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2406: 	 '</label>');
 2407:     } elsif ($can_assign{'krb4'}) {
 2408:         $result .= &mt
 2409:         ('[_1] Kerberos authenticated with domain [_2] '.
 2410:          '[_3] Version 4 [_4]',
 2411:          '<label>'.$authtype,
 2412:          '</label><input type="text" size="10" name="krbarg" '.
 2413:              'value="'.$krbarg.'" '.
 2414:              'onchange="'.$jscall.'" />',
 2415:          '<label><input type="hidden" name="krbver" value="4" />',
 2416:          '</label>');
 2417:     } elsif ($can_assign{'krb5'}) {
 2418:         $result .= &mt
 2419:         ('[_1] Kerberos authenticated with domain [_2] '.
 2420:          '[_3] Version 5 [_4]',
 2421:          '<label>'.$authtype,
 2422:          '</label><input type="text" size="10" name="krbarg" '.
 2423:              'value="'.$krbarg.'" '.
 2424:              'onchange="'.$jscall.'" />',
 2425:          '<label><input type="hidden" name="krbver" value="5" />',
 2426:          '</label>');
 2427:     }
 2428:     return $result;
 2429: }
 2430: 
 2431: sub authform_internal{  
 2432:     my %in = (
 2433:                 formname => 'document.cu',
 2434:                 kerb_def_dom => 'MSU.EDU',
 2435:                 @_,
 2436:                 );
 2437:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2438:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2439:     if (defined($in{'curr_authtype'})) {
 2440:         if ($in{'curr_authtype'} eq 'int') {
 2441:             if ($can_assign{'int'}) {
 2442:                 $intcheck = 'checked="checked" ';
 2443:                 if (defined($in{'mode'})) {
 2444:                     if ($in{'mode'} eq 'modifyuser') {
 2445:                         $intcheck = '';
 2446:                     }
 2447:                 }
 2448:                 if (defined($in{'curr_autharg'})) {
 2449:                     $intarg = $in{'curr_autharg'};
 2450:                 }
 2451:             } else {
 2452:                 $result = &mt('Currently internally authenticated.');
 2453:                 return $result;
 2454:             }
 2455:         }
 2456:     } else {
 2457:         if ($authnum == 1) {
 2458:             $authtype = '<input type="hidden" name="login" value="int" />';
 2459:         }
 2460:     }
 2461:     if (!$can_assign{'int'}) {
 2462:         return;
 2463:     } elsif ($authtype eq '') {
 2464:         if (defined($in{'mode'})) {
 2465:             if ($in{'mode'} eq 'modifycourse') {
 2466:                 if ($authnum == 1) {
 2467:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2468:                 }
 2469:             }
 2470:         }
 2471:     }
 2472:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2473:     if ($authtype eq '') {
 2474:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2475:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2476:     }
 2477:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2478:                $intarg.'" onchange="'.$jscall.'" />';
 2479:     $result = &mt
 2480:         ('[_1] Internally authenticated (with initial password [_2])',
 2481:          '<label>'.$authtype,'</label>'.$autharg);
 2482:     $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>';
 2483:     return $result;
 2484: }
 2485: 
 2486: sub authform_local{  
 2487:     my %in = (
 2488:               formname => 'document.cu',
 2489:               kerb_def_dom => 'MSU.EDU',
 2490:               @_,
 2491:               );
 2492:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2493:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2494:     if (defined($in{'curr_authtype'})) {
 2495:         if ($in{'curr_authtype'} eq 'loc') {
 2496:             if ($can_assign{'loc'}) {
 2497:                 $loccheck = 'checked="checked" ';
 2498:                 if (defined($in{'mode'})) {
 2499:                     if ($in{'mode'} eq 'modifyuser') {
 2500:                         $loccheck = '';
 2501:                     }
 2502:                 }
 2503:                 if (defined($in{'curr_autharg'})) {
 2504:                     $locarg = $in{'curr_autharg'};
 2505:                 }
 2506:             } else {
 2507:                 $result = &mt('Currently using local (institutional) authentication.');
 2508:                 return $result;
 2509:             }
 2510:         }
 2511:     } else {
 2512:         if ($authnum == 1) {
 2513:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2514:         }
 2515:     }
 2516:     if (!$can_assign{'loc'}) {
 2517:         return;
 2518:     } elsif ($authtype eq '') {
 2519:         if (defined($in{'mode'})) {
 2520:             if ($in{'mode'} eq 'modifycourse') {
 2521:                 if ($authnum == 1) {
 2522:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2523:                 }
 2524:             }
 2525:         }
 2526:     }
 2527:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2528:     if ($authtype eq '') {
 2529:         $authtype = '<input type="radio" name="login" value="loc" '.
 2530:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2531:                     $jscall.'" />';
 2532:     }
 2533:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2534:                $locarg.'" onchange="'.$jscall.'" />';
 2535:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2536:                   '<label>'.$authtype,'</label>'.$autharg);
 2537:     return $result;
 2538: }
 2539: 
 2540: sub authform_filesystem{  
 2541:     my %in = (
 2542:               formname => 'document.cu',
 2543:               kerb_def_dom => 'MSU.EDU',
 2544:               @_,
 2545:               );
 2546:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2547:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2548:     if (defined($in{'curr_authtype'})) {
 2549:         if ($in{'curr_authtype'} eq 'fsys') {
 2550:             if ($can_assign{'fsys'}) {
 2551:                 $fsyscheck = 'checked="checked" ';
 2552:                 if (defined($in{'mode'})) {
 2553:                     if ($in{'mode'} eq 'modifyuser') {
 2554:                         $fsyscheck = '';
 2555:                     }
 2556:                 }
 2557:             } else {
 2558:                 $result = &mt('Currently Filesystem Authenticated.');
 2559:                 return $result;
 2560:             }           
 2561:         }
 2562:     } else {
 2563:         if ($authnum == 1) {
 2564:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2565:         }
 2566:     }
 2567:     if (!$can_assign{'fsys'}) {
 2568:         return;
 2569:     } elsif ($authtype eq '') {
 2570:         if (defined($in{'mode'})) {
 2571:             if ($in{'mode'} eq 'modifycourse') {
 2572:                 if ($authnum == 1) {
 2573:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2574:                 }
 2575:             }
 2576:         }
 2577:     }
 2578:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2579:     if ($authtype eq '') {
 2580:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2581:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2582:                     $jscall.'" />';
 2583:     }
 2584:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2585:                ' onchange="'.$jscall.'" />';
 2586:     $result = &mt
 2587:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2588:          '<label><input type="radio" name="login" value="fsys" '.
 2589:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2590:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2591:                   'onchange="'.$jscall.'" />');
 2592:     return $result;
 2593: }
 2594: 
 2595: sub get_assignable_auth {
 2596:     my ($dom) = @_;
 2597:     if ($dom eq '') {
 2598:         $dom = $env{'request.role.domain'};
 2599:     }
 2600:     my %can_assign = (
 2601:                           krb4 => 1,
 2602:                           krb5 => 1,
 2603:                           int  => 1,
 2604:                           loc  => 1,
 2605:                      );
 2606:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2607:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2608:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2609:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2610:             my $context;
 2611:             if ($env{'request.role'} =~ /^au/) {
 2612:                 $context = 'author';
 2613:             } elsif ($env{'request.role'} =~ /^dc/) {
 2614:                 $context = 'domain';
 2615:             } elsif ($env{'request.course.id'}) {
 2616:                 $context = 'course';
 2617:             }
 2618:             if ($context) {
 2619:                 if (ref($authhash->{$context}) eq 'HASH') {
 2620:                    %can_assign = %{$authhash->{$context}}; 
 2621:                 }
 2622:             }
 2623:         }
 2624:     }
 2625:     my $authnum = 0;
 2626:     foreach my $key (keys(%can_assign)) {
 2627:         if ($can_assign{$key}) {
 2628:             $authnum ++;
 2629:         }
 2630:     }
 2631:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2632:         $authnum --;
 2633:     }
 2634:     return ($authnum,%can_assign);
 2635: }
 2636: 
 2637: ###############################################################
 2638: ##    Get Kerberos Defaults for Domain                 ##
 2639: ###############################################################
 2640: ##
 2641: ## Returns default kerberos version and an associated argument
 2642: ## as listed in file domain.tab. If not listed, provides
 2643: ## appropriate default domain and kerberos version.
 2644: ##
 2645: #-------------------------------------------
 2646: 
 2647: =pod
 2648: 
 2649: =item * &get_kerberos_defaults()
 2650: 
 2651: get_kerberos_defaults($target_domain) returns the default kerberos
 2652: version and domain. If not found, it defaults to version 4 and the 
 2653: domain of the server.
 2654: 
 2655: =over 4
 2656: 
 2657: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2658: 
 2659: =back
 2660: 
 2661: =back
 2662: 
 2663: =cut
 2664: 
 2665: #-------------------------------------------
 2666: sub get_kerberos_defaults {
 2667:     my $domain=shift;
 2668:     my ($krbdef,$krbdefdom);
 2669:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2670:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2671:         $krbdef = $domdefaults{'auth_def'};
 2672:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2673:     } else {
 2674:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2675:         my $krbdefdom=$1;
 2676:         $krbdefdom=~tr/a-z/A-Z/;
 2677:         $krbdef = "krb4";
 2678:     }
 2679:     return ($krbdef,$krbdefdom);
 2680: }
 2681: 
 2682: 
 2683: ###############################################################
 2684: ##                Thesaurus Functions                        ##
 2685: ###############################################################
 2686: 
 2687: =pod
 2688: 
 2689: =head1 Thesaurus Functions
 2690: 
 2691: =over 4
 2692: 
 2693: =item * &initialize_keywords()
 2694: 
 2695: Initializes the package variable %Keywords if it is empty.  Uses the
 2696: package variable $thesaurus_db_file.
 2697: 
 2698: =cut
 2699: 
 2700: ###################################################
 2701: 
 2702: sub initialize_keywords {
 2703:     return 1 if (scalar keys(%Keywords));
 2704:     # If we are here, %Keywords is empty, so fill it up
 2705:     #   Make sure the file we need exists...
 2706:     if (! -e $thesaurus_db_file) {
 2707:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2708:                                  " failed because it does not exist");
 2709:         return 0;
 2710:     }
 2711:     #   Set up the hash as a database
 2712:     my %thesaurus_db;
 2713:     if (! tie(%thesaurus_db,'GDBM_File',
 2714:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2715:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2716:                                  $thesaurus_db_file);
 2717:         return 0;
 2718:     } 
 2719:     #  Get the average number of appearances of a word.
 2720:     my $avecount = $thesaurus_db{'average.count'};
 2721:     #  Put keywords (those that appear > average) into %Keywords
 2722:     while (my ($word,$data)=each (%thesaurus_db)) {
 2723:         my ($count,undef) = split /:/,$data;
 2724:         $Keywords{$word}++ if ($count > $avecount);
 2725:     }
 2726:     untie %thesaurus_db;
 2727:     # Remove special values from %Keywords.
 2728:     foreach my $value ('total.count','average.count') {
 2729:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2730:   }
 2731:     return 1;
 2732: }
 2733: 
 2734: ###################################################
 2735: 
 2736: =pod
 2737: 
 2738: =item * &keyword($word)
 2739: 
 2740: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2741: than the average number of times in the thesaurus database.  Calls 
 2742: &initialize_keywords
 2743: 
 2744: =cut
 2745: 
 2746: ###################################################
 2747: 
 2748: sub keyword {
 2749:     return if (!&initialize_keywords());
 2750:     my $word=lc(shift());
 2751:     $word=~s/\W//g;
 2752:     return exists($Keywords{$word});
 2753: }
 2754: 
 2755: ###############################################################
 2756: 
 2757: =pod 
 2758: 
 2759: =item * &get_related_words()
 2760: 
 2761: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2762: an array of words.  If the keyword is not in the thesaurus, an empty array
 2763: will be returned.  The order of the words returned is determined by the
 2764: database which holds them.
 2765: 
 2766: Uses global $thesaurus_db_file.
 2767: 
 2768: =cut
 2769: 
 2770: ###############################################################
 2771: sub get_related_words {
 2772:     my $keyword = shift;
 2773:     my %thesaurus_db;
 2774:     if (! -e $thesaurus_db_file) {
 2775:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2776:                                  "failed because the file does not exist");
 2777:         return ();
 2778:     }
 2779:     if (! tie(%thesaurus_db,'GDBM_File',
 2780:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2781:         return ();
 2782:     } 
 2783:     my @Words=();
 2784:     my $count=0;
 2785:     if (exists($thesaurus_db{$keyword})) {
 2786: 	# The first element is the number of times
 2787: 	# the word appears.  We do not need it now.
 2788: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2789: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2790: 	my $threshold=$mostfrequentcount/10;
 2791:         foreach my $possibleword (@RelatedWords) {
 2792:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2793:             if ($wordcount>$threshold) {
 2794: 		push(@Words,$word);
 2795:                 $count++;
 2796:                 if ($count>10) { last; }
 2797: 	    }
 2798:         }
 2799:     }
 2800:     untie %thesaurus_db;
 2801:     return @Words;
 2802: }
 2803: 
 2804: =pod
 2805: 
 2806: =back
 2807: 
 2808: =cut
 2809: 
 2810: # -------------------------------------------------------------- Plaintext name
 2811: =pod
 2812: 
 2813: =head1 User Name Functions
 2814: 
 2815: =over 4
 2816: 
 2817: =item * &plainname($uname,$udom,$first)
 2818: 
 2819: Takes a users logon name and returns it as a string in
 2820: "first middle last generation" form 
 2821: if $first is set to 'lastname' then it returns it as
 2822: 'lastname generation, firstname middlename' if their is a lastname
 2823: 
 2824: =cut
 2825: 
 2826: 
 2827: ###############################################################
 2828: sub plainname {
 2829:     my ($uname,$udom,$first)=@_;
 2830:     return if (!defined($uname) || !defined($udom));
 2831:     my %names=&getnames($uname,$udom);
 2832:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2833: 					  $names{'middlename'},
 2834: 					  $names{'lastname'},
 2835: 					  $names{'generation'},$first);
 2836:     $name=~s/^\s+//;
 2837:     $name=~s/\s+$//;
 2838:     $name=~s/\s+/ /g;
 2839:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2840:     return $name;
 2841: }
 2842: 
 2843: # -------------------------------------------------------------------- Nickname
 2844: =pod
 2845: 
 2846: =item * &nickname($uname,$udom)
 2847: 
 2848: Gets a users name and returns it as a string as
 2849: 
 2850: "&quot;nickname&quot;"
 2851: 
 2852: if the user has a nickname or
 2853: 
 2854: "first middle last generation"
 2855: 
 2856: if the user does not
 2857: 
 2858: =cut
 2859: 
 2860: sub nickname {
 2861:     my ($uname,$udom)=@_;
 2862:     return if (!defined($uname) || !defined($udom));
 2863:     my %names=&getnames($uname,$udom);
 2864:     my $name=$names{'nickname'};
 2865:     if ($name) {
 2866:        $name='&quot;'.$name.'&quot;'; 
 2867:     } else {
 2868:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2869: 	     $names{'lastname'}.' '.$names{'generation'};
 2870:        $name=~s/\s+$//;
 2871:        $name=~s/\s+/ /g;
 2872:     }
 2873:     return $name;
 2874: }
 2875: 
 2876: sub getnames {
 2877:     my ($uname,$udom)=@_;
 2878:     return if (!defined($uname) || !defined($udom));
 2879:     if ($udom eq 'public' && $uname eq 'public') {
 2880: 	return ('lastname' => &mt('Public'));
 2881:     }
 2882:     my $id=$uname.':'.$udom;
 2883:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2884:     if ($cached) {
 2885: 	return %{$names};
 2886:     } else {
 2887: 	my %loadnames=&Apache::lonnet::get('environment',
 2888:                     ['firstname','middlename','lastname','generation','nickname'],
 2889: 					 $udom,$uname);
 2890: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2891: 	return %loadnames;
 2892:     }
 2893: }
 2894: 
 2895: # -------------------------------------------------------------------- getemails
 2896: 
 2897: =pod
 2898: 
 2899: =item * &getemails($uname,$udom)
 2900: 
 2901: Gets a user's email information and returns it as a hash with keys:
 2902: notification, critnotification, permanentemail
 2903: 
 2904: For notification and critnotification, values are comma-separated lists 
 2905: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2906:  
 2907: 
 2908: =cut
 2909: 
 2910: 
 2911: sub getemails {
 2912:     my ($uname,$udom)=@_;
 2913:     if ($udom eq 'public' && $uname eq 'public') {
 2914: 	return;
 2915:     }
 2916:     if (!$udom) { $udom=$env{'user.domain'}; }
 2917:     if (!$uname) { $uname=$env{'user.name'}; }
 2918:     my $id=$uname.':'.$udom;
 2919:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2920:     if ($cached) {
 2921: 	return %{$names};
 2922:     } else {
 2923: 	my %loadnames=&Apache::lonnet::get('environment',
 2924:                     			   ['notification','critnotification',
 2925: 					    'permanentemail'],
 2926: 					   $udom,$uname);
 2927: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2928: 	return %loadnames;
 2929:     }
 2930: }
 2931: 
 2932: sub flush_email_cache {
 2933:     my ($uname,$udom)=@_;
 2934:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2935:     if (!$uname) { $uname=$env{'user.name'};   }
 2936:     return if ($udom eq 'public' && $uname eq 'public');
 2937:     my $id=$uname.':'.$udom;
 2938:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2939: }
 2940: 
 2941: # -------------------------------------------------------------------- getlangs
 2942: 
 2943: =pod
 2944: 
 2945: =item * &getlangs($uname,$udom)
 2946: 
 2947: Gets a user's language preference and returns it as a hash with key:
 2948: language.
 2949: 
 2950: =cut
 2951: 
 2952: 
 2953: sub getlangs {
 2954:     my ($uname,$udom) = @_;
 2955:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2956:     if (!$uname) { $uname=$env{'user.name'};   }
 2957:     my $id=$uname.':'.$udom;
 2958:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2959:     if ($cached) {
 2960:         return %{$langs};
 2961:     } else {
 2962:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2963:                                            $udom,$uname);
 2964:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2965:         return %loadlangs;
 2966:     }
 2967: }
 2968: 
 2969: sub flush_langs_cache {
 2970:     my ($uname,$udom)=@_;
 2971:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2972:     if (!$uname) { $uname=$env{'user.name'};   }
 2973:     return if ($udom eq 'public' && $uname eq 'public');
 2974:     my $id=$uname.':'.$udom;
 2975:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2976: }
 2977: 
 2978: # ------------------------------------------------------------------ Screenname
 2979: 
 2980: =pod
 2981: 
 2982: =item * &screenname($uname,$udom)
 2983: 
 2984: Gets a users screenname and returns it as a string
 2985: 
 2986: =cut
 2987: 
 2988: sub screenname {
 2989:     my ($uname,$udom)=@_;
 2990:     if ($uname eq $env{'user.name'} &&
 2991: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2992:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2993:     return $names{'screenname'};
 2994: }
 2995: 
 2996: 
 2997: # ------------------------------------------------------------- Confirm Wrapper
 2998: =pod
 2999: 
 3000: =item confirmwrapper
 3001: 
 3002: Wrap messages about completion of operation in box
 3003: 
 3004: =cut
 3005: 
 3006: sub confirmwrapper {
 3007:     my ($message)=@_;
 3008:     if ($message) {
 3009:         return "\n".'<div class="LC_confirm_box">'."\n"
 3010:                .$message."\n"
 3011:                .'</div>'."\n";
 3012:     } else {
 3013:         return $message;
 3014:     }
 3015: }
 3016: 
 3017: # ------------------------------------------------------------- Message Wrapper
 3018: 
 3019: sub messagewrapper {
 3020:     my ($link,$username,$domain,$subject,$text)=@_;
 3021:     return 
 3022:         '<a href="/adm/email?compose=individual&amp;'.
 3023:         'recname='.$username.'&amp;recdom='.$domain.
 3024: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3025:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3026: }
 3027: 
 3028: # --------------------------------------------------------------- Notes Wrapper
 3029: 
 3030: sub noteswrapper {
 3031:     my ($link,$un,$do)=@_;
 3032:     return 
 3033: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3034: }
 3035: 
 3036: # ------------------------------------------------------------- Aboutme Wrapper
 3037: 
 3038: sub aboutmewrapper {
 3039:     my ($link,$username,$domain,$target)=@_;
 3040:     if (!defined($username)  && !defined($domain)) {
 3041:         return;
 3042:     }
 3043:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3044: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3045: }
 3046: 
 3047: # ------------------------------------------------------------ Syllabus Wrapper
 3048: 
 3049: sub syllabuswrapper {
 3050:     my ($linktext,$coursedir,$domain)=@_;
 3051:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3052: }
 3053: 
 3054: # -----------------------------------------------------------------------------
 3055: 
 3056: sub track_student_link {
 3057:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3058:     my $link ="/adm/trackstudent?";
 3059:     my $title = 'View recent activity';
 3060:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3061:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3062:         $link .= "selected_student=$sname:$sdom";
 3063:         $title .= ' of this student';
 3064:     } 
 3065:     if (defined($target) && $target !~ /^\s*$/) {
 3066:         $target = qq{target="$target"};
 3067:     } else {
 3068:         $target = '';
 3069:     }
 3070:     if ($start) { $link.='&amp;start='.$start; }
 3071:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3072:     $title = &mt($title);
 3073:     $linktext = &mt($linktext);
 3074:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3075: 	&help_open_topic('View_recent_activity');
 3076: }
 3077: 
 3078: sub slot_reservations_link {
 3079:     my ($linktext,$sname,$sdom,$target) = @_;
 3080:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3081:     my $title = 'View slot reservation history';
 3082:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3083:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3084:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3085:         $title .= ' of this student';
 3086:     }
 3087:     if (defined($target) && $target !~ /^\s*$/) {
 3088:         $target = qq{target="$target"};
 3089:     } else {
 3090:         $target = '';
 3091:     }
 3092:     $title = &mt($title);
 3093:     $linktext = &mt($linktext);
 3094:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3095: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3096: 
 3097: }
 3098: 
 3099: # ===================================================== Display a student photo
 3100: 
 3101: 
 3102: sub student_image_tag {
 3103:     my ($domain,$user)=@_;
 3104:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3105:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3106: 	return '<img src="'.$imgsrc.'" align="right" />';
 3107:     } else {
 3108: 	return '';
 3109:     }
 3110: }
 3111: 
 3112: =pod
 3113: 
 3114: =back
 3115: 
 3116: =head1 Access .tab File Data
 3117: 
 3118: =over 4
 3119: 
 3120: =item * &languageids() 
 3121: 
 3122: returns list of all language ids
 3123: 
 3124: =cut
 3125: 
 3126: sub languageids {
 3127:     return sort(keys(%language));
 3128: }
 3129: 
 3130: =pod
 3131: 
 3132: =item * &languagedescription() 
 3133: 
 3134: returns description of a specified language id
 3135: 
 3136: =cut
 3137: 
 3138: sub languagedescription {
 3139:     my $code=shift;
 3140:     return  ($supported_language{$code}?'* ':'').
 3141:             $language{$code}.
 3142: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3143: }
 3144: 
 3145: sub plainlanguagedescription {
 3146:     my $code=shift;
 3147:     return $language{$code};
 3148: }
 3149: 
 3150: sub supportedlanguagecode {
 3151:     my $code=shift;
 3152:     return $supported_language{$code};
 3153: }
 3154: 
 3155: =pod
 3156: 
 3157: =item * &copyrightids() 
 3158: 
 3159: returns list of all copyrights
 3160: 
 3161: =cut
 3162: 
 3163: sub copyrightids {
 3164:     return sort(keys(%cprtag));
 3165: }
 3166: 
 3167: =pod
 3168: 
 3169: =item * &copyrightdescription() 
 3170: 
 3171: returns description of a specified copyright id
 3172: 
 3173: =cut
 3174: 
 3175: sub copyrightdescription {
 3176:     return &mt($cprtag{shift(@_)});
 3177: }
 3178: 
 3179: =pod
 3180: 
 3181: =item * &source_copyrightids() 
 3182: 
 3183: returns list of all source copyrights
 3184: 
 3185: =cut
 3186: 
 3187: sub source_copyrightids {
 3188:     return sort(keys(%scprtag));
 3189: }
 3190: 
 3191: =pod
 3192: 
 3193: =item * &source_copyrightdescription() 
 3194: 
 3195: returns description of a specified source copyright id
 3196: 
 3197: =cut
 3198: 
 3199: sub source_copyrightdescription {
 3200:     return &mt($scprtag{shift(@_)});
 3201: }
 3202: 
 3203: =pod
 3204: 
 3205: =item * &filecategories() 
 3206: 
 3207: returns list of all file categories
 3208: 
 3209: =cut
 3210: 
 3211: sub filecategories {
 3212:     return sort(keys(%category_extensions));
 3213: }
 3214: 
 3215: =pod
 3216: 
 3217: =item * &filecategorytypes() 
 3218: 
 3219: returns list of file types belonging to a given file
 3220: category
 3221: 
 3222: =cut
 3223: 
 3224: sub filecategorytypes {
 3225:     my ($cat) = @_;
 3226:     return @{$category_extensions{lc($cat)}};
 3227: }
 3228: 
 3229: =pod
 3230: 
 3231: =item * &fileembstyle() 
 3232: 
 3233: returns embedding style for a specified file type
 3234: 
 3235: =cut
 3236: 
 3237: sub fileembstyle {
 3238:     return $fe{lc(shift(@_))};
 3239: }
 3240: 
 3241: sub filemimetype {
 3242:     return $fm{lc(shift(@_))};
 3243: }
 3244: 
 3245: 
 3246: sub filecategoryselect {
 3247:     my ($name,$value)=@_;
 3248:     return &select_form($value,$name,
 3249: 			'' => &mt('Any category'),
 3250: 			map { $_,$_ } sort(keys(%category_extensions)));
 3251: }
 3252: 
 3253: =pod
 3254: 
 3255: =item * &filedescription() 
 3256: 
 3257: returns description for a specified file type
 3258: 
 3259: =cut
 3260: 
 3261: sub filedescription {
 3262:     my $file_description = $fd{lc(shift())};
 3263:     $file_description =~ s:([\[\]]):~$1:g;
 3264:     return &mt($file_description);
 3265: }
 3266: 
 3267: =pod
 3268: 
 3269: =item * &filedescriptionex() 
 3270: 
 3271: returns description for a specified file type with
 3272: extra formatting
 3273: 
 3274: =cut
 3275: 
 3276: sub filedescriptionex {
 3277:     my $ex=shift;
 3278:     my $file_description = $fd{lc($ex)};
 3279:     $file_description =~ s:([\[\]]):~$1:g;
 3280:     return '.'.$ex.' '.&mt($file_description);
 3281: }
 3282: 
 3283: # End of .tab access
 3284: =pod
 3285: 
 3286: =back
 3287: 
 3288: =cut
 3289: 
 3290: # ------------------------------------------------------------------ File Types
 3291: sub fileextensions {
 3292:     return sort(keys(%fe));
 3293: }
 3294: 
 3295: # ----------------------------------------------------------- Display Languages
 3296: # returns a hash with all desired display languages
 3297: #
 3298: 
 3299: sub display_languages {
 3300:     my %languages=();
 3301:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3302: 	$languages{$lang}=1;
 3303:     }
 3304:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3305:     if ($env{'form.displaylanguage'}) {
 3306: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3307: 	    $languages{$lang}=1;
 3308:         }
 3309:     }
 3310:     return %languages;
 3311: }
 3312: 
 3313: sub languages {
 3314:     my ($possible_langs) = @_;
 3315:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3316:     if (!ref($possible_langs)) {
 3317: 	if( wantarray ) {
 3318: 	    return @preferred_langs;
 3319: 	} else {
 3320: 	    return $preferred_langs[0];
 3321: 	}
 3322:     }
 3323:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3324:     my @preferred_possibilities;
 3325:     foreach my $preferred_lang (@preferred_langs) {
 3326: 	if (exists($possibilities{$preferred_lang})) {
 3327: 	    push(@preferred_possibilities, $preferred_lang);
 3328: 	}
 3329:     }
 3330:     if( wantarray ) {
 3331: 	return @preferred_possibilities;
 3332:     }
 3333:     return $preferred_possibilities[0];
 3334: }
 3335: 
 3336: sub user_lang {
 3337:     my ($touname,$toudom,$fromcid) = @_;
 3338:     my @userlangs;
 3339:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3340:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3341:                     $env{'course.'.$fromcid.'.languages'}));
 3342:     } else {
 3343:         my %langhash = &getlangs($touname,$toudom);
 3344:         if ($langhash{'languages'} ne '') {
 3345:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3346:         } else {
 3347:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3348:             if ($domdefs{'lang_def'} ne '') {
 3349:                 @userlangs = ($domdefs{'lang_def'});
 3350:             }
 3351:         }
 3352:     }
 3353:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3354:     my $user_lh = Apache::localize->get_handle(@languages);
 3355:     return $user_lh;
 3356: }
 3357: 
 3358: 
 3359: ###############################################################
 3360: ##               Student Answer Attempts                     ##
 3361: ###############################################################
 3362: 
 3363: =pod
 3364: 
 3365: =head1 Alternate Problem Views
 3366: 
 3367: =over 4
 3368: 
 3369: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3370:     $getattempt, $regexp, $gradesub)
 3371: 
 3372: Return string with previous attempt on problem. Arguments:
 3373: 
 3374: =over 4
 3375: 
 3376: =item * $symb: Problem, including path
 3377: 
 3378: =item * $username: username of the desired student
 3379: 
 3380: =item * $domain: domain of the desired student
 3381: 
 3382: =item * $course: Course ID
 3383: 
 3384: =item * $getattempt: Leave blank for all attempts, otherwise put
 3385:     something
 3386: 
 3387: =item * $regexp: if string matches this regexp, the string will be
 3388:     sent to $gradesub
 3389: 
 3390: =item * $gradesub: routine that processes the string if it matches $regexp
 3391: 
 3392: =back
 3393: 
 3394: The output string is a table containing all desired attempts, if any.
 3395: 
 3396: =cut
 3397: 
 3398: sub get_previous_attempt {
 3399:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3400:   my $prevattempts='';
 3401:   no strict 'refs';
 3402:   if ($symb) {
 3403:     my (%returnhash)=
 3404:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3405:     if ($returnhash{'version'}) {
 3406:       my %lasthash=();
 3407:       my $version;
 3408:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3409:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3410: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3411:         }
 3412:       }
 3413:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3414:       $prevattempts.='<th>'.&mt('History').'</th>';
 3415:       my %typeparts;
 3416:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3417:       foreach my $key (sort(keys(%lasthash))) {
 3418: 	my ($ign,@parts) = split(/\./,$key);
 3419: 	if ($#parts > 0) {
 3420: 	  my $data=$parts[-1];
 3421: 	  pop(@parts);
 3422:           if ($data eq 'type') {
 3423:               unless ($showsurv) {
 3424:                   my $id = join(',',@parts);
 3425:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3426:               }
 3427:               delete($lasthash{$key});
 3428:           } else {
 3429: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3430:           }
 3431: 	} else {
 3432: 	  if ($#parts == 0) {
 3433: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3434: 	  } else {
 3435: 	    $prevattempts.='<th>'.$ign.'</th>';
 3436: 	  }
 3437: 	}
 3438:       }
 3439:       $prevattempts.=&end_data_table_header_row();
 3440:       my %lasthidden;
 3441:       if ($getattempt eq '') {
 3442: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3443:             my @hidden;
 3444:             if (%typeparts) {
 3445:                 foreach my $id (keys(%typeparts)) {
 3446:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3447:                         push(@hidden,$id);
 3448:                         $lasthidden{$id} = 1;
 3449:                     } elsif ($lasthidden{$id}) {
 3450:                         if (exists($returnhash{$version.':'.$id.'.award'})) {
 3451:                             delete($lasthidden{$id});
 3452:                         }
 3453:                     }
 3454:                 }
 3455:             }
 3456:             $prevattempts.=&start_data_table_row().
 3457:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3458:             if (@hidden) {
 3459:                 foreach my $key (sort(keys(%lasthash))) {
 3460:                     my $hide;
 3461:                     foreach my $id (@hidden) {
 3462:                         if ($key =~ /^\Q$id\E/) {
 3463:                             $hide = 1;
 3464:                             last;
 3465:                         }
 3466:                     }
 3467:                     if ($hide) {
 3468:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3469:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3470:                             my $value = &format_previous_attempt_value($key,
 3471:                                              $returnhash{$version.':'.$key});
 3472:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3473:                         } else {
 3474:                             $prevattempts.='<td>&nbsp;</td>';
 3475:                         }
 3476:                     } else {
 3477:                         if ($key =~ /\./) {
 3478:                             my $value = &format_previous_attempt_value($key,
 3479:                                               $returnhash{$version.':'.$key});
 3480:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3481:                         } else {
 3482:                             $prevattempts.='<td>&nbsp;</td>';
 3483:                         }
 3484:                     }
 3485:                 }
 3486:             } else {
 3487: 	        foreach my $key (sort(keys(%lasthash))) {
 3488: 		    my $value = &format_previous_attempt_value($key,
 3489: 			            $returnhash{$version.':'.$key});
 3490: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3491: 	        }
 3492:             }
 3493: 	    $prevattempts.=&end_data_table_row();
 3494: 	 }
 3495:       }
 3496:       my @currhidden = keys(%lasthidden);
 3497:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3498:       foreach my $key (sort(keys(%lasthash))) {
 3499:           if (%typeparts) {
 3500:               my $hidden;
 3501:               foreach my $id (@currhidden) {
 3502:                   if ($key =~ /^\Q$id\E/) {
 3503:                       $hidden = 1;
 3504:                       last;
 3505:                   }
 3506:               }
 3507:               if ($hidden) {
 3508:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3509:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3510:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3511:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3512:                           $value = &$gradesub($value);
 3513:                       }
 3514:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3515:                   } else {
 3516:                       $prevattempts.='<td>&nbsp;</td>';
 3517:                   }
 3518:               } else {
 3519:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3520:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3521:                       $value = &$gradesub($value);
 3522:                   }
 3523:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3524:               }
 3525:           } else {
 3526: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3527: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3528:                   $value = &$gradesub($value);
 3529:               }
 3530: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3531:           }
 3532:       }
 3533:       $prevattempts.= &end_data_table_row().&end_data_table();
 3534:     } else {
 3535:       $prevattempts=
 3536: 	  &start_data_table().&start_data_table_row().
 3537: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3538: 	  &end_data_table_row().&end_data_table();
 3539:     }
 3540:   } else {
 3541:     $prevattempts=
 3542: 	  &start_data_table().&start_data_table_row().
 3543: 	  '<td>'.&mt('No data.').'</td>'.
 3544: 	  &end_data_table_row().&end_data_table();
 3545:   }
 3546: }
 3547: 
 3548: sub format_previous_attempt_value {
 3549:     my ($key,$value) = @_;
 3550:     if ($key =~ /timestamp/) {
 3551: 	$value = &Apache::lonlocal::locallocaltime($value);
 3552:     } elsif (ref($value) eq 'ARRAY') {
 3553: 	$value = '('.join(', ', @{ $value }).')';
 3554:     } else {
 3555: 	$value = &unescape($value);
 3556:     }
 3557:     return $value;
 3558: }
 3559: 
 3560: 
 3561: sub relative_to_absolute {
 3562:     my ($url,$output)=@_;
 3563:     my $parser=HTML::TokeParser->new(\$output);
 3564:     my $token;
 3565:     my $thisdir=$url;
 3566:     my @rlinks=();
 3567:     while ($token=$parser->get_token) {
 3568: 	if ($token->[0] eq 'S') {
 3569: 	    if ($token->[1] eq 'a') {
 3570: 		if ($token->[2]->{'href'}) {
 3571: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3572: 		}
 3573: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3574: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3575: 	    } elsif ($token->[1] eq 'base') {
 3576: 		$thisdir=$token->[2]->{'href'};
 3577: 	    }
 3578: 	}
 3579:     }
 3580:     $thisdir=~s-/[^/]*$--;
 3581:     foreach my $link (@rlinks) {
 3582: 	unless (($link=~/^https?\:\/\//i) ||
 3583: 		($link=~/^\//) ||
 3584: 		($link=~/^javascript:/i) ||
 3585: 		($link=~/^mailto:/i) ||
 3586: 		($link=~/^\#/)) {
 3587: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3588: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3589: 	}
 3590:     }
 3591: # -------------------------------------------------- Deal with Applet codebases
 3592:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3593:     return $output;
 3594: }
 3595: 
 3596: =pod
 3597: 
 3598: =item * &get_student_view()
 3599: 
 3600: show a snapshot of what student was looking at
 3601: 
 3602: =cut
 3603: 
 3604: sub get_student_view {
 3605:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3606:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3607:   my (%form);
 3608:   my @elements=('symb','courseid','domain','username');
 3609:   foreach my $element (@elements) {
 3610:       $form{'grade_'.$element}=eval '$'.$element #'
 3611:   }
 3612:   if (defined($moreenv)) {
 3613:       %form=(%form,%{$moreenv});
 3614:   }
 3615:   if (defined($target)) { $form{'grade_target'} = $target; }
 3616:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3617:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3618:   $userview=~s/\<body[^\>]*\>//gi;
 3619:   $userview=~s/\<\/body\>//gi;
 3620:   $userview=~s/\<html\>//gi;
 3621:   $userview=~s/\<\/html\>//gi;
 3622:   $userview=~s/\<head\>//gi;
 3623:   $userview=~s/\<\/head\>//gi;
 3624:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3625:   $userview=&relative_to_absolute($feedurl,$userview);
 3626:   if (wantarray) {
 3627:      return ($userview,$response);
 3628:   } else {
 3629:      return $userview;
 3630:   }
 3631: }
 3632: 
 3633: sub get_student_view_with_retries {
 3634:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3635: 
 3636:     my $ok = 0;                 # True if we got a good response.
 3637:     my $content;
 3638:     my $response;
 3639: 
 3640:     # Try to get the student_view done. within the retries count:
 3641:     
 3642:     do {
 3643:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3644:          $ok      = $response->is_success;
 3645:          if (!$ok) {
 3646:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3647:          }
 3648:          $retries--;
 3649:     } while (!$ok && ($retries > 0));
 3650:     
 3651:     if (!$ok) {
 3652:        $content = '';          # On error return an empty content.
 3653:     }
 3654:     if (wantarray) {
 3655:        return ($content, $response);
 3656:     } else {
 3657:        return $content;
 3658:     }
 3659: }
 3660: 
 3661: =pod
 3662: 
 3663: =item * &get_student_answers() 
 3664: 
 3665: show a snapshot of how student was answering problem
 3666: 
 3667: =cut
 3668: 
 3669: sub get_student_answers {
 3670:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3671:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3672:   my (%moreenv);
 3673:   my @elements=('symb','courseid','domain','username');
 3674:   foreach my $element (@elements) {
 3675:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3676:   }
 3677:   $moreenv{'grade_target'}='answer';
 3678:   %moreenv=(%form,%moreenv);
 3679:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3680:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3681:   return $userview;
 3682: }
 3683: 
 3684: =pod
 3685: 
 3686: =item * &submlink()
 3687: 
 3688: Inputs: $text $uname $udom $symb $target
 3689: 
 3690: Returns: A link to grades.pm such as to see the SUBM view of a student
 3691: 
 3692: =cut
 3693: 
 3694: ###############################################
 3695: sub submlink {
 3696:     my ($text,$uname,$udom,$symb,$target)=@_;
 3697:     if (!($uname && $udom)) {
 3698: 	(my $cursymb, my $courseid,$udom,$uname)=
 3699: 	    &Apache::lonnet::whichuser($symb);
 3700: 	if (!$symb) { $symb=$cursymb; }
 3701:     }
 3702:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3703:     $symb=&escape($symb);
 3704:     if ($target) { $target="target=\"$target\""; }
 3705:     return '<a href="/adm/grades?&command=submission&'.
 3706: 	'symb='.$symb.'&student='.$uname.
 3707: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3708: }
 3709: ##############################################
 3710: 
 3711: =pod
 3712: 
 3713: =item * &pgrdlink()
 3714: 
 3715: Inputs: $text $uname $udom $symb $target
 3716: 
 3717: Returns: A link to grades.pm such as to see the PGRD view of a student
 3718: 
 3719: =cut
 3720: 
 3721: ###############################################
 3722: sub pgrdlink {
 3723:     my $link=&submlink(@_);
 3724:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3725:     return $link;
 3726: }
 3727: ##############################################
 3728: 
 3729: =pod
 3730: 
 3731: =item * &pprmlink()
 3732: 
 3733: Inputs: $text $uname $udom $symb $target
 3734: 
 3735: Returns: A link to parmset.pm such as to see the PPRM view of a
 3736: student and a specific resource
 3737: 
 3738: =cut
 3739: 
 3740: ###############################################
 3741: sub pprmlink {
 3742:     my ($text,$uname,$udom,$symb,$target)=@_;
 3743:     if (!($uname && $udom)) {
 3744: 	(my $cursymb, my $courseid,$udom,$uname)=
 3745: 	    &Apache::lonnet::whichuser($symb);
 3746: 	if (!$symb) { $symb=$cursymb; }
 3747:     }
 3748:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3749:     $symb=&escape($symb);
 3750:     if ($target) { $target="target=\"$target\""; }
 3751:     return '<a href="/adm/parmset?command=set&amp;'.
 3752: 	'symb='.$symb.'&amp;uname='.$uname.
 3753: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3754: }
 3755: ##############################################
 3756: 
 3757: =pod
 3758: 
 3759: =back
 3760: 
 3761: =cut
 3762: 
 3763: ###############################################
 3764: 
 3765: 
 3766: sub timehash {
 3767:     my ($thistime) = @_;
 3768:     my $timezone = &Apache::lonlocal::gettimezone();
 3769:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3770:                      ->set_time_zone($timezone);
 3771:     my $wday = $dt->day_of_week();
 3772:     if ($wday == 7) { $wday = 0; }
 3773:     return ( 'second' => $dt->second(),
 3774:              'minute' => $dt->minute(),
 3775:              'hour'   => $dt->hour(),
 3776:              'day'     => $dt->day_of_month(),
 3777:              'month'   => $dt->month(),
 3778:              'year'    => $dt->year(),
 3779:              'weekday' => $wday,
 3780:              'dayyear' => $dt->day_of_year(),
 3781:              'dlsav'   => $dt->is_dst() );
 3782: }
 3783: 
 3784: sub utc_string {
 3785:     my ($date)=@_;
 3786:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3787: }
 3788: 
 3789: sub maketime {
 3790:     my %th=@_;
 3791:     my ($epoch_time,$timezone,$dt);
 3792:     $timezone = &Apache::lonlocal::gettimezone();
 3793:     eval {
 3794:         $dt = DateTime->new( year   => $th{'year'},
 3795:                              month  => $th{'month'},
 3796:                              day    => $th{'day'},
 3797:                              hour   => $th{'hour'},
 3798:                              minute => $th{'minute'},
 3799:                              second => $th{'second'},
 3800:                              time_zone => $timezone,
 3801:                          );
 3802:     };
 3803:     if (!$@) {
 3804:         $epoch_time = $dt->epoch;
 3805:         if ($epoch_time) {
 3806:             return $epoch_time;
 3807:         }
 3808:     }
 3809:     return POSIX::mktime(
 3810:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3811:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3812: }
 3813: 
 3814: #########################################
 3815: 
 3816: sub findallcourses {
 3817:     my ($roles,$uname,$udom) = @_;
 3818:     my %roles;
 3819:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3820:     my %courses;
 3821:     my $now=time;
 3822:     if (!defined($uname)) {
 3823:         $uname = $env{'user.name'};
 3824:     }
 3825:     if (!defined($udom)) {
 3826:         $udom = $env{'user.domain'};
 3827:     }
 3828:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3829:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3830:         if (!%roles) {
 3831:             %roles = (
 3832:                        cc => 1,
 3833:                        co => 1,
 3834:                        in => 1,
 3835:                        ep => 1,
 3836:                        ta => 1,
 3837:                        cr => 1,
 3838:                        st => 1,
 3839:              );
 3840:         }
 3841:         foreach my $entry (keys(%roleshash)) {
 3842:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3843:             if ($trole =~ /^cr/) { 
 3844:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3845:             } else {
 3846:                 next if (!exists($roles{$trole}));
 3847:             }
 3848:             if ($tend) {
 3849:                 next if ($tend < $now);
 3850:             }
 3851:             if ($tstart) {
 3852:                 next if ($tstart > $now);
 3853:             }
 3854:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3855:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3856:             if ($secpart eq '') {
 3857:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3858:                 $sec = 'none';
 3859:                 $realsec = '';
 3860:             } else {
 3861:                 $cnum = $cnumpart;
 3862:                 ($sec,$role) = split(/_/,$secpart);
 3863:                 $realsec = $sec;
 3864:             }
 3865:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3866:         }
 3867:     } else {
 3868:         foreach my $key (keys(%env)) {
 3869: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3870:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3871: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3872: 	        next if ($role eq 'ca' || $role eq 'aa');
 3873: 	        next if (%roles && !exists($roles{$role}));
 3874: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3875:                 my $active=1;
 3876:                 if ($starttime) {
 3877: 		    if ($now<$starttime) { $active=0; }
 3878:                 }
 3879:                 if ($endtime) {
 3880:                     if ($now>$endtime) { $active=0; }
 3881:                 }
 3882:                 if ($active) {
 3883:                     if ($sec eq '') {
 3884:                         $sec = 'none';
 3885:                     }
 3886:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3887:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3888:                 }
 3889:             }
 3890:         }
 3891:     }
 3892:     return %courses;
 3893: }
 3894: 
 3895: ###############################################
 3896: 
 3897: sub blockcheck {
 3898:     my ($setters,$activity,$uname,$udom) = @_;
 3899: 
 3900:     if (!defined($udom)) {
 3901:         $udom = $env{'user.domain'};
 3902:     }
 3903:     if (!defined($uname)) {
 3904:         $uname = $env{'user.name'};
 3905:     }
 3906: 
 3907:     # If uname and udom are for a course, check for blocks in the course.
 3908: 
 3909:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3910:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3911:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3912:         return ($startblock,$endblock);
 3913:     }
 3914: 
 3915:     my $startblock = 0;
 3916:     my $endblock = 0;
 3917:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3918: 
 3919:     # If uname is for a user, and activity is course-specific, i.e.,
 3920:     # boards, chat or groups, check for blocking in current course only.
 3921: 
 3922:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3923:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3924:         foreach my $key (keys(%live_courses)) {
 3925:             if ($key ne $env{'request.course.id'}) {
 3926:                 delete($live_courses{$key});
 3927:             }
 3928:         }
 3929:     }
 3930: 
 3931:     my $otheruser = 0;
 3932:     my %own_courses;
 3933:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3934:         # Resource belongs to user other than current user.
 3935:         $otheruser = 1;
 3936:         # Gather courses for current user
 3937:         %own_courses = 
 3938:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3939:     }
 3940: 
 3941:     # Gather active course roles - course coordinator, instructor, 
 3942:     # exam proctor, ta, student, or custom role.
 3943: 
 3944:     foreach my $course (keys(%live_courses)) {
 3945:         my ($cdom,$cnum);
 3946:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3947:             $cdom = $env{'course.'.$course.'.domain'};
 3948:             $cnum = $env{'course.'.$course.'.num'};
 3949:         } else {
 3950:             ($cdom,$cnum) = split(/_/,$course); 
 3951:         }
 3952:         my $no_ownblock = 0;
 3953:         my $no_userblock = 0;
 3954:         if ($otheruser && $activity ne 'com') {
 3955:             # Check if current user has 'evb' priv for this
 3956:             if (defined($own_courses{$course})) {
 3957:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3958:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3959:                     if ($sec ne 'none') {
 3960:                         $checkrole .= '/'.$sec;
 3961:                     }
 3962:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3963:                         $no_ownblock = 1;
 3964:                         last;
 3965:                     }
 3966:                 }
 3967:             }
 3968:             # if they have 'evb' priv and are currently not playing student
 3969:             next if (($no_ownblock) &&
 3970:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3971:         }
 3972:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3973:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3974:             if ($sec ne 'none') {
 3975:                 $checkrole .= '/'.$sec;
 3976:             }
 3977:             if ($otheruser) {
 3978:                 # Resource belongs to user other than current user.
 3979:                 # Assemble privs for that user, and check for 'evb' priv.
 3980:                 my ($trole,$tdom,$tnum,$tsec);
 3981:                 my $entry = $live_courses{$course}{$sec};
 3982:                 if ($entry =~ /^cr/) {
 3983:                     ($trole,$tdom,$tnum,$tsec) = 
 3984:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3985:                 } else {
 3986:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3987:                 }
 3988:                 my ($spec,$area,$trest,%allroles,%userroles);
 3989:                 $area = '/'.$tdom.'/'.$tnum;
 3990:                 $trest = $tnum;
 3991:                 if ($tsec ne '') {
 3992:                     $area .= '/'.$tsec;
 3993:                     $trest .= '/'.$tsec;
 3994:                 }
 3995:                 $spec = $trole.'.'.$area;
 3996:                 if ($trole =~ /^cr/) {
 3997:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3998:                                                       $tdom,$spec,$trest,$area);
 3999:                 } else {
 4000:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4001:                                                        $tdom,$spec,$trest,$area);
 4002:                 }
 4003:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4004:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4005:                     if ($1) {
 4006:                         $no_userblock = 1;
 4007:                         last;
 4008:                     }
 4009:                 }
 4010:             } else {
 4011:                 # Resource belongs to current user
 4012:                 # Check for 'evb' priv via lonnet::allowed().
 4013:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4014:                     $no_ownblock = 1;
 4015:                     last;
 4016:                 }
 4017:             }
 4018:         }
 4019:         # if they have the evb priv and are currently not playing student
 4020:         next if (($no_ownblock) &&
 4021:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4022:         next if ($no_userblock);
 4023: 
 4024:         # Retrieve blocking times and identity of locker for course
 4025:         # of specified user, unless user has 'evb' privilege.
 4026:         
 4027:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4028:         if (($start != 0) && 
 4029:             (($startblock == 0) || ($startblock > $start))) {
 4030:             $startblock = $start;
 4031:         }
 4032:         if (($end != 0)  &&
 4033:             (($endblock == 0) || ($endblock < $end))) {
 4034:             $endblock = $end;
 4035:         }
 4036:     }
 4037:     return ($startblock,$endblock);
 4038: }
 4039: 
 4040: sub get_blocks {
 4041:     my ($setters,$activity,$cdom,$cnum) = @_;
 4042:     my $startblock = 0;
 4043:     my $endblock = 0;
 4044:     my $course = $cdom.'_'.$cnum;
 4045:     $setters->{$course} = {};
 4046:     $setters->{$course}{'staff'} = [];
 4047:     $setters->{$course}{'times'} = [];
 4048:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4049:     foreach my $record (keys(%records)) {
 4050:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4051:         if ($start <= time && $end >= time) {
 4052:             my ($staff_name,$staff_dom,$title,$blocks) =
 4053:                 &parse_block_record($records{$record});
 4054:             if ($blocks->{$activity} eq 'on') {
 4055:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4056:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4057:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4058:                     $startblock = $start;
 4059:                 }
 4060:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4061:                     $endblock = $end;
 4062:                 }
 4063:             }
 4064:         }
 4065:     }
 4066:     return ($startblock,$endblock);
 4067: }
 4068: 
 4069: sub parse_block_record {
 4070:     my ($record) = @_;
 4071:     my ($setuname,$setudom,$title,$blocks);
 4072:     if (ref($record) eq 'HASH') {
 4073:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4074:         $title = &unescape($record->{'event'});
 4075:         $blocks = $record->{'blocks'};
 4076:     } else {
 4077:         my @data = split(/:/,$record,3);
 4078:         if (scalar(@data) eq 2) {
 4079:             $title = $data[1];
 4080:             ($setuname,$setudom) = split(/@/,$data[0]);
 4081:         } else {
 4082:             ($setuname,$setudom,$title) = @data;
 4083:         }
 4084:         $blocks = { 'com' => 'on' };
 4085:     }
 4086:     return ($setuname,$setudom,$title,$blocks);
 4087: }
 4088: 
 4089: sub blocking_status {
 4090:   my ($activity,$uname,$udom) = @_;
 4091:   my %setters;
 4092: 
 4093:   # check for active blocking
 4094:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4095: 
 4096:   my $blocked = $startblock && $endblock ? 1 : 0;
 4097: 
 4098:   # caller just wants to know whether a block is active
 4099:   if (!wantarray) { return $blocked; }
 4100: 
 4101:   # build a link to a popup window containing the details
 4102:   my $querystring  = "?activity=$activity";
 4103:   # $uname and $udom decide whose portfolio the user is trying to look at
 4104:      $querystring .= "&amp;udom=$udom"      if $udom;
 4105:      $querystring .= "&amp;uname=$uname"    if $uname;
 4106: 
 4107:   my $output .= <<'END_MYBLOCK';
 4108:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4109:         var options = "width=" + w + ",height=" + h + ",";
 4110:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4111:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4112:         var newWin = window.open(url, wdwName, options);
 4113:         newWin.focus();
 4114:     }
 4115: END_MYBLOCK
 4116: 
 4117:   $output = Apache::lonhtmlcommon::scripttag($output);
 4118:   
 4119:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4120:   my $text = mt('Communication Blocked');
 4121: 
 4122:   $output .= <<"END_BLOCK";
 4123: <div class='LC_comblock'>
 4124:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4125:   title='$text'>
 4126:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4127:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4128:   title='$text'>$text</a>
 4129: </div>
 4130: 
 4131: END_BLOCK
 4132: 
 4133:   return ($blocked, $output);
 4134: }
 4135: 
 4136: ###############################################
 4137: 
 4138: sub check_ip_acc {
 4139:     my ($acc)=@_;
 4140:     &Apache::lonxml::debug("acc is $acc");
 4141:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4142:         return 1;
 4143:     }
 4144:     my $allowed=0;
 4145:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4146: 
 4147:     my $name;
 4148:     foreach my $pattern (split(',',$acc)) {
 4149:         $pattern =~ s/^\s*//;
 4150:         $pattern =~ s/\s*$//;
 4151:         if ($pattern =~ /\*$/) {
 4152:             #35.8.*
 4153:             $pattern=~s/\*//;
 4154:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4155:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4156:             #35.8.3.[34-56]
 4157:             my $low=$2;
 4158:             my $high=$3;
 4159:             $pattern=$1;
 4160:             if ($ip =~ /^\Q$pattern\E/) {
 4161:                 my $last=(split(/\./,$ip))[3];
 4162:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4163:             }
 4164:         } elsif ($pattern =~ /^\*/) {
 4165:             #*.msu.edu
 4166:             $pattern=~s/\*//;
 4167:             if (!defined($name)) {
 4168:                 use Socket;
 4169:                 my $netaddr=inet_aton($ip);
 4170:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4171:             }
 4172:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4173:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4174:             #127.0.0.1
 4175:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4176:         } else {
 4177:             #some.name.com
 4178:             if (!defined($name)) {
 4179:                 use Socket;
 4180:                 my $netaddr=inet_aton($ip);
 4181:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4182:             }
 4183:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4184:         }
 4185:         if ($allowed) { last; }
 4186:     }
 4187:     return $allowed;
 4188: }
 4189: 
 4190: ###############################################
 4191: 
 4192: =pod
 4193: 
 4194: =head1 Domain Template Functions
 4195: 
 4196: =over 4
 4197: 
 4198: =item * &determinedomain()
 4199: 
 4200: Inputs: $domain (usually will be undef)
 4201: 
 4202: Returns: Determines which domain should be used for designs
 4203: 
 4204: =cut
 4205: 
 4206: ###############################################
 4207: sub determinedomain {
 4208:     my $domain=shift;
 4209:     if (! $domain) {
 4210:         # Determine domain if we have not been given one
 4211:         $domain = &Apache::lonnet::default_login_domain();
 4212:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4213:         if ($env{'request.role.domain'}) { 
 4214:             $domain=$env{'request.role.domain'}; 
 4215:         }
 4216:     }
 4217:     return $domain;
 4218: }
 4219: ###############################################
 4220: 
 4221: sub devalidate_domconfig_cache {
 4222:     my ($udom)=@_;
 4223:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4224: }
 4225: 
 4226: # ---------------------- Get domain configuration for a domain
 4227: sub get_domainconf {
 4228:     my ($udom) = @_;
 4229:     my $cachetime=1800;
 4230:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4231:     if (defined($cached)) { return %{$result}; }
 4232: 
 4233:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4234: 					     ['login','rolecolors','autoenroll'],$udom);
 4235:     my (%designhash,%legacy);
 4236:     if (keys(%domconfig) > 0) {
 4237:         if (ref($domconfig{'login'}) eq 'HASH') {
 4238:             if (keys(%{$domconfig{'login'}})) {
 4239:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4240:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4241:                         if ($key eq 'loginvia') {
 4242:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4243:                                 my @ids = &Apache::lonnet::current_machine_ids();
 4244:                                 foreach my $hostname (@ids) {
 4245:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4246:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4247:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4248:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4249:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4250: 
 4251:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4252:                                             } else {
 4253:                                                  $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4254:                                             }
 4255:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4256:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4257:                                             }
 4258:                                         }
 4259:                                     }
 4260:                                 }
 4261:                             }
 4262:                         } else {
 4263:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4264:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4265:                                     $domconfig{'login'}{$key}{$img};
 4266:                             }
 4267:                         }
 4268:                     } else {
 4269:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4270:                     }
 4271:                 }
 4272:             } else {
 4273:                 $legacy{'login'} = 1;
 4274:             }
 4275:         } else {
 4276:             $legacy{'login'} = 1;
 4277:         }
 4278:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4279:             if (keys(%{$domconfig{'rolecolors'}})) {
 4280:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4281:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4282:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4283:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4284:                         }
 4285:                     }
 4286:                 }
 4287:             } else {
 4288:                 $legacy{'rolecolors'} = 1;
 4289:             }
 4290:         } else {
 4291:             $legacy{'rolecolors'} = 1;
 4292:         }
 4293:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4294:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4295:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4296:             }
 4297:         }
 4298:         if (keys(%legacy) > 0) {
 4299:             my %legacyhash = &get_legacy_domconf($udom);
 4300:             foreach my $item (keys(%legacyhash)) {
 4301:                 if ($item =~ /^\Q$udom\E\.login/) {
 4302:                     if ($legacy{'login'}) { 
 4303:                         $designhash{$item} = $legacyhash{$item};
 4304:                     }
 4305:                 } else {
 4306:                     if ($legacy{'rolecolors'}) {
 4307:                         $designhash{$item} = $legacyhash{$item};
 4308:                     }
 4309:                 }
 4310:             }
 4311:         }
 4312:     } else {
 4313:         %designhash = &get_legacy_domconf($udom); 
 4314:     }
 4315:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4316: 				  $cachetime);
 4317:     return %designhash;
 4318: }
 4319: 
 4320: sub get_legacy_domconf {
 4321:     my ($udom) = @_;
 4322:     my %legacyhash;
 4323:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4324:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4325:     if (-e $designfile) {
 4326:         if ( open (my $fh,"<$designfile") ) {
 4327:             while (my $line = <$fh>) {
 4328:                 next if ($line =~ /^\#/);
 4329:                 chomp($line);
 4330:                 my ($key,$val)=(split(/\=/,$line));
 4331:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4332:             }
 4333:             close($fh);
 4334:         }
 4335:     }
 4336:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4337:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4338:     }
 4339:     return %legacyhash;
 4340: }
 4341: 
 4342: =pod
 4343: 
 4344: =item * &domainlogo()
 4345: 
 4346: Inputs: $domain (usually will be undef)
 4347: 
 4348: Returns: A link to a domain logo, if the domain logo exists.
 4349: If the domain logo does not exist, a description of the domain.
 4350: 
 4351: =cut
 4352: 
 4353: ###############################################
 4354: sub domainlogo {
 4355:     my $domain = &determinedomain(shift);
 4356:     my %designhash = &get_domainconf($domain);    
 4357:     # See if there is a logo
 4358:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4359:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4360:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4361: 	    if ($imgsrc =~ m{^/res/}) {
 4362: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4363: 		&Apache::lonnet::repcopy($local_name);
 4364: 	    }
 4365: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4366:         } 
 4367:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4368:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4369:         return &Apache::lonnet::domain($domain,'description');
 4370:     } else {
 4371:         return '';
 4372:     }
 4373: }
 4374: ##############################################
 4375: 
 4376: =pod
 4377: 
 4378: =item * &designparm()
 4379: 
 4380: Inputs: $which parameter; $domain (usually will be undef)
 4381: 
 4382: Returns: value of designparamter $which
 4383: 
 4384: =cut
 4385: 
 4386: 
 4387: ##############################################
 4388: sub designparm {
 4389:     my ($which,$domain)=@_;
 4390:     if (exists($env{'environment.color.'.$which})) {
 4391:         return $env{'environment.color.'.$which};
 4392:     }
 4393:     $domain=&determinedomain($domain);
 4394:     my %domdesign = &get_domainconf($domain);
 4395:     my $output;
 4396:     if ($domdesign{$domain.'.'.$which} ne '') {
 4397:         $output = $domdesign{$domain.'.'.$which};
 4398:     } else {
 4399:         $output = $defaultdesign{$which};
 4400:     }
 4401:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4402:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4403:         if ($output =~ m{^/(adm|res)/}) {
 4404:             if ($output =~ m{^/res/}) {
 4405:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4406:                 &Apache::lonnet::repcopy($local_name);
 4407:             }
 4408:             $output = &lonhttpdurl($output);
 4409:         }
 4410:     }
 4411:     return $output;
 4412: }
 4413: 
 4414: ##############################################
 4415: =pod
 4416: 
 4417: =item * &authorspace()
 4418: 
 4419: Inputs: ./.
 4420: 
 4421: Returns: Path to the Construction Space of the current user's
 4422:          accessed author space
 4423:          The author space will be that of the current user
 4424:          when accessing the own author space
 4425:          and that of the co-author/assistent co-author
 4426:          when accessing the co-author's/assistent co-author's
 4427:          space
 4428: 
 4429: =cut
 4430: 
 4431: sub authorspace {
 4432:     my $caname = '';
 4433:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4434:         (undef,$caname) =
 4435:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4436:     } else {
 4437:         $caname = $env{'user.name'};
 4438:     }
 4439:     return '/priv/'.$caname.'/';
 4440: }
 4441: 
 4442: ##############################################
 4443: =pod
 4444: 
 4445: =item * &head_subbox()
 4446: 
 4447: Inputs: $content (contains HTML code with page functions, etc.)
 4448: 
 4449: Returns: HTML div with $content
 4450:          To be included in page header
 4451: 
 4452: =cut
 4453: 
 4454: sub head_subbox {
 4455:     my ($content)=@_;
 4456:     my $output =
 4457:         '<div id="LC_head_subbox">'
 4458:        .$content
 4459:        .'</div>'
 4460: }
 4461: 
 4462: ##############################################
 4463: =pod
 4464: 
 4465: =item * &CSTR_pageheader()
 4466: 
 4467: Inputs: ./.
 4468: 
 4469: Returns: HTML div with CSTR path and recent box
 4470:          To be included on Construction Space pages
 4471: 
 4472: =cut
 4473: 
 4474: sub CSTR_pageheader {
 4475:     # this is for resources; directories have customtitle, and crumbs
 4476:             # and select recent are created in lonpubdir.pm  
 4477:     my ($uname,$thisdisfn)=
 4478:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4479:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4480:     $formaction=~s/\/+/\//g;
 4481: 
 4482:     my $parentpath = '';
 4483:     my $lastitem = '';
 4484:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4485:         $parentpath = $1;
 4486:         $lastitem = $2;
 4487:     } else {
 4488:         $lastitem = $thisdisfn;
 4489:     }
 4490: 
 4491:     my $output =
 4492:          '<div>'
 4493:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4494:         .'<b>'.&mt('Construction Space:').'</b> '
 4495:         .'<form name="dirs" method="post" action="'.$formaction
 4496:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4497:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4498: 
 4499:     if ($lastitem) {
 4500:         $output .=
 4501:              '<span class="LC_filename">'
 4502:             .$lastitem
 4503:             .'</span>';
 4504:     }
 4505:     $output .=
 4506:          '<br />'
 4507:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4508:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4509:         .'</form>'
 4510:         .&Apache::lonmenu::constspaceform()
 4511:         .'</div>';
 4512: 
 4513:     return $output;
 4514: }
 4515: 
 4516: ###############################################
 4517: ###############################################
 4518: 
 4519: =pod
 4520: 
 4521: =back
 4522: 
 4523: =head1 HTML Helpers
 4524: 
 4525: =over 4
 4526: 
 4527: =item * &bodytag()
 4528: 
 4529: Returns a uniform header for LON-CAPA web pages.
 4530: 
 4531: Inputs: 
 4532: 
 4533: =over 4
 4534: 
 4535: =item * $title, A title to be displayed on the page.
 4536: 
 4537: =item * $function, the current role (can be undef).
 4538: 
 4539: =item * $addentries, extra parameters for the <body> tag.
 4540: 
 4541: =item * $bodyonly, if defined, only return the <body> tag.
 4542: 
 4543: =item * $domain, if defined, force a given domain.
 4544: 
 4545: =item * $forcereg, if page should register as content page (relevant for 
 4546:             text interface only)
 4547: 
 4548: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4549:                      navigational links
 4550: 
 4551: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4552: 
 4553: =item * $no_inline_link, if true and in remote mode, don't show the 
 4554:          'Switch To Inline Menu' link
 4555: 
 4556: =item * $args, optional argument valid values are
 4557:             no_auto_mt_title -> prevents &mt()ing the title arg
 4558:             inherit_jsmath -> when creating popup window in a page,
 4559:                               should it have jsmath forced on by the
 4560:                               current page
 4561: 
 4562: =back
 4563: 
 4564: Returns: A uniform header for LON-CAPA web pages.  
 4565: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4566: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4567: other decorations will be returned.
 4568: 
 4569: =cut
 4570: 
 4571: sub bodytag {
 4572:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4573:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4574: 
 4575:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4576: 
 4577:     $function = &get_users_function() if (!$function);
 4578:     my $img =    &designparm($function.'.img',$domain);
 4579:     my $font =   &designparm($function.'.font',$domain);
 4580:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4581: 
 4582:     my %design = ( 'style'   => 'margin-top: 0',
 4583: 		   'bgcolor' => $pgbg,
 4584: 		   'text'    => $font,
 4585:                    'alink'   => &designparm($function.'.alink',$domain),
 4586: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4587: 		   'link'    => &designparm($function.'.link',$domain),);
 4588:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4589: 
 4590:  # role and realm
 4591:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4592:     if ($role  eq 'ca') {
 4593:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4594:         $realm = &plainname($rname,$rdom);
 4595:     } 
 4596: # realm
 4597:     if ($env{'request.course.id'}) {
 4598:         if ($env{'request.role'} !~ /^cr/) {
 4599:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4600:         }
 4601:         if ($env{'request.course.sec'}) {
 4602:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4603:         }   
 4604: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4605:     } else {
 4606:         $role = &Apache::lonnet::plaintext($role);
 4607:     }
 4608: 
 4609:     if (!$realm) { $realm='&nbsp;'; }
 4610: # Set messages
 4611:     my $messages=&domainlogo($domain);
 4612: 
 4613:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4614: 
 4615: # construct main body tag
 4616:     my $bodytag = "<body $extra_body_attr>".
 4617: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4618: 
 4619:     if ($bodyonly) {
 4620:         return $bodytag;
 4621:     } 
 4622: 
 4623:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4624:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4625: 	undef($role);
 4626:     } else {
 4627: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4628:     }
 4629:     
 4630:     my $titleinfo = '<h1>'.$title.'</h1>';
 4631:     #
 4632:     # Extra info if you are the DC
 4633:     my $dc_info = '';
 4634:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4635:                         $env{'course.'.$env{'request.course.id'}.
 4636:                                  '.domain'}.'/'})) {
 4637:         my $cid = $env{'request.course.id'};
 4638:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4639:         $dc_info =~ s/\s+$//;
 4640:     }
 4641: 
 4642:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4643:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4644: 
 4645:     if ($env{'environment.remote'} eq 'off') {
 4646:         # No Remote
 4647:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4648:             return $bodytag; 
 4649:         } 
 4650: 
 4651:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4652: 
 4653:         #    if ($env{'request.state'} eq 'construct') {
 4654:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4655:         #    }
 4656: 
 4657: 
 4658: 
 4659:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4660:              if ($dc_info) {
 4661:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4662:              }
 4663:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4664:                 <em>$realm</em> $dc_info</div>|;
 4665:             return $bodytag;
 4666:         }
 4667: 
 4668:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4669:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4670:         }
 4671: 
 4672:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4673:             Apache::lonmenu::utilityfunctions(), 'start');
 4674: 
 4675:         $bodytag .= Apache::lonmenu::primary_menu();
 4676: 
 4677:         if ($dc_info) {
 4678:             $dc_info = &dc_courseid_toggle($dc_info);
 4679:         }
 4680:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4681: 
 4682:         #don't show menus for public users
 4683:         if($env{'user.name'} ne 'public' && $env{'user.domain'} ne 'public'){
 4684:             $bodytag .= Apache::lonmenu::secondary_menu();
 4685:             $bodytag .= Apache::lonmenu::serverform();
 4686:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4687:             if ($env{'request.state'} eq 'construct') {
 4688:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,'',
 4689:                                 $args->{'bread_crumbs'});
 4690:             } elsif ($forcereg) { 
 4691:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4692:             }
 4693:         }else{
 4694:             # this is to seperate menu from content when there's no secondary
 4695:             # menu. Especially needed for public accessible ressources.
 4696:             $bodytag .= '<hr style="clear:both" />';
 4697:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4698:         }
 4699: 
 4700:         return $bodytag;
 4701:     }
 4702: 
 4703: #
 4704: # Top frame rendering, Remote is up
 4705: #
 4706: 
 4707:     my $imgsrc = $img;
 4708:     if ($img =~ /^\/adm/) {
 4709:         $imgsrc = &lonhttpdurl($img);
 4710:     }
 4711:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4712: 
 4713:     # Explicit link to get inline menu
 4714:     my $menu= ($no_inline_link?''
 4715: 	       :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 4716: 
 4717:     if ($dc_info) {
 4718:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 4719:     }
 4720: 
 4721:     $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 4722:             <ol class="LC_primary_menu LC_right">
 4723:                 <li>$menu</li>
 4724:             </ol><div id="LC_realm"> $realm $dc_info</div>| unless $env{'form.inhibitmenu'};
 4725:     return(<<ENDBODY);
 4726: $bodytag
 4727: <table id="LC_title_bar" class="LC_with_remote">
 4728: <tr><td>$upperleft</td>
 4729:     <td>$messages&nbsp;</td>
 4730: </tr>
 4731: <tr><td>$titleinfo $dc_info $menu</td>
 4732: </tr>
 4733: </table>
 4734: ENDBODY
 4735: }
 4736: 
 4737: sub dc_courseid_toggle {
 4738:     my ($dc_info) = @_;
 4739:     return ' <span id="dccidtext" class="LC_cusr_subheading">'.
 4740:            '<a href="javascript:showCourseID();">'.
 4741:            &mt('(More ...)').'</a></span>'.
 4742:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4743: }
 4744: 
 4745: sub make_attr_string {
 4746:     my ($register,$attr_ref) = @_;
 4747: 
 4748:     if ($attr_ref && !ref($attr_ref)) {
 4749: 	die("addentries Must be a hash ref ".
 4750: 	    join(':',caller(1))." ".
 4751: 	    join(':',caller(0))." ");
 4752:     }
 4753: 
 4754:     if ($register) {
 4755: 	my ($on_load,$on_unload);
 4756: 	foreach my $key (keys(%{$attr_ref})) {
 4757: 	    if      (lc($key) eq 'onload') {
 4758: 		$on_load.=$attr_ref->{$key}.';';
 4759: 		delete($attr_ref->{$key});
 4760: 
 4761: 	    } elsif (lc($key) eq 'onunload') {
 4762: 		$on_unload.=$attr_ref->{$key}.';';
 4763: 		delete($attr_ref->{$key});
 4764: 	    }
 4765: 	}
 4766: 	$attr_ref->{'onload'}  =
 4767: 	    &Apache::lonmenu::loadevents().  $on_load;
 4768: 	$attr_ref->{'onunload'}=
 4769: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4770:     }
 4771: 
 4772: # Accessibility font enhance
 4773:     if ($env{'browser.fontenhance'} eq 'on') {
 4774: 	my $style;
 4775: 	foreach my $key (keys(%{$attr_ref})) {
 4776: 	    if (lc($key) eq 'style') {
 4777: 		$style.=$attr_ref->{$key}.';';
 4778: 		delete($attr_ref->{$key});
 4779: 	    }
 4780: 	}
 4781: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4782:     }
 4783: 
 4784:     my $attr_string;
 4785:     foreach my $attr (keys(%$attr_ref)) {
 4786: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4787:     }
 4788:     return $attr_string;
 4789: }
 4790: 
 4791: 
 4792: ###############################################
 4793: ###############################################
 4794: 
 4795: =pod
 4796: 
 4797: =item * &endbodytag()
 4798: 
 4799: Returns a uniform footer for LON-CAPA web pages.
 4800: 
 4801: Inputs: 1 - optional reference to an args hash
 4802: If in the hash, key for noredirectlink has a value which evaluates to true,
 4803: a 'Continue' link is not displayed if the page contains an
 4804: internal redirect in the <head></head> section,
 4805: i.e., $env{'internal.head.redirect'} exists   
 4806: 
 4807: =cut
 4808: 
 4809: sub endbodytag {
 4810:     my ($args) = @_;
 4811:     my $endbodytag='</body>';
 4812:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4813:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4814:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4815: 	    $endbodytag=
 4816: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4817: 	        &mt('Continue').'</a>'.
 4818: 	        $endbodytag;
 4819:         }
 4820:     }
 4821:     return $endbodytag;
 4822: }
 4823: 
 4824: =pod
 4825: 
 4826: =item * &standard_css()
 4827: 
 4828: Returns a style sheet
 4829: 
 4830: Inputs: (all optional)
 4831:             domain         -> force to color decorate a page for a specific
 4832:                                domain
 4833:             function       -> force usage of a specific rolish color scheme
 4834:             bgcolor        -> override the default page bgcolor
 4835: 
 4836: =cut
 4837: 
 4838: sub standard_css {
 4839:     my ($function,$domain,$bgcolor) = @_;
 4840:     $function  = &get_users_function() if (!$function);
 4841:     my $img    = &designparm($function.'.img',   $domain);
 4842:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4843:     my $font   = &designparm($function.'.font',  $domain);
 4844:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4845: #second colour for later usage
 4846:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4847:     my $pgbg_or_bgcolor =
 4848: 	         $bgcolor ||
 4849: 	         &designparm($function.'.pgbg',  $domain);
 4850:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4851:     my $alink  = &designparm($function.'.alink', $domain);
 4852:     my $vlink  = &designparm($function.'.vlink', $domain);
 4853:     my $link   = &designparm($function.'.link',  $domain);
 4854: 
 4855:     my $loginbg = &designparm('login.sidebg',$domain);
 4856:     my $bgcol = &designparm('login.bgcol',$domain);
 4857:     my $textcol = &designparm('login.textcol',$domain);
 4858: 
 4859:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4860:     my $mono                 = 'monospace';
 4861:     my $data_table_head      = $sidebg;
 4862:     my $data_table_light     = '#FAFAFA';
 4863:     my $data_table_dark      = '#F0F0F0';
 4864:     my $data_table_darker    = '#CCCCCC';
 4865:     my $data_table_highlight = '#FFFF00';
 4866:     my $mail_new             = '#FFBB77';
 4867:     my $mail_new_hover       = '#DD9955';
 4868:     my $mail_read            = '#BBBB77';
 4869:     my $mail_read_hover      = '#999944';
 4870:     my $mail_replied         = '#AAAA88';
 4871:     my $mail_replied_hover   = '#888855';
 4872:     my $mail_other           = '#99BBBB';
 4873:     my $mail_other_hover     = '#669999';
 4874:     my $table_header         = '#DDDDDD';
 4875:     my $feedback_link_bg     = '#BBBBBB';
 4876:     my $lg_border_color      = '#C8C8C8';
 4877: 
 4878:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4879:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4880:                                              : '0 3px 0 4px';
 4881: 
 4882: 
 4883:     return <<END;
 4884: 
 4885: /* needed for iframe to allow 100% height in FF */
 4886: body, html { 
 4887:     margin: 0;
 4888:     padding: 0 0.5%;
 4889:     height: 99%; /* to avoid scrollbars */
 4890: }
 4891: 
 4892: body {
 4893:   font-family: $sans;
 4894:   line-height:130%;
 4895:   font-size:0.83em;
 4896:   color:$font;
 4897: }
 4898: 
 4899: a:focus {
 4900:   color: red;
 4901:   background: yellow;
 4902: }
 4903: 
 4904: form, .inline {
 4905:   display: inline;
 4906: }
 4907: 
 4908: .LC_right {
 4909:   text-align:right;
 4910: }
 4911: 
 4912: .LC_middle {
 4913:   vertical-align:middle;
 4914: }
 4915: 
 4916: .LC_400Box {
 4917:   width:400px;
 4918: }
 4919: 
 4920: .LC_iframecontainer {
 4921:     width: 98%;
 4922:     margin: 0;
 4923:     position: fixed;
 4924:     top: 8.5em;
 4925:     bottom: 0;
 4926: }
 4927: 
 4928: .LC_iframecontainer iframe{
 4929:     border: none;
 4930:     width: 100%;
 4931:     height: 100%;
 4932: }
 4933: 
 4934: .LC_filename {
 4935:   font-family: $mono;
 4936:   white-space:pre;
 4937:   font-size: 120%;
 4938: }
 4939: 
 4940: .LC_fileicon {
 4941:   border: none;
 4942:   height: 1.3em;
 4943:   vertical-align: text-bottom;
 4944:   margin-right: 0.3em;
 4945:   text-decoration:none;
 4946: }
 4947: 
 4948: .LC_error {
 4949:   color: red;
 4950:   font-size: larger;
 4951: }
 4952: 
 4953: .LC_warning,
 4954: .LC_diff_removed {
 4955:   color: red;
 4956: }
 4957: 
 4958: .LC_info,
 4959: .LC_success,
 4960: .LC_diff_added {
 4961:   color: green;
 4962: }
 4963: 
 4964: div.LC_confirm_box {
 4965:   background-color: #FAFAFA;
 4966:   border: 1px solid $lg_border_color;
 4967:   margin-right: 0;
 4968:   padding: 5px;
 4969: }
 4970: 
 4971: div.LC_confirm_box .LC_error img,
 4972: div.LC_confirm_box .LC_success img {
 4973:   vertical-align: middle;
 4974: }
 4975: 
 4976: .LC_icon {
 4977:   border: none;
 4978:   vertical-align: middle;
 4979: }
 4980: 
 4981: .LC_docs_spacer {
 4982:   width: 25px;
 4983:   height: 1px;
 4984:   border: none;
 4985: }
 4986: 
 4987: .LC_internal_info {
 4988:   color: #999999;
 4989: }
 4990: 
 4991: .LC_discussion {
 4992:   background: $tabbg;
 4993:   border: 1px solid black;
 4994:   margin: 2px;
 4995: }
 4996: 
 4997: .LC_disc_action_links_bar {
 4998:   background: $tabbg;
 4999:   border: none;
 5000:   margin: 4px;
 5001: }
 5002: 
 5003: .LC_disc_action_left {
 5004:   text-align: left;
 5005: }
 5006: 
 5007: .LC_disc_action_right {
 5008:   text-align: right;
 5009: }
 5010: 
 5011: .LC_disc_new_item {
 5012:   background: white;
 5013:   border: 2px solid red;
 5014:   margin: 2px;
 5015: }
 5016: 
 5017: .LC_disc_old_item {
 5018:   background: white;
 5019:   border: 1px solid black;
 5020:   margin: 2px;
 5021: }
 5022: 
 5023: table.LC_pastsubmission {
 5024:   border: 1px solid black;
 5025:   margin: 2px;
 5026: }
 5027: 
 5028: table#LC_menubuttons {
 5029:   width: 100%;
 5030:   background: $pgbg;
 5031:   border: 2px;
 5032:   border-collapse: separate;
 5033:   padding: 0;
 5034: }
 5035: 
 5036: table#LC_title_bar a {
 5037:   color: $fontmenu;
 5038: }
 5039: 
 5040: table#LC_title_bar {
 5041:   clear: both;
 5042:   display: none;
 5043: }
 5044: 
 5045: table#LC_title_bar,
 5046: table.LC_breadcrumbs, /* obsolete? */
 5047: table#LC_title_bar.LC_with_remote {
 5048:   width: 100%;
 5049:   border-color: $pgbg;
 5050:   border-style: solid;
 5051:   border-width: $border;
 5052:   background: $pgbg;
 5053:   color: $fontmenu;
 5054:   border-collapse: collapse;
 5055:   padding: 0;
 5056:   margin: 0;
 5057: }
 5058: 
 5059: ul.LC_breadcrumb_tools_outerlist {
 5060:     margin: 0;
 5061:     padding: 0;
 5062:     position: relative;
 5063:     list-style: none;
 5064: }
 5065: ul.LC_breadcrumb_tools_outerlist li {
 5066:     display: inline;
 5067: }
 5068: 
 5069: .LC_breadcrumb_tools_navigation {
 5070:     padding: 0;
 5071:     margin: 0;
 5072:     float: left;
 5073: }
 5074: .LC_breadcrumb_tools_tools {
 5075:     padding: 0;
 5076:     margin: 0;
 5077:     float: right;
 5078: }
 5079: 
 5080: table#LC_title_bar td {
 5081:   background: $tabbg;
 5082: }
 5083: 
 5084: table#LC_menubuttons img {
 5085:   border: none;
 5086: }
 5087: 
 5088: .LC_breadcrumbs_component {
 5089:   float: right;
 5090:   margin: 0 1em;
 5091: }
 5092: .LC_breadcrumbs_component img {
 5093:   vertical-align: middle;
 5094: }
 5095: 
 5096: td.LC_table_cell_checkbox {
 5097:   text-align: center;
 5098: }
 5099: 
 5100: .LC_fontsize_small {
 5101:   font-size: 70%;
 5102: }
 5103: 
 5104: #LC_breadcrumbs {
 5105:   clear:both;
 5106:   background: $sidebg;
 5107:   border-bottom: 1px solid $lg_border_color;
 5108:   line-height: 2.5em;
 5109:   overflow: hidden;
 5110:   margin: 0;
 5111:   padding: 0;
 5112: }
 5113: 
 5114: /* Preliminary fix to hide breadcrumbs inside remote control window */
 5115: #LC_remote #LC_breadcrumbs {
 5116:   display:none;
 5117: }
 5118: 
 5119: #LC_head_subbox {
 5120:   clear:both;
 5121:   background: #F8F8F8; /* $sidebg; */
 5122:   border: 1px solid $sidebg;
 5123:   margin: 0 0 10px 0;      
 5124: }
 5125: 
 5126: .LC_fontsize_medium {
 5127:   font-size: 85%;
 5128: }
 5129: 
 5130: .LC_fontsize_large {
 5131:   font-size: 120%;
 5132: }
 5133: 
 5134: .LC_menubuttons_inline_text {
 5135:   color: $font;
 5136:   font-size: 90%;
 5137:   padding-left:3px;
 5138: }
 5139: 
 5140: .LC_menubuttons_inline_text img{
 5141:   vertical-align: middle;
 5142: }
 5143: 
 5144: .LC_menubuttons_link {
 5145:   text-decoration: none;
 5146: }
 5147: 
 5148: .LC_menubuttons_category {
 5149:   color: $font;
 5150:   background: $pgbg;
 5151:   font-size: larger;
 5152:   font-weight: bold;
 5153: }
 5154: 
 5155: td.LC_menubuttons_text {
 5156:   color: $font;
 5157: }
 5158: 
 5159: .LC_current_location {
 5160:   background: $tabbg;
 5161: }
 5162: 
 5163: table.LC_data_table {
 5164:   border: 1px solid #000000;
 5165:   border-collapse: separate;
 5166:   border-spacing: 1px;
 5167:   background: $pgbg;
 5168: }
 5169: 
 5170: .LC_data_table_dense {
 5171:   font-size: small;
 5172: }
 5173: 
 5174: table.LC_nested_outer {
 5175:   border: 1px solid #000000;
 5176:   border-collapse: collapse;
 5177:   border-spacing: 0;
 5178:   width: 100%;
 5179: }
 5180: 
 5181: table.LC_innerpickbox,
 5182: table.LC_nested {
 5183:   border: none;
 5184:   border-collapse: collapse;
 5185:   border-spacing: 0;
 5186:   width: 100%;
 5187: }
 5188: 
 5189: .ui-accordion,
 5190: .ui-accordion table.LC_data_table,
 5191: .ui-accordion table.LC_nested_outer{
 5192:   border: 0px;
 5193:   border-spacing: 0px;
 5194:   margin: 3px;
 5195: }
 5196: 
 5197: table.LC_data_table tr th,
 5198: table.LC_calendar tr th,
 5199: table.LC_prior_tries tr th,
 5200: table.LC_innerpickbox tr th {
 5201:   font-weight: bold;
 5202:   background-color: $data_table_head;
 5203:   color:$fontmenu;
 5204:   font-size:90%;
 5205: }
 5206: 
 5207: table.LC_innerpickbox tr th,
 5208: table.LC_innerpickbox tr td {
 5209:   vertical-align: top;
 5210: }
 5211: 
 5212: table.LC_data_table tr.LC_info_row > td {
 5213:   background-color: #CCCCCC;
 5214:   font-weight: bold;
 5215:   text-align: left;
 5216: }
 5217: 
 5218: table.LC_data_table tr.LC_odd_row > td {
 5219:   background-color: $data_table_light;
 5220:   padding: 2px;
 5221:   vertical-align: top;
 5222: }
 5223: 
 5224: table.LC_pick_box tr > td.LC_odd_row {
 5225:   background-color: $data_table_light;
 5226:   vertical-align: top;
 5227: }
 5228: 
 5229: table.LC_data_table tr.LC_even_row > td {
 5230:   background-color: $data_table_dark;
 5231:   padding: 2px;
 5232:   vertical-align: top;
 5233: }
 5234: 
 5235: table.LC_pick_box tr > td.LC_even_row {
 5236:   background-color: $data_table_dark;
 5237:   vertical-align: top;
 5238: }
 5239: 
 5240: table.LC_data_table tr.LC_data_table_highlight td {
 5241:   background-color: $data_table_darker;
 5242: }
 5243: 
 5244: table.LC_data_table tr td.LC_leftcol_header {
 5245:   background-color: $data_table_head;
 5246:   font-weight: bold;
 5247: }
 5248: 
 5249: table.LC_data_table tr.LC_empty_row td,
 5250: table.LC_nested tr.LC_empty_row td {
 5251:   font-weight: bold;
 5252:   font-style: italic;
 5253:   text-align: center;
 5254:   padding: 8px;
 5255: }
 5256: 
 5257: table.LC_data_table tr.LC_empty_row td {
 5258:   background-color: $sidebg;
 5259: }
 5260: 
 5261: table.LC_nested tr.LC_empty_row td {
 5262:   background-color: #FFFFFF;
 5263: }
 5264: 
 5265: table.LC_caption {
 5266: }
 5267: 
 5268: table.LC_nested tr.LC_empty_row td {
 5269:   padding: 4ex
 5270: }
 5271: 
 5272: table.LC_nested_outer tr th {
 5273:   font-weight: bold;
 5274:   color:$fontmenu;
 5275:   background-color: $data_table_head;
 5276:   font-size: small;
 5277:   border-bottom: 1px solid #000000;
 5278: }
 5279: 
 5280: table.LC_nested_outer tr td.LC_subheader {
 5281:   background-color: $data_table_head;
 5282:   font-weight: bold;
 5283:   font-size: small;
 5284:   border-bottom: 1px solid #000000;
 5285:   text-align: right;
 5286: }
 5287: 
 5288: table.LC_nested tr.LC_info_row td {
 5289:   background-color: #CCCCCC;
 5290:   font-weight: bold;
 5291:   font-size: small;
 5292:   text-align: center;
 5293: }
 5294: 
 5295: table.LC_nested tr.LC_info_row td.LC_left_item,
 5296: table.LC_nested_outer tr th.LC_left_item {
 5297:   text-align: left;
 5298: }
 5299: 
 5300: table.LC_nested td {
 5301:   background-color: #FFFFFF;
 5302:   font-size: small;
 5303: }
 5304: 
 5305: table.LC_nested_outer tr th.LC_right_item,
 5306: table.LC_nested tr.LC_info_row td.LC_right_item,
 5307: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5308: table.LC_nested tr td.LC_right_item {
 5309:   text-align: right;
 5310: }
 5311: 
 5312: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
 5313: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
 5314:   text-align: right;
 5315:   width: 40%;
 5316:   padding-right:10px;
 5317:   vertical-align: top;
 5318:   padding: 5px;
 5319: }
 5320: 
 5321: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
 5322: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
 5323:   text-align: left;
 5324:   width: 60%;
 5325:   padding: 2px 4px;
 5326: }
 5327: 
 5328: table.LC_nested tr.LC_odd_row td {
 5329:   background-color: #EEEEEE;
 5330: }
 5331: 
 5332: table.LC_createuser {
 5333: }
 5334: 
 5335: table.LC_createuser tr.LC_section_row td {
 5336:   font-size: small;
 5337: }
 5338: 
 5339: table.LC_createuser tr.LC_info_row td  {
 5340:   background-color: #CCCCCC;
 5341:   font-weight: bold;
 5342:   text-align: center;
 5343: }
 5344: 
 5345: table.LC_calendar {
 5346:   border: 1px solid #000000;
 5347:   border-collapse: collapse;
 5348:   width: 98%;
 5349: }
 5350: 
 5351: table.LC_calendar_pickdate {
 5352:   font-size: xx-small;
 5353: }
 5354: 
 5355: table.LC_calendar tr td {
 5356:   border: 1px solid #000000;
 5357:   vertical-align: top;
 5358:   width: 14%;
 5359: }
 5360: 
 5361: table.LC_calendar tr td.LC_calendar_day_empty {
 5362:   background-color: $data_table_dark;
 5363: }
 5364: 
 5365: table.LC_calendar tr td.LC_calendar_day_current {
 5366:   background-color: $data_table_highlight;
 5367: }
 5368: 
 5369: table.LC_data_table tr td.LC_mail_new {
 5370:   background-color: $mail_new;
 5371: }
 5372: 
 5373: table.LC_data_table tr.LC_mail_new:hover {
 5374:   background-color: $mail_new_hover;
 5375: }
 5376: 
 5377: table.LC_data_table tr td.LC_mail_read {
 5378:   background-color: $mail_read;
 5379: }
 5380: 
 5381: /*
 5382: table.LC_data_table tr.LC_mail_read:hover {
 5383:   background-color: $mail_read_hover;
 5384: }
 5385: */
 5386: 
 5387: table.LC_data_table tr td.LC_mail_replied {
 5388:   background-color: $mail_replied;
 5389: }
 5390: 
 5391: /*
 5392: table.LC_data_table tr.LC_mail_replied:hover {
 5393:   background-color: $mail_replied_hover;
 5394: }
 5395: */
 5396: 
 5397: table.LC_data_table tr td.LC_mail_other {
 5398:   background-color: $mail_other;
 5399: }
 5400: 
 5401: /*
 5402: table.LC_data_table tr.LC_mail_other:hover {
 5403:   background-color: $mail_other_hover;
 5404: }
 5405: */
 5406: 
 5407: table.LC_data_table tr > td.LC_browser_file,
 5408: table.LC_data_table tr > td.LC_browser_file_published {
 5409:   background: #AAEE77;
 5410: }
 5411: 
 5412: table.LC_data_table tr > td.LC_browser_file_locked,
 5413: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5414:   background: #FFAA99;
 5415: }
 5416: 
 5417: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5418:   background: #888888;
 5419: }
 5420: 
 5421: table.LC_data_table tr > td.LC_browser_file_modified,
 5422: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5423:   background: #F8F866;
 5424: }
 5425: 
 5426: table.LC_data_table tr.LC_browser_folder > td {
 5427:   background: #E0E8FF;
 5428: }
 5429: 
 5430: table.LC_data_table tr > td.LC_roles_is {
 5431:   /* background: #77FF77; */
 5432: }
 5433: 
 5434: table.LC_data_table tr > td.LC_roles_future {
 5435:   border-right: 8px solid #FFFF77;
 5436: }
 5437: 
 5438: table.LC_data_table tr > td.LC_roles_will {
 5439:   border-right: 8px solid #FFAA77;
 5440: }
 5441: 
 5442: table.LC_data_table tr > td.LC_roles_expired {
 5443:   border-right: 8px solid #FF7777;
 5444: }
 5445: 
 5446: table.LC_data_table tr > td.LC_roles_will_not {
 5447:   border-right: 8px solid #AAFF77;
 5448: }
 5449: 
 5450: table.LC_data_table tr > td.LC_roles_selected {
 5451:   border-right: 8px solid #11CC55;
 5452: }
 5453: 
 5454: span.LC_current_location {
 5455:   font-size:larger;
 5456:   background: $pgbg;
 5457: }
 5458: 
 5459: span.LC_parm_menu_item {
 5460:   font-size: larger;
 5461: }
 5462: 
 5463: span.LC_parm_scope_all {
 5464:   color: red;
 5465: }
 5466: 
 5467: span.LC_parm_scope_folder {
 5468:   color: green;
 5469: }
 5470: 
 5471: span.LC_parm_scope_resource {
 5472:   color: orange;
 5473: }
 5474: 
 5475: span.LC_parm_part {
 5476:   color: blue;
 5477: }
 5478: 
 5479: span.LC_parm_folder,
 5480: span.LC_parm_symb {
 5481:   font-size: x-small;
 5482:   font-family: $mono;
 5483:   color: #AAAAAA;
 5484: }
 5485: 
 5486: td.LC_parm_overview_level_menu,
 5487: td.LC_parm_overview_map_menu,
 5488: td.LC_parm_overview_parm_selectors,
 5489: td.LC_parm_overview_restrictions  {
 5490:   border: 1px solid black;
 5491:   border-collapse: collapse;
 5492: }
 5493: 
 5494: table.LC_parm_overview_restrictions td {
 5495:   border-width: 1px 4px 1px 4px;
 5496:   border-style: solid;
 5497:   border-color: $pgbg;
 5498:   text-align: center;
 5499: }
 5500: 
 5501: table.LC_parm_overview_restrictions th {
 5502:   background: $tabbg;
 5503:   border-width: 1px 4px 1px 4px;
 5504:   border-style: solid;
 5505:   border-color: $pgbg;
 5506: }
 5507: 
 5508: table#LC_helpmenu {
 5509:   border: none;
 5510:   height: 55px;
 5511:   border-spacing: 0;
 5512: }
 5513: 
 5514: table#LC_helpmenu fieldset legend {
 5515:   font-size: larger;
 5516: }
 5517: 
 5518: table#LC_helpmenu_links {
 5519:   width: 100%;
 5520:   border: 1px solid black;
 5521:   background: $pgbg;
 5522:   padding: 0;
 5523:   border-spacing: 1px;
 5524: }
 5525: 
 5526: table#LC_helpmenu_links tr td {
 5527:   padding: 1px;
 5528:   background: $tabbg;
 5529:   text-align: center;
 5530:   font-weight: bold;
 5531: }
 5532: 
 5533: table#LC_helpmenu_links a:link,
 5534: table#LC_helpmenu_links a:visited,
 5535: table#LC_helpmenu_links a:active {
 5536:   text-decoration: none;
 5537:   color: $font;
 5538: }
 5539: 
 5540: table#LC_helpmenu_links a:hover {
 5541:   text-decoration: underline;
 5542:   color: $vlink;
 5543: }
 5544: 
 5545: .LC_chrt_popup_exists {
 5546:   border: 1px solid #339933;
 5547:   margin: -1px;
 5548: }
 5549: 
 5550: .LC_chrt_popup_up {
 5551:   border: 1px solid yellow;
 5552:   margin: -1px;
 5553: }
 5554: 
 5555: .LC_chrt_popup {
 5556:   border: 1px solid #8888FF;
 5557:   background: #CCCCFF;
 5558: }
 5559: 
 5560: table.LC_pick_box {
 5561:   border-collapse: separate;
 5562:   background: white;
 5563:   border: 1px solid black;
 5564:   border-spacing: 1px;
 5565: }
 5566: 
 5567: table.LC_pick_box td.LC_pick_box_title {
 5568:   background: $sidebg;
 5569:   font-weight: bold;
 5570:   text-align: left;
 5571:   vertical-align: top;
 5572:   width: 184px;
 5573:   padding: 8px;
 5574: }
 5575: 
 5576: table.LC_pick_box td.LC_pick_box_value {
 5577:   text-align: left;
 5578:   padding: 8px;
 5579: }
 5580: 
 5581: table.LC_pick_box td.LC_pick_box_select {
 5582:   text-align: left;
 5583:   padding: 8px;
 5584: }
 5585: 
 5586: table.LC_pick_box td.LC_pick_box_separator {
 5587:   padding: 0;
 5588:   height: 1px;
 5589:   background: black;
 5590: }
 5591: 
 5592: table.LC_pick_box td.LC_pick_box_submit {
 5593:   text-align: right;
 5594: }
 5595: 
 5596: table.LC_pick_box td.LC_evenrow_value {
 5597:   text-align: left;
 5598:   padding: 8px;
 5599:   background-color: $data_table_light;
 5600: }
 5601: 
 5602: table.LC_pick_box td.LC_oddrow_value {
 5603:   text-align: left;
 5604:   padding: 8px;
 5605:   background-color: $data_table_light;
 5606: }
 5607: 
 5608: span.LC_helpform_receipt_cat {
 5609:   font-weight: bold;
 5610: }
 5611: 
 5612: table.LC_group_priv_box {
 5613:   background: white;
 5614:   border: 1px solid black;
 5615:   border-spacing: 1px;
 5616: }
 5617: 
 5618: table.LC_group_priv_box td.LC_pick_box_title {
 5619:   background: $tabbg;
 5620:   font-weight: bold;
 5621:   text-align: right;
 5622:   width: 184px;
 5623: }
 5624: 
 5625: table.LC_group_priv_box td.LC_groups_fixed {
 5626:   background: $data_table_light;
 5627:   text-align: center;
 5628: }
 5629: 
 5630: table.LC_group_priv_box td.LC_groups_optional {
 5631:   background: $data_table_dark;
 5632:   text-align: center;
 5633: }
 5634: 
 5635: table.LC_group_priv_box td.LC_groups_functionality {
 5636:   background: $data_table_darker;
 5637:   text-align: center;
 5638:   font-weight: bold;
 5639: }
 5640: 
 5641: table.LC_group_priv td {
 5642:   text-align: left;
 5643:   padding: 0;
 5644: }
 5645: 
 5646: table.LC_notify_front_page {
 5647:   background: white;
 5648:   border: 1px solid black;
 5649:   padding: 8px;
 5650: }
 5651: 
 5652: table.LC_notify_front_page td {
 5653:   padding: 8px;
 5654: }
 5655: 
 5656: .LC_navbuttons {
 5657:   margin: 2ex 0ex 2ex 0ex;
 5658: }
 5659: 
 5660: .LC_topic_bar {
 5661:   font-weight: bold;
 5662:   background: $tabbg;
 5663:   margin: 1em 0em 1em 2em;
 5664:   padding: 3px;
 5665:   font-size: 1.2em;
 5666: }
 5667: 
 5668: .LC_topic_bar span {
 5669:   left: 0.5em;
 5670:   position: absolute;
 5671:   vertical-align: middle;
 5672:   font-size: 1.2em;
 5673: }
 5674: 
 5675: table.LC_course_group_status {
 5676:   margin: 20px;
 5677: }
 5678: 
 5679: table.LC_status_selector td {
 5680:   vertical-align: top;
 5681:   text-align: center;
 5682:   padding: 4px;
 5683: }
 5684: 
 5685: div.LC_feedback_link {
 5686:   clear: both;
 5687:   background: $sidebg;
 5688:   width: 100%;
 5689:   padding-bottom: 10px;
 5690:   border: 1px $tabbg solid;
 5691:   height: 22px;
 5692:   line-height: 22px;
 5693:   padding-top: 5px;
 5694: }
 5695: 
 5696: div.LC_feedback_link img {
 5697:   height: 22px;
 5698:   vertical-align:middle;
 5699: }
 5700: 
 5701: div.LC_feedback_link a {
 5702:   text-decoration: none;
 5703: }
 5704: 
 5705: div.LC_comblock {
 5706:   display:inline;
 5707:   color:$font;
 5708:   font-size:90%;
 5709: }
 5710: 
 5711: div.LC_feedback_link div.LC_comblock {
 5712:   padding-left:5px;
 5713: }
 5714: 
 5715: div.LC_feedback_link div.LC_comblock a {
 5716:   color:$font;
 5717: }
 5718: 
 5719: span.LC_feedback_link {
 5720:   /* background: $feedback_link_bg; */
 5721:   font-size: larger;
 5722: }
 5723: 
 5724: span.LC_message_link {
 5725:   /* background: $feedback_link_bg; */
 5726:   font-size: larger;
 5727:   position: absolute;
 5728:   right: 1em;
 5729: }
 5730: 
 5731: table.LC_prior_tries {
 5732:   border: 1px solid #000000;
 5733:   border-collapse: separate;
 5734:   border-spacing: 1px;
 5735: }
 5736: 
 5737: table.LC_prior_tries td {
 5738:   padding: 2px;
 5739: }
 5740: 
 5741: .LC_answer_correct {
 5742:   background: lightgreen;
 5743:   color: darkgreen;
 5744:   padding: 6px;
 5745: }
 5746: 
 5747: .LC_answer_charged_try {
 5748:   background: #FFAAAA;
 5749:   color: darkred;
 5750:   padding: 6px;
 5751: }
 5752: 
 5753: .LC_answer_not_charged_try,
 5754: .LC_answer_no_grade,
 5755: .LC_answer_late {
 5756:   background: lightyellow;
 5757:   color: black;
 5758:   padding: 6px;
 5759: }
 5760: 
 5761: .LC_answer_previous {
 5762:   background: lightblue;
 5763:   color: darkblue;
 5764:   padding: 6px;
 5765: }
 5766: 
 5767: .LC_answer_no_message {
 5768:   background: #FFFFFF;
 5769:   color: black;
 5770:   padding: 6px;
 5771: }
 5772: 
 5773: .LC_answer_unknown {
 5774:   background: orange;
 5775:   color: black;
 5776:   padding: 6px;
 5777: }
 5778: 
 5779: span.LC_prior_numerical,
 5780: span.LC_prior_string,
 5781: span.LC_prior_custom,
 5782: span.LC_prior_reaction,
 5783: span.LC_prior_math {
 5784:   font-family: $mono;
 5785:   white-space: pre;
 5786: }
 5787: 
 5788: span.LC_prior_string {
 5789:   font-family: $mono;
 5790:   white-space: pre;
 5791: }
 5792: 
 5793: table.LC_prior_option {
 5794:   width: 100%;
 5795:   border-collapse: collapse;
 5796: }
 5797: 
 5798: table.LC_prior_rank,
 5799: table.LC_prior_match {
 5800:   border-collapse: collapse;
 5801: }
 5802: 
 5803: table.LC_prior_option tr td,
 5804: table.LC_prior_rank tr td,
 5805: table.LC_prior_match tr td {
 5806:   border: 1px solid #000000;
 5807: }
 5808: 
 5809: .LC_nobreak {
 5810:   white-space: nowrap;
 5811: }
 5812: 
 5813: span.LC_cusr_emph {
 5814:   font-style: italic;
 5815: }
 5816: 
 5817: span.LC_cusr_subheading {
 5818:   font-weight: normal;
 5819:   font-size: 85%;
 5820: }
 5821: 
 5822: div.LC_docs_entry_move {
 5823:   border: 1px solid #BBBBBB;
 5824:   background: #DDDDDD;
 5825:   width: 22px;
 5826:   padding: 1px;
 5827:   margin: 0;
 5828: }
 5829: 
 5830: table.LC_data_table tr > td.LC_docs_entry_commands,
 5831: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5832:   background: #DDDDDD;
 5833:   font-size: x-small;
 5834: }
 5835: 
 5836: .LC_docs_entry_parameter {
 5837:   white-space: nowrap;
 5838: }
 5839: 
 5840: .LC_docs_copy {
 5841:   color: #000099;
 5842: }
 5843: 
 5844: .LC_docs_cut {
 5845:   color: #550044;
 5846: }
 5847: 
 5848: .LC_docs_rename {
 5849:   color: #009900;
 5850: }
 5851: 
 5852: .LC_docs_remove {
 5853:   color: #990000;
 5854: }
 5855: 
 5856: .LC_docs_reinit_warn,
 5857: .LC_docs_ext_edit {
 5858:   font-size: x-small;
 5859: }
 5860: 
 5861: table.LC_docs_adddocs td,
 5862: table.LC_docs_adddocs th {
 5863:   border: 1px solid #BBBBBB;
 5864:   padding: 4px;
 5865:   background: #DDDDDD;
 5866: }
 5867: 
 5868: table.LC_sty_begin {
 5869:   background: #BBFFBB;
 5870: }
 5871: 
 5872: table.LC_sty_end {
 5873:   background: #FFBBBB;
 5874: }
 5875: 
 5876: table.LC_double_column {
 5877:   border-width: 0;
 5878:   border-collapse: collapse;
 5879:   width: 100%;
 5880:   padding: 2px;
 5881: }
 5882: 
 5883: table.LC_double_column tr td.LC_left_col {
 5884:   top: 2px;
 5885:   left: 2px;
 5886:   width: 47%;
 5887:   vertical-align: top;
 5888: }
 5889: 
 5890: table.LC_double_column tr td.LC_right_col {
 5891:   top: 2px;
 5892:   right: 2px;
 5893:   width: 47%;
 5894:   vertical-align: top;
 5895: }
 5896: 
 5897: div.LC_left_float {
 5898:   float: left;
 5899:   padding-right: 5%;
 5900:   padding-bottom: 4px;
 5901: }
 5902: 
 5903: div.LC_clear_float_header {
 5904:   padding-bottom: 2px;
 5905: }
 5906: 
 5907: div.LC_clear_float_footer {
 5908:   padding-top: 10px;
 5909:   clear: both;
 5910: }
 5911: 
 5912: div.LC_grade_show_user {
 5913: /*  border-left: 5px solid $sidebg; */
 5914:   border-top: 5px solid #000000;
 5915:   margin: 50px 0 0 0;
 5916:   padding: 15px 0 5px 10px;
 5917: }
 5918: 
 5919: div.LC_grade_show_user_odd_row {
 5920: /*  border-left: 5px solid #000000; */
 5921: }
 5922: 
 5923: div.LC_grade_show_user div.LC_Box {
 5924:   margin-right: 50px;
 5925: }
 5926: 
 5927: div.LC_grade_submissions,
 5928: div.LC_grade_message_center,
 5929: div.LC_grade_info_links {
 5930:   margin: 5px;
 5931:   width: 99%;
 5932:   background: #FFFFFF;
 5933: }
 5934: 
 5935: div.LC_grade_submissions_header,
 5936: div.LC_grade_message_center_header {
 5937:   font-weight: bold;
 5938:   font-size: large;
 5939: }
 5940: 
 5941: div.LC_grade_submissions_body,
 5942: div.LC_grade_message_center_body {
 5943:   border: 1px solid black;
 5944:   width: 99%;
 5945:   background: #FFFFFF;
 5946: }
 5947: 
 5948: table.LC_scantron_action {
 5949:   width: 100%;
 5950: }
 5951: 
 5952: table.LC_scantron_action tr th {
 5953:   font-weight:bold;
 5954:   font-style:normal;
 5955: }
 5956: 
 5957: .LC_edit_problem_header,
 5958: div.LC_edit_problem_footer {
 5959:   font-weight: normal;
 5960:   font-size:  medium;
 5961:   margin: 2px;
 5962: }
 5963: 
 5964: div.LC_edit_problem_header,
 5965: div.LC_edit_problem_header div,
 5966: div.LC_edit_problem_footer,
 5967: div.LC_edit_problem_footer div,
 5968: div.LC_edit_problem_editxml_header,
 5969: div.LC_edit_problem_editxml_header div {
 5970:   margin-top: 5px;
 5971: }
 5972: 
 5973: div.LC_edit_problem_header_title {
 5974:   font-weight: bold;
 5975:   font-size: larger;
 5976:   background: $tabbg;
 5977:   padding: 3px;
 5978: }
 5979: 
 5980: table.LC_edit_problem_header_title {
 5981:   width: 100%;
 5982:   background: $tabbg;
 5983: }
 5984: 
 5985: div.LC_edit_problem_discards {
 5986:   float: left;
 5987:   padding-bottom: 5px;
 5988: }
 5989: 
 5990: div.LC_edit_problem_saves {
 5991:   float: right;
 5992:   padding-bottom: 5px;
 5993: }
 5994: 
 5995: img.stift {
 5996:   border-width: 0;
 5997:   vertical-align: middle;
 5998: }
 5999: 
 6000: table td.LC_mainmenu_col_fieldset {
 6001:   vertical-align: top;
 6002: }
 6003: 
 6004: div.LC_createcourse {
 6005:   margin: 10px 10px 10px 10px;
 6006: }
 6007: 
 6008: .LC_dccid {
 6009:   margin: 0.2em 0 0 0;
 6010:   padding: 0;
 6011:   font-size: 90%;
 6012:   display:none;
 6013: }
 6014: 
 6015: a:hover,
 6016: ol.LC_primary_menu a:hover,
 6017: ol#LC_MenuBreadcrumbs a:hover,
 6018: ol#LC_PathBreadcrumbs a:hover,
 6019: ul#LC_secondary_menu a:hover,
 6020: .LC_FormSectionClearButton input:hover
 6021: ul.LC_TabContent   li:hover a {
 6022:   color:#BF2317;
 6023:   text-decoration:none;
 6024: }
 6025: 
 6026: h1 {
 6027:   padding: 0;
 6028:   line-height:130%;
 6029: }
 6030: 
 6031: h2,
 6032: h3,
 6033: h4,
 6034: h5,
 6035: h6 {
 6036:   margin: 5px 0 5px 0;
 6037:   padding: 0;
 6038:   line-height:130%;
 6039: }
 6040: 
 6041: .LC_hcell {
 6042:   padding:3px 15px 3px 15px;
 6043:   margin: 0;
 6044:   background-color:$tabbg;
 6045:   color:$fontmenu;
 6046:   border-bottom:solid 1px $lg_border_color;
 6047: }
 6048: 
 6049: .LC_Box > .LC_hcell {
 6050:   margin: 0 -10px 10px -10px;
 6051: }
 6052: 
 6053: .LC_noBorder {
 6054:   border: 0;
 6055: }
 6056: 
 6057: .LC_FormSectionClearButton input {
 6058:   background-color:transparent;
 6059:   border: none;
 6060:   cursor:pointer;
 6061:   text-decoration:underline;
 6062: }
 6063: 
 6064: .LC_help_open_topic {
 6065:   color: #FFFFFF;
 6066:   background-color: #EEEEFF;
 6067:   margin: 1px;
 6068:   padding: 4px;
 6069:   border: 1px solid #000033;
 6070:   white-space: nowrap;
 6071:   /* vertical-align: middle; */
 6072: }
 6073: 
 6074: dl,
 6075: ul,
 6076: div,
 6077: fieldset {
 6078:   margin: 10px 10px 10px 0;
 6079:   /* overflow: hidden; */
 6080: }
 6081: 
 6082: fieldset > legend {
 6083:   font-weight: bold;
 6084:   padding: 0 5px 0 5px;
 6085: }
 6086: 
 6087: #LC_nav_bar {
 6088:   float: left;
 6089:   margin: 0;
 6090: }
 6091: 
 6092: #LC_realm {
 6093:   margin: 0.2em 0 0 0;
 6094:   padding: 0;
 6095:   font-weight: bold;
 6096:   text-align: center;
 6097: }
 6098: 
 6099: #LC_nav_bar em {
 6100:   font-weight: bold;
 6101:   font-style: normal;
 6102: }
 6103: 
 6104: ol.LC_primary_menu {
 6105:   float: right;
 6106:   margin: 0;
 6107: }
 6108: 
 6109: span.LC_new_message{
 6110:   font-weight:bold;
 6111:   color: darkred;
 6112: }
 6113: 
 6114: ol#LC_PathBreadcrumbs {
 6115:   margin: 0;
 6116: }
 6117: 
 6118: ol.LC_primary_menu li {
 6119:   display: inline;
 6120:   padding: 5px 5px 0 10px;
 6121:   vertical-align: top;
 6122: }
 6123: 
 6124: ol.LC_primary_menu li img {
 6125:   vertical-align: bottom;
 6126:   height: 1.1em;
 6127: }
 6128: 
 6129: ol.LC_primary_menu a {
 6130:   color: RGB(80, 80, 80);
 6131:   text-decoration: none;
 6132: }
 6133: 
 6134: ul#LC_secondary_menu {
 6135:   clear: both;
 6136:   color: $fontmenu;
 6137:   background: $tabbg;
 6138:   list-style: none;
 6139:   padding: 0;
 6140:   margin: 0;
 6141:   width: 100%;
 6142: }
 6143: 
 6144: ul#LC_secondary_menu li {
 6145:   font-weight: bold;
 6146:   line-height: 1.8em;
 6147:   padding: 0 0.8em;
 6148:   border-right: 1px solid black;
 6149:   display: inline;
 6150:   vertical-align: middle;
 6151: }
 6152: 
 6153: ul.LC_TabContent {
 6154:   display:block;
 6155:   background: $sidebg;
 6156:   border-bottom: solid 1px $lg_border_color;
 6157:   list-style:none;
 6158:   margin: 0 -10px;
 6159:   padding: 0;
 6160: }
 6161: 
 6162: ul.LC_TabContent li,
 6163: ul.LC_TabContentBigger li {
 6164:   float:left;
 6165: }
 6166: 
 6167: ul#LC_secondary_menu li a {
 6168:   color: $fontmenu;
 6169:   text-decoration: none;
 6170: }
 6171: 
 6172: ul.LC_TabContent {
 6173:   min-height:1.5em;
 6174: }
 6175: 
 6176: ul.LC_TabContent li {
 6177:   vertical-align:middle;
 6178:   padding: 0 10px 0 10px;
 6179:   background-color:$tabbg;
 6180:   border-bottom:solid 1px $lg_border_color;
 6181: }
 6182: 
 6183: ul.LC_TabContent .right {
 6184:   float:right;
 6185: }
 6186: 
 6187: ul.LC_TabContent li a,
 6188: ul.LC_TabContent li {
 6189:   color:rgb(47,47,47);
 6190:   text-decoration:none;
 6191:   font-size:95%;
 6192:   font-weight:bold;
 6193:   padding-right: 16px;
 6194: }
 6195: 
 6196: ul.LC_TabContent li:hover,
 6197: ul.LC_TabContent li.active {
 6198:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6199:   border-bottom:solid 2px #FFFFFF;
 6200:   padding-right: 16px;
 6201: }
 6202: 
 6203: #maincoursedoc {
 6204:   clear:both;
 6205: }
 6206: 
 6207: ul.LC_TabContentBigger {
 6208:   display:block;
 6209:   list-style:none;
 6210:   padding: 0;
 6211: }
 6212: 
 6213: ul.LC_TabContentBigger li {
 6214:   vertical-align:bottom;
 6215:   height: 30px;
 6216:   font-size:110%;
 6217:   font-weight:bold;
 6218:   color: #737373;
 6219: }
 6220: 
 6221: 
 6222: ul.LC_TabContentBigger li a {
 6223:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6224:   height: 30px;
 6225:   line-height: 30px;
 6226:   text-align: center;
 6227:   display: block;
 6228:   text-decoration: none;
 6229: }
 6230: 
 6231: ul.LC_TabContentBigger li:hover a,
 6232: ul.LC_TabContentBigger li.active a {
 6233:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6234:   color:$font;
 6235:   text-decoration: underline;
 6236: }
 6237: 
 6238: 
 6239: ul.LC_TabContentBigger li b {
 6240:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6241:   display: block;
 6242:   float: left;
 6243:   padding: 0 30px;
 6244: }
 6245: 
 6246: ul.LC_TabContentBigger li:hover b,
 6247: ul.LC_TabContentBigger li.active b {
 6248:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6249:   color:$font;
 6250:   border-bottom: 1px solid #FFFFFF;
 6251: }
 6252: 
 6253: 
 6254: ul.LC_CourseBreadcrumbs {
 6255:   background: $sidebg;
 6256:   line-height: 32px;
 6257:   padding-left: 10px;
 6258:   margin: 0 0 10px 0;
 6259:   list-style-position: inside;
 6260: 
 6261: }
 6262: 
 6263: ol#LC_MenuBreadcrumbs,
 6264: ol#LC_PathBreadcrumbs {
 6265:   padding-left: 10px;
 6266:   margin: 0;
 6267:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6268: }
 6269: 
 6270: ol#LC_MenuBreadcrumbs li,
 6271: ol#LC_PathBreadcrumbs li,
 6272: ul.LC_CourseBreadcrumbs li {
 6273:   display: inline;
 6274:   white-space: normal;  
 6275: }
 6276: 
 6277: ol#LC_MenuBreadcrumbs li a,
 6278: ul.LC_CourseBreadcrumbs li a {
 6279:   text-decoration: none;
 6280:   font-size:90%;
 6281: }
 6282: 
 6283: ol#LC_PathBreadcrumbs li a {
 6284:   text-decoration:none;
 6285:   font-size:100%;
 6286:   font-weight:bold;
 6287: }
 6288: 
 6289: .LC_Box {
 6290:   border: solid 1px $lg_border_color;
 6291:   padding: 0 10px 10px 10px;
 6292: }
 6293: 
 6294: .LC_AboutMe_Image {
 6295:   float:left;
 6296:   margin-right:10px;
 6297: }
 6298: 
 6299: .LC_Clear_AboutMe_Image {
 6300:   clear:left;
 6301: }
 6302: 
 6303: dl.LC_ListStyleClean dt {
 6304:   padding-right: 5px;
 6305:   display: table-header-group;
 6306: }
 6307: 
 6308: dl.LC_ListStyleClean dd {
 6309:   display: table-row;
 6310: }
 6311: 
 6312: .LC_ListStyleClean,
 6313: .LC_ListStyleSimple,
 6314: .LC_ListStyleNormal,
 6315: .LC_ListStyleSpecial {
 6316:   /* display:block; */
 6317:   list-style-position: inside;
 6318:   list-style-type: none;
 6319:   overflow: hidden;
 6320:   padding: 0;
 6321: }
 6322: 
 6323: .LC_ListStyleSimple li,
 6324: .LC_ListStyleSimple dd,
 6325: .LC_ListStyleNormal li,
 6326: .LC_ListStyleNormal dd,
 6327: .LC_ListStyleSpecial li,
 6328: .LC_ListStyleSpecial dd {
 6329:   margin: 0;
 6330:   padding: 5px 5px 5px 10px;
 6331:   clear: both;
 6332: }
 6333: 
 6334: .LC_ListStyleClean li,
 6335: .LC_ListStyleClean dd {
 6336:   padding-top: 0;
 6337:   padding-bottom: 0;
 6338: }
 6339: 
 6340: .LC_ListStyleSimple dd,
 6341: .LC_ListStyleSimple li {
 6342:   border-bottom: solid 1px $lg_border_color;
 6343: }
 6344: 
 6345: .LC_ListStyleSpecial li,
 6346: .LC_ListStyleSpecial dd {
 6347:   list-style-type: none;
 6348:   background-color: RGB(220, 220, 220);
 6349:   margin-bottom: 4px;
 6350: }
 6351: 
 6352: table.LC_SimpleTable {
 6353:   margin:5px;
 6354:   border:solid 1px $lg_border_color;
 6355: }
 6356: 
 6357: table.LC_SimpleTable tr {
 6358:   padding: 0;
 6359:   border:solid 1px $lg_border_color;
 6360: }
 6361: 
 6362: table.LC_SimpleTable thead {
 6363:   background:rgb(220,220,220);
 6364: }
 6365: 
 6366: div.LC_columnSection {
 6367:   display: block;
 6368:   clear: both;
 6369:   overflow: hidden;
 6370:   margin: 0;
 6371: }
 6372: 
 6373: div.LC_columnSection>* {
 6374:   float: left;
 6375:   margin: 10px 20px 10px 0;
 6376:   overflow:hidden;
 6377: }
 6378: 
 6379: .LC_loginpage_container {
 6380:   text-align:left;
 6381:   margin : 0 auto;
 6382:   width:90%;
 6383:   padding: 10px;
 6384:   height: auto;
 6385:   background-color:#FFFFFF;
 6386:   border:1px solid #CCCCCC;
 6387: }
 6388: 
 6389: 
 6390: .LC_loginpage_loginContainer {
 6391:   float:left;
 6392:   width: 182px;
 6393:   padding: 2px;
 6394:   border:1px solid #CCCCCC;
 6395:   background-color:$loginbg;
 6396: }
 6397: 
 6398: .LC_loginpage_loginContainer h2 {
 6399:   margin-top: 0;
 6400:   display:block;
 6401:   background:$bgcol;
 6402:   color:$textcol;
 6403:   padding-left:5px;
 6404: }
 6405: 
 6406: .LC_loginpage_loginInfo {
 6407:   float:left;
 6408:   width:182px;
 6409:   border:1px solid #CCCCCC;
 6410:   padding:2px;
 6411: }
 6412: 
 6413: .LC_loginpage_space {
 6414:   clear: both;
 6415:   margin-bottom: 20px;
 6416:   border-bottom: 1px solid #CCCCCC;
 6417: }
 6418: 
 6419: .LC_loginpage_floatLeft {
 6420:   float: left;
 6421:   width: 200px;
 6422:   margin: 0;
 6423: }
 6424: 
 6425: table em {
 6426:   font-weight: bold;
 6427:   font-style: normal;
 6428: }
 6429: 
 6430: table.LC_tableBrowseRes,
 6431: table.LC_tableOfContent {
 6432:   border:none;
 6433:   border-spacing: 1px;
 6434:   padding: 3px;
 6435:   background-color: #FFFFFF;
 6436:   font-size: 90%;
 6437: }
 6438: 
 6439: table.LC_tableOfContent {
 6440:   border-collapse: collapse;
 6441: }
 6442: 
 6443: table.LC_tableBrowseRes a,
 6444: table.LC_tableOfContent a {
 6445:   background-color: transparent;
 6446:   text-decoration: none;
 6447: }
 6448: 
 6449: table.LC_tableOfContent img {
 6450:   border: none;
 6451:   height: 1.3em;
 6452:   vertical-align: text-bottom;
 6453:   margin-right: 0.3em;
 6454: }
 6455: 
 6456: a#LC_content_toolbar_firsthomework {
 6457:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6458: }
 6459: 
 6460: a#LC_content_toolbar_launchnav {
 6461:   background-image:url(/res/adm/pages/start-navigation.gif);
 6462: }
 6463: 
 6464: a#LC_content_toolbar_closenav {
 6465:   background-image:url(/res/adm/pages/close-navigation.gif);
 6466: }
 6467: 
 6468: a#LC_content_toolbar_everything {
 6469:   background-image:url(/res/adm/pages/show-all.gif);
 6470: }
 6471: 
 6472: a#LC_content_toolbar_uncompleted {
 6473:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6474: }
 6475: 
 6476: #LC_content_toolbar_clearbubbles {
 6477:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6478: }
 6479: 
 6480: a#LC_content_toolbar_changefolder {
 6481:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6482: }
 6483: 
 6484: a#LC_content_toolbar_changefolder_toggled {
 6485:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6486: }
 6487: 
 6488: ul#LC_toolbar li a:hover {
 6489:   background-position: bottom center;
 6490: }
 6491: 
 6492: ul#LC_toolbar {
 6493:   padding: 0;
 6494:   margin: 2px;
 6495:   list-style:none;
 6496:   position:relative;
 6497:   background-color:white;
 6498: }
 6499: 
 6500: ul#LC_toolbar li {
 6501:   border:1px solid white;
 6502:   padding: 0;
 6503:   margin: 0;
 6504:   float: left;
 6505:   display:inline;
 6506:   vertical-align:middle;
 6507: }
 6508: 
 6509: 
 6510: a.LC_toolbarItem {
 6511:   display:block;
 6512:   padding: 0;
 6513:   margin: 0;
 6514:   height: 32px;
 6515:   width: 32px;
 6516:   color:white;
 6517:   border: none;
 6518:   background-repeat:no-repeat;
 6519:   background-color:transparent;
 6520: }
 6521: 
 6522: ul.LC_funclist {
 6523:     margin: 0;
 6524:     padding: 0.5em 1em 0.5em 0;
 6525: }
 6526: 
 6527: ul.LC_funclist > li:first-child {
 6528:     font-weight:bold; 
 6529:     margin-left:0.8em;
 6530: }
 6531: 
 6532: ul.LC_funclist + ul.LC_funclist {
 6533:     /* 
 6534:        left border as a seperator if we have more than
 6535:        one list 
 6536:     */
 6537:     border-left: 1px solid $sidebg;
 6538:     /* 
 6539:        this hides the left border behind the border of the 
 6540:        outer box if element is wrapped to the next 'line' 
 6541:     */
 6542:     margin-left: -1px;
 6543: }
 6544: 
 6545: ul.LC_funclist li {
 6546:   display: inline;
 6547:   white-space: nowrap;
 6548:   margin: 0 0 0 25px;
 6549:   line-height: 150%;
 6550: }
 6551: 
 6552: .ui-accordion .LC_advanced_toggle {
 6553:   float: right;
 6554:   font-size: 90%;
 6555:   padding: 0px 4px
 6556: }
 6557: 
 6558: END
 6559: }
 6560: 
 6561: =pod
 6562: 
 6563: =item * &headtag()
 6564: 
 6565: Returns a uniform footer for LON-CAPA web pages.
 6566: 
 6567: Inputs: $title - optional title for the head
 6568:         $head_extra - optional extra HTML to put inside the <head>
 6569:         $args - optional arguments
 6570:             force_register - if is true call registerurl so the remote is 
 6571:                              informed
 6572:             redirect       -> array ref of
 6573:                                    1- seconds before redirect occurs
 6574:                                    2- url to redirect to
 6575:                                    3- whether the side effect should occur
 6576:                            (side effect of setting 
 6577:                                $env{'internal.head.redirect'} to the url 
 6578:                                redirected too)
 6579:             domain         -> force to color decorate a page for a specific
 6580:                                domain
 6581:             function       -> force usage of a specific rolish color scheme
 6582:             bgcolor        -> override the default page bgcolor
 6583:             no_auto_mt_title
 6584:                            -> prevent &mt()ing the title arg
 6585: 
 6586: =cut
 6587: 
 6588: sub headtag {
 6589:     my ($title,$head_extra,$args) = @_;
 6590:     
 6591:     my $function = $args->{'function'} || &get_users_function();
 6592:     my $domain   = $args->{'domain'}   || &determinedomain();
 6593:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6594:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6595: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6596: 		   #time(),
 6597: 		   $env{'environment.color.timestamp'},
 6598: 		   $function,$domain,$bgcolor);
 6599: 
 6600:     $url = '/adm/css/'.&escape($url).'.css';
 6601: 
 6602:     my $result =
 6603: 	'<head>'.
 6604: 	&font_settings();
 6605: 
 6606:     if (!$args->{'frameset'}) {
 6607: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6608:     }
 6609:     if ($args->{'force_register'}) {
 6610: 	$result .= &Apache::lonmenu::registerurl(1);
 6611:     }
 6612:     if (!$args->{'no_nav_bar'} 
 6613: 	&& !$args->{'only_body'}
 6614: 	&& !$args->{'frameset'}) {
 6615: 	$result .= &help_menu_js();
 6616:     }
 6617: 
 6618:     if (ref($args->{'redirect'})) {
 6619: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6620: 	$url = &Apache::lonenc::check_encrypt($url);
 6621: 	if (!$inhibit_continue) {
 6622: 	    $env{'internal.head.redirect'} = $url;
 6623: 	}
 6624: 	$result.=<<ADDMETA
 6625: <meta http-equiv="pragma" content="no-cache" />
 6626: <meta http-equiv="Refresh" content="$time; url=$url" />
 6627: ADDMETA
 6628:     }
 6629:     if (!defined($title)) {
 6630: 	$title = 'The LearningOnline Network with CAPA';
 6631:     }
 6632:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6633:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6634: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6635: 	.$head_extra;
 6636:     return $result;
 6637: }
 6638: 
 6639: =pod
 6640: 
 6641: =item * &font_settings()
 6642: 
 6643: Returns neccessary <meta> to set the proper encoding
 6644: 
 6645: Inputs: none
 6646: 
 6647: =cut
 6648: 
 6649: sub font_settings {
 6650:     my $headerstring='';
 6651:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6652: 	$headerstring.=
 6653: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6654:     }
 6655:     return $headerstring;
 6656: }
 6657: 
 6658: =pod
 6659: 
 6660: =item * &xml_begin()
 6661: 
 6662: Returns the needed doctype and <html>
 6663: 
 6664: Inputs: none
 6665: 
 6666: =cut
 6667: 
 6668: sub xml_begin {
 6669:     my $output='';
 6670: 
 6671:     if ($env{'internal.start_page'}==1) {
 6672: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6673:     }
 6674: 
 6675:     if ($env{'browser.mathml'}) {
 6676: 	$output='<?xml version="1.0"?>'
 6677:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6678: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6679:             
 6680: #	    .'<!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">] >'
 6681: 	    .'<!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">'
 6682:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6683: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6684:     } else {
 6685: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6686:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6687:     }
 6688:     return $output;
 6689: }
 6690: 
 6691: =pod
 6692: 
 6693: =item * &endheadtag()
 6694: 
 6695: Returns a uniform </head> for LON-CAPA web pages.
 6696: 
 6697: Inputs: none
 6698: 
 6699: =cut
 6700: 
 6701: sub endheadtag {
 6702:     return '</head>';
 6703: }
 6704: 
 6705: =pod
 6706: 
 6707: =item * &head()
 6708: 
 6709: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6710: 
 6711: Inputs:
 6712: 
 6713: =over 4
 6714: 
 6715: $title - optional title for the page
 6716: 
 6717: $head_extra - optional extra HTML to put inside the <head>
 6718: 
 6719: =back
 6720: 
 6721: =cut
 6722: 
 6723: sub head {
 6724:     my ($title,$head_extra,$args) = @_;
 6725:     return &headtag($title,$head_extra,$args).&endheadtag();
 6726: }
 6727: 
 6728: =pod
 6729: 
 6730: =item * &start_page()
 6731: 
 6732: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6733: 
 6734: Inputs:
 6735: 
 6736: =over 4
 6737: 
 6738: $title - optional title for the page
 6739: 
 6740: $head_extra - optional extra HTML to incude inside the <head>
 6741: 
 6742: $args - additional optional args supported are:
 6743: 
 6744: =over 8
 6745: 
 6746:              only_body      -> is true will set &bodytag() onlybodytag
 6747:                                     arg on
 6748:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6749:              add_entries    -> additional attributes to add to the  <body>
 6750:              domain         -> force to color decorate a page for a 
 6751:                                     specific domain
 6752:              function       -> force usage of a specific rolish color
 6753:                                     scheme
 6754:              redirect       -> see &headtag()
 6755:              bgcolor        -> override the default page bg color
 6756:              js_ready       -> return a string ready for being used in 
 6757:                                     a javascript writeln
 6758:              html_encode    -> return a string ready for being used in 
 6759:                                     a html attribute
 6760:              force_register -> if is true will turn on the &bodytag()
 6761:                                     $forcereg arg
 6762:              frameset       -> if true will start with a <frameset>
 6763:                                     rather than <body>
 6764:              skip_phases    -> hash ref of 
 6765:                                     head -> skip the <html><head> generation
 6766:                                     body -> skip all <body> generation
 6767:              no_inline_link -> if true and in remote mode, don't show the 
 6768:                                     'Switch To Inline Menu' link
 6769:              no_auto_mt_title -> prevent &mt()ing the title arg
 6770:              inherit_jsmath -> when creating popup window in a page,
 6771:                                     should it have jsmath forced on by the
 6772:                                     current page
 6773:              bread_crumbs ->             Array containing breadcrumbs
 6774:              bread_crumbs_components ->  if exists show it as headline else show only the breadcrumbs
 6775: 
 6776: =back
 6777: 
 6778: =back
 6779: 
 6780: =cut
 6781: 
 6782: sub start_page {
 6783:     my ($title,$head_extra,$args) = @_;
 6784:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6785:     my %head_args;
 6786:     foreach my $arg ('redirect','force_register','domain','function',
 6787: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6788: 		     'no_auto_mt_title') {
 6789: 	if (defined($args->{$arg})) {
 6790: 	    $head_args{$arg} = $args->{$arg};
 6791: 	}
 6792:     }
 6793: 
 6794:     $env{'internal.start_page'}++;
 6795:     my $result;
 6796:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6797: 	$result.=
 6798: 	    &xml_begin().
 6799: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6800:     }
 6801:     
 6802:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6803: 	if ($args->{'frameset'}) {
 6804: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6805: 						$args->{'add_entries'});
 6806: 	    $result .= "\n<frameset $attr_string>\n";
 6807:         } else {
 6808:             $result .=
 6809:                 &bodytag($title, 
 6810:                          $args->{'function'},       $args->{'add_entries'},
 6811:                          $args->{'only_body'},      $args->{'domain'},
 6812:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6813:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 6814:                          $args);
 6815:         }
 6816:     }
 6817: 
 6818:     if ($args->{'js_ready'}) {
 6819: 		$result = &js_ready($result);
 6820:     }
 6821:     if ($args->{'html_encode'}) {
 6822: 		$result = &html_encode($result);
 6823:     }
 6824: 
 6825:     # Preparation for new and consistent functionlist at top of screen
 6826:     # if ($args->{'functionlist'}) {
 6827:     #            $result .= &build_functionlist();
 6828:     #}
 6829: 
 6830:     # Don't add anything more if only_body wanted
 6831:     return $result if $args->{'only_body'};
 6832: 
 6833:     #Breadcrumbs for Construction Space provided by &bodytag. 
 6834:     if (($env{'environment.remote'} eq 'off') && ($env{'request.state'} eq 'construct')) {
 6835:         return $result;
 6836:     }
 6837:  
 6838:     #Breadcrumbs
 6839:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6840: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6841: 		#if any br links exists, add them to the breadcrumbs
 6842: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6843: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6844: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6845: 			}
 6846: 		}
 6847: 
 6848: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6849: 		if(exists($args->{'bread_crumbs_component'})){
 6850: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6851: 		}else{
 6852: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6853: 		}
 6854:     }
 6855:     return $result;
 6856: }
 6857: 
 6858: 
 6859: =pod
 6860: 
 6861: =item * &head()
 6862: 
 6863: Returns a complete </body></html> section for LON-CAPA web pages.
 6864: 
 6865: Inputs:         $args - additional optional args supported are:
 6866:                  js_ready     -> return a string ready for being used in 
 6867:                                  a javascript writeln
 6868:                  html_encode  -> return a string ready for being used in 
 6869:                                  a html attribute
 6870:                  frameset     -> if true will start with a <frameset>
 6871:                                  rather than <body>
 6872:                  dicsussion   -> if true will get discussion from
 6873:                                   lonxml::xmlend
 6874:                                  (you can pass the target and parser arguments
 6875:                                   through optional 'target' and 'parser' args
 6876:                                   to this routine)
 6877: 
 6878: =cut
 6879: 
 6880: sub end_page {
 6881:     my ($args) = @_;
 6882:     $env{'internal.end_page'}++;
 6883:     my $result;
 6884:     if ($args->{'discussion'}) {
 6885: 	my ($target,$parser);
 6886: 	if (ref($args->{'discussion'})) {
 6887: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6888: 				$args->{'discussion'}{'parser'});
 6889: 	}
 6890: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6891:     }
 6892: 
 6893:     if ($args->{'frameset'}) {
 6894: 	$result .= '</frameset>';
 6895:     } else {
 6896: 	$result .= &endbodytag($args);
 6897:     }
 6898:     $result .= "\n</html>";
 6899: 
 6900:     if ($args->{'js_ready'}) {
 6901: 	$result = &js_ready($result);
 6902:     }
 6903: 
 6904:     if ($args->{'html_encode'}) {
 6905: 	$result = &html_encode($result);
 6906:     }
 6907: 
 6908:     return $result;
 6909: }
 6910: 
 6911: sub html_encode {
 6912:     my ($result) = @_;
 6913: 
 6914:     $result = &HTML::Entities::encode($result,'<>&"');
 6915:     
 6916:     return $result;
 6917: }
 6918: sub js_ready {
 6919:     my ($result) = @_;
 6920: 
 6921:     $result =~ s/[\n\r]/ /xmsg;
 6922:     $result =~ s/\\/\\\\/xmsg;
 6923:     $result =~ s/'/\\'/xmsg;
 6924:     $result =~ s{</}{<\\/}xmsg;
 6925:     
 6926:     return $result;
 6927: }
 6928: 
 6929: sub validate_page {
 6930:     if (  exists($env{'internal.start_page'})
 6931: 	  &&     $env{'internal.start_page'} > 1) {
 6932: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6933: 				 $env{'internal.start_page'}.' '.
 6934: 				 $ENV{'request.filename'});
 6935:     }
 6936:     if (  exists($env{'internal.end_page'})
 6937: 	  &&     $env{'internal.end_page'} > 1) {
 6938: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6939: 				 $env{'internal.end_page'}.' '.
 6940: 				 $env{'request.filename'});
 6941:     }
 6942:     if (     exists($env{'internal.start_page'})
 6943: 	&& ! exists($env{'internal.end_page'})) {
 6944: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6945: 				 $env{'request.filename'});
 6946:     }
 6947:     if (   ! exists($env{'internal.start_page'})
 6948: 	&&   exists($env{'internal.end_page'})) {
 6949: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6950: 				 $env{'request.filename'});
 6951:     }
 6952: }
 6953: 
 6954: sub simple_error_page {
 6955:     my ($r,$title,$msg) = @_;
 6956:     my $page =
 6957: 	&Apache::loncommon::start_page($title).
 6958: 	&mt($msg).
 6959: 	&Apache::loncommon::end_page();
 6960:     if (ref($r)) {
 6961: 	$r->print($page);
 6962: 	return;
 6963:     }
 6964:     return $page;
 6965: }
 6966: 
 6967: {
 6968:     my @row_count;
 6969:     sub start_data_table {
 6970: 	my ($add_class) = @_;
 6971: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6972: 	unshift(@row_count,0);
 6973: 	return '<table class="'.$css_class.'">'."\n";
 6974:     }
 6975: 
 6976:     sub end_data_table {
 6977: 	shift(@row_count);
 6978: 	return '</table>'."\n";;
 6979:     }
 6980: 
 6981:     sub start_data_table_row {
 6982: 	my ($add_class) = @_;
 6983: 	$row_count[0]++;
 6984: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6985: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6986: 	return  '<tr class="'.$css_class.'">'."\n";;
 6987:     }
 6988:     
 6989:     sub continue_data_table_row {
 6990: 	my ($add_class) = @_;
 6991: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6992: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');;
 6993: 	return  '<tr class="'.$css_class.'">'."\n";;
 6994:     }
 6995: 
 6996:     sub end_data_table_row {
 6997: 	return '</tr>'."\n";;
 6998:     }
 6999: 
 7000:     sub start_data_table_empty_row {
 7001: #	$row_count[0]++;
 7002: 	return  '<tr class="LC_empty_row" >'."\n";;
 7003:     }
 7004: 
 7005:     sub end_data_table_empty_row {
 7006: 	return '</tr>'."\n";;
 7007:     }
 7008: 
 7009:     sub start_data_table_header_row {
 7010: 	return  '<tr class="LC_header_row">'."\n";;
 7011:     }
 7012: 
 7013:     sub end_data_table_header_row {
 7014: 	return '</tr>'."\n";;
 7015:     }
 7016: 
 7017:     sub data_table_caption {
 7018:         my $caption = shift;
 7019:         return "<caption class=\"LC_caption\">$caption</caption>";
 7020:     }
 7021: }
 7022: 
 7023: =pod
 7024: 
 7025: =item * &inhibit_menu_check($arg)
 7026: 
 7027: Checks for a inhibitmenu state and generates output to preserve it
 7028: 
 7029: Inputs:         $arg - can be any of
 7030:                      - undef - in which case the return value is a string 
 7031:                                to add  into arguments list of a uri
 7032:                      - 'input' - in which case the return value is a HTML
 7033:                                  <form> <input> field of type hidden to
 7034:                                  preserve the value
 7035:                      - a url - in which case the return value is the url with
 7036:                                the neccesary cgi args added to preserve the
 7037:                                inhibitmenu state
 7038:                      - a ref to a url - no return value, but the string is
 7039:                                         updated to include the neccessary cgi
 7040:                                         args to preserve the inhibitmenu state
 7041: 
 7042: =cut
 7043: 
 7044: sub inhibit_menu_check {
 7045:     my ($arg) = @_;
 7046:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7047:     if ($arg eq 'input') {
 7048: 	if ($env{'form.inhibitmenu'}) {
 7049: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7050: 	} else {
 7051: 	    return
 7052: 	}
 7053:     }
 7054:     if ($env{'form.inhibitmenu'}) {
 7055: 	if (ref($arg)) {
 7056: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7057: 	} elsif ($arg eq '') {
 7058: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7059: 	} else {
 7060: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7061: 	}
 7062:     }
 7063:     if (!ref($arg)) {
 7064: 	return $arg;
 7065:     }
 7066: }
 7067: 
 7068: ###############################################
 7069: 
 7070: =pod
 7071: 
 7072: =back
 7073: 
 7074: =head1 User Information Routines
 7075: 
 7076: =over 4
 7077: 
 7078: =item * &get_users_function()
 7079: 
 7080: Used by &bodytag to determine the current users primary role.
 7081: Returns either 'student','coordinator','admin', or 'author'.
 7082: 
 7083: =cut
 7084: 
 7085: ###############################################
 7086: sub get_users_function {
 7087:     my $function = 'norole';
 7088:     if ($env{'request.role'}=~/^(st)/) {
 7089:         $function='student';
 7090:     }
 7091:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7092:         $function='coordinator';
 7093:     }
 7094:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7095:         $function='admin';
 7096:     }
 7097:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7098:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7099:         $function='author';
 7100:     }
 7101:     return $function;
 7102: }
 7103: 
 7104: ###############################################
 7105: 
 7106: =pod
 7107: 
 7108: =item * &show_course()
 7109: 
 7110: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7111: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7112: 
 7113: Inputs:
 7114: None
 7115: 
 7116: Outputs:
 7117: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7118: 
 7119: =cut
 7120: 
 7121: ###############################################
 7122: sub show_course {
 7123:     my $course = !$env{'user.adv'};
 7124:     if (!$env{'user.adv'}) {
 7125:         foreach my $env (keys(%env)) {
 7126:             next if ($env !~ m/^user\.priv\./);
 7127:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7128:                 $course = 0;
 7129:                 last;
 7130:             }
 7131:         }
 7132:     }
 7133:     return $course;
 7134: }
 7135: 
 7136: ###############################################
 7137: 
 7138: =pod
 7139: 
 7140: =item * &check_user_status()
 7141: 
 7142: Determines current status of supplied role for a
 7143: specific user. Roles can be active, previous or future.
 7144: 
 7145: Inputs: 
 7146: user's domain, user's username, course's domain,
 7147: course's number, optional section ID.
 7148: 
 7149: Outputs:
 7150: role status: active, previous or future. 
 7151: 
 7152: =cut
 7153: 
 7154: sub check_user_status {
 7155:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7156:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 7157:     my @uroles = keys %userinfo;
 7158:     my $srchstr;
 7159:     my $active_chk = 'none';
 7160:     my $now = time;
 7161:     if (@uroles > 0) {
 7162:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7163:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7164:         } else {
 7165:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7166:         }
 7167:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7168:             my $role_end = 0;
 7169:             my $role_start = 0;
 7170:             $active_chk = 'active';
 7171:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7172:                 $role_end = $1;
 7173:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7174:                     $role_start = $1;
 7175:                 }
 7176:             }
 7177:             if ($role_start > 0) {
 7178:                 if ($now < $role_start) {
 7179:                     $active_chk = 'future';
 7180:                 }
 7181:             }
 7182:             if ($role_end > 0) {
 7183:                 if ($now > $role_end) {
 7184:                     $active_chk = 'previous';
 7185:                 }
 7186:             }
 7187:         }
 7188:     }
 7189:     return $active_chk;
 7190: }
 7191: 
 7192: ###############################################
 7193: 
 7194: =pod
 7195: 
 7196: =item * &get_sections()
 7197: 
 7198: Determines all the sections for a course including
 7199: sections with students and sections containing other roles.
 7200: Incoming parameters: 
 7201: 
 7202: 1. domain
 7203: 2. course number 
 7204: 3. reference to array containing roles for which sections should 
 7205: be gathered (optional).
 7206: 4. reference to array containing status types for which sections 
 7207: should be gathered (optional).
 7208: 
 7209: If the third argument is undefined, sections are gathered for any role. 
 7210: If the fourth argument is undefined, sections are gathered for any status.
 7211: Permissible values are 'active' or 'future' or 'previous'.
 7212:  
 7213: Returns section hash (keys are section IDs, values are
 7214: number of users in each section), subject to the
 7215: optional roles filter, optional status filter 
 7216: 
 7217: =cut
 7218: 
 7219: ###############################################
 7220: sub get_sections {
 7221:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7222:     if (!defined($cdom) || !defined($cnum)) {
 7223:         my $cid =  $env{'request.course.id'};
 7224: 
 7225: 	return if (!defined($cid));
 7226: 
 7227:         $cdom = $env{'course.'.$cid.'.domain'};
 7228:         $cnum = $env{'course.'.$cid.'.num'};
 7229:     }
 7230: 
 7231:     my %sectioncount;
 7232:     my $now = time;
 7233: 
 7234:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7235: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7236: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7237: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7238:         my $start_index = &Apache::loncoursedata::CL_START();
 7239:         my $end_index = &Apache::loncoursedata::CL_END();
 7240:         my $status;
 7241: 	while (my ($student,$data) = each(%$classlist)) {
 7242: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7243: 				                     $data->[$status_index],
 7244:                                                      $data->[$start_index],
 7245:                                                      $data->[$end_index]);
 7246:             if ($stu_status eq 'Active') {
 7247:                 $status = 'active';
 7248:             } elsif ($end < $now) {
 7249:                 $status = 'previous';
 7250:             } elsif ($start > $now) {
 7251:                 $status = 'future';
 7252:             } 
 7253: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7254:                 if ((!defined($possible_status)) || (($status ne '') && 
 7255:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7256: 		    $sectioncount{$section}++;
 7257:                 }
 7258: 	    }
 7259: 	}
 7260:     }
 7261:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7262:     foreach my $user (sort(keys(%courseroles))) {
 7263: 	if ($user !~ /^(\w{2})/) { next; }
 7264: 	my ($role) = ($user =~ /^(\w{2})/);
 7265: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7266: 	my ($section,$status);
 7267: 	if ($role eq 'cr' &&
 7268: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7269: 	    $section=$1;
 7270: 	}
 7271: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7272: 	if (!defined($section) || $section eq '-1') { next; }
 7273:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7274:         if ($end == -1 && $start == -1) {
 7275:             next; #deleted role
 7276:         }
 7277:         if (!defined($possible_status)) { 
 7278:             $sectioncount{$section}++;
 7279:         } else {
 7280:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7281:                 $status = 'active';
 7282:             } elsif ($end < $now) {
 7283:                 $status = 'future';
 7284:             } elsif ($start > $now) {
 7285:                 $status = 'previous';
 7286:             }
 7287:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7288:                 $sectioncount{$section}++;
 7289:             }
 7290:         }
 7291:     }
 7292:     return %sectioncount;
 7293: }
 7294: 
 7295: ###############################################
 7296: 
 7297: =pod
 7298: 
 7299: =item * &get_course_users()
 7300: 
 7301: Retrieves usernames:domains for users in the specified course
 7302: with specific role(s), and access status. 
 7303: 
 7304: Incoming parameters:
 7305: 1. course domain
 7306: 2. course number
 7307: 3. access status: users must have - either active, 
 7308: previous, future, or all.
 7309: 4. reference to array of permissible roles
 7310: 5. reference to array of section restrictions (optional)
 7311: 6. reference to results object (hash of hashes).
 7312: 7. reference to optional userdata hash
 7313: 8. reference to optional statushash
 7314: 9. flag if privileged users (except those set to unhide in
 7315:    course settings) should be excluded    
 7316: Keys of top level results hash are roles.
 7317: Keys of inner hashes are username:domain, with 
 7318: values set to access type.
 7319: Optional userdata hash returns an array with arguments in the 
 7320: same order as loncoursedata::get_classlist() for student data.
 7321: 
 7322: Optional statushash returns
 7323: 
 7324: Entries for end, start, section and status are blank because
 7325: of the possibility of multiple values for non-student roles.
 7326: 
 7327: =cut
 7328: 
 7329: ###############################################
 7330: 
 7331: sub get_course_users {
 7332:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7333:     my %idx = ();
 7334:     my %seclists;
 7335: 
 7336:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7337:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7338:     $idx{end} = &Apache::loncoursedata::CL_END();
 7339:     $idx{start} = &Apache::loncoursedata::CL_START();
 7340:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7341:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7342:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7343:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7344: 
 7345:     if (grep(/^st$/,@{$roles})) {
 7346:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7347:         my $now = time;
 7348:         foreach my $student (keys(%{$classlist})) {
 7349:             my $match = 0;
 7350:             my $secmatch = 0;
 7351:             my $section = $$classlist{$student}[$idx{section}];
 7352:             my $status = $$classlist{$student}[$idx{status}];
 7353:             if ($section eq '') {
 7354:                 $section = 'none';
 7355:             }
 7356:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7357:                 if (grep(/^all$/,@{$sections})) {
 7358:                     $secmatch = 1;
 7359:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7360:                     if (grep(/^none$/,@{$sections})) {
 7361:                         $secmatch = 1;
 7362:                     }
 7363:                 } else {  
 7364: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7365: 		        $secmatch = 1;
 7366:                     }
 7367: 		}
 7368:                 if (!$secmatch) {
 7369:                     next;
 7370:                 }
 7371:             }
 7372:             if (defined($$types{'active'})) {
 7373:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7374:                     push(@{$$users{st}{$student}},'active');
 7375:                     $match = 1;
 7376:                 }
 7377:             }
 7378:             if (defined($$types{'previous'})) {
 7379:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7380:                     push(@{$$users{st}{$student}},'previous');
 7381:                     $match = 1;
 7382:                 }
 7383:             }
 7384:             if (defined($$types{'future'})) {
 7385:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7386:                     push(@{$$users{st}{$student}},'future');
 7387:                     $match = 1;
 7388:                 }
 7389:             }
 7390:             if ($match) {
 7391:                 push(@{$seclists{$student}},$section);
 7392:                 if (ref($userdata) eq 'HASH') {
 7393:                     $$userdata{$student} = $$classlist{$student};
 7394:                 }
 7395:                 if (ref($statushash) eq 'HASH') {
 7396:                     $statushash->{$student}{'st'}{$section} = $status;
 7397:                 }
 7398:             }
 7399:         }
 7400:     }
 7401:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7402:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7403:         my $now = time;
 7404:         my %displaystatus = ( previous => 'Expired',
 7405:                               active   => 'Active',
 7406:                               future   => 'Future',
 7407:                             );
 7408:         my %nothide;
 7409:         if ($hidepriv) {
 7410:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7411:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7412:                 if ($user !~ /:/) {
 7413:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7414:                 } else {
 7415:                     $nothide{$user} = 1;
 7416:                 }
 7417:             }
 7418:         }
 7419:         foreach my $person (sort(keys(%coursepersonnel))) {
 7420:             my $match = 0;
 7421:             my $secmatch = 0;
 7422:             my $status;
 7423:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7424:             $user =~ s/:$//;
 7425:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7426:             if ($end == -1 || $start == -1) {
 7427:                 next;
 7428:             }
 7429:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7430:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7431:                 my ($uname,$udom) = split(/:/,$user);
 7432:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7433:                     if (grep(/^all$/,@{$sections})) {
 7434:                         $secmatch = 1;
 7435:                     } elsif ($usec eq '') {
 7436:                         if (grep(/^none$/,@{$sections})) {
 7437:                             $secmatch = 1;
 7438:                         }
 7439:                     } else {
 7440:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7441:                             $secmatch = 1;
 7442:                         }
 7443:                     }
 7444:                     if (!$secmatch) {
 7445:                         next;
 7446:                     }
 7447:                 }
 7448:                 if ($usec eq '') {
 7449:                     $usec = 'none';
 7450:                 }
 7451:                 if ($uname ne '' && $udom ne '') {
 7452:                     if ($hidepriv) {
 7453:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7454:                             (!$nothide{$uname.':'.$udom})) {
 7455:                             next;
 7456:                         }
 7457:                     }
 7458:                     if ($end > 0 && $end < $now) {
 7459:                         $status = 'previous';
 7460:                     } elsif ($start > $now) {
 7461:                         $status = 'future';
 7462:                     } else {
 7463:                         $status = 'active';
 7464:                     }
 7465:                     foreach my $type (keys(%{$types})) { 
 7466:                         if ($status eq $type) {
 7467:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7468:                                 push(@{$$users{$role}{$user}},$type);
 7469:                             }
 7470:                             $match = 1;
 7471:                         }
 7472:                     }
 7473:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7474:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7475: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7476:                         }
 7477:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7478:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7479:                         }
 7480:                         if (ref($statushash) eq 'HASH') {
 7481:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7482:                         }
 7483:                     }
 7484:                 }
 7485:             }
 7486:         }
 7487:         if (grep(/^ow$/,@{$roles})) {
 7488:             if ((defined($cdom)) && (defined($cnum))) {
 7489:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7490:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7491:                     my $owner = $csettings{'internal.courseowner'};
 7492:                     next if ($owner eq '');
 7493:                     my ($ownername,$ownerdom);
 7494:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7495:                         $ownername = $1;
 7496:                         $ownerdom = $2;
 7497:                     } else {
 7498:                         $ownername = $owner;
 7499:                         $ownerdom = $cdom;
 7500:                         $owner = $ownername.':'.$ownerdom;
 7501:                     }
 7502:                     @{$$users{'ow'}{$owner}} = 'any';
 7503:                     if (defined($userdata) && 
 7504: 			!exists($$userdata{$owner})) {
 7505: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7506:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7507:                             push(@{$seclists{$owner}},'none');
 7508:                         }
 7509:                         if (ref($statushash) eq 'HASH') {
 7510:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7511:                         }
 7512: 		    }
 7513:                 }
 7514:             }
 7515:         }
 7516:         foreach my $user (keys(%seclists)) {
 7517:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7518:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7519:         }
 7520:     }
 7521:     return;
 7522: }
 7523: 
 7524: sub get_user_info {
 7525:     my ($udom,$uname,$idx,$userdata) = @_;
 7526:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7527: 	&plainname($uname,$udom,'lastname');
 7528:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7529:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7530:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7531:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7532:     return;
 7533: }
 7534: 
 7535: ###############################################
 7536: 
 7537: =pod
 7538: 
 7539: =item * &get_user_quota()
 7540: 
 7541: Retrieves quota assigned for storage of portfolio files for a user  
 7542: 
 7543: Incoming parameters:
 7544: 1. user's username
 7545: 2. user's domain
 7546: 
 7547: Returns:
 7548: 1. Disk quota (in Mb) assigned to student.
 7549: 2. (Optional) Type of setting: custom or default
 7550:    (individually assigned or default for user's 
 7551:    institutional status).
 7552: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7553:    or student - types as defined in localenroll::inst_usertypes 
 7554:    for user's domain, which determines default quota for user.
 7555: 4. (Optional) - Default quota which would apply to the user.
 7556: 
 7557: If a value has been stored in the user's environment, 
 7558: it will return that, otherwise it returns the maximal default
 7559: defined for the user's instituional status(es) in the domain.
 7560: 
 7561: =cut
 7562: 
 7563: ###############################################
 7564: 
 7565: 
 7566: sub get_user_quota {
 7567:     my ($uname,$udom) = @_;
 7568:     my ($quota,$quotatype,$settingstatus,$defquota);
 7569:     if (!defined($udom)) {
 7570:         $udom = $env{'user.domain'};
 7571:     }
 7572:     if (!defined($uname)) {
 7573:         $uname = $env{'user.name'};
 7574:     }
 7575:     if (($udom eq '' || $uname eq '') ||
 7576:         ($udom eq 'public') && ($uname eq 'public')) {
 7577:         $quota = 0;
 7578:         $quotatype = 'default';
 7579:         $defquota = 0; 
 7580:     } else {
 7581:         my $inststatus;
 7582:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7583:             $quota = $env{'environment.portfolioquota'};
 7584:             $inststatus = $env{'environment.inststatus'};
 7585:         } else {
 7586:             my %userenv = 
 7587:                 &Apache::lonnet::get('environment',['portfolioquota',
 7588:                                      'inststatus'],$udom,$uname);
 7589:             my ($tmp) = keys(%userenv);
 7590:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7591:                 $quota = $userenv{'portfolioquota'};
 7592:                 $inststatus = $userenv{'inststatus'};
 7593:             } else {
 7594:                 undef(%userenv);
 7595:             }
 7596:         }
 7597:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7598:         if ($quota eq '') {
 7599:             $quota = $defquota;
 7600:             $quotatype = 'default';
 7601:         } else {
 7602:             $quotatype = 'custom';
 7603:         }
 7604:     }
 7605:     if (wantarray) {
 7606:         return ($quota,$quotatype,$settingstatus,$defquota);
 7607:     } else {
 7608:         return $quota;
 7609:     }
 7610: }
 7611: 
 7612: ###############################################
 7613: 
 7614: =pod
 7615: 
 7616: =item * &default_quota()
 7617: 
 7618: Retrieves default quota assigned for storage of user portfolio files,
 7619: given an (optional) user's institutional status.
 7620: 
 7621: Incoming parameters:
 7622: 1. domain
 7623: 2. (Optional) institutional status(es).  This is a : separated list of 
 7624:    status types (e.g., faculty, staff, student etc.)
 7625:    which apply to the user for whom the default is being retrieved.
 7626:    If the institutional status string in undefined, the domain
 7627:    default quota will be returned. 
 7628: 
 7629: Returns:
 7630: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7631: 2. (Optional) institutional type which determined the value of the
 7632:    default quota.
 7633: 
 7634: If a value has been stored in the domain's configuration db,
 7635: it will return that, otherwise it returns 20 (for backwards 
 7636: compatibility with domains which have not set up a configuration
 7637: db file; the original statically defined portfolio quota was 20 Mb). 
 7638: 
 7639: If the user's status includes multiple types (e.g., staff and student),
 7640: the largest default quota which applies to the user determines the
 7641: default quota returned.
 7642: 
 7643: =back
 7644: 
 7645: =cut
 7646: 
 7647: ###############################################
 7648: 
 7649: 
 7650: sub default_quota {
 7651:     my ($udom,$inststatus) = @_;
 7652:     my ($defquota,$settingstatus);
 7653:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7654:                                             ['quotas'],$udom);
 7655:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7656:         if ($inststatus ne '') {
 7657:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7658:             foreach my $item (@statuses) {
 7659:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7660:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7661:                         if ($defquota eq '') {
 7662:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7663:                             $settingstatus = $item;
 7664:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7665:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7666:                             $settingstatus = $item;
 7667:                         }
 7668:                     }
 7669:                 } else {
 7670:                     if ($quotahash{'quotas'}{$item} ne '') {
 7671:                         if ($defquota eq '') {
 7672:                             $defquota = $quotahash{'quotas'}{$item};
 7673:                             $settingstatus = $item;
 7674:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7675:                             $defquota = $quotahash{'quotas'}{$item};
 7676:                             $settingstatus = $item;
 7677:                         }
 7678:                     }
 7679:                 }
 7680:             }
 7681:         }
 7682:         if ($defquota eq '') {
 7683:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7684:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7685:             } else {
 7686:                 $defquota = $quotahash{'quotas'}{'default'};
 7687:             }
 7688:             $settingstatus = 'default';
 7689:         }
 7690:     } else {
 7691:         $settingstatus = 'default';
 7692:         $defquota = 20;
 7693:     }
 7694:     if (wantarray) {
 7695:         return ($defquota,$settingstatus);
 7696:     } else {
 7697:         return $defquota;
 7698:     }
 7699: }
 7700: 
 7701: sub get_secgrprole_info {
 7702:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7703:     my %sections_count = &get_sections($cdom,$cnum);
 7704:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7705:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7706:     my @groups = sort(keys(%curr_groups));
 7707:     my $allroles = [];
 7708:     my $rolehash;
 7709:     my $accesshash = {
 7710:                      active => 'Currently has access',
 7711:                      future => 'Will have future access',
 7712:                      previous => 'Previously had access',
 7713:                   };
 7714:     if ($needroles) {
 7715:         $rolehash = {'all' => 'all'};
 7716:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7717: 	if (&Apache::lonnet::error(%user_roles)) {
 7718: 	    undef(%user_roles);
 7719: 	}
 7720:         foreach my $item (keys(%user_roles)) {
 7721:             my ($role)=split(/\:/,$item,2);
 7722:             if ($role eq 'cr') { next; }
 7723:             if ($role =~ /^cr/) {
 7724:                 $$rolehash{$role} = (split('/',$role))[3];
 7725:             } else {
 7726:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7727:             }
 7728:         }
 7729:         foreach my $key (sort(keys(%{$rolehash}))) {
 7730:             push(@{$allroles},$key);
 7731:         }
 7732:         push (@{$allroles},'st');
 7733:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7734:     }
 7735:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7736: }
 7737: 
 7738: sub user_picker {
 7739:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7740:     my $currdom = $dom;
 7741:     my %curr_selected = (
 7742:                         srchin => 'dom',
 7743:                         srchby => 'lastname',
 7744:                       );
 7745:     my $srchterm;
 7746:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7747:         if ($srch->{'srchby'} ne '') {
 7748:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7749:         }
 7750:         if ($srch->{'srchin'} ne '') {
 7751:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7752:         }
 7753:         if ($srch->{'srchtype'} ne '') {
 7754:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7755:         }
 7756:         if ($srch->{'srchdomain'} ne '') {
 7757:             $currdom = $srch->{'srchdomain'};
 7758:         }
 7759:         $srchterm = $srch->{'srchterm'};
 7760:     }
 7761:     my %lt=&Apache::lonlocal::texthash(
 7762:                     'usr'       => 'Search criteria',
 7763:                     'doma'      => 'Domain/institution to search',
 7764:                     'uname'     => 'username',
 7765:                     'lastname'  => 'last name',
 7766:                     'lastfirst' => 'last name, first name',
 7767:                     'crs'       => 'in this course',
 7768:                     'dom'       => 'in selected LON-CAPA domain', 
 7769:                     'alc'       => 'all LON-CAPA',
 7770:                     'instd'     => 'in institutional directory for selected domain',
 7771:                     'exact'     => 'is',
 7772:                     'contains'  => 'contains',
 7773:                     'begins'    => 'begins with',
 7774:                     'youm'      => "You must include some text to search for.",
 7775:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7776:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7777:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7778:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7779:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7780:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7781:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7782:                                        );
 7783:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7784:     my $srchinsel = ' <select name="srchin">';
 7785: 
 7786:     my @srchins = ('crs','dom','alc','instd');
 7787: 
 7788:     foreach my $option (@srchins) {
 7789:         # FIXME 'alc' option unavailable until 
 7790:         #       loncreateuser::print_user_query_page()
 7791:         #       has been completed.
 7792:         next if ($option eq 'alc');
 7793:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7794:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7795:         if ($curr_selected{'srchin'} eq $option) {
 7796:             $srchinsel .= ' 
 7797:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7798:         } else {
 7799:             $srchinsel .= '
 7800:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7801:         }
 7802:     }
 7803:     $srchinsel .= "\n  </select>\n";
 7804: 
 7805:     my $srchbysel =  ' <select name="srchby">';
 7806:     foreach my $option ('lastname','lastfirst','uname') {
 7807:         if ($curr_selected{'srchby'} eq $option) {
 7808:             $srchbysel .= '
 7809:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7810:         } else {
 7811:             $srchbysel .= '
 7812:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7813:          }
 7814:     }
 7815:     $srchbysel .= "\n  </select>\n";
 7816: 
 7817:     my $srchtypesel = ' <select name="srchtype">';
 7818:     foreach my $option ('begins','contains','exact') {
 7819:         if ($curr_selected{'srchtype'} eq $option) {
 7820:             $srchtypesel .= '
 7821:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7822:         } else {
 7823:             $srchtypesel .= '
 7824:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7825:         }
 7826:     }
 7827:     $srchtypesel .= "\n  </select>\n";
 7828: 
 7829:     my ($newuserscript,$new_user_create);
 7830: 
 7831:     if ($forcenewuser) {
 7832:         if (ref($srch) eq 'HASH') {
 7833:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7834:                 if ($cancreate) {
 7835:                     $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>';
 7836:                 } else {
 7837:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7838:                     my %usertypetext = (
 7839:                         official   => 'institutional',
 7840:                         unofficial => 'non-institutional',
 7841:                     );
 7842:                     $new_user_create = '<p class="LC_warning">'
 7843:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7844:                                       .' '
 7845:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7846:                                           ,'<a href="'.$helplink.'">','</a>')
 7847:                                       .'</p><br />';
 7848:                 }
 7849:             }
 7850:         }
 7851: 
 7852:         $newuserscript = <<"ENDSCRIPT";
 7853: 
 7854: function setSearch(createnew,callingForm) {
 7855:     if (createnew == 1) {
 7856:         for (var i=0; i<callingForm.srchby.length; i++) {
 7857:             if (callingForm.srchby.options[i].value == 'uname') {
 7858:                 callingForm.srchby.selectedIndex = i;
 7859:             }
 7860:         }
 7861:         for (var i=0; i<callingForm.srchin.length; i++) {
 7862:             if ( callingForm.srchin.options[i].value == 'dom') {
 7863: 		callingForm.srchin.selectedIndex = i;
 7864:             }
 7865:         }
 7866:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7867:             if (callingForm.srchtype.options[i].value == 'exact') {
 7868:                 callingForm.srchtype.selectedIndex = i;
 7869:             }
 7870:         }
 7871:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7872:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7873:                 callingForm.srchdomain.selectedIndex = i;
 7874:             }
 7875:         }
 7876:     }
 7877: }
 7878: ENDSCRIPT
 7879: 
 7880:     }
 7881: 
 7882:     my $output = <<"END_BLOCK";
 7883: <script type="text/javascript">
 7884: // <![CDATA[
 7885: function validateEntry(callingForm) {
 7886: 
 7887:     var checkok = 1;
 7888:     var srchin;
 7889:     for (var i=0; i<callingForm.srchin.length; i++) {
 7890: 	if ( callingForm.srchin[i].checked ) {
 7891: 	    srchin = callingForm.srchin[i].value;
 7892: 	}
 7893:     }
 7894: 
 7895:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7896:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7897:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7898:     var srchterm =  callingForm.srchterm.value;
 7899:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7900:     var msg = "";
 7901: 
 7902:     if (srchterm == "") {
 7903:         checkok = 0;
 7904:         msg += "$lt{'youm'}\\n";
 7905:     }
 7906: 
 7907:     if (srchtype== 'begins') {
 7908:         if (srchterm.length < 2) {
 7909:             checkok = 0;
 7910:             msg += "$lt{'thte'}\\n";
 7911:         }
 7912:     }
 7913: 
 7914:     if (srchtype== 'contains') {
 7915:         if (srchterm.length < 3) {
 7916:             checkok = 0;
 7917:             msg += "$lt{'thet'}\\n";
 7918:         }
 7919:     }
 7920:     if (srchin == 'instd') {
 7921:         if (srchdomain == '') {
 7922:             checkok = 0;
 7923:             msg += "$lt{'yomc'}\\n";
 7924:         }
 7925:     }
 7926:     if (srchin == 'dom') {
 7927:         if (srchdomain == '') {
 7928:             checkok = 0;
 7929:             msg += "$lt{'ymcd'}\\n";
 7930:         }
 7931:     }
 7932:     if (srchby == 'lastfirst') {
 7933:         if (srchterm.indexOf(",") == -1) {
 7934:             checkok = 0;
 7935:             msg += "$lt{'whus'}\\n";
 7936:         }
 7937:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7938:             checkok = 0;
 7939:             msg += "$lt{'whse'}\\n";
 7940:         }
 7941:     }
 7942:     if (checkok == 0) {
 7943:         alert("$lt{'thfo'}\\n"+msg);
 7944:         return;
 7945:     }
 7946:     if (checkok == 1) {
 7947:         callingForm.submit();
 7948:     }
 7949: }
 7950: 
 7951: $newuserscript
 7952: 
 7953: // ]]>
 7954: </script>
 7955: 
 7956: $new_user_create
 7957: 
 7958: END_BLOCK
 7959: 
 7960:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7961:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7962:                $domform.
 7963:                &Apache::lonhtmlcommon::row_closure().
 7964:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7965:                $srchbysel.
 7966:                $srchtypesel. 
 7967:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7968:                $srchinsel.
 7969:                &Apache::lonhtmlcommon::row_closure(1). 
 7970:                &Apache::lonhtmlcommon::end_pick_box().
 7971:                '<br />';
 7972:     return $output;
 7973: }
 7974: 
 7975: sub user_rule_check {
 7976:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7977:     my $response;
 7978:     if (ref($usershash) eq 'HASH') {
 7979:         foreach my $user (keys(%{$usershash})) {
 7980:             my ($uname,$udom) = split(/:/,$user);
 7981:             next if ($udom eq '' || $uname eq '');
 7982:             my ($id,$newuser);
 7983:             if (ref($usershash->{$user}) eq 'HASH') {
 7984:                 $newuser = $usershash->{$user}->{'newuser'};
 7985:                 $id = $usershash->{$user}->{'id'};
 7986:             }
 7987:             my $inst_response;
 7988:             if (ref($checks) eq 'HASH') {
 7989:                 if (defined($checks->{'username'})) {
 7990:                     ($inst_response,%{$inst_results->{$user}}) = 
 7991:                         &Apache::lonnet::get_instuser($udom,$uname);
 7992:                 } elsif (defined($checks->{'id'})) {
 7993:                     ($inst_response,%{$inst_results->{$user}}) =
 7994:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7995:                 }
 7996:             } else {
 7997:                 ($inst_response,%{$inst_results->{$user}}) =
 7998:                     &Apache::lonnet::get_instuser($udom,$uname);
 7999:                 return;
 8000:             }
 8001:             if (!$got_rules->{$udom}) {
 8002:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8003:                                                   ['usercreation'],$udom);
 8004:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8005:                     foreach my $item ('username','id') {
 8006:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8007:                             $$curr_rules{$udom}{$item} = 
 8008:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8009:                         }
 8010:                     }
 8011:                 }
 8012:                 $got_rules->{$udom} = 1;  
 8013:             }
 8014:             foreach my $item (keys(%{$checks})) {
 8015:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8016:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8017:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8018:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8019:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8020:                                 if ($rule_check{$rule}) {
 8021:                                     $$rulematch{$user}{$item} = $rule;
 8022:                                     if ($inst_response eq 'ok') {
 8023:                                         if (ref($inst_results) eq 'HASH') {
 8024:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8025:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8026:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8027:                                                 }
 8028:                                             }
 8029:                                         }
 8030:                                     }
 8031:                                     last;
 8032:                                 }
 8033:                             }
 8034:                         }
 8035:                     }
 8036:                 }
 8037:             }
 8038:         }
 8039:     }
 8040:     return;
 8041: }
 8042: 
 8043: sub user_rule_formats {
 8044:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8045:     my %text = ( 
 8046:                  'username' => 'Usernames',
 8047:                  'id'       => 'IDs',
 8048:                );
 8049:     my $output;
 8050:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8051:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8052:         if (@{$ruleorder} > 0) {
 8053:             $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>';
 8054:             foreach my $rule (@{$ruleorder}) {
 8055:                 if (ref($curr_rules) eq 'ARRAY') {
 8056:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8057:                         if (ref($rules->{$rule}) eq 'HASH') {
 8058:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8059:                                         $rules->{$rule}{'desc'}.'</li>';
 8060:                         }
 8061:                     }
 8062:                 }
 8063:             }
 8064:             $output .= '</ul>';
 8065:         }
 8066:     }
 8067:     return $output;
 8068: }
 8069: 
 8070: sub instrule_disallow_msg {
 8071:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8072:     my $response;
 8073:     my %text = (
 8074:                   item   => 'username',
 8075:                   items  => 'usernames',
 8076:                   match  => 'matches',
 8077:                   do     => 'does',
 8078:                   action => 'a username',
 8079:                   one    => 'one',
 8080:                );
 8081:     if ($count > 1) {
 8082:         $text{'item'} = 'usernames';
 8083:         $text{'match'} ='match';
 8084:         $text{'do'} = 'do';
 8085:         $text{'action'} = 'usernames',
 8086:         $text{'one'} = 'ones';
 8087:     }
 8088:     if ($checkitem eq 'id') {
 8089:         $text{'items'} = 'IDs';
 8090:         $text{'item'} = 'ID';
 8091:         $text{'action'} = 'an ID';
 8092:         if ($count > 1) {
 8093:             $text{'item'} = 'IDs';
 8094:             $text{'action'} = 'IDs';
 8095:         }
 8096:     }
 8097:     $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 />';
 8098:     if ($mode eq 'upload') {
 8099:         if ($checkitem eq 'username') {
 8100:             $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'}.");
 8101:         } elsif ($checkitem eq 'id') {
 8102:             $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.");
 8103:         }
 8104:     } elsif ($mode eq 'selfcreate') {
 8105:         if ($checkitem eq 'id') {
 8106:             $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.");
 8107:         }
 8108:     } else {
 8109:         if ($checkitem eq 'username') {
 8110:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8111:         } elsif ($checkitem eq 'id') {
 8112:             $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.");
 8113:         }
 8114:     }
 8115:     return $response;
 8116: }
 8117: 
 8118: sub personal_data_fieldtitles {
 8119:     my %fieldtitles = &Apache::lonlocal::texthash (
 8120:                         id => 'Student/Employee ID',
 8121:                         permanentemail => 'E-mail address',
 8122:                         lastname => 'Last Name',
 8123:                         firstname => 'First Name',
 8124:                         middlename => 'Middle Name',
 8125:                         generation => 'Generation',
 8126:                         gen => 'Generation',
 8127:                         inststatus => 'Affiliation',
 8128:                    );
 8129:     return %fieldtitles;
 8130: }
 8131: 
 8132: sub sorted_inst_types {
 8133:     my ($dom) = @_;
 8134:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8135:     my $othertitle = &mt('All users');
 8136:     if ($env{'request.course.id'}) {
 8137:         $othertitle  = &mt('Any users');
 8138:     }
 8139:     my @types;
 8140:     if (ref($order) eq 'ARRAY') {
 8141:         @types = @{$order};
 8142:     }
 8143:     if (@types == 0) {
 8144:         if (ref($usertypes) eq 'HASH') {
 8145:             @types = sort(keys(%{$usertypes}));
 8146:         }
 8147:     }
 8148:     if (keys(%{$usertypes}) > 0) {
 8149:         $othertitle = &mt('Other users');
 8150:     }
 8151:     return ($othertitle,$usertypes,\@types);
 8152: }
 8153: 
 8154: sub get_institutional_codes {
 8155:     my ($settings,$allcourses,$LC_code) = @_;
 8156: # Get complete list of course sections to update
 8157:     my @currsections = ();
 8158:     my @currxlists = ();
 8159:     my $coursecode = $$settings{'internal.coursecode'};
 8160: 
 8161:     if ($$settings{'internal.sectionnums'} ne '') {
 8162:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8163:     }
 8164: 
 8165:     if ($$settings{'internal.crosslistings'} ne '') {
 8166:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8167:     }
 8168: 
 8169:     if (@currxlists > 0) {
 8170:         foreach (@currxlists) {
 8171:             if (m/^([^:]+):(\w*)$/) {
 8172:                 unless (grep/^$1$/,@{$allcourses}) {
 8173:                     push @{$allcourses},$1;
 8174:                     $$LC_code{$1} = $2;
 8175:                 }
 8176:             }
 8177:         }
 8178:     }
 8179:  
 8180:     if (@currsections > 0) {
 8181:         foreach (@currsections) {
 8182:             if (m/^(\w+):(\w*)$/) {
 8183:                 my $sec = $coursecode.$1;
 8184:                 my $lc_sec = $2;
 8185:                 unless (grep/^$sec$/,@{$allcourses}) {
 8186:                     push @{$allcourses},$sec;
 8187:                     $$LC_code{$sec} = $lc_sec;
 8188:                 }
 8189:             }
 8190:         }
 8191:     }
 8192:     return;
 8193: }
 8194: 
 8195: =pod
 8196: 
 8197: =head1 Slot Helpers
 8198: 
 8199: =over 4
 8200: 
 8201: =item * sorted_slots()
 8202: 
 8203: Sorts an array of slot names in order of slot start time (earliest first). 
 8204: 
 8205: Inputs:
 8206: 
 8207: =over 4
 8208: 
 8209: slotsarr  - Reference to array of unsorted slot names.
 8210: 
 8211: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8212: 
 8213: =back
 8214: 
 8215: Returns:
 8216: 
 8217: =over 4
 8218: 
 8219: sorted   - An array of slot names sorted by the start time of the slot.
 8220: 
 8221: =back
 8222: 
 8223: =back
 8224: 
 8225: =cut
 8226: 
 8227: 
 8228: sub sorted_slots {
 8229:     my ($slotsarr,$slots) = @_;
 8230:     my @sorted;
 8231:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8232:         @sorted =
 8233:             sort {
 8234:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8235:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8236:                      }
 8237:                      if (ref($slots->{$a})) { return -1;}
 8238:                      if (ref($slots->{$b})) { return 1;}
 8239:                      return 0;
 8240:                  } @{$slotsarr};
 8241:     }
 8242:     return @sorted;
 8243: }
 8244: 
 8245: 
 8246: =pod
 8247: 
 8248: =head1 HTTP Helpers
 8249: 
 8250: =over 4
 8251: 
 8252: =item * &get_unprocessed_cgi($query,$possible_names)
 8253: 
 8254: Modify the %env hash to contain unprocessed CGI form parameters held in
 8255: $query.  The parameters listed in $possible_names (an array reference),
 8256: will be set in $env{'form.name'} if they do not already exist.
 8257: 
 8258: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8259: $possible_names is an ref to an array of form element names.  As an example:
 8260: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8261: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8262: 
 8263: =cut
 8264: 
 8265: sub get_unprocessed_cgi {
 8266:   my ($query,$possible_names)= @_;
 8267:   # $Apache::lonxml::debug=1;
 8268:   foreach my $pair (split(/&/,$query)) {
 8269:     my ($name, $value) = split(/=/,$pair);
 8270:     $name = &unescape($name);
 8271:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8272:       $value =~ tr/+/ /;
 8273:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8274:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8275:     }
 8276:   }
 8277: }
 8278: 
 8279: =pod
 8280: 
 8281: =item * &cacheheader() 
 8282: 
 8283: returns cache-controlling header code
 8284: 
 8285: =cut
 8286: 
 8287: sub cacheheader {
 8288:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8289:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8290:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8291:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8292:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8293:     return $output;
 8294: }
 8295: 
 8296: =pod
 8297: 
 8298: =item * &no_cache($r) 
 8299: 
 8300: specifies header code to not have cache
 8301: 
 8302: =cut
 8303: 
 8304: sub no_cache {
 8305:     my ($r) = @_;
 8306:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8307: 	$env{'request.method'} ne 'GET') { return ''; }
 8308:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8309:     $r->no_cache(1);
 8310:     $r->header_out("Expires" => $date);
 8311:     $r->header_out("Pragma" => "no-cache");
 8312: }
 8313: 
 8314: sub content_type {
 8315:     my ($r,$type,$charset) = @_;
 8316:     if ($r) {
 8317: 	#  Note that printout.pl calls this with undef for $r.
 8318: 	&no_cache($r);
 8319:     }
 8320:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8321:     unless ($charset) {
 8322: 	$charset=&Apache::lonlocal::current_encoding;
 8323:     }
 8324:     if ($charset) { $type.='; charset='.$charset; }
 8325:     if ($r) {
 8326: 	$r->content_type($type);
 8327:     } else {
 8328: 	print("Content-type: $type\n\n");
 8329:     }
 8330: }
 8331: 
 8332: =pod
 8333: 
 8334: =item * &add_to_env($name,$value) 
 8335: 
 8336: adds $name to the %env hash with value
 8337: $value, if $name already exists, the entry is converted to an array
 8338: reference and $value is added to the array.
 8339: 
 8340: =cut
 8341: 
 8342: sub add_to_env {
 8343:   my ($name,$value)=@_;
 8344:   if (defined($env{$name})) {
 8345:     if (ref($env{$name})) {
 8346:       #already have multiple values
 8347:       push(@{ $env{$name} },$value);
 8348:     } else {
 8349:       #first time seeing multiple values, convert hash entry to an arrayref
 8350:       my $first=$env{$name};
 8351:       undef($env{$name});
 8352:       push(@{ $env{$name} },$first,$value);
 8353:     }
 8354:   } else {
 8355:     $env{$name}=$value;
 8356:   }
 8357: }
 8358: 
 8359: =pod
 8360: 
 8361: =item * &get_env_multiple($name) 
 8362: 
 8363: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8364: values may be defined and end up as an array ref.
 8365: 
 8366: returns an array of values
 8367: 
 8368: =cut
 8369: 
 8370: sub get_env_multiple {
 8371:     my ($name) = @_;
 8372:     my @values;
 8373:     if (defined($env{$name})) {
 8374:         # exists is it an array
 8375:         if (ref($env{$name})) {
 8376:             @values=@{ $env{$name} };
 8377:         } else {
 8378:             $values[0]=$env{$name};
 8379:         }
 8380:     }
 8381:     return(@values);
 8382: }
 8383: 
 8384: sub ask_for_embedded_content {
 8385:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8386:     my $upload_output = '
 8387:    <form name="upload_embedded" action="'.$actionurl.'"
 8388:                   method="post" enctype="multipart/form-data">';
 8389:     $upload_output .= $state;
 8390:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8391: 
 8392:     my $num = 0;
 8393:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8394:         $upload_output .= &start_data_table_row().
 8395:             '<td>'.$embed_file.'</td><td>';
 8396:         if ($args->{'ignore_remote_references'}
 8397:             && $embed_file =~ m{^\w+://}) {
 8398:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8399:         } elsif ($args->{'error_on_invalid_names'}
 8400:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8401: 
 8402:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8403: 
 8404:         } else {
 8405:             $upload_output .='
 8406:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8407:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8408:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8409:             $upload_output .=
 8410:                 "\n\t\t".
 8411:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8412:                 $attrib.'" />';
 8413:             if (exists($$codebase{$embed_file})) {
 8414:                 $upload_output .=
 8415:                     "\n\t\t".
 8416:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8417:                     &escape($$codebase{$embed_file}).'" />';
 8418:             }
 8419:         }
 8420:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8421:         $num++;
 8422:     }
 8423:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8424:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8425:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8426:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8427:    </form>';
 8428:     return $upload_output;
 8429: }
 8430: 
 8431: sub upload_embedded {
 8432:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8433:         $current_disk_usage) = @_;
 8434:     my $output;
 8435:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8436:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8437:         my $orig_uploaded_filename =
 8438:             $env{'form.embedded_item_'.$i.'.filename'};
 8439: 
 8440:         $env{'form.embedded_orig_'.$i} =
 8441:             &unescape($env{'form.embedded_orig_'.$i});
 8442:         my ($path,$fname) =
 8443:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8444:         # no path, whole string is fname
 8445:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8446: 
 8447:         $path = $env{'form.currentpath'}.$path;
 8448:         $fname = &Apache::lonnet::clean_filename($fname);
 8449:         # See if there is anything left
 8450:         next if ($fname eq '');
 8451: 
 8452:         # Check if file already exists as a file or directory.
 8453:         my ($state,$msg);
 8454:         if ($context eq 'portfolio') {
 8455:             my $port_path = $dirpath;
 8456:             if ($group ne '') {
 8457:                 $port_path = "groups/$group/$port_path";
 8458:             }
 8459:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8460:                                               $dir_root,$port_path,$disk_quota,
 8461:                                               $current_disk_usage,$uname,$udom);
 8462:             if ($state eq 'will_exceed_quota'
 8463:                 || $state eq 'file_locked'
 8464:                 || $state eq 'file_exists' ) {
 8465:                 $output .= $msg;
 8466:                 next;
 8467:             }
 8468:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8469:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8470:             if ($state eq 'exists') {
 8471:                 $output .= $msg;
 8472:                 next;
 8473:             }
 8474:         }
 8475:         # Check if extension is valid
 8476:         if (($fname =~ /\.(\w+)$/) &&
 8477:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8478:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8479:             next;
 8480:         } elsif (($fname =~ /\.(\w+)$/) &&
 8481:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8482:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8483:             next;
 8484:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8485:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8486:             next;
 8487:         }
 8488: 
 8489:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8490:         if ($context eq 'portfolio') {
 8491:             my $result=
 8492:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8493:                                                 $dirpath.$path);
 8494:             if ($result !~ m|^/uploaded/|) {
 8495:                 $output .= '<span class="LC_error">'
 8496:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8497:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8498:                       .'</span><br />';
 8499:                 next;
 8500:             } else {
 8501:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8502:                            $path.$fname.'</span>').'</p>';     
 8503:             }
 8504:         } else {
 8505: # Save the file
 8506:             my $target = $env{'form.embedded_item_'.$i};
 8507:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8508:             my $dest = $fullpath.$fname;
 8509:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8510:             my @parts=split(/\//,$fullpath);
 8511:             my $count;
 8512:             my $filepath = $dir_root;
 8513:             for ($count=4;$count<=$#parts;$count++) {
 8514:                 $filepath .= "/$parts[$count]";
 8515:                 if ((-e $filepath)!=1) {
 8516:                     mkdir($filepath,0770);
 8517:                 }
 8518:             }
 8519:             my $fh;
 8520:             if (!open($fh,'>'.$dest)) {
 8521:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8522:                 $output .= '<span class="LC_error">'.
 8523:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8524:                            '</span><br />';
 8525:             } else {
 8526:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8527:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8528:                     $output .= '<span class="LC_error">'.
 8529:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8530:                               '</span><br />';
 8531:                 } else {
 8532:                     if ($context eq 'testbank') {
 8533:                         $output .= &mt('Embedded file uploaded successfully:').
 8534:                                    '&nbsp;<a href="'.$url.'">'.
 8535:                                    $orig_uploaded_filename.'</a><br />';
 8536:                     } else {
 8537:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8538:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8539:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8540:                     }
 8541:                 }
 8542:                 close($fh);
 8543:             }
 8544:         }
 8545:     }
 8546:     return $output;
 8547: }
 8548: 
 8549: sub check_for_existing {
 8550:     my ($path,$fname,$element) = @_;
 8551:     my ($state,$msg);
 8552:     if (-d $path.'/'.$fname) {
 8553:         $state = 'exists';
 8554:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8555:     } elsif (-e $path.'/'.$fname) {
 8556:         $state = 'exists';
 8557:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8558:     }
 8559:     if ($state eq 'exists') {
 8560:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8561:     }
 8562:     return ($state,$msg);
 8563: }
 8564: 
 8565: sub check_for_upload {
 8566:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8567:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8568:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8569:     my $getpropath = 1;
 8570:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8571:                                             $getpropath);
 8572:     my $found_file = 0;
 8573:     my $locked_file = 0;
 8574:     foreach my $line (@dir_list) {
 8575:         my ($file_name)=split(/\&/,$line,2);
 8576:         if ($file_name eq $fname){
 8577:             $file_name = $path.$file_name;
 8578:             if ($group ne '') {
 8579:                 $file_name = $group.$file_name;
 8580:             }
 8581:             $found_file = 1;
 8582:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8583:                 $locked_file = 1;
 8584:             }
 8585:         }
 8586:     }
 8587:     if (($current_disk_usage + $filesize) > $disk_quota){
 8588:         my $msg = '<span class="LC_error">'.
 8589:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8590:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8591:         return ('will_exceed_quota',$msg);
 8592:     } elsif ($found_file) {
 8593:         if ($locked_file) {
 8594:             my $msg = '<span class="LC_error">';
 8595:             $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>');
 8596:             $msg .= '</span><br />';
 8597:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8598:             return ('file_locked',$msg);
 8599:         } else {
 8600:             my $msg = '<span class="LC_error">';
 8601:             $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'});
 8602:             $msg .= '</span>';
 8603:             $msg .= '<br />';
 8604:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8605:             return ('file_exists',$msg);
 8606:         }
 8607:     }
 8608: }
 8609: 
 8610: 
 8611: =pod
 8612: 
 8613: =back
 8614: 
 8615: =head1 CSV Upload/Handling functions
 8616: 
 8617: =over 4
 8618: 
 8619: =item * &upfile_store($r)
 8620: 
 8621: Store uploaded file, $r should be the HTTP Request object,
 8622: needs $env{'form.upfile'}
 8623: returns $datatoken to be put into hidden field
 8624: 
 8625: =cut
 8626: 
 8627: sub upfile_store {
 8628:     my $r=shift;
 8629:     $env{'form.upfile'}=~s/\r/\n/gs;
 8630:     $env{'form.upfile'}=~s/\f/\n/gs;
 8631:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8632:     $env{'form.upfile'}=~s/\n+$//gs;
 8633: 
 8634:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8635: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8636:     {
 8637:         my $datafile = $r->dir_config('lonDaemons').
 8638:                            '/tmp/'.$datatoken.'.tmp';
 8639:         if ( open(my $fh,">$datafile") ) {
 8640:             print $fh $env{'form.upfile'};
 8641:             close($fh);
 8642:         }
 8643:     }
 8644:     return $datatoken;
 8645: }
 8646: 
 8647: =pod
 8648: 
 8649: =item * &load_tmp_file($r)
 8650: 
 8651: Load uploaded file from tmp, $r should be the HTTP Request object,
 8652: needs $env{'form.datatoken'},
 8653: sets $env{'form.upfile'} to the contents of the file
 8654: 
 8655: =cut
 8656: 
 8657: sub load_tmp_file {
 8658:     my $r=shift;
 8659:     my @studentdata=();
 8660:     {
 8661:         my $studentfile = $r->dir_config('lonDaemons').
 8662:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8663:         if ( open(my $fh,"<$studentfile") ) {
 8664:             @studentdata=<$fh>;
 8665:             close($fh);
 8666:         }
 8667:     }
 8668:     $env{'form.upfile'}=join('',@studentdata);
 8669: }
 8670: 
 8671: =pod
 8672: 
 8673: =item * &upfile_record_sep()
 8674: 
 8675: Separate uploaded file into records
 8676: returns array of records,
 8677: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8678: 
 8679: =cut
 8680: 
 8681: sub upfile_record_sep {
 8682:     if ($env{'form.upfiletype'} eq 'xml') {
 8683:     } else {
 8684: 	my @records;
 8685: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8686: 	    if ($line=~/^\s*$/) { next; }
 8687: 	    push(@records,$line);
 8688: 	}
 8689: 	return @records;
 8690:     }
 8691: }
 8692: 
 8693: =pod
 8694: 
 8695: =item * &record_sep($record)
 8696: 
 8697: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8698: 
 8699: =cut
 8700: 
 8701: sub takeleft {
 8702:     my $index=shift;
 8703:     return substr('0000'.$index,-4,4);
 8704: }
 8705: 
 8706: sub record_sep {
 8707:     my $record=shift;
 8708:     my %components=();
 8709:     if ($env{'form.upfiletype'} eq 'xml') {
 8710:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8711:         my $i=0;
 8712:         foreach my $field (split(/\s+/,$record)) {
 8713:             $field=~s/^(\"|\')//;
 8714:             $field=~s/(\"|\')$//;
 8715:             $components{&takeleft($i)}=$field;
 8716:             $i++;
 8717:         }
 8718:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8719:         my $i=0;
 8720:         foreach my $field (split(/\t/,$record)) {
 8721:             $field=~s/^(\"|\')//;
 8722:             $field=~s/(\"|\')$//;
 8723:             $components{&takeleft($i)}=$field;
 8724:             $i++;
 8725:         }
 8726:     } else {
 8727:         my $separator=',';
 8728:         if ($env{'form.upfiletype'} eq 'semisv') {
 8729:             $separator=';';
 8730:         }
 8731:         my $i=0;
 8732: # the character we are looking for to indicate the end of a quote or a record 
 8733:         my $looking_for=$separator;
 8734: # do not add the characters to the fields
 8735:         my $ignore=0;
 8736: # we just encountered a separator (or the beginning of the record)
 8737:         my $just_found_separator=1;
 8738: # store the field we are working on here
 8739:         my $field='';
 8740: # work our way through all characters in record
 8741:         foreach my $character ($record=~/(.)/g) {
 8742:             if ($character eq $looking_for) {
 8743:                if ($character ne $separator) {
 8744: # Found the end of a quote, again looking for separator
 8745:                   $looking_for=$separator;
 8746:                   $ignore=1;
 8747:                } else {
 8748: # Found a separator, store away what we got
 8749:                   $components{&takeleft($i)}=$field;
 8750: 	          $i++;
 8751:                   $just_found_separator=1;
 8752:                   $ignore=0;
 8753:                   $field='';
 8754:                }
 8755:                next;
 8756:             }
 8757: # single or double quotation marks after a separator indicate beginning of a quote
 8758: # we are now looking for the end of the quote and need to ignore separators
 8759:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8760:                $looking_for=$character;
 8761:                next;
 8762:             }
 8763: # ignore would be true after we reached the end of a quote
 8764:             if ($ignore) { next; }
 8765:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8766:             $field.=$character;
 8767:             $just_found_separator=0; 
 8768:         }
 8769: # catch the very last entry, since we never encountered the separator
 8770:         $components{&takeleft($i)}=$field;
 8771:     }
 8772:     return %components;
 8773: }
 8774: 
 8775: ######################################################
 8776: ######################################################
 8777: 
 8778: =pod
 8779: 
 8780: =item * &upfile_select_html()
 8781: 
 8782: Return HTML code to select a file from the users machine and specify 
 8783: the file type.
 8784: 
 8785: =cut
 8786: 
 8787: ######################################################
 8788: ######################################################
 8789: sub upfile_select_html {
 8790:     my %Types = (
 8791:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8792:                  semisv => &mt('Semicolon separated values'),
 8793:                  space => &mt('Space separated'),
 8794:                  tab   => &mt('Tabulator separated'),
 8795: #                 xml   => &mt('HTML/XML'),
 8796:                  );
 8797:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8798:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8799:     foreach my $type (sort(keys(%Types))) {
 8800:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8801:     }
 8802:     $Str .= "</select>\n";
 8803:     return $Str;
 8804: }
 8805: 
 8806: sub get_samples {
 8807:     my ($records,$toget) = @_;
 8808:     my @samples=({});
 8809:     my $got=0;
 8810:     foreach my $rec (@$records) {
 8811: 	my %temp = &record_sep($rec);
 8812: 	if (! grep(/\S/, values(%temp))) { next; }
 8813: 	if (%temp) {
 8814: 	    $samples[$got]=\%temp;
 8815: 	    $got++;
 8816: 	    if ($got == $toget) { last; }
 8817: 	}
 8818:     }
 8819:     return \@samples;
 8820: }
 8821: 
 8822: ######################################################
 8823: ######################################################
 8824: 
 8825: =pod
 8826: 
 8827: =item * &csv_print_samples($r,$records)
 8828: 
 8829: Prints a table of sample values from each column uploaded $r is an
 8830: Apache Request ref, $records is an arrayref from
 8831: &Apache::loncommon::upfile_record_sep
 8832: 
 8833: =cut
 8834: 
 8835: ######################################################
 8836: ######################################################
 8837: sub csv_print_samples {
 8838:     my ($r,$records) = @_;
 8839:     my $samples = &get_samples($records,5);
 8840: 
 8841:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8842:               &start_data_table_header_row());
 8843:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8844:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 8845:     $r->print(&end_data_table_header_row());
 8846:     foreach my $hash (@$samples) {
 8847: 	$r->print(&start_data_table_row());
 8848: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8849: 	    $r->print('<td>');
 8850: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8851: 	    $r->print('</td>');
 8852: 	}
 8853: 	$r->print(&end_data_table_row());
 8854:     }
 8855:     $r->print(&end_data_table().'<br />'."\n");
 8856: }
 8857: 
 8858: ######################################################
 8859: ######################################################
 8860: 
 8861: =pod
 8862: 
 8863: =item * &csv_print_select_table($r,$records,$d)
 8864: 
 8865: Prints a table to create associations between values and table columns.
 8866: 
 8867: $r is an Apache Request ref,
 8868: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8869: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8870: 
 8871: =cut
 8872: 
 8873: ######################################################
 8874: ######################################################
 8875: sub csv_print_select_table {
 8876:     my ($r,$records,$d) = @_;
 8877:     my $i=0;
 8878:     my $samples = &get_samples($records,1);
 8879:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8880: 	      &start_data_table().&start_data_table_header_row().
 8881:               '<th>'.&mt('Attribute').'</th>'.
 8882:               '<th>'.&mt('Column').'</th>'.
 8883:               &end_data_table_header_row()."\n");
 8884:     foreach my $array_ref (@$d) {
 8885: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8886: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8887: 
 8888: 	$r->print('<td><select name="f'.$i.'"'.
 8889: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8890: 	$r->print('<option value="none"></option>');
 8891: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8892: 	    $r->print('<option value="'.$sample.'"'.
 8893:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8894:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8895: 	}
 8896: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8897: 	$i++;
 8898:     }
 8899:     $r->print(&end_data_table());
 8900:     $i--;
 8901:     return $i;
 8902: }
 8903: 
 8904: ######################################################
 8905: ######################################################
 8906: 
 8907: =pod
 8908: 
 8909: =item * &csv_samples_select_table($r,$records,$d)
 8910: 
 8911: Prints a table of sample values from the upload and can make associate samples to internal names.
 8912: 
 8913: $r is an Apache Request ref,
 8914: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8915: $d is an array of 2 element arrays (internal name, displayed name)
 8916: 
 8917: =cut
 8918: 
 8919: ######################################################
 8920: ######################################################
 8921: sub csv_samples_select_table {
 8922:     my ($r,$records,$d) = @_;
 8923:     my $i=0;
 8924:     #
 8925:     my $max_samples = 5;
 8926:     my $samples = &get_samples($records,$max_samples);
 8927:     $r->print(&start_data_table().
 8928:               &start_data_table_header_row().'<th>'.
 8929:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8930:               &end_data_table_header_row());
 8931: 
 8932:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8933: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8934: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8935: 	foreach my $option (@$d) {
 8936: 	    my ($value,$display,$defaultcol)=@{ $option };
 8937: 	    $r->print('<option value="'.$value.'"'.
 8938:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8939:                       $display.'</option>');
 8940: 	}
 8941: 	$r->print('</select></td><td>');
 8942: 	foreach my $line (0..($max_samples-1)) {
 8943: 	    if (defined($samples->[$line]{$key})) { 
 8944: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8945: 	    }
 8946: 	}
 8947: 	$r->print('</td>'.&end_data_table_row());
 8948: 	$i++;
 8949:     }
 8950:     $r->print(&end_data_table());
 8951:     $i--;
 8952:     return($i);
 8953: }
 8954: 
 8955: ######################################################
 8956: ######################################################
 8957: 
 8958: =pod
 8959: 
 8960: =item * &clean_excel_name($name)
 8961: 
 8962: Returns a replacement for $name which does not contain any illegal characters.
 8963: 
 8964: =cut
 8965: 
 8966: ######################################################
 8967: ######################################################
 8968: sub clean_excel_name {
 8969:     my ($name) = @_;
 8970:     $name =~ s/[:\*\?\/\\]//g;
 8971:     if (length($name) > 31) {
 8972:         $name = substr($name,0,31);
 8973:     }
 8974:     return $name;
 8975: }
 8976: 
 8977: =pod
 8978: 
 8979: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8980: 
 8981: Returns either 1 or undef
 8982: 
 8983: 1 if the part is to be hidden, undef if it is to be shown
 8984: 
 8985: Arguments are:
 8986: 
 8987: $id the id of the part to be checked
 8988: $symb, optional the symb of the resource to check
 8989: $udom, optional the domain of the user to check for
 8990: $uname, optional the username of the user to check for
 8991: 
 8992: =cut
 8993: 
 8994: sub check_if_partid_hidden {
 8995:     my ($id,$symb,$udom,$uname) = @_;
 8996:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8997: 					 $symb,$udom,$uname);
 8998:     my $truth=1;
 8999:     #if the string starts with !, then the list is the list to show not hide
 9000:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9001:     my @hiddenlist=split(/,/,$hiddenparts);
 9002:     foreach my $checkid (@hiddenlist) {
 9003: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9004:     }
 9005:     return !$truth;
 9006: }
 9007: 
 9008: 
 9009: ############################################################
 9010: ############################################################
 9011: 
 9012: =pod
 9013: 
 9014: =back 
 9015: 
 9016: =head1 cgi-bin script and graphing routines
 9017: 
 9018: =over 4
 9019: 
 9020: =item * &get_cgi_id()
 9021: 
 9022: Inputs: none
 9023: 
 9024: Returns an id which can be used to pass environment variables
 9025: to various cgi-bin scripts.  These environment variables will
 9026: be removed from the users environment after a given time by
 9027: the routine &Apache::lonnet::transfer_profile_to_env.
 9028: 
 9029: =cut
 9030: 
 9031: ############################################################
 9032: ############################################################
 9033: my $uniq=0;
 9034: sub get_cgi_id {
 9035:     $uniq=($uniq+1)%100000;
 9036:     return (time.'_'.$$.'_'.$uniq);
 9037: }
 9038: 
 9039: ############################################################
 9040: ############################################################
 9041: 
 9042: =pod
 9043: 
 9044: =item * &DrawBarGraph()
 9045: 
 9046: Facilitates the plotting of data in a (stacked) bar graph.
 9047: Puts plot definition data into the users environment in order for 
 9048: graph.png to plot it.  Returns an <img> tag for the plot.
 9049: The bars on the plot are labeled '1','2',...,'n'.
 9050: 
 9051: Inputs:
 9052: 
 9053: =over 4
 9054: 
 9055: =item $Title: string, the title of the plot
 9056: 
 9057: =item $xlabel: string, text describing the X-axis of the plot
 9058: 
 9059: =item $ylabel: string, text describing the Y-axis of the plot
 9060: 
 9061: =item $Max: scalar, the maximum Y value to use in the plot
 9062: If $Max is < any data point, the graph will not be rendered.
 9063: 
 9064: =item $colors: array ref holding the colors to be used for the data sets when
 9065: they are plotted.  If undefined, default values will be used.
 9066: 
 9067: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9068: 
 9069: =item @Values: An array of array references.  Each array reference holds data
 9070: to be plotted in a stacked bar chart.
 9071: 
 9072: =item If the final element of @Values is a hash reference the key/value
 9073: pairs will be added to the graph definition.
 9074: 
 9075: =back
 9076: 
 9077: Returns:
 9078: 
 9079: An <img> tag which references graph.png and the appropriate identifying
 9080: information for the plot.
 9081: 
 9082: =cut
 9083: 
 9084: ############################################################
 9085: ############################################################
 9086: sub DrawBarGraph {
 9087:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9088:     #
 9089:     if (! defined($colors)) {
 9090:         $colors = ['#33ff00', 
 9091:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9092:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9093:                   ]; 
 9094:     }
 9095:     my $extra_settings = {};
 9096:     if (ref($Values[-1]) eq 'HASH') {
 9097:         $extra_settings = pop(@Values);
 9098:     }
 9099:     #
 9100:     my $identifier = &get_cgi_id();
 9101:     my $id = 'cgi.'.$identifier;        
 9102:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9103:         return '';
 9104:     }
 9105:     #
 9106:     my @Labels;
 9107:     if (defined($labels)) {
 9108:         @Labels = @$labels;
 9109:     } else {
 9110:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9111:             push (@Labels,$i+1);
 9112:         }
 9113:     }
 9114:     #
 9115:     my $NumBars = scalar(@{$Values[0]});
 9116:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9117:     my %ValuesHash;
 9118:     my $NumSets=1;
 9119:     foreach my $array (@Values) {
 9120:         next if (! ref($array));
 9121:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9122:             join(',',@$array);
 9123:     }
 9124:     #
 9125:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9126:     if ($NumBars < 3) {
 9127:         $width = 120+$NumBars*32;
 9128:         $xskip = 1;
 9129:         $bar_width = 30;
 9130:     } elsif ($NumBars < 5) {
 9131:         $width = 120+$NumBars*20;
 9132:         $xskip = 1;
 9133:         $bar_width = 20;
 9134:     } elsif ($NumBars < 10) {
 9135:         $width = 120+$NumBars*15;
 9136:         $xskip = 1;
 9137:         $bar_width = 15;
 9138:     } elsif ($NumBars <= 25) {
 9139:         $width = 120+$NumBars*11;
 9140:         $xskip = 5;
 9141:         $bar_width = 8;
 9142:     } elsif ($NumBars <= 50) {
 9143:         $width = 120+$NumBars*8;
 9144:         $xskip = 5;
 9145:         $bar_width = 4;
 9146:     } else {
 9147:         $width = 120+$NumBars*8;
 9148:         $xskip = 5;
 9149:         $bar_width = 4;
 9150:     }
 9151:     #
 9152:     $Max = 1 if ($Max < 1);
 9153:     if ( int($Max) < $Max ) {
 9154:         $Max++;
 9155:         $Max = int($Max);
 9156:     }
 9157:     $Title  = '' if (! defined($Title));
 9158:     $xlabel = '' if (! defined($xlabel));
 9159:     $ylabel = '' if (! defined($ylabel));
 9160:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9161:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9162:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9163:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9164:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9165:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9166:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9167:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9168:     $ValuesHash{$id.'.height'}   = $height;
 9169:     $ValuesHash{$id.'.width'}    = $width;
 9170:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9171:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9172:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9173:     #
 9174:     # Deal with other parameters
 9175:     while (my ($key,$value) = each(%$extra_settings)) {
 9176:         $ValuesHash{$id.'.'.$key} = $value;
 9177:     }
 9178:     #
 9179:     &Apache::lonnet::appenv(\%ValuesHash);
 9180:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9181: }
 9182: 
 9183: ############################################################
 9184: ############################################################
 9185: 
 9186: =pod
 9187: 
 9188: =item * &DrawXYGraph()
 9189: 
 9190: Facilitates the plotting of data in an XY graph.
 9191: Puts plot definition data into the users environment in order for 
 9192: graph.png to plot it.  Returns an <img> tag for the plot.
 9193: 
 9194: Inputs:
 9195: 
 9196: =over 4
 9197: 
 9198: =item $Title: string, the title of the plot
 9199: 
 9200: =item $xlabel: string, text describing the X-axis of the plot
 9201: 
 9202: =item $ylabel: string, text describing the Y-axis of the plot
 9203: 
 9204: =item $Max: scalar, the maximum Y value to use in the plot
 9205: If $Max is < any data point, the graph will not be rendered.
 9206: 
 9207: =item $colors: Array ref containing the hex color codes for the data to be 
 9208: plotted in.  If undefined, default values will be used.
 9209: 
 9210: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9211: 
 9212: =item $Ydata: Array ref containing Array refs.  
 9213: Each of the contained arrays will be plotted as a separate curve.
 9214: 
 9215: =item %Values: hash indicating or overriding any default values which are 
 9216: passed to graph.png.  
 9217: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9218: 
 9219: =back
 9220: 
 9221: Returns:
 9222: 
 9223: An <img> tag which references graph.png and the appropriate identifying
 9224: information for the plot.
 9225: 
 9226: =cut
 9227: 
 9228: ############################################################
 9229: ############################################################
 9230: sub DrawXYGraph {
 9231:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9232:     #
 9233:     # Create the identifier for the graph
 9234:     my $identifier = &get_cgi_id();
 9235:     my $id = 'cgi.'.$identifier;
 9236:     #
 9237:     $Title  = '' if (! defined($Title));
 9238:     $xlabel = '' if (! defined($xlabel));
 9239:     $ylabel = '' if (! defined($ylabel));
 9240:     my %ValuesHash = 
 9241:         (
 9242:          $id.'.title'  => &escape($Title),
 9243:          $id.'.xlabel' => &escape($xlabel),
 9244:          $id.'.ylabel' => &escape($ylabel),
 9245:          $id.'.y_max_value'=> $Max,
 9246:          $id.'.labels'     => join(',',@$Xlabels),
 9247:          $id.'.PlotType'   => 'XY',
 9248:          );
 9249:     #
 9250:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9251:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9252:     }
 9253:     #
 9254:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9255:         return '';
 9256:     }
 9257:     my $NumSets=1;
 9258:     foreach my $array (@{$Ydata}){
 9259:         next if (! ref($array));
 9260:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9261:     }
 9262:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9263:     #
 9264:     # Deal with other parameters
 9265:     while (my ($key,$value) = each(%Values)) {
 9266:         $ValuesHash{$id.'.'.$key} = $value;
 9267:     }
 9268:     #
 9269:     &Apache::lonnet::appenv(\%ValuesHash);
 9270:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9271: }
 9272: 
 9273: ############################################################
 9274: ############################################################
 9275: 
 9276: =pod
 9277: 
 9278: =item * &DrawXYYGraph()
 9279: 
 9280: Facilitates the plotting of data in an XY graph with two Y axes.
 9281: Puts plot definition data into the users environment in order for 
 9282: graph.png to plot it.  Returns an <img> tag for the plot.
 9283: 
 9284: Inputs:
 9285: 
 9286: =over 4
 9287: 
 9288: =item $Title: string, the title of the plot
 9289: 
 9290: =item $xlabel: string, text describing the X-axis of the plot
 9291: 
 9292: =item $ylabel: string, text describing the Y-axis of the plot
 9293: 
 9294: =item $colors: Array ref containing the hex color codes for the data to be 
 9295: plotted in.  If undefined, default values will be used.
 9296: 
 9297: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9298: 
 9299: =item $Ydata1: The first data set
 9300: 
 9301: =item $Min1: The minimum value of the left Y-axis
 9302: 
 9303: =item $Max1: The maximum value of the left Y-axis
 9304: 
 9305: =item $Ydata2: The second data set
 9306: 
 9307: =item $Min2: The minimum value of the right Y-axis
 9308: 
 9309: =item $Max2: The maximum value of the left Y-axis
 9310: 
 9311: =item %Values: hash indicating or overriding any default values which are 
 9312: passed to graph.png.  
 9313: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9314: 
 9315: =back
 9316: 
 9317: Returns:
 9318: 
 9319: An <img> tag which references graph.png and the appropriate identifying
 9320: information for the plot.
 9321: 
 9322: =cut
 9323: 
 9324: ############################################################
 9325: ############################################################
 9326: sub DrawXYYGraph {
 9327:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9328:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9329:     #
 9330:     # Create the identifier for the graph
 9331:     my $identifier = &get_cgi_id();
 9332:     my $id = 'cgi.'.$identifier;
 9333:     #
 9334:     $Title  = '' if (! defined($Title));
 9335:     $xlabel = '' if (! defined($xlabel));
 9336:     $ylabel = '' if (! defined($ylabel));
 9337:     my %ValuesHash = 
 9338:         (
 9339:          $id.'.title'  => &escape($Title),
 9340:          $id.'.xlabel' => &escape($xlabel),
 9341:          $id.'.ylabel' => &escape($ylabel),
 9342:          $id.'.labels' => join(',',@$Xlabels),
 9343:          $id.'.PlotType' => 'XY',
 9344:          $id.'.NumSets' => 2,
 9345:          $id.'.two_axes' => 1,
 9346:          $id.'.y1_max_value' => $Max1,
 9347:          $id.'.y1_min_value' => $Min1,
 9348:          $id.'.y2_max_value' => $Max2,
 9349:          $id.'.y2_min_value' => $Min2,
 9350:          );
 9351:     #
 9352:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9353:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9354:     }
 9355:     #
 9356:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9357:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9358:         return '';
 9359:     }
 9360:     my $NumSets=1;
 9361:     foreach my $array ($Ydata1,$Ydata2){
 9362:         next if (! ref($array));
 9363:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9364:     }
 9365:     #
 9366:     # Deal with other parameters
 9367:     while (my ($key,$value) = each(%Values)) {
 9368:         $ValuesHash{$id.'.'.$key} = $value;
 9369:     }
 9370:     #
 9371:     &Apache::lonnet::appenv(\%ValuesHash);
 9372:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9373: }
 9374: 
 9375: ############################################################
 9376: ############################################################
 9377: 
 9378: =pod
 9379: 
 9380: =back 
 9381: 
 9382: =head1 Statistics helper routines?  
 9383: 
 9384: Bad place for them but what the hell.
 9385: 
 9386: =over 4
 9387: 
 9388: =item * &chartlink()
 9389: 
 9390: Returns a link to the chart for a specific student.  
 9391: 
 9392: Inputs:
 9393: 
 9394: =over 4
 9395: 
 9396: =item $linktext: The text of the link
 9397: 
 9398: =item $sname: The students username
 9399: 
 9400: =item $sdomain: The students domain
 9401: 
 9402: =back
 9403: 
 9404: =back
 9405: 
 9406: =cut
 9407: 
 9408: ############################################################
 9409: ############################################################
 9410: sub chartlink {
 9411:     my ($linktext, $sname, $sdomain) = @_;
 9412:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9413:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9414:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9415:        '">'.$linktext.'</a>';
 9416: }
 9417: 
 9418: #######################################################
 9419: #######################################################
 9420: 
 9421: =pod
 9422: 
 9423: =head1 Course Environment Routines
 9424: 
 9425: =over 4
 9426: 
 9427: =item * &restore_course_settings()
 9428: 
 9429: =item * &store_course_settings()
 9430: 
 9431: Restores/Store indicated form parameters from the course environment.
 9432: Will not overwrite existing values of the form parameters.
 9433: 
 9434: Inputs: 
 9435: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9436: 
 9437: a hash ref describing the data to be stored.  For example:
 9438:    
 9439: %Save_Parameters = ('Status' => 'scalar',
 9440:     'chartoutputmode' => 'scalar',
 9441:     'chartoutputdata' => 'scalar',
 9442:     'Section' => 'array',
 9443:     'Group' => 'array',
 9444:     'StudentData' => 'array',
 9445:     'Maps' => 'array');
 9446: 
 9447: Returns: both routines return nothing
 9448: 
 9449: =back
 9450: 
 9451: =cut
 9452: 
 9453: #######################################################
 9454: #######################################################
 9455: sub store_course_settings {
 9456:     return &store_settings($env{'request.course.id'},@_);
 9457: }
 9458: 
 9459: sub store_settings {
 9460:     # save to the environment
 9461:     # appenv the same items, just to be safe
 9462:     my $udom  = $env{'user.domain'};
 9463:     my $uname = $env{'user.name'};
 9464:     my ($context,$prefix,$Settings) = @_;
 9465:     my %SaveHash;
 9466:     my %AppHash;
 9467:     while (my ($setting,$type) = each(%$Settings)) {
 9468:         my $basename = join('.','internal',$context,$prefix,$setting);
 9469:         my $envname = 'environment.'.$basename;
 9470:         if (exists($env{'form.'.$setting})) {
 9471:             # Save this value away
 9472:             if ($type eq 'scalar' &&
 9473:                 (! exists($env{$envname}) || 
 9474:                  $env{$envname} ne $env{'form.'.$setting})) {
 9475:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9476:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9477:             } elsif ($type eq 'array') {
 9478:                 my $stored_form;
 9479:                 if (ref($env{'form.'.$setting})) {
 9480:                     $stored_form = join(',',
 9481:                                         map {
 9482:                                             &escape($_);
 9483:                                         } sort(@{$env{'form.'.$setting}}));
 9484:                 } else {
 9485:                     $stored_form = 
 9486:                         &escape($env{'form.'.$setting});
 9487:                 }
 9488:                 # Determine if the array contents are the same.
 9489:                 if ($stored_form ne $env{$envname}) {
 9490:                     $SaveHash{$basename} = $stored_form;
 9491:                     $AppHash{$envname}   = $stored_form;
 9492:                 }
 9493:             }
 9494:         }
 9495:     }
 9496:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9497:                                           $udom,$uname);
 9498:     if ($put_result !~ /^(ok|delayed)/) {
 9499:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9500:                                  'got error:'.$put_result);
 9501:     }
 9502:     # Make sure these settings stick around in this session, too
 9503:     &Apache::lonnet::appenv(\%AppHash);
 9504:     return;
 9505: }
 9506: 
 9507: sub restore_course_settings {
 9508:     return &restore_settings($env{'request.course.id'},@_);
 9509: }
 9510: 
 9511: sub restore_settings {
 9512:     my ($context,$prefix,$Settings) = @_;
 9513:     while (my ($setting,$type) = each(%$Settings)) {
 9514:         next if (exists($env{'form.'.$setting}));
 9515:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9516:             '.'.$setting;
 9517:         if (exists($env{$envname})) {
 9518:             if ($type eq 'scalar') {
 9519:                 $env{'form.'.$setting} = $env{$envname};
 9520:             } elsif ($type eq 'array') {
 9521:                 $env{'form.'.$setting} = [ 
 9522:                                            map { 
 9523:                                                &unescape($_); 
 9524:                                            } split(',',$env{$envname})
 9525:                                            ];
 9526:             }
 9527:         }
 9528:     }
 9529: }
 9530: 
 9531: #######################################################
 9532: #######################################################
 9533: 
 9534: =pod
 9535: 
 9536: =head1 Domain E-mail Routines  
 9537: 
 9538: =over 4
 9539: 
 9540: =item * &build_recipient_list()
 9541: 
 9542: Build recipient lists for five types of e-mail:
 9543: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9544: (d) Help requests, (e) Course requests needing approval,  generated by
 9545: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
 9546: loncoursequeueadmin.pm respectively.
 9547: 
 9548: Inputs:
 9549: defmail (scalar - email address of default recipient), 
 9550: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9551: defdom (domain for which to retrieve configuration settings),
 9552: origmail (scalar - email address of recipient from loncapa.conf, 
 9553: i.e., predates configuration by DC via domainprefs.pm 
 9554: 
 9555: Returns: comma separated list of addresses to which to send e-mail.
 9556: 
 9557: =back
 9558: 
 9559: =cut
 9560: 
 9561: ############################################################
 9562: ############################################################
 9563: sub build_recipient_list {
 9564:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9565:     my @recipients;
 9566:     my $otheremails;
 9567:     my %domconfig =
 9568:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9569:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9570:         if (exists($domconfig{'contacts'}{$mailing})) {
 9571:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9572:                 my @contacts = ('adminemail','supportemail');
 9573:                 foreach my $item (@contacts) {
 9574:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9575:                         my $addr = $domconfig{'contacts'}{$item}; 
 9576:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9577:                             push(@recipients,$addr);
 9578:                         }
 9579:                     }
 9580:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9581:                 }
 9582:             }
 9583:         } elsif ($origmail ne '') {
 9584:             push(@recipients,$origmail);
 9585:         }
 9586:     } elsif ($origmail ne '') {
 9587:         push(@recipients,$origmail);
 9588:     }
 9589:     if (defined($defmail)) {
 9590:         if ($defmail ne '') {
 9591:             push(@recipients,$defmail);
 9592:         }
 9593:     }
 9594:     if ($otheremails) {
 9595:         my @others;
 9596:         if ($otheremails =~ /,/) {
 9597:             @others = split(/,/,$otheremails);
 9598:         } else {
 9599:             push(@others,$otheremails);
 9600:         }
 9601:         foreach my $addr (@others) {
 9602:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9603:                 push(@recipients,$addr);
 9604:             }
 9605:         }
 9606:     }
 9607:     my $recipientlist = join(',',@recipients); 
 9608:     return $recipientlist;
 9609: }
 9610: 
 9611: ############################################################
 9612: ############################################################
 9613: 
 9614: =pod
 9615: 
 9616: =head1 Course Catalog Routines
 9617: 
 9618: =over 4
 9619: 
 9620: =item * &gather_categories()
 9621: 
 9622: Converts category definitions - keys of categories hash stored in  
 9623: coursecategories in configuration.db on the primary library server in a 
 9624: domain - to an array.  Also generates javascript and idx hash used to 
 9625: generate Domain Coordinator interface for editing Course Categories.
 9626: 
 9627: Inputs:
 9628: 
 9629: categories (reference to hash of category definitions).
 9630: 
 9631: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9632:       categories and subcategories).
 9633: 
 9634: idx (reference to hash of counters used in Domain Coordinator interface for 
 9635:       editing Course Categories).
 9636: 
 9637: jsarray (reference to array of categories used to create Javascript arrays for
 9638:          Domain Coordinator interface for editing Course Categories).
 9639: 
 9640: Returns: nothing
 9641: 
 9642: Side effects: populates cats, idx and jsarray. 
 9643: 
 9644: =cut
 9645: 
 9646: sub gather_categories {
 9647:     my ($categories,$cats,$idx,$jsarray) = @_;
 9648:     my %counters;
 9649:     my $num = 0;
 9650:     foreach my $item (keys(%{$categories})) {
 9651:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9652:         if ($container eq '' && $depth == 0) {
 9653:             $cats->[$depth][$categories->{$item}] = $cat;
 9654:         } else {
 9655:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9656:         }
 9657:         my ($escitem,$tail) = split(/:/,$item,2);
 9658:         if ($counters{$tail} eq '') {
 9659:             $counters{$tail} = $num;
 9660:             $num ++;
 9661:         }
 9662:         if (ref($idx) eq 'HASH') {
 9663:             $idx->{$item} = $counters{$tail};
 9664:         }
 9665:         if (ref($jsarray) eq 'ARRAY') {
 9666:             push(@{$jsarray->[$counters{$tail}]},$item);
 9667:         }
 9668:     }
 9669:     return;
 9670: }
 9671: 
 9672: =pod
 9673: 
 9674: =item * &extract_categories()
 9675: 
 9676: Used to generate breadcrumb trails for course categories.
 9677: 
 9678: Inputs:
 9679: 
 9680: categories (reference to hash of category definitions).
 9681: 
 9682: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9683:       categories and subcategories).
 9684: 
 9685: trails (reference to array of breacrumb trails for each category).
 9686: 
 9687: allitems (reference to hash - key is category key 
 9688:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9689: 
 9690: idx (reference to hash of counters used in Domain Coordinator interface for
 9691:       editing Course Categories).
 9692: 
 9693: jsarray (reference to array of categories used to create Javascript arrays for
 9694:          Domain Coordinator interface for editing Course Categories).
 9695: 
 9696: subcats (reference to hash of arrays containing all subcategories within each 
 9697:          category, -recursive)
 9698: 
 9699: Returns: nothing
 9700: 
 9701: Side effects: populates trails and allitems hash references.
 9702: 
 9703: =cut
 9704: 
 9705: sub extract_categories {
 9706:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9707:     if (ref($categories) eq 'HASH') {
 9708:         &gather_categories($categories,$cats,$idx,$jsarray);
 9709:         if (ref($cats->[0]) eq 'ARRAY') {
 9710:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9711:                 my $name = $cats->[0][$i];
 9712:                 my $item = &escape($name).'::0';
 9713:                 my $trailstr;
 9714:                 if ($name eq 'instcode') {
 9715:                     $trailstr = &mt('Official courses (with institutional codes)');
 9716:                 } elsif ($name eq 'communities') {
 9717:                     $trailstr = &mt('Communities');
 9718:                 } else {
 9719:                     $trailstr = $name;
 9720:                 }
 9721:                 if ($allitems->{$item} eq '') {
 9722:                     push(@{$trails},$trailstr);
 9723:                     $allitems->{$item} = scalar(@{$trails})-1;
 9724:                 }
 9725:                 my @parents = ($name);
 9726:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9727:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9728:                         my $category = $cats->[1]{$name}[$j];
 9729:                         if (ref($subcats) eq 'HASH') {
 9730:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9731:                         }
 9732:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9733:                     }
 9734:                 } else {
 9735:                     if (ref($subcats) eq 'HASH') {
 9736:                         $subcats->{$item} = [];
 9737:                     }
 9738:                 }
 9739:             }
 9740:         }
 9741:     }
 9742:     return;
 9743: }
 9744: 
 9745: =pod
 9746: 
 9747: =item *&recurse_categories()
 9748: 
 9749: Recursively used to generate breadcrumb trails for course categories.
 9750: 
 9751: Inputs:
 9752: 
 9753: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9754:       categories and subcategories).
 9755: 
 9756: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9757: 
 9758: category (current course category, for which breadcrumb trail is being generated).
 9759: 
 9760: trails (reference to array of breadcrumb trails for each category).
 9761: 
 9762: allitems (reference to hash - key is category key
 9763:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9764: 
 9765: parents (array containing containers directories for current category, 
 9766:          back to top level). 
 9767: 
 9768: Returns: nothing
 9769: 
 9770: Side effects: populates trails and allitems hash references
 9771: 
 9772: =cut
 9773: 
 9774: sub recurse_categories {
 9775:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9776:     my $shallower = $depth - 1;
 9777:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9778:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9779:             my $name = $cats->[$depth]{$category}[$k];
 9780:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9781:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9782:             if ($allitems->{$item} eq '') {
 9783:                 push(@{$trails},$trailstr);
 9784:                 $allitems->{$item} = scalar(@{$trails})-1;
 9785:             }
 9786:             my $deeper = $depth+1;
 9787:             push(@{$parents},$category);
 9788:             if (ref($subcats) eq 'HASH') {
 9789:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9790:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9791:                     my $higher;
 9792:                     if ($j > 0) {
 9793:                         $higher = &escape($parents->[$j]).':'.
 9794:                                   &escape($parents->[$j-1]).':'.$j;
 9795:                     } else {
 9796:                         $higher = &escape($parents->[$j]).'::'.$j;
 9797:                     }
 9798:                     push(@{$subcats->{$higher}},$subcat);
 9799:                 }
 9800:             }
 9801:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9802:                                 $subcats);
 9803:             pop(@{$parents});
 9804:         }
 9805:     } else {
 9806:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9807:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9808:         if ($allitems->{$item} eq '') {
 9809:             push(@{$trails},$trailstr);
 9810:             $allitems->{$item} = scalar(@{$trails})-1;
 9811:         }
 9812:     }
 9813:     return;
 9814: }
 9815: 
 9816: =pod
 9817: 
 9818: =item *&assign_categories_table()
 9819: 
 9820: Create a datatable for display of hierarchical categories in a domain,
 9821: with checkboxes to allow a course to be categorized. 
 9822: 
 9823: Inputs:
 9824: 
 9825: cathash - reference to hash of categories defined for the domain (from
 9826:           configuration.db)
 9827: 
 9828: currcat - scalar with an & separated list of categories assigned to a course. 
 9829: 
 9830: type    - scalar contains course type (Course or Community).
 9831: 
 9832: Returns: $output (markup to be displayed) 
 9833: 
 9834: =cut
 9835: 
 9836: sub assign_categories_table {
 9837:     my ($cathash,$currcat,$type) = @_;
 9838:     my $output;
 9839:     if (ref($cathash) eq 'HASH') {
 9840:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9841:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9842:         $maxdepth = scalar(@cats);
 9843:         if (@cats > 0) {
 9844:             my $itemcount = 0;
 9845:             if (ref($cats[0]) eq 'ARRAY') {
 9846:                 my @currcategories;
 9847:                 if ($currcat ne '') {
 9848:                     @currcategories = split('&',$currcat);
 9849:                 }
 9850:                 my $table;
 9851:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9852:                     my $parent = $cats[0][$i];
 9853:                     next if ($parent eq 'instcode');
 9854:                     if ($type eq 'Community') {
 9855:                         next unless ($parent eq 'communities');
 9856:                     } else {
 9857:                         next if ($parent eq 'communities');
 9858:                     }
 9859:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9860:                     my $item = &escape($parent).'::0';
 9861:                     my $checked = '';
 9862:                     if (@currcategories > 0) {
 9863:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9864:                             $checked = ' checked="checked"';
 9865:                         }
 9866:                     }
 9867:                     my $parent_title = $parent;
 9868:                     if ($parent eq 'communities') {
 9869:                         $parent_title = &mt('Communities');
 9870:                     }
 9871:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9872:                               '<input type="checkbox" name="usecategory" value="'.
 9873:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
 9874:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9875:                     my $depth = 1;
 9876:                     push(@path,$parent);
 9877:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9878:                     pop(@path);
 9879:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9880:                     $itemcount ++;
 9881:                 }
 9882:                 if ($itemcount) {
 9883:                     $output = &Apache::loncommon::start_data_table().
 9884:                               $table.
 9885:                               &Apache::loncommon::end_data_table();
 9886:                 }
 9887:             }
 9888:         }
 9889:     }
 9890:     return $output;
 9891: }
 9892: 
 9893: =pod
 9894: 
 9895: =item *&assign_category_rows()
 9896: 
 9897: Create a datatable row for display of nested categories in a domain,
 9898: with checkboxes to allow a course to be categorized,called recursively.
 9899: 
 9900: Inputs:
 9901: 
 9902: itemcount - track row number for alternating colors
 9903: 
 9904: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9905:       categories and subcategories.
 9906: 
 9907: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9908: 
 9909: parent - parent of current category item
 9910: 
 9911: path - Array containing all categories back up through the hierarchy from the
 9912:        current category to the top level.
 9913: 
 9914: currcategories - reference to array of current categories assigned to the course
 9915: 
 9916: Returns: $output (markup to be displayed).
 9917: 
 9918: =cut
 9919: 
 9920: sub assign_category_rows {
 9921:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9922:     my ($text,$name,$item,$chgstr);
 9923:     if (ref($cats) eq 'ARRAY') {
 9924:         my $maxdepth = scalar(@{$cats});
 9925:         if (ref($cats->[$depth]) eq 'HASH') {
 9926:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9927:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9928:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9929:                 $text .= '<td><table class="LC_datatable">';
 9930:                 for (my $j=0; $j<$numchildren; $j++) {
 9931:                     $name = $cats->[$depth]{$parent}[$j];
 9932:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9933:                     my $deeper = $depth+1;
 9934:                     my $checked = '';
 9935:                     if (ref($currcategories) eq 'ARRAY') {
 9936:                         if (@{$currcategories} > 0) {
 9937:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9938:                                 $checked = ' checked="checked"';
 9939:                             }
 9940:                         }
 9941:                     }
 9942:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9943:                              '<input type="checkbox" name="usecategory" value="'.
 9944:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9945:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9946:                              '</td><td>';
 9947:                     if (ref($path) eq 'ARRAY') {
 9948:                         push(@{$path},$name);
 9949:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9950:                         pop(@{$path});
 9951:                     }
 9952:                     $text .= '</td></tr>';
 9953:                 }
 9954:                 $text .= '</table></td>';
 9955:             }
 9956:         }
 9957:     }
 9958:     return $text;
 9959: }
 9960: 
 9961: ############################################################
 9962: ############################################################
 9963: 
 9964: 
 9965: sub commit_customrole {
 9966:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9967:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9968:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9969:                          ($end?', ending '.localtime($end):'').': <b>'.
 9970:               &Apache::lonnet::assigncustomrole(
 9971:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9972:                  '</b><br />';
 9973:     return $output;
 9974: }
 9975: 
 9976: sub commit_standardrole {
 9977:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9978:     my ($output,$logmsg,$linefeed);
 9979:     if ($context eq 'auto') {
 9980:         $linefeed = "\n";
 9981:     } else {
 9982:         $linefeed = "<br />\n";
 9983:     }  
 9984:     if ($three eq 'st') {
 9985:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9986:                                          $one,$two,$sec,$context);
 9987:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9988:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9989:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9990:         } else {
 9991:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9992:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9993:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9994:             if ($context eq 'auto') {
 9995:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9996:             } else {
 9997:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9998:                &mt('Add to classlist').': <b>ok</b>';
 9999:             }
10000:             $output .= $linefeed;
10001:         }
10002:     } else {
10003:         $output = &mt('Assigning').' '.$three.' in '.$url.
10004:                ($start?', '.&mt('starting').' '.localtime($start):'').
10005:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10006:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10007:         if ($context eq 'auto') {
10008:             $output .= $result.$linefeed;
10009:         } else {
10010:             $output .= '<b>'.$result.'</b>'.$linefeed;
10011:         }
10012:     }
10013:     return $output;
10014: }
10015: 
10016: sub commit_studentrole {
10017:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10018:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10019:     if ($context eq 'auto') {
10020:         $linefeed = "\n";
10021:     } else {
10022:         $linefeed = '<br />'."\n";
10023:     }
10024:     if (defined($one) && defined($two)) {
10025:         my $cid=$one.'_'.$two;
10026:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10027:         my $secchange = 0;
10028:         my $expire_role_result;
10029:         my $modify_section_result;
10030:         if ($oldsec ne '-1') { 
10031:             if ($oldsec ne $sec) {
10032:                 $secchange = 1;
10033:                 my $now = time;
10034:                 my $uurl='/'.$cid;
10035:                 $uurl=~s/\_/\//g;
10036:                 if ($oldsec) {
10037:                     $uurl.='/'.$oldsec;
10038:                 }
10039:                 $oldsecurl = $uurl;
10040:                 $expire_role_result = 
10041:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10042:                 if ($env{'request.course.sec'} ne '') { 
10043:                     if ($expire_role_result eq 'refused') {
10044:                         my @roles = ('st');
10045:                         my @statuses = ('previous');
10046:                         my @roledoms = ($one);
10047:                         my $withsec = 1;
10048:                         my %roleshash = 
10049:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10050:                                               \@statuses,\@roles,\@roledoms,$withsec);
10051:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10052:                             my ($oldstart,$oldend) = 
10053:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10054:                             if ($oldend > 0 && $oldend <= $now) {
10055:                                 $expire_role_result = 'ok';
10056:                             }
10057:                         }
10058:                     }
10059:                 }
10060:                 $result = $expire_role_result;
10061:             }
10062:         }
10063:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10064:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10065:             if ($modify_section_result =~ /^ok/) {
10066:                 if ($secchange == 1) {
10067:                     if ($sec eq '') {
10068:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10069:                     } else {
10070:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10071:                     }
10072:                 } elsif ($oldsec eq '-1') {
10073:                     if ($sec eq '') {
10074:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10075:                     } else {
10076:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10077:                     }
10078:                 } else {
10079:                     if ($sec eq '') {
10080:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10081:                     } else {
10082:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10083:                     }
10084:                 }
10085:             } else {
10086:                 if ($secchange) {       
10087:                     $$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;
10088:                 } else {
10089:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10090:                 }
10091:             }
10092:             $result = $modify_section_result;
10093:         } elsif ($secchange == 1) {
10094:             if ($oldsec eq '') {
10095:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10096:             } else {
10097:                 $$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;
10098:             }
10099:             if ($expire_role_result eq 'refused') {
10100:                 my $newsecurl = '/'.$cid;
10101:                 $newsecurl =~ s/\_/\//g;
10102:                 if ($sec ne '') {
10103:                     $newsecurl.='/'.$sec;
10104:                 }
10105:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10106:                     if ($sec eq '') {
10107:                         $$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;
10108:                     } else {
10109:                         $$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;
10110:                     }
10111:                 }
10112:             }
10113:         }
10114:     } else {
10115:         $$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;
10116:         $result = "error: incomplete course id\n";
10117:     }
10118:     return $result;
10119: }
10120: 
10121: ############################################################
10122: ############################################################
10123: 
10124: sub check_clone {
10125:     my ($args,$linefeed) = @_;
10126:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10127:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10128:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10129:     my $clonemsg;
10130:     my $can_clone = 0;
10131:     my $lctype = lc($args->{'crstype'});
10132:     if ($lctype ne 'community') {
10133:         $lctype = 'course';
10134:     }
10135:     if ($clonehome eq 'no_host') {
10136:         if ($args->{'crstype'} eq 'Community') {
10137:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10138:         } else {
10139:             $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'});
10140:         }     
10141:     } else {
10142: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10143:         if ($args->{'crstype'} eq 'Community') {
10144:             if ($clonedesc{'type'} ne 'Community') {
10145:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
10146:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10147:             }
10148:         }
10149: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10150:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10151: 	    $can_clone = 1;
10152: 	} else {
10153: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10154: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10155: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10156:             if (grep(/^\*$/,@cloners)) {
10157:                 $can_clone = 1;
10158:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10159:                 $can_clone = 1;
10160:             } else {
10161:                 my $ccrole = 'cc';
10162:                 if ($args->{'crstype'} eq 'Community') {
10163:                     $ccrole = 'co';
10164:                 }
10165: 	        my %roleshash =
10166: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10167: 					 $args->{'ccdomain'},
10168:                                          'userroles',['active'],[$ccrole],
10169: 					 [$args->{'clonedomain'}]);
10170: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10171:                     $can_clone = 1;
10172:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10173:                     $can_clone = 1;
10174:                 } else {
10175:                     if ($args->{'crstype'} eq 'Community') {
10176:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
10177:                     } else {
10178:                         $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'});
10179:                     }
10180: 	        }
10181: 	    }
10182:         }
10183:     }
10184:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10185: }
10186: 
10187: sub construct_course {
10188:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10189:     my $outcome;
10190:     my $linefeed =  '<br />'."\n";
10191:     if ($context eq 'auto') {
10192:         $linefeed = "\n";
10193:     }
10194: 
10195: #
10196: # Are we cloning?
10197: #
10198:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10199:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10200: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10201: 	if ($context ne 'auto') {
10202:             if ($clonemsg ne '') {
10203: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10204:             }
10205: 	}
10206: 	$outcome .= $clonemsg.$linefeed;
10207: 
10208:         if (!$can_clone) {
10209: 	    return (0,$outcome);
10210: 	}
10211:     }
10212: 
10213: #
10214: # Open course
10215: #
10216:     my $crstype = lc($args->{'crstype'});
10217:     my %cenv=();
10218:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10219:                                              $args->{'cdescr'},
10220:                                              $args->{'curl'},
10221:                                              $args->{'course_home'},
10222:                                              $args->{'nonstandard'},
10223:                                              $args->{'crscode'},
10224:                                              $args->{'ccuname'}.':'.
10225:                                              $args->{'ccdomain'},
10226:                                              $args->{'crstype'},
10227:                                              $cnum,$context,$category);
10228: 
10229:     # Note: The testing routines depend on this being output; see 
10230:     # Utils::Course. This needs to at least be output as a comment
10231:     # if anyone ever decides to not show this, and Utils::Course::new
10232:     # will need to be suitably modified.
10233:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10234:     if ($$courseid =~ /^error:/) {
10235:         return (0,$outcome);
10236:     }
10237: 
10238: #
10239: # Check if created correctly
10240: #
10241:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10242:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10243:     if ($crsuhome eq 'no_host') {
10244:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10245:         return (0,$outcome);
10246:     }
10247:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10248: 
10249: #
10250: # Do the cloning
10251: #   
10252:     if ($can_clone && $cloneid) {
10253: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10254: 	if ($context ne 'auto') {
10255: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10256: 	}
10257: 	$outcome .= $clonemsg.$linefeed;
10258: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10259: # Copy all files
10260: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10261: # Restore URL
10262: 	$cenv{'url'}=$oldcenv{'url'};
10263: # Restore title
10264: 	$cenv{'description'}=$oldcenv{'description'};
10265: # Mark as cloned
10266: 	$cenv{'clonedfrom'}=$cloneid;
10267: # Need to clone grading mode
10268:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10269:         $cenv{'grading'}=$newenv{'grading'};
10270: # Do not clone these environment entries
10271:         &Apache::lonnet::del('environment',
10272:                   ['default_enrollment_start_date',
10273:                    'default_enrollment_end_date',
10274:                    'question.email',
10275:                    'policy.email',
10276:                    'comment.email',
10277:                    'pch.users.denied',
10278:                    'plc.users.denied',
10279:                    'hidefromcat',
10280:                    'categories'],
10281:                    $$crsudom,$$crsunum);
10282:     }
10283: 
10284: #
10285: # Set environment (will override cloned, if existing)
10286: #
10287:     my @sections = ();
10288:     my @xlists = ();
10289:     if ($args->{'crstype'}) {
10290:         $cenv{'type'}=$args->{'crstype'};
10291:     }
10292:     if ($args->{'crsid'}) {
10293:         $cenv{'courseid'}=$args->{'crsid'};
10294:     }
10295:     if ($args->{'crscode'}) {
10296:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10297:     }
10298:     if ($args->{'crsquota'} ne '') {
10299:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10300:     } else {
10301:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10302:     }
10303:     if ($args->{'ccuname'}) {
10304:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10305:                                         ':'.$args->{'ccdomain'};
10306:     } else {
10307:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10308:     }
10309:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10310:     if ($args->{'crssections'}) {
10311:         $cenv{'internal.sectionnums'} = '';
10312:         if ($args->{'crssections'} =~ m/,/) {
10313:             @sections = split/,/,$args->{'crssections'};
10314:         } else {
10315:             $sections[0] = $args->{'crssections'};
10316:         }
10317:         if (@sections > 0) {
10318:             foreach my $item (@sections) {
10319:                 my ($sec,$gp) = split/:/,$item;
10320:                 my $class = $args->{'crscode'}.$sec;
10321:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10322:                 $cenv{'internal.sectionnums'} .= $item.',';
10323:                 unless ($addcheck eq 'ok') {
10324:                     push @badclasses, $class;
10325:                 }
10326:             }
10327:             $cenv{'internal.sectionnums'} =~ s/,$//;
10328:         }
10329:     }
10330: # do not hide course coordinator from staff listing, 
10331: # even if privileged
10332:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10333: # add crosslistings
10334:     if ($args->{'crsxlist'}) {
10335:         $cenv{'internal.crosslistings'}='';
10336:         if ($args->{'crsxlist'} =~ m/,/) {
10337:             @xlists = split/,/,$args->{'crsxlist'};
10338:         } else {
10339:             $xlists[0] = $args->{'crsxlist'};
10340:         }
10341:         if (@xlists > 0) {
10342:             foreach my $item (@xlists) {
10343:                 my ($xl,$gp) = split/:/,$item;
10344:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10345:                 $cenv{'internal.crosslistings'} .= $item.',';
10346:                 unless ($addcheck eq 'ok') {
10347:                     push @badclasses, $xl;
10348:                 }
10349:             }
10350:             $cenv{'internal.crosslistings'} =~ s/,$//;
10351:         }
10352:     }
10353:     if ($args->{'autoadds'}) {
10354:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10355:     }
10356:     if ($args->{'autodrops'}) {
10357:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10358:     }
10359: # check for notification of enrollment changes
10360:     my @notified = ();
10361:     if ($args->{'notify_owner'}) {
10362:         if ($args->{'ccuname'} ne '') {
10363:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10364:         }
10365:     }
10366:     if ($args->{'notify_dc'}) {
10367:         if ($uname ne '') { 
10368:             push(@notified,$uname.':'.$udom);
10369:         }
10370:     }
10371:     if (@notified > 0) {
10372:         my $notifylist;
10373:         if (@notified > 1) {
10374:             $notifylist = join(',',@notified);
10375:         } else {
10376:             $notifylist = $notified[0];
10377:         }
10378:         $cenv{'internal.notifylist'} = $notifylist;
10379:     }
10380:     if (@badclasses > 0) {
10381:         my %lt=&Apache::lonlocal::texthash(
10382:                 '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',
10383:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10384:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10385:         );
10386:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10387:                            ' ('.$lt{'adby'}.')';
10388:         if ($context eq 'auto') {
10389:             $outcome .= $badclass_msg.$linefeed;
10390:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10391:             foreach my $item (@badclasses) {
10392:                 if ($context eq 'auto') {
10393:                     $outcome .= " - $item\n";
10394:                 } else {
10395:                     $outcome .= "<li>$item</li>\n";
10396:                 }
10397:             }
10398:             if ($context eq 'auto') {
10399:                 $outcome .= $linefeed;
10400:             } else {
10401:                 $outcome .= "</ul><br /><br /></div>\n";
10402:             }
10403:         } 
10404:     }
10405:     if ($args->{'no_end_date'}) {
10406:         $args->{'endaccess'} = 0;
10407:     }
10408:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10409:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10410:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10411:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10412:     if ($args->{'showphotos'}) {
10413:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10414:     }
10415:     $cenv{'internal.authtype'} = $args->{'authtype'};
10416:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10417:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10418:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10419:             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'); 
10420:             if ($context eq 'auto') {
10421:                 $outcome .= $krb_msg;
10422:             } else {
10423:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10424:             }
10425:             $outcome .= $linefeed;
10426:         }
10427:     }
10428:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10429:        if ($args->{'setpolicy'}) {
10430:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10431:        }
10432:        if ($args->{'setcontent'}) {
10433:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10434:        }
10435:     }
10436:     if ($args->{'reshome'}) {
10437: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10438: 	$cenv{'reshome'}=~s/\/+$/\//;
10439:     }
10440: #
10441: # course has keyed access
10442: #
10443:     if ($args->{'setkeys'}) {
10444:        $cenv{'keyaccess'}='yes';
10445:     }
10446: # if specified, key authority is not course, but user
10447: # only active if keyaccess is yes
10448:     if ($args->{'keyauth'}) {
10449: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10450: 	$user = &LONCAPA::clean_username($user);
10451: 	$domain = &LONCAPA::clean_username($domain);
10452: 	if ($user ne '' && $domain ne '') {
10453: 	    $cenv{'keyauth'}=$user.':'.$domain;
10454: 	}
10455:     }
10456: 
10457:     if ($args->{'disresdis'}) {
10458:         $cenv{'pch.roles.denied'}='st';
10459:     }
10460:     if ($args->{'disablechat'}) {
10461:         $cenv{'plc.roles.denied'}='st';
10462:     }
10463: 
10464:     # Record we've not yet viewed the Course Initialization Helper for this 
10465:     # course
10466:     $cenv{'course.helper.not.run'} = 1;
10467:     #
10468:     # Use new Randomseed
10469:     #
10470:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10471:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10472:     #
10473:     # The encryption code and receipt prefix for this course
10474:     #
10475:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10476:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10477:     #
10478:     # By default, use standard grading
10479:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10480: 
10481:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10482:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10483: #
10484: # Open all assignments
10485: #
10486:     if ($args->{'openall'}) {
10487:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10488:        my %storecontent = ($storeunder         => time,
10489:                            $storeunder.'.type' => 'date_start');
10490:        
10491:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10492:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10493:    }
10494: #
10495: # Set first page
10496: #
10497:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10498: 	    || ($cloneid)) {
10499: 	use LONCAPA::map;
10500: 	$outcome .= &mt('Setting first resource').': ';
10501: 
10502: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10503:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10504: 
10505:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10506:         my $title; my $url;
10507:         if ($args->{'firstres'} eq 'syl') {
10508: 	    $title=&mt('Syllabus');
10509:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10510:         } else {
10511:             $title=&mt('Navigate Contents');
10512:             $url='/adm/navmaps';
10513:         }
10514: 
10515:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10516: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10517: 
10518: 	if ($errtext) { $fatal=2; }
10519:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10520:     }
10521: 
10522:     return (1,$outcome);
10523: }
10524: 
10525: ############################################################
10526: ############################################################
10527: 
10528: sub course_type {
10529:     my ($cid) = @_;
10530:     if (!defined($cid)) {
10531:         $cid = $env{'request.course.id'};
10532:     }
10533:     if (defined($env{'course.'.$cid.'.type'})) {
10534:         return $env{'course.'.$cid.'.type'};
10535:     } else {
10536:         return 'Course';
10537:     }
10538: }
10539: 
10540: sub group_term {
10541:     my $crstype = &course_type();
10542:     my %names = (
10543:                   'Course' => 'group',
10544:                   'Community' => 'group',
10545:                 );
10546:     return $names{$crstype};
10547: }
10548: 
10549: sub course_types {
10550:     my @types = ('official','unofficial','community');
10551:     my %typename = (
10552:                          official   => 'Official course',
10553:                          unofficial => 'Unofficial course',
10554:                          community  => 'Community',
10555:                    );
10556:     return (\@types,\%typename);
10557: }
10558: 
10559: sub icon {
10560:     my ($file)=@_;
10561:     my $curfext = lc((split(/\./,$file))[-1]);
10562:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10563:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10564:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10565: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10566: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10567: 	            $curfext.".gif") {
10568: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10569: 		$curfext.".gif";
10570: 	}
10571:     }
10572:     return &lonhttpdurl($iconname);
10573: } 
10574: 
10575: sub lonhttpdurl {
10576: #
10577: # Had been used for "small fry" static images on separate port 8080.
10578: # Modify here if lightweight http functionality desired again.
10579: # Currently eliminated due to increasing firewall issues.
10580: #
10581:     my ($url)=@_;
10582:     return $url;
10583: }
10584: 
10585: sub connection_aborted {
10586:     my ($r)=@_;
10587:     $r->print(" ");$r->rflush();
10588:     my $c = $r->connection;
10589:     return $c->aborted();
10590: }
10591: 
10592: #    Escapes strings that may have embedded 's that will be put into
10593: #    strings as 'strings'.
10594: sub escape_single {
10595:     my ($input) = @_;
10596:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10597:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10598:     return $input;
10599: }
10600: 
10601: #  Same as escape_single, but escape's "'s  This 
10602: #  can be used for  "strings"
10603: sub escape_double {
10604:     my ($input) = @_;
10605:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10606:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10607:     return $input;
10608: }
10609:  
10610: #   Escapes the last element of a full URL.
10611: sub escape_url {
10612:     my ($url)   = @_;
10613:     my @urlslices = split(/\//, $url,-1);
10614:     my $lastitem = &escape(pop(@urlslices));
10615:     return join('/',@urlslices).'/'.$lastitem;
10616: }
10617: 
10618: sub compare_arrays {
10619:     my ($arrayref1,$arrayref2) = @_;
10620:     my (@difference,%count);
10621:     @difference = ();
10622:     %count = ();
10623:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10624:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10625:         foreach my $element (keys(%count)) {
10626:             if ($count{$element} == 1) {
10627:                 push(@difference,$element);
10628:             }
10629:         }
10630:     }
10631:     return @difference;
10632: }
10633: 
10634: # -------------------------------------------------------- Initialize user login
10635: sub init_user_environment {
10636:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10637:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10638: 
10639:     my $public=($username eq 'public' && $domain eq 'public');
10640: 
10641: # See if old ID present, if so, remove
10642: 
10643:     my ($filename,$cookie,$userroles);
10644:     my $now=time;
10645: 
10646:     if ($public) {
10647: 	my $max_public=100;
10648: 	my $oldest;
10649: 	my $oldest_time=0;
10650: 	for(my $next=1;$next<=$max_public;$next++) {
10651: 	    if (-e $lonids."/publicuser_$next.id") {
10652: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10653: 		if ($mtime<$oldest_time || !$oldest_time) {
10654: 		    $oldest_time=$mtime;
10655: 		    $oldest=$next;
10656: 		}
10657: 	    } else {
10658: 		$cookie="publicuser_$next";
10659: 		last;
10660: 	    }
10661: 	}
10662: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10663:     } else {
10664: 	# if this isn't a robot, kill any existing non-robot sessions
10665: 	if (!$args->{'robot'}) {
10666: 	    opendir(DIR,$lonids);
10667: 	    while ($filename=readdir(DIR)) {
10668: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10669: 		    unlink($lonids.'/'.$filename);
10670: 		}
10671: 	    }
10672: 	    closedir(DIR);
10673: 	}
10674: # Give them a new cookie
10675: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10676: 		                   : $now.$$.int(rand(10000)));
10677: 	$cookie="$username\_$id\_$domain\_$authhost";
10678:     
10679: # Initialize roles
10680: 
10681: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10682:     }
10683: # ------------------------------------ Check browser type and MathML capability
10684: 
10685:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10686:         $clientunicode,$clientos) = &decode_user_agent($r);
10687: 
10688: # ------------------------------------------------------------- Get environment
10689: 
10690:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10691:     my ($tmp) = keys(%userenv);
10692:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10693: 	# default remote control to off
10694: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10695:     } else {
10696: 	undef(%userenv);
10697:     }
10698:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10699: 	$form->{'interface'}=$userenv{'interface'};
10700:     }
10701:     $env{'environment.remote'}=$userenv{'remote'};
10702:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10703: 
10704: # --------------- Do not trust query string to be put directly into environment
10705:     foreach my $option ('interface','localpath','localres') {
10706:         $form->{$option}=~s/[\n\r\=]//gs;
10707:     }
10708: # --------------------------------------------------------- Write first profile
10709: 
10710:     {
10711: 	my %initial_env = 
10712: 	    ("user.name"          => $username,
10713: 	     "user.domain"        => $domain,
10714: 	     "user.home"          => $authhost,
10715: 	     "browser.type"       => $clientbrowser,
10716: 	     "browser.version"    => $clientversion,
10717: 	     "browser.mathml"     => $clientmathml,
10718: 	     "browser.unicode"    => $clientunicode,
10719: 	     "browser.os"         => $clientos,
10720: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10721: 	     "request.course.fn"  => '',
10722: 	     "request.course.uri" => '',
10723: 	     "request.course.sec" => '',
10724: 	     "request.role"       => 'cm',
10725: 	     "request.role.adv"   => $env{'user.adv'},
10726: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10727: 
10728:         if ($form->{'localpath'}) {
10729: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10730: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10731:         }
10732: 	
10733: 	if ($public) {
10734: 	    $initial_env{"environment.remote"} = "off";
10735: 	}
10736: 	if ($form->{'interface'}) {
10737: 	    $form->{'interface'}=~s/\W//gs;
10738: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10739: 	    $env{'browser.interface'}=$form->{'interface'};
10740: 	}
10741: 
10742:         foreach my $tool ('aboutme','blog','portfolio') {
10743:             $userenv{'availabletools.'.$tool} = 
10744:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10745:         }
10746: 
10747:         foreach my $crstype ('official','unofficial','community') {
10748:             $userenv{'canrequest.'.$crstype} =
10749:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10750:                                                   'reload','requestcourses');
10751:         }
10752: 
10753: 	$env{'user.environment'} = "$lonids/$cookie.id";
10754: 	
10755: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10756: 		 &GDBM_WRCREAT(),0640)) {
10757: 	    &_add_to_env(\%disk_env,\%initial_env);
10758: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10759: 	    &_add_to_env(\%disk_env,$userroles);
10760: 	    if (ref($args->{'extra_env'})) {
10761: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10762: 	    }
10763: 	    untie(%disk_env);
10764: 	} else {
10765: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10766: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10767: 	    return 'error: '.$!;
10768: 	}
10769:     }
10770:     $env{'request.role'}='cm';
10771:     $env{'request.role.adv'}=$env{'user.adv'};
10772:     $env{'browser.type'}=$clientbrowser;
10773: 
10774:     return $cookie;
10775: 
10776: }
10777: 
10778: sub _add_to_env {
10779:     my ($idf,$env_data,$prefix) = @_;
10780:     if (ref($env_data) eq 'HASH') {
10781:         while (my ($key,$value) = each(%$env_data)) {
10782: 	    $idf->{$prefix.$key} = $value;
10783: 	    $env{$prefix.$key}   = $value;
10784:         }
10785:     }
10786: }
10787: 
10788: # --- Get the symbolic name of a problem and the url
10789: sub get_symb {
10790:     my ($request,$silent) = @_;
10791:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10792:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10793:     if ($symb eq '') {
10794:         if (!$silent) {
10795:             $request->print("Unable to handle ambiguous references:$url:.");
10796:             return ();
10797:         }
10798:     }
10799:     &Apache::lonenc::check_decrypt(\$symb);
10800:     return ($symb);
10801: }
10802: 
10803: # --------------------------------------------------------------Get annotation
10804: 
10805: sub get_annotation {
10806:     my ($symb,$enc) = @_;
10807: 
10808:     my $key = $symb;
10809:     if (!$enc) {
10810:         $key =
10811:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10812:     }
10813:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10814:     return $annotation{$key};
10815: }
10816: 
10817: sub clean_symb {
10818:     my ($symb,$delete_enc) = @_;
10819: 
10820:     &Apache::lonenc::check_decrypt(\$symb);
10821:     my $enc = $env{'request.enc'};
10822:     if ($delete_enc) {
10823:         delete($env{'request.enc'});
10824:     }
10825: 
10826:     return ($symb,$enc);
10827: }
10828: 
10829: =pod
10830: 
10831: =back
10832: 
10833: =cut
10834: 
10835: 1;
10836: __END__;
10837: 

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