File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1003: download - view: text, annotated - select for diffs
Tue May 3 21:38:40 2011 UTC (13 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
"Content" does not need to show up in print

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1003 2011/05/03 21:38:40 www 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,clicker,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:                                     '&clicker='+clicker;
  426: 	if (roleflag) { url+="&roles=1"; }
  427:         if (courseadvonly) { url+="&courseadvonly=1"; }
  428:         var title = 'Student_Browser';
  429:         var options = 'scrollbars=1,resizable=1,menubar=0';
  430:         options += ',width=700,height=600';
  431:         stdeditbrowser = open(url,title,options,'1');
  432:         stdeditbrowser.focus();
  433:     }
  434: // ]]>
  435: </script>
  436: ENDSTDBRW
  437: }
  438: 
  439: sub resourcebrowser_javascript {
  440:    unless ($env{'request.course.id'}) { return ''; }
  441:    return (<<'ENDSTDBRW');
  442: <script type="text/javascript" language="Javascript">
  443: // <![CDATA[
  444:     var reseditbrowser;
  445:     function openresbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  446:         var url = '/adm/pickresource?';
  447:         var title = 'Resource_Browser';
  448:         var options = 'scrollbars=1,resizable=1,menubar=0';
  449:         options += ',width=700,height=600';
  450:         stdeditbrowser = open(url,title,options,'1');
  451:         stdeditbrowser.focus();
  452:     }
  453: // ]]>
  454: </script>
  455: ENDSTDBRW
  456: }
  457: 
  458: sub selectstudent_link {
  459:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  460:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  461:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  462:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  463:    if ($env{'request.course.id'}) {  
  464:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  465: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  466: 					'/'.$env{'request.course.sec'})) {
  467: 	   return '';
  468:        }
  469:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  470:        if ($courseadvonly)  {
  471:            $callargs .= ",'',1,1";
  472:        }
  473:        return '<span class="LC_nobreak">'.
  474:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  475:               &mt('Select User').'</a></span>';
  476:    }
  477:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  478:        $callargs .= ",1"; 
  479:        return '<span class="LC_nobreak">'.
  480:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  481:               &mt('Select User').'</a></span>';
  482:    }
  483:    return '';
  484: }
  485: 
  486: sub authorbrowser_javascript {
  487:     return <<"ENDAUTHORBRW";
  488: <script type="text/javascript" language="JavaScript">
  489: // <![CDATA[
  490: var stdeditbrowser;
  491: 
  492: function openauthorbrowser(formname,udom) {
  493:     var url = '/adm/pickauthor?';
  494:     url += 'form='+formname+'&roledom='+udom;
  495:     var title = 'Author_Browser';
  496:     var options = 'scrollbars=1,resizable=1,menubar=0';
  497:     options += ',width=700,height=600';
  498:     stdeditbrowser = open(url,title,options,'1');
  499:     stdeditbrowser.focus();
  500: }
  501: 
  502: // ]]>
  503: </script>
  504: ENDAUTHORBRW
  505: }
  506: 
  507: sub coursebrowser_javascript {
  508:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  509:     my $wintitle = 'Course_Browser';
  510:     if ($crstype eq 'Community') {
  511:         $wintitle = 'Community_Browser';
  512:     }
  513:     my $id_functions = &javascript_index_functions();
  514:     my $output = '
  515: <script type="text/javascript" language="JavaScript">
  516: // <![CDATA[
  517:     var stdeditbrowser;'."\n";
  518: 
  519:     $output .= <<"ENDSTDBRW";
  520:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  521:         var url = '/adm/pickcourse?';
  522:         var formid = getFormIdByName(formname);
  523:         var domainfilter = getDomainFromSelectbox(formname,udom);
  524:         if (domainfilter != null) {
  525:            if (domainfilter != '') {
  526:                url += 'domainfilter='+domainfilter+'&';
  527: 	   }
  528:         }
  529:         url += 'form=' + formname + '&cnumelement='+uname+
  530: 	                            '&cdomelement='+udom+
  531:                                     '&cnameelement='+desc;
  532:         if (extra_element !=null && extra_element != '') {
  533:             if (formname == 'rolechoice' || formname == 'studentform') {
  534:                 url += '&roleelement='+extra_element;
  535:                 if (domainfilter == null || domainfilter == '') {
  536:                     url += '&domainfilter='+extra_element;
  537:                 }
  538:             }
  539:             else {
  540:                 if (formname == 'portform') {
  541:                     url += '&setroles='+extra_element;
  542:                 } else {
  543:                     if (formname == 'rules') {
  544:                         url += '&fixeddom='+extra_element; 
  545:                     }
  546:                 }
  547:             }     
  548:         }
  549:         if (type != null && type != '') {
  550:             url += '&type='+type;
  551:         }
  552:         if (type_elem != null && type_elem != '') {
  553:             url += '&typeelement='+type_elem;
  554:         }
  555:         if (formname == 'ccrs') {
  556:             var ownername = document.forms[formid].ccuname.value;
  557:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  558:             url += '&cloner='+ownername+':'+ownerdom;
  559:         }
  560:         if (multflag !=null && multflag != '') {
  561:             url += '&multiple='+multflag;
  562:         }
  563:         var title = '$wintitle';
  564:         var options = 'scrollbars=1,resizable=1,menubar=0';
  565:         options += ',width=700,height=600';
  566:         stdeditbrowser = open(url,title,options,'1');
  567:         stdeditbrowser.focus();
  568:     }
  569: $id_functions
  570: ENDSTDBRW
  571:     if (($sec_element ne '') || ($role_element ne '')) {
  572:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  573:     }
  574:     $output .= '
  575: // ]]>
  576: </script>';
  577:     return $output;
  578: }
  579: 
  580: sub javascript_index_functions {
  581:     return <<"ENDJS";
  582: 
  583: function getFormIdByName(formname) {
  584:     for (var i=0;i<document.forms.length;i++) {
  585:         if (document.forms[i].name == formname) {
  586:             return i;
  587:         }
  588:     }
  589:     return -1;
  590: }
  591: 
  592: function getIndexByName(formid,item) {
  593:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  594:         if (document.forms[formid].elements[i].name == item) {
  595:             return i;
  596:         }
  597:     }
  598:     return -1;
  599: }
  600: 
  601: function getDomainFromSelectbox(formname,udom) {
  602:     var userdom;
  603:     var formid = getFormIdByName(formname);
  604:     if (formid > -1) {
  605:         var domid = getIndexByName(formid,udom);
  606:         if (domid > -1) {
  607:             if (document.forms[formid].elements[domid].type == 'select-one') {
  608:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  609:             }
  610:             if (document.forms[formid].elements[domid].type == 'hidden') {
  611:                 userdom=document.forms[formid].elements[domid].value;
  612:             }
  613:         }
  614:     }
  615:     return userdom;
  616: }
  617: 
  618: ENDJS
  619: 
  620: }
  621: 
  622: sub userbrowser_javascript {
  623:     my $id_functions = &javascript_index_functions();
  624:     return <<"ENDUSERBRW";
  625: 
  626: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  627:     var url = '/adm/pickuser?';
  628:     var userdom = getDomainFromSelectbox(formname,udom);
  629:     if (userdom != null) {
  630:        if (userdom != '') {
  631:            url += 'srchdom='+userdom+'&';
  632:        }
  633:     }
  634:     url += 'form=' + formname + '&unameelement='+uname+
  635:                                 '&udomelement='+udom+
  636:                                 '&ulastelement='+ulast+
  637:                                 '&ufirstelement='+ufirst+
  638:                                 '&uemailelement='+uemail+
  639:                                 '&hideudomelement='+hideudom+
  640:                                 '&coursedom='+crsdom;
  641:     if ((caller != null) && (caller != undefined)) {
  642:         url += '&caller='+caller;
  643:     }
  644:     var title = 'User_Browser';
  645:     var options = 'scrollbars=1,resizable=1,menubar=0';
  646:     options += ',width=700,height=600';
  647:     var stdeditbrowser = open(url,title,options,'1');
  648:     stdeditbrowser.focus();
  649: }
  650: 
  651: function fix_domain (formname,udom,origdom,uname) {
  652:     var formid = getFormIdByName(formname);
  653:     if (formid > -1) {
  654:         var unameid = getIndexByName(formid,uname);
  655:         var domid = getIndexByName(formid,udom);
  656:         var hidedomid = getIndexByName(formid,origdom);
  657:         if (hidedomid > -1) {
  658:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  659:             var unameval = document.forms[formid].elements[unameid].value;
  660:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  661:                 if (domid > -1) {
  662:                     var slct = document.forms[formid].elements[domid];
  663:                     if (slct.type == 'select-one') {
  664:                         var i;
  665:                         for (i=0;i<slct.length;i++) {
  666:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  667:                         }
  668:                     }
  669:                     if (slct.type == 'hidden') {
  670:                         slct.value = fixeddom;
  671:                     }
  672:                 }
  673:             }
  674:         }
  675:     }
  676:     return;
  677: }
  678: 
  679: $id_functions
  680: ENDUSERBRW
  681: }
  682: 
  683: sub setsec_javascript {
  684:     my ($sec_element,$formname,$role_element) = @_;
  685:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  686:         $communityrolestr);
  687:     if ($role_element ne '') {
  688:         my @allroles = ('st','ta','ep','in','ad');
  689:         foreach my $crstype ('Course','Community') {
  690:             if ($crstype eq 'Community') {
  691:                 foreach my $role (@allroles) {
  692:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  693:                 }
  694:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  695:             } else {
  696:                 foreach my $role (@allroles) {
  697:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  698:                 }
  699:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  700:             }
  701:         }
  702:         $rolestr = '"'.join('","',@allroles).'"';
  703:         $courserolestr = '"'.join('","',@courserolenames).'"';
  704:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  705:     }
  706:     my $setsections = qq|
  707: function setSect(sectionlist) {
  708:     var sectionsArray = new Array();
  709:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  710:         sectionsArray = sectionlist.split(",");
  711:     }
  712:     var numSections = sectionsArray.length;
  713:     document.$formname.$sec_element.length = 0;
  714:     if (numSections == 0) {
  715:         document.$formname.$sec_element.multiple=false;
  716:         document.$formname.$sec_element.size=1;
  717:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  718:     } else {
  719:         if (numSections == 1) {
  720:             document.$formname.$sec_element.multiple=false;
  721:             document.$formname.$sec_element.size=1;
  722:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  723:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  724:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  725:         } else {
  726:             for (var i=0; i<numSections; i++) {
  727:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  728:             }
  729:             document.$formname.$sec_element.multiple=true
  730:             if (numSections < 3) {
  731:                 document.$formname.$sec_element.size=numSections;
  732:             } else {
  733:                 document.$formname.$sec_element.size=3;
  734:             }
  735:             document.$formname.$sec_element.options[0].selected = false
  736:         }
  737:     }
  738: }
  739: 
  740: function setRole(crstype) {
  741: |;
  742:     if ($role_element eq '') {
  743:         $setsections .= '    return;
  744: }
  745: ';
  746:     } else {
  747:         $setsections .= qq|
  748:     var elementLength = document.$formname.$role_element.length;
  749:     var allroles = Array($rolestr);
  750:     var courserolenames = Array($courserolestr);
  751:     var communityrolenames = Array($communityrolestr);
  752:     if (elementLength != undefined) {
  753:         if (document.$formname.$role_element.options[5].value == 'cc') {
  754:             if (crstype == 'Course') {
  755:                 return;
  756:             } else {
  757:                 allroles[5] = 'co';
  758:                 for (var i=0; i<6; i++) {
  759:                     document.$formname.$role_element.options[i].value = allroles[i];
  760:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  761:                 }
  762:             }
  763:         } else {
  764:             if (crstype == 'Community') {
  765:                 return;
  766:             } else {
  767:                 allroles[5] = 'cc';
  768:                 for (var i=0; i<6; i++) {
  769:                     document.$formname.$role_element.options[i].value = allroles[i];
  770:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  771:                 }
  772:             }
  773:         }
  774:     }
  775:     return;
  776: }
  777: |;
  778:     }
  779:     return $setsections;
  780: }
  781: 
  782: sub selectcourse_link {
  783:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  784:        $typeelement) = @_;
  785:    my $type = $selecttype;
  786:    my $linktext = &mt('Select Course');
  787:    if ($selecttype eq 'Community') {
  788:        $linktext = &mt('Select Community');
  789:    } elsif ($selecttype eq 'Course/Community') {
  790:        $linktext = &mt('Select Course/Community');
  791:        $type = '';
  792:    }
  793:    return '<span class="LC_nobreak">'
  794:          ."<a href='"
  795:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  796:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  797:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  798:          ."'>".$linktext.'</a>'
  799:          .'</span>';
  800: }
  801: 
  802: sub selectauthor_link {
  803:    my ($form,$udom)=@_;
  804:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  805:           &mt('Select Author').'</a>';
  806: }
  807: 
  808: sub selectuser_link {
  809:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  810:         $coursedom,$linktext,$caller) = @_;
  811:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  812:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  813:            ');">'.$linktext.'</a>';
  814: }
  815: 
  816: sub check_uncheck_jscript {
  817:     my $jscript = <<"ENDSCRT";
  818: function checkAll(field) {
  819:     if (field.length > 0) {
  820:         for (i = 0; i < field.length; i++) {
  821:             field[i].checked = true ;
  822:         }
  823:     } else {
  824:         field.checked = true
  825:     }
  826: }
  827:  
  828: function uncheckAll(field) {
  829:     if (field.length > 0) {
  830:         for (i = 0; i < field.length; i++) {
  831:             field[i].checked = false ;
  832:         }
  833:     } else {
  834:         field.checked = false ;
  835:     }
  836: }
  837: ENDSCRT
  838:     return $jscript;
  839: }
  840: 
  841: sub select_timezone {
  842:    my ($name,$selected,$onchange,$includeempty)=@_;
  843:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  844:    if ($includeempty) {
  845:        $output .= '<option value=""';
  846:        if (($selected eq '') || ($selected eq 'local')) {
  847:            $output .= ' selected="selected" ';
  848:        }
  849:        $output .= '> </option>';
  850:    }
  851:    my @timezones = DateTime::TimeZone->all_names;
  852:    foreach my $tzone (@timezones) {
  853:        $output.= '<option value="'.$tzone.'"';
  854:        if ($tzone eq $selected) {
  855:            $output.=' selected="selected"';
  856:        }
  857:        $output.=">$tzone</option>\n";
  858:    }
  859:    $output.="</select>";
  860:    return $output;
  861: }
  862: 
  863: sub select_datelocale {
  864:     my ($name,$selected,$onchange,$includeempty)=@_;
  865:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  866:     if ($includeempty) {
  867:         $output .= '<option value=""';
  868:         if ($selected eq '') {
  869:             $output .= ' selected="selected" ';
  870:         }
  871:         $output .= '> </option>';
  872:     }
  873:     my (@possibles,%locale_names);
  874:     my @locales = DateTime::Locale::Catalog::Locales;
  875:     foreach my $locale (@locales) {
  876:         if (ref($locale) eq 'HASH') {
  877:             my $id = $locale->{'id'};
  878:             if ($id ne '') {
  879:                 my $en_terr = $locale->{'en_territory'};
  880:                 my $native_terr = $locale->{'native_territory'};
  881:                 my @languages = &Apache::lonlocal::preferred_languages();
  882:                 if (grep(/^en$/,@languages) || !@languages) {
  883:                     if ($en_terr ne '') {
  884:                         $locale_names{$id} = '('.$en_terr.')';
  885:                     } elsif ($native_terr ne '') {
  886:                         $locale_names{$id} = $native_terr;
  887:                     }
  888:                 } else {
  889:                     if ($native_terr ne '') {
  890:                         $locale_names{$id} = $native_terr.' ';
  891:                     } elsif ($en_terr ne '') {
  892:                         $locale_names{$id} = '('.$en_terr.')';
  893:                     }
  894:                 }
  895:                 push (@possibles,$id);
  896:             }
  897:         }
  898:     }
  899:     foreach my $item (sort(@possibles)) {
  900:         $output.= '<option value="'.$item.'"';
  901:         if ($item eq $selected) {
  902:             $output.=' selected="selected"';
  903:         }
  904:         $output.=">$item";
  905:         if ($locale_names{$item} ne '') {
  906:             $output.="  $locale_names{$item}</option>\n";
  907:         }
  908:         $output.="</option>\n";
  909:     }
  910:     $output.="</select>";
  911:     return $output;
  912: }
  913: 
  914: sub select_language {
  915:     my ($name,$selected,$includeempty) = @_;
  916:     my %langchoices;
  917:     if ($includeempty) {
  918:         %langchoices = ('' => 'No language preference');
  919:     }
  920:     foreach my $id (&languageids()) {
  921:         my $code = &supportedlanguagecode($id);
  922:         if ($code) {
  923:             $langchoices{$code} = &plainlanguagedescription($id);
  924:         }
  925:     }
  926:     return &select_form($selected,$name,\%langchoices);
  927: }
  928: 
  929: =pod
  930: 
  931: =item * &linked_select_forms(...)
  932: 
  933: linked_select_forms returns a string containing a <script></script> block
  934: and html for two <select> menus.  The select menus will be linked in that
  935: changing the value of the first menu will result in new values being placed
  936: in the second menu.  The values in the select menu will appear in alphabetical
  937: order unless a defined order is provided.
  938: 
  939: linked_select_forms takes the following ordered inputs:
  940: 
  941: =over 4
  942: 
  943: =item * $formname, the name of the <form> tag
  944: 
  945: =item * $middletext, the text which appears between the <select> tags
  946: 
  947: =item * $firstdefault, the default value for the first menu
  948: 
  949: =item * $firstselectname, the name of the first <select> tag
  950: 
  951: =item * $secondselectname, the name of the second <select> tag
  952: 
  953: =item * $hashref, a reference to a hash containing the data for the menus.
  954: 
  955: =item * $menuorder, the order of values in the first menu
  956: 
  957: =back 
  958: 
  959: Below is an example of such a hash.  Only the 'text', 'default', and 
  960: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  961: values for the first select menu.  The text that coincides with the 
  962: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  963: and text for the second menu are given in the hash pointed to by 
  964: $menu{$choice1}->{'select2'}.  
  965: 
  966:  my %menu = ( A1 => { text =>"Choice A1" ,
  967:                        default => "B3",
  968:                        select2 => { 
  969:                            B1 => "Choice B1",
  970:                            B2 => "Choice B2",
  971:                            B3 => "Choice B3",
  972:                            B4 => "Choice B4"
  973:                            },
  974:                        order => ['B4','B3','B1','B2'],
  975:                    },
  976:                A2 => { text =>"Choice A2" ,
  977:                        default => "C2",
  978:                        select2 => { 
  979:                            C1 => "Choice C1",
  980:                            C2 => "Choice C2",
  981:                            C3 => "Choice C3"
  982:                            },
  983:                        order => ['C2','C1','C3'],
  984:                    },
  985:                A3 => { text =>"Choice A3" ,
  986:                        default => "D6",
  987:                        select2 => { 
  988:                            D1 => "Choice D1",
  989:                            D2 => "Choice D2",
  990:                            D3 => "Choice D3",
  991:                            D4 => "Choice D4",
  992:                            D5 => "Choice D5",
  993:                            D6 => "Choice D6",
  994:                            D7 => "Choice D7"
  995:                            },
  996:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  997:                    }
  998:                );
  999: 
 1000: =cut
 1001: 
 1002: sub linked_select_forms {
 1003:     my ($formname,
 1004:         $middletext,
 1005:         $firstdefault,
 1006:         $firstselectname,
 1007:         $secondselectname, 
 1008:         $hashref,
 1009:         $menuorder,
 1010:         ) = @_;
 1011:     my $second = "document.$formname.$secondselectname";
 1012:     my $first = "document.$formname.$firstselectname";
 1013:     # output the javascript to do the changing
 1014:     my $result = '';
 1015:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1016:     $result.="// <![CDATA[\n";
 1017:     $result.="var select2data = new Object();\n";
 1018:     $" = '","';
 1019:     my $debug = '';
 1020:     foreach my $s1 (sort(keys(%$hashref))) {
 1021:         $result.="select2data.d_$s1 = new Object();\n";        
 1022:         $result.="select2data.d_$s1.def = new String('".
 1023:             $hashref->{$s1}->{'default'}."');\n";
 1024:         $result.="select2data.d_$s1.values = new Array(";
 1025:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1026:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1027:             @s2values = @{$hashref->{$s1}->{'order'}};
 1028:         }
 1029:         $result.="\"@s2values\");\n";
 1030:         $result.="select2data.d_$s1.texts = new Array(";        
 1031:         my @s2texts;
 1032:         foreach my $value (@s2values) {
 1033:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1034:         }
 1035:         $result.="\"@s2texts\");\n";
 1036:     }
 1037:     $"=' ';
 1038:     $result.= <<"END";
 1039: 
 1040: function select1_changed() {
 1041:     // Determine new choice
 1042:     var newvalue = "d_" + $first.value;
 1043:     // update select2
 1044:     var values     = select2data[newvalue].values;
 1045:     var texts      = select2data[newvalue].texts;
 1046:     var select2def = select2data[newvalue].def;
 1047:     var i;
 1048:     // out with the old
 1049:     for (i = 0; i < $second.options.length; i++) {
 1050:         $second.options[i] = null;
 1051:     }
 1052:     // in with the nuclear
 1053:     for (i=0;i<values.length; i++) {
 1054:         $second.options[i] = new Option(values[i]);
 1055:         $second.options[i].value = values[i];
 1056:         $second.options[i].text = texts[i];
 1057:         if (values[i] == select2def) {
 1058:             $second.options[i].selected = true;
 1059:         }
 1060:     }
 1061: }
 1062: // ]]>
 1063: </script>
 1064: END
 1065:     # output the initial values for the selection lists
 1066:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1067:     my @order = sort(keys(%{$hashref}));
 1068:     if (ref($menuorder) eq 'ARRAY') {
 1069:         @order = @{$menuorder};
 1070:     }
 1071:     foreach my $value (@order) {
 1072:         $result.="    <option value=\"$value\" ";
 1073:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1074:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1075:     }
 1076:     $result .= "</select>\n";
 1077:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1078:     $result .= $middletext;
 1079:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1080:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1081:     
 1082:     my @secondorder = sort(keys(%select2));
 1083:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1084:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1085:     }
 1086:     foreach my $value (@secondorder) {
 1087:         $result.="    <option value=\"$value\" ";        
 1088:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1089:         $result.=">".&mt($select2{$value})."</option>\n";
 1090:     }
 1091:     $result .= "</select>\n";
 1092:     #    return $debug;
 1093:     return $result;
 1094: }   #  end of sub linked_select_forms {
 1095: 
 1096: =pod
 1097: 
 1098: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1099: 
 1100: Returns a string corresponding to an HTML link to the given help
 1101: $topic, where $topic corresponds to the name of a .tex file in
 1102: /home/httpd/html/adm/help/tex, with underscores replaced by
 1103: spaces. 
 1104: 
 1105: $text will optionally be linked to the same topic, allowing you to
 1106: link text in addition to the graphic. If you do not want to link
 1107: text, but wish to specify one of the later parameters, pass an
 1108: empty string. 
 1109: 
 1110: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1111: the link will not open a new window. If false, the link will open
 1112: a new window using Javascript. (Default is false.) 
 1113: 
 1114: $width and $height are optional numerical parameters that will
 1115: override the width and height of the popped up window, which may
 1116: be useful for certain help topics with big pictures included.
 1117: 
 1118: $imgid is the id of the img tag used for the help icon. This may be
 1119: used in a javascript call to switch the image src.  See 
 1120: lonhtmlcommon::htmlareaselectactive() for an example.
 1121: 
 1122: =cut
 1123: 
 1124: sub help_open_topic {
 1125:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1126:     $text = "" if (not defined $text);
 1127:     $stayOnPage = 0 if (not defined $stayOnPage);
 1128:     $width = 350 if (not defined $width);
 1129:     $height = 400 if (not defined $height);
 1130:     my $filename = $topic;
 1131:     $filename =~ s/ /_/g;
 1132: 
 1133:     my $template = "";
 1134:     my $link;
 1135:     
 1136:     $topic=~s/\W/\_/g;
 1137: 
 1138:     if (!$stayOnPage) {
 1139: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1140:     } else {
 1141: 	$link = "/adm/help/${filename}.hlp";
 1142:     }
 1143: 
 1144:     # Add the text
 1145:     if ($text ne "") {	
 1146: 	$template.='<span class="LC_help_open_topic">'
 1147:                   .'<a target="_top" href="'.$link.'">'
 1148:                   .$text.'</a>';
 1149:     }
 1150: 
 1151:     # (Always) Add the graphic
 1152:     my $title = &mt('Online Help');
 1153:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1154:     if ($imgid ne '') {
 1155:         $imgid = ' id="'.$imgid.'"';
 1156:     }
 1157:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1158:               .'<img src="'.$helpicon.'" border="0"'
 1159:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1160:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1161:               .' /></a>';
 1162:     if ($text ne "") {	
 1163:         $template.='</span>';
 1164:     }
 1165:     return $template;
 1166: 
 1167: }
 1168: 
 1169: # This is a quicky function for Latex cheatsheet editing, since it 
 1170: # appears in at least four places
 1171: sub helpLatexCheatsheet {
 1172:     my ($topic,$text,$not_author) = @_;
 1173:     my $out;
 1174:     my $addOther = '';
 1175:     if ($topic) {
 1176: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1177: 							       undef, undef, 600).
 1178: 								   '</span> ';
 1179:     }
 1180:     $out = '<span>' # Start cheatsheet
 1181: 	  .$addOther
 1182:           .'<span>'
 1183: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1184: 					       undef,undef,600)
 1185: 	  .'</span> <span>'
 1186: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1187: 					       undef,undef,600)
 1188: 	  .'</span>';
 1189:     unless ($not_author) {
 1190:         $out .= ' <span>'
 1191: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1192: 	                                            undef,undef,600)
 1193: 	       .'</span>';
 1194:     }
 1195:     $out .= '</span>'; # End cheatsheet
 1196:     return $out;
 1197: }
 1198: 
 1199: sub general_help {
 1200:     my $helptopic='Student_Intro';
 1201:     if ($env{'request.role'}=~/^(ca|au)/) {
 1202: 	$helptopic='Authoring_Intro';
 1203:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1204: 	$helptopic='Course_Coordination_Intro';
 1205:     } elsif ($env{'request.role'}=~/^dc/) {
 1206:         $helptopic='Domain_Coordination_Intro';
 1207:     }
 1208:     return $helptopic;
 1209: }
 1210: 
 1211: sub update_help_link {
 1212:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1213:     my $origurl = $ENV{'REQUEST_URI'};
 1214:     $origurl=~s|^/~|/priv/|;
 1215:     my $timestamp = time;
 1216:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1217:         $$datum = &escape($$datum);
 1218:     }
 1219: 
 1220:     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";
 1221:     my $output .= <<"ENDOUTPUT";
 1222: <script type="text/javascript">
 1223: // <![CDATA[
 1224: banner_link = '$banner_link';
 1225: // ]]>
 1226: </script>
 1227: ENDOUTPUT
 1228:     return $output;
 1229: }
 1230: 
 1231: # now just updates the help link and generates a blue icon
 1232: sub help_open_menu {
 1233:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1234: 	= @_;    
 1235:     $stayOnPage = 1;
 1236:     my $output;
 1237:     if ($component_help) {
 1238: 	if (!$text) {
 1239: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1240: 				       $width,$height);
 1241: 	} else {
 1242: 	    my $help_text;
 1243: 	    $help_text=&unescape($topic);
 1244: 	    $output='<table><tr><td>'.
 1245: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1246: 				 $width,$height).'</td></tr></table>';
 1247: 	}
 1248:     }
 1249:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1250:     return $output.$banner_link;
 1251: }
 1252: 
 1253: sub top_nav_help {
 1254:     my ($text) = @_;
 1255:     $text = &mt($text);
 1256:     my $stay_on_page = 1;
 1257: 
 1258:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1259: 	                     : "javascript:helpMenu('open')";
 1260:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1261: 
 1262:     my $title = &mt('Get help');
 1263: 
 1264:     return <<"END";
 1265: $banner_link
 1266:  <a href="$link" title="$title">$text</a>
 1267: END
 1268: }
 1269: 
 1270: sub help_menu_js {
 1271:     my ($text) = @_;
 1272:     my $stayOnPage = 1;
 1273:     my $width = 620;
 1274:     my $height = 600;
 1275:     my $helptopic=&general_help();
 1276:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1277:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1278:     my $start_page =
 1279:         &Apache::loncommon::start_page('Help Menu', undef,
 1280: 				       {'frameset'    => 1,
 1281: 					'js_ready'    => 1,
 1282: 					'add_entries' => {
 1283: 					    'border' => '0',
 1284: 					    'rows'   => "110,*",},});
 1285:     my $end_page =
 1286:         &Apache::loncommon::end_page({'frameset' => 1,
 1287: 				      'js_ready' => 1,});
 1288: 
 1289:     my $template .= <<"ENDTEMPLATE";
 1290: <script type="text/javascript">
 1291: // <![CDATA[
 1292: // <!-- BEGIN LON-CAPA Internal
 1293: var banner_link = '';
 1294: function helpMenu(target) {
 1295:     var caller = this;
 1296:     if (target == 'open') {
 1297:         var newWindow = null;
 1298:         try {
 1299:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1300:         }
 1301:         catch(error) {
 1302:             writeHelp(caller);
 1303:             return;
 1304:         }
 1305:         if (newWindow) {
 1306:             caller = newWindow;
 1307:         }
 1308:     }
 1309:     writeHelp(caller);
 1310:     return;
 1311: }
 1312: function writeHelp(caller) {
 1313:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1314:     caller.document.close()
 1315:     caller.focus()
 1316: }
 1317: // END LON-CAPA Internal -->
 1318: // ]]>
 1319: </script>
 1320: ENDTEMPLATE
 1321:     return $template;
 1322: }
 1323: 
 1324: sub help_open_bug {
 1325:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1326:     unless ($env{'user.adv'}) { return ''; }
 1327:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1328:     $text = "" if (not defined $text);
 1329: 	$stayOnPage=1;
 1330:     $width = 600 if (not defined $width);
 1331:     $height = 600 if (not defined $height);
 1332: 
 1333:     $topic=~s/\W+/\+/g;
 1334:     my $link='';
 1335:     my $template='';
 1336:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1337: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1338:     if (!$stayOnPage)
 1339:     {
 1340: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1341:     }
 1342:     else
 1343:     {
 1344: 	$link = $url;
 1345:     }
 1346:     # Add the text
 1347:     if ($text ne "")
 1348:     {
 1349: 	$template .= 
 1350:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1351:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1352:     }
 1353: 
 1354:     # Add the graphic
 1355:     my $title = &mt('Report a Bug');
 1356:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1357:     $template .= <<"ENDTEMPLATE";
 1358:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1359: ENDTEMPLATE
 1360:     if ($text ne '') { $template.='</td></tr></table>' };
 1361:     return $template;
 1362: 
 1363: }
 1364: 
 1365: sub help_open_faq {
 1366:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1367:     unless ($env{'user.adv'}) { return ''; }
 1368:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1369:     $text = "" if (not defined $text);
 1370: 	$stayOnPage=1;
 1371:     $width = 350 if (not defined $width);
 1372:     $height = 400 if (not defined $height);
 1373: 
 1374:     $topic=~s/\W+/\+/g;
 1375:     my $link='';
 1376:     my $template='';
 1377:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1378:     if (!$stayOnPage)
 1379:     {
 1380: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1381:     }
 1382:     else
 1383:     {
 1384: 	$link = $url;
 1385:     }
 1386: 
 1387:     # Add the text
 1388:     if ($text ne "")
 1389:     {
 1390: 	$template .= 
 1391:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1392:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1393:     }
 1394: 
 1395:     # Add the graphic
 1396:     my $title = &mt('View the FAQ');
 1397:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1398:     $template .= <<"ENDTEMPLATE";
 1399:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1400: ENDTEMPLATE
 1401:     if ($text ne '') { $template.='</td></tr></table>' };
 1402:     return $template;
 1403: 
 1404: }
 1405: 
 1406: ###############################################################
 1407: ###############################################################
 1408: 
 1409: =pod
 1410: 
 1411: =item * &change_content_javascript():
 1412: 
 1413: This and the next function allow you to create small sections of an
 1414: otherwise static HTML page that you can update on the fly with
 1415: Javascript, even in Netscape 4.
 1416: 
 1417: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1418: must be written to the HTML page once. It will prove the Javascript
 1419: function "change(name, content)". Calling the change function with the
 1420: name of the section 
 1421: you want to update, matching the name passed to C<changable_area>, and
 1422: the new content you want to put in there, will put the content into
 1423: that area.
 1424: 
 1425: B<Note>: Netscape 4 only reserves enough space for the changable area
 1426: to contain room for the original contents. You need to "make space"
 1427: for whatever changes you wish to make, and be B<sure> to check your
 1428: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1429: it's adequate for updating a one-line status display, but little more.
 1430: This script will set the space to 100% width, so you only need to
 1431: worry about height in Netscape 4.
 1432: 
 1433: Modern browsers are much less limiting, and if you can commit to the
 1434: user not using Netscape 4, this feature may be used freely with
 1435: pretty much any HTML.
 1436: 
 1437: =cut
 1438: 
 1439: sub change_content_javascript {
 1440:     # If we're on Netscape 4, we need to use Layer-based code
 1441:     if ($env{'browser.type'} eq 'netscape' &&
 1442: 	$env{'browser.version'} =~ /^4\./) {
 1443: 	return (<<NETSCAPE4);
 1444: 	function change(name, content) {
 1445: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1446: 	    doc.open();
 1447: 	    doc.write(content);
 1448: 	    doc.close();
 1449: 	}
 1450: NETSCAPE4
 1451:     } else {
 1452: 	# Otherwise, we need to use semi-standards-compliant code
 1453: 	# (technically, "innerHTML" isn't standard but the equivalent
 1454: 	# is really scary, and every useful browser supports it
 1455: 	return (<<DOMBASED);
 1456: 	function change(name, content) {
 1457: 	    element = document.getElementById(name);
 1458: 	    element.innerHTML = content;
 1459: 	}
 1460: DOMBASED
 1461:     }
 1462: }
 1463: 
 1464: =pod
 1465: 
 1466: =item * &changable_area($name,$origContent):
 1467: 
 1468: This provides a "changable area" that can be modified on the fly via
 1469: the Javascript code provided in C<change_content_javascript>. $name is
 1470: the name you will use to reference the area later; do not repeat the
 1471: same name on a given HTML page more then once. $origContent is what
 1472: the area will originally contain, which can be left blank.
 1473: 
 1474: =cut
 1475: 
 1476: sub changable_area {
 1477:     my ($name, $origContent) = @_;
 1478: 
 1479:     if ($env{'browser.type'} eq 'netscape' &&
 1480: 	$env{'browser.version'} =~ /^4\./) {
 1481: 	# If this is netscape 4, we need to use the Layer tag
 1482: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1483:     } else {
 1484: 	return "<span id='$name'>$origContent</span>";
 1485:     }
 1486: }
 1487: 
 1488: =pod
 1489: 
 1490: =item * &viewport_geometry_js 
 1491: 
 1492: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1493: 
 1494: =cut
 1495: 
 1496: 
 1497: sub viewport_geometry_js { 
 1498:     return <<"GEOMETRY";
 1499: var Geometry = {};
 1500: function init_geometry() {
 1501:     if (Geometry.init) { return };
 1502:     Geometry.init=1;
 1503:     if (window.innerHeight) {
 1504:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1505:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1506:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1507:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1508:     }
 1509:     else if (document.documentElement && document.documentElement.clientHeight) {
 1510:         Geometry.getViewportHeight =
 1511:             function() { return document.documentElement.clientHeight; };
 1512:         Geometry.getViewportWidth =
 1513:             function() { return document.documentElement.clientWidth; };
 1514: 
 1515:         Geometry.getHorizontalScroll =
 1516:             function() { return document.documentElement.scrollLeft; };
 1517:         Geometry.getVerticalScroll =
 1518:             function() { return document.documentElement.scrollTop; };
 1519:     }
 1520:     else if (document.body.clientHeight) {
 1521:         Geometry.getViewportHeight =
 1522:             function() { return document.body.clientHeight; };
 1523:         Geometry.getViewportWidth =
 1524:             function() { return document.body.clientWidth; };
 1525:         Geometry.getHorizontalScroll =
 1526:             function() { return document.body.scrollLeft; };
 1527:         Geometry.getVerticalScroll =
 1528:             function() { return document.body.scrollTop; };
 1529:     }
 1530: }
 1531: 
 1532: GEOMETRY
 1533: }
 1534: 
 1535: =pod
 1536: 
 1537: =item * &viewport_size_js()
 1538: 
 1539: 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. 
 1540: 
 1541: =cut
 1542: 
 1543: sub viewport_size_js {
 1544:     my $geometry = &viewport_geometry_js();
 1545:     return <<"DIMS";
 1546: 
 1547: $geometry
 1548: 
 1549: function getViewportDims(width,height) {
 1550:     init_geometry();
 1551:     width.value = Geometry.getViewportWidth();
 1552:     height.value = Geometry.getViewportHeight();
 1553:     return;
 1554: }
 1555: 
 1556: DIMS
 1557: }
 1558: 
 1559: =pod
 1560: 
 1561: =item * &resize_textarea_js()
 1562: 
 1563: emits the needed javascript to resize a textarea to be as big as possible
 1564: 
 1565: creates a function resize_textrea that takes two IDs first should be
 1566: the id of the element to resize, second should be the id of a div that
 1567: surrounds everything that comes after the textarea, this routine needs
 1568: to be attached to the <body> for the onload and onresize events.
 1569: 
 1570: =back
 1571: 
 1572: =cut
 1573: 
 1574: sub resize_textarea_js {
 1575:     my $geometry = &viewport_geometry_js();
 1576:     return <<"RESIZE";
 1577:     <script type="text/javascript">
 1578: // <![CDATA[
 1579: $geometry
 1580: 
 1581: function getX(element) {
 1582:     var x = 0;
 1583:     while (element) {
 1584: 	x += element.offsetLeft;
 1585: 	element = element.offsetParent;
 1586:     }
 1587:     return x;
 1588: }
 1589: function getY(element) {
 1590:     var y = 0;
 1591:     while (element) {
 1592: 	y += element.offsetTop;
 1593: 	element = element.offsetParent;
 1594:     }
 1595:     return y;
 1596: }
 1597: 
 1598: 
 1599: function resize_textarea(textarea_id,bottom_id) {
 1600:     init_geometry();
 1601:     var textarea        = document.getElementById(textarea_id);
 1602:     //alert(textarea);
 1603: 
 1604:     var textarea_top    = getY(textarea);
 1605:     var textarea_height = textarea.offsetHeight;
 1606:     var bottom          = document.getElementById(bottom_id);
 1607:     var bottom_top      = getY(bottom);
 1608:     var bottom_height   = bottom.offsetHeight;
 1609:     var window_height   = Geometry.getViewportHeight();
 1610:     var fudge           = 23;
 1611:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1612:     if (new_height < 300) {
 1613: 	new_height = 300;
 1614:     }
 1615:     textarea.style.height=new_height+'px';
 1616: }
 1617: // ]]>
 1618: </script>
 1619: RESIZE
 1620: 
 1621: }
 1622: 
 1623: =pod
 1624: 
 1625: =head1 Excel and CSV file utility routines
 1626: 
 1627: =over 4
 1628: 
 1629: =cut
 1630: 
 1631: ###############################################################
 1632: ###############################################################
 1633: 
 1634: =pod
 1635: 
 1636: =item * &csv_translate($text) 
 1637: 
 1638: Translate $text to allow it to be output as a 'comma separated values' 
 1639: format.
 1640: 
 1641: =cut
 1642: 
 1643: ###############################################################
 1644: ###############################################################
 1645: sub csv_translate {
 1646:     my $text = shift;
 1647:     $text =~ s/\"/\"\"/g;
 1648:     $text =~ s/\n/ /g;
 1649:     return $text;
 1650: }
 1651: 
 1652: ###############################################################
 1653: ###############################################################
 1654: 
 1655: =pod
 1656: 
 1657: =item * &define_excel_formats()
 1658: 
 1659: Define some commonly used Excel cell formats.
 1660: 
 1661: Currently supported formats:
 1662: 
 1663: =over 4
 1664: 
 1665: =item header
 1666: 
 1667: =item bold
 1668: 
 1669: =item h1
 1670: 
 1671: =item h2
 1672: 
 1673: =item h3
 1674: 
 1675: =item h4
 1676: 
 1677: =item i
 1678: 
 1679: =item date
 1680: 
 1681: =back
 1682: 
 1683: Inputs: $workbook
 1684: 
 1685: Returns: $format, a hash reference.
 1686: 
 1687: =cut
 1688: 
 1689: ###############################################################
 1690: ###############################################################
 1691: sub define_excel_formats {
 1692:     my ($workbook) = @_;
 1693:     my $format;
 1694:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1695:                                                 bottom    => 1,
 1696:                                                 align     => 'center');
 1697:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1698:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1699:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1700:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1701:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1702:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1703:     $format->{'date'} = $workbook->add_format(num_format=>
 1704:                                             'mm/dd/yyyy hh:mm:ss');
 1705:     return $format;
 1706: }
 1707: 
 1708: ###############################################################
 1709: ###############################################################
 1710: 
 1711: =pod
 1712: 
 1713: =item * &create_workbook()
 1714: 
 1715: Create an Excel worksheet.  If it fails, output message on the
 1716: request object and return undefs.
 1717: 
 1718: Inputs: Apache request object
 1719: 
 1720: Returns (undef) on failure, 
 1721:     Excel worksheet object, scalar with filename, and formats 
 1722:     from &Apache::loncommon::define_excel_formats on success
 1723: 
 1724: =cut
 1725: 
 1726: ###############################################################
 1727: ###############################################################
 1728: sub create_workbook {
 1729:     my ($r) = @_;
 1730:         #
 1731:     # Create the excel spreadsheet
 1732:     my $filename = '/prtspool/'.
 1733:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1734:         time.'_'.rand(1000000000).'.xls';
 1735:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1736:     if (! defined($workbook)) {
 1737:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1738:         $r->print(
 1739:             '<p class="LC_error">'
 1740:            .&mt('Problems occurred in creating the new Excel file.')
 1741:            .' '.&mt('This error has been logged.')
 1742:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1743:            .'</p>'
 1744:         );
 1745:         return (undef);
 1746:     }
 1747:     #
 1748:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1749:     #
 1750:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1751:     return ($workbook,$filename,$format);
 1752: }
 1753: 
 1754: ###############################################################
 1755: ###############################################################
 1756: 
 1757: =pod
 1758: 
 1759: =item * &create_text_file()
 1760: 
 1761: Create a file to write to and eventually make available to the user.
 1762: If file creation fails, outputs an error message on the request object and 
 1763: return undefs.
 1764: 
 1765: Inputs: Apache request object, and file suffix
 1766: 
 1767: Returns (undef) on failure, 
 1768:     Filehandle and filename on success.
 1769: 
 1770: =cut
 1771: 
 1772: ###############################################################
 1773: ###############################################################
 1774: sub create_text_file {
 1775:     my ($r,$suffix) = @_;
 1776:     if (! defined($suffix)) { $suffix = 'txt'; };
 1777:     my $fh;
 1778:     my $filename = '/prtspool/'.
 1779:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1780:         time.'_'.rand(1000000000).'.'.$suffix;
 1781:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1782:     if (! defined($fh)) {
 1783:         $r->log_error("Couldn't open $filename for output $!");
 1784:         $r->print(
 1785:             '<p class="LC_error">'
 1786:            .&mt('Problems occurred in creating the output file.')
 1787:            .' '.&mt('This error has been logged.')
 1788:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1789:            .'</p>'
 1790:         );
 1791:     }
 1792:     return ($fh,$filename)
 1793: }
 1794: 
 1795: 
 1796: =pod 
 1797: 
 1798: =back
 1799: 
 1800: =cut
 1801: 
 1802: ###############################################################
 1803: ##        Home server <option> list generating code          ##
 1804: ###############################################################
 1805: 
 1806: # ------------------------------------------
 1807: 
 1808: sub domain_select {
 1809:     my ($name,$value,$multiple)=@_;
 1810:     my %domains=map { 
 1811: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1812:     } &Apache::lonnet::all_domains();
 1813:     if ($multiple) {
 1814: 	$domains{''}=&mt('Any domain');
 1815: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1816: 	return &multiple_select_form($name,$value,4,\%domains);
 1817:     } else {
 1818: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1819: 	return &select_form($name,$value,\%domains);
 1820:     }
 1821: }
 1822: 
 1823: #-------------------------------------------
 1824: 
 1825: =pod
 1826: 
 1827: =head1 Routines for form select boxes
 1828: 
 1829: =over 4
 1830: 
 1831: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1832: 
 1833: Returns a string containing a <select> element int multiple mode
 1834: 
 1835: 
 1836: Args:
 1837:   $name - name of the <select> element
 1838:   $value - scalar or array ref of values that should already be selected
 1839:   $size - number of rows long the select element is
 1840:   $hash - the elements should be 'option' => 'shown text'
 1841:           (shown text should already have been &mt())
 1842:   $order - (optional) array ref of the order to show the elements in
 1843: 
 1844: =cut
 1845: 
 1846: #-------------------------------------------
 1847: sub multiple_select_form {
 1848:     my ($name,$value,$size,$hash,$order)=@_;
 1849:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1850:     my $output='';
 1851:     if (! defined($size)) {
 1852:         $size = 4;
 1853:         if (scalar(keys(%$hash))<4) {
 1854:             $size = scalar(keys(%$hash));
 1855:         }
 1856:     }
 1857:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1858:     my @order;
 1859:     if (ref($order) eq 'ARRAY')  {
 1860:         @order = @{$order};
 1861:     } else {
 1862:         @order = sort(keys(%$hash));
 1863:     }
 1864:     if (exists($$hash{'select_form_order'})) {
 1865:         @order = @{$$hash{'select_form_order'}};
 1866:     }
 1867:         
 1868:     foreach my $key (@order) {
 1869:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1870:         $output.='selected="selected" ' if ($selected{$key});
 1871:         $output.='>'.$hash->{$key}."</option>\n";
 1872:     }
 1873:     $output.="</select>\n";
 1874:     return $output;
 1875: }
 1876: 
 1877: #-------------------------------------------
 1878: 
 1879: =pod
 1880: 
 1881: =item * &select_form($defdom,$name,$hashref,$onchange)
 1882: 
 1883: Returns a string containing a <select name='$name' size='1'> form to 
 1884: allow a user to select options from a ref to a hash containing:
 1885: option_name => displayed text. An optional $onchange can include
 1886: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1887: 
 1888: See lonrights.pm for an example invocation and use.
 1889: 
 1890: =cut
 1891: 
 1892: #-------------------------------------------
 1893: sub select_form {
 1894:     my ($def,$name,$hashref,$onchange) = @_;
 1895:     return unless (ref($hashref) eq 'HASH');
 1896:     if ($onchange) {
 1897:         $onchange = ' onchange="'.$onchange.'"';
 1898:     }
 1899:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1900:     my @keys;
 1901:     if (exists($hashref->{'select_form_order'})) {
 1902: 	@keys=@{$hashref->{'select_form_order'}};
 1903:     } else {
 1904: 	@keys=sort(keys(%{$hashref}));
 1905:     }
 1906:     foreach my $key (@keys) {
 1907:         $selectform.=
 1908: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1909:             ($key eq $def ? 'selected="selected" ' : '').
 1910:                 ">".$hashref->{$key}."</option>\n";
 1911:     }
 1912:     $selectform.="</select>";
 1913:     return $selectform;
 1914: }
 1915: 
 1916: # For display filters
 1917: 
 1918: sub display_filter {
 1919:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1920:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1921:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1922: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1923: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1924: 	   '</label></span> <span class="LC_nobreak">'.
 1925:            &mt('Filter [_1]',
 1926: 	   &select_form($env{'form.displayfilter'},
 1927: 			'displayfilter',
 1928: 			{'currentfolder' => 'Current folder/page',
 1929: 			 'containing' => 'Containing phrase',
 1930: 			 'none' => 'None'})).
 1931: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1932: }
 1933: 
 1934: sub gradeleveldescription {
 1935:     my $gradelevel=shift;
 1936:     my %gradelevels=(0 => 'Not specified',
 1937: 		     1 => 'Grade 1',
 1938: 		     2 => 'Grade 2',
 1939: 		     3 => 'Grade 3',
 1940: 		     4 => 'Grade 4',
 1941: 		     5 => 'Grade 5',
 1942: 		     6 => 'Grade 6',
 1943: 		     7 => 'Grade 7',
 1944: 		     8 => 'Grade 8',
 1945: 		     9 => 'Grade 9',
 1946: 		     10 => 'Grade 10',
 1947: 		     11 => 'Grade 11',
 1948: 		     12 => 'Grade 12',
 1949: 		     13 => 'Grade 13',
 1950: 		     14 => '100 Level',
 1951: 		     15 => '200 Level',
 1952: 		     16 => '300 Level',
 1953: 		     17 => '400 Level',
 1954: 		     18 => 'Graduate Level');
 1955:     return &mt($gradelevels{$gradelevel});
 1956: }
 1957: 
 1958: sub select_level_form {
 1959:     my ($deflevel,$name)=@_;
 1960:     unless ($deflevel) { $deflevel=0; }
 1961:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1962:     for (my $i=0; $i<=18; $i++) {
 1963:         $selectform.="<option value=\"$i\" ".
 1964:             ($i==$deflevel ? 'selected="selected" ' : '').
 1965:                 ">".&gradeleveldescription($i)."</option>\n";
 1966:     }
 1967:     $selectform.="</select>";
 1968:     return $selectform;
 1969: }
 1970: 
 1971: #-------------------------------------------
 1972: 
 1973: =pod
 1974: 
 1975: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 1976: 
 1977: Returns a string containing a <select name='$name' size='1'> form to 
 1978: allow a user to select the domain to preform an operation in.  
 1979: See loncreateuser.pm for an example invocation and use.
 1980: 
 1981: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1982: selected");
 1983: 
 1984: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1985: 
 1986: 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.
 1987: 
 1988: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 1989: 
 1990: =cut
 1991: 
 1992: #-------------------------------------------
 1993: sub select_dom_form {
 1994:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 1995:     if ($onchange) {
 1996:         $onchange = ' onchange="'.$onchange.'"';
 1997:     }
 1998:     my @domains;
 1999:     if (ref($incdoms) eq 'ARRAY') {
 2000:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2001:     } else {
 2002:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2003:     }
 2004:     if ($includeempty) { @domains=('',@domains); }
 2005:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2006:     foreach my $dom (@domains) {
 2007:         $selectdomain.="<option value=\"$dom\" ".
 2008:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2009:         if ($showdomdesc) {
 2010:             if ($dom ne '') {
 2011:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2012:                 if ($domdesc ne '') {
 2013:                     $selectdomain .= ' ('.$domdesc.')';
 2014:                 }
 2015:             } 
 2016:         }
 2017:         $selectdomain .= "</option>\n";
 2018:     }
 2019:     $selectdomain.="</select>";
 2020:     return $selectdomain;
 2021: }
 2022: 
 2023: #-------------------------------------------
 2024: 
 2025: =pod
 2026: 
 2027: =item * &home_server_form_item($domain,$name,$defaultflag)
 2028: 
 2029: input: 4 arguments (two required, two optional) - 
 2030:     $domain - domain of new user
 2031:     $name - name of form element
 2032:     $default - Value of 'default' causes a default item to be first 
 2033:                             option, and selected by default. 
 2034:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2035:                             if 1 server found, or default, if 0 found.
 2036: output: returns 2 items: 
 2037: (a) form element which contains either:
 2038:    (i) <select name="$name">
 2039:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2040:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2041:        </select>
 2042:        form item if there are multiple library servers in $domain, or
 2043:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2044:        if there is only one library server in $domain.
 2045: 
 2046: (b) number of library servers found.
 2047: 
 2048: See loncreateuser.pm for example of use.
 2049: 
 2050: =cut
 2051: 
 2052: #-------------------------------------------
 2053: sub home_server_form_item {
 2054:     my ($domain,$name,$default,$hide) = @_;
 2055:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2056:     my $result;
 2057:     my $numlib = keys(%servers);
 2058:     if ($numlib > 1) {
 2059:         $result .= '<select name="'.$name.'" />'."\n";
 2060:         if ($default) {
 2061:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2062:                        '</option>'."\n";
 2063:         }
 2064:         foreach my $hostid (sort(keys(%servers))) {
 2065:             $result.= '<option value="'.$hostid.'">'.
 2066: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2067:         }
 2068:         $result .= '</select>'."\n";
 2069:     } elsif ($numlib == 1) {
 2070:         my $hostid;
 2071:         foreach my $item (keys(%servers)) {
 2072:             $hostid = $item;
 2073:         }
 2074:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2075:                    $hostid.'" />';
 2076:                    if (!$hide) {
 2077:                        $result .= $hostid.' '.$servers{$hostid};
 2078:                    }
 2079:                    $result .= "\n";
 2080:     } elsif ($default) {
 2081:         $result .= '<input type="hidden" name="'.$name.
 2082:                    '" value="default" />';
 2083:                    if (!$hide) {
 2084:                        $result .= &mt('default');
 2085:                    }
 2086:                    $result .= "\n";
 2087:     }
 2088:     return ($result,$numlib);
 2089: }
 2090: 
 2091: =pod
 2092: 
 2093: =back 
 2094: 
 2095: =cut
 2096: 
 2097: ###############################################################
 2098: ##                  Decoding User Agent                      ##
 2099: ###############################################################
 2100: 
 2101: =pod
 2102: 
 2103: =head1 Decoding the User Agent
 2104: 
 2105: =over 4
 2106: 
 2107: =item * &decode_user_agent()
 2108: 
 2109: Inputs: $r
 2110: 
 2111: Outputs:
 2112: 
 2113: =over 4
 2114: 
 2115: =item * $httpbrowser
 2116: 
 2117: =item * $clientbrowser
 2118: 
 2119: =item * $clientversion
 2120: 
 2121: =item * $clientmathml
 2122: 
 2123: =item * $clientunicode
 2124: 
 2125: =item * $clientos
 2126: 
 2127: =back
 2128: 
 2129: =back 
 2130: 
 2131: =cut
 2132: 
 2133: ###############################################################
 2134: ###############################################################
 2135: sub decode_user_agent {
 2136:     my ($r)=@_;
 2137:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2138:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2139:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2140:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2141:     my $clientbrowser='unknown';
 2142:     my $clientversion='0';
 2143:     my $clientmathml='';
 2144:     my $clientunicode='0';
 2145:     for (my $i=0;$i<=$#browsertype;$i++) {
 2146:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2147: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2148: 	    $clientbrowser=$bname;
 2149:             $httpbrowser=~/$vreg/i;
 2150: 	    $clientversion=$1;
 2151:             $clientmathml=($clientversion>=$minv);
 2152:             $clientunicode=($clientversion>=$univ);
 2153: 	}
 2154:     }
 2155:     my $clientos='unknown';
 2156:     if (($httpbrowser=~/linux/i) ||
 2157:         ($httpbrowser=~/unix/i) ||
 2158:         ($httpbrowser=~/ux/i) ||
 2159:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2160:     if (($httpbrowser=~/vax/i) ||
 2161:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2162:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2163:     if (($httpbrowser=~/mac/i) ||
 2164:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2165:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2166:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2167:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2168:             $clientunicode,$clientos,);
 2169: }
 2170: 
 2171: ###############################################################
 2172: ##    Authentication changing form generation subroutines    ##
 2173: ###############################################################
 2174: ##
 2175: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2176: ## hash, and have reasonable default values.
 2177: ##
 2178: ##    formname = the name given in the <form> tag.
 2179: #-------------------------------------------
 2180: 
 2181: =pod
 2182: 
 2183: =head1 Authentication Routines
 2184: 
 2185: =over 4
 2186: 
 2187: =item * &authform_xxxxxx()
 2188: 
 2189: The authform_xxxxxx subroutines provide javascript and html forms which 
 2190: handle some of the conveniences required for authentication forms.  
 2191: This is not an optimal method, but it works.  
 2192: 
 2193: =over 4
 2194: 
 2195: =item * authform_header
 2196: 
 2197: =item * authform_authorwarning
 2198: 
 2199: =item * authform_nochange
 2200: 
 2201: =item * authform_kerberos
 2202: 
 2203: =item * authform_internal
 2204: 
 2205: =item * authform_filesystem
 2206: 
 2207: =back
 2208: 
 2209: See loncreateuser.pm for invocation and use examples.
 2210: 
 2211: =cut
 2212: 
 2213: #-------------------------------------------
 2214: sub authform_header{  
 2215:     my %in = (
 2216:         formname => 'cu',
 2217:         kerb_def_dom => '',
 2218:         @_,
 2219:     );
 2220:     $in{'formname'} = 'document.' . $in{'formname'};
 2221:     my $result='';
 2222: 
 2223: #---------------------------------------------- Code for upper case translation
 2224:     my $Javascript_toUpperCase;
 2225:     unless ($in{kerb_def_dom}) {
 2226:         $Javascript_toUpperCase =<<"END";
 2227:         switch (choice) {
 2228:            case 'krb': currentform.elements[choicearg].value =
 2229:                currentform.elements[choicearg].value.toUpperCase();
 2230:                break;
 2231:            default:
 2232:         }
 2233: END
 2234:     } else {
 2235:         $Javascript_toUpperCase = "";
 2236:     }
 2237: 
 2238:     my $radioval = "'nochange'";
 2239:     if (defined($in{'curr_authtype'})) {
 2240:         if ($in{'curr_authtype'} ne '') {
 2241:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2242:         }
 2243:     }
 2244:     my $argfield = 'null';
 2245:     if (defined($in{'mode'})) {
 2246:         if ($in{'mode'} eq 'modifycourse')  {
 2247:             if (defined($in{'curr_autharg'})) {
 2248:                 if ($in{'curr_autharg'} ne '') {
 2249:                     $argfield = "'$in{'curr_autharg'}'";
 2250:                 }
 2251:             }
 2252:         }
 2253:     }
 2254: 
 2255:     $result.=<<"END";
 2256: var current = new Object();
 2257: current.radiovalue = $radioval;
 2258: current.argfield = $argfield;
 2259: 
 2260: function changed_radio(choice,currentform) {
 2261:     var choicearg = choice + 'arg';
 2262:     // If a radio button in changed, we need to change the argfield
 2263:     if (current.radiovalue != choice) {
 2264:         current.radiovalue = choice;
 2265:         if (current.argfield != null) {
 2266:             currentform.elements[current.argfield].value = '';
 2267:         }
 2268:         if (choice == 'nochange') {
 2269:             current.argfield = null;
 2270:         } else {
 2271:             current.argfield = choicearg;
 2272:             switch(choice) {
 2273:                 case 'krb': 
 2274:                     currentform.elements[current.argfield].value = 
 2275:                         "$in{'kerb_def_dom'}";
 2276:                 break;
 2277:               default:
 2278:                 break;
 2279:             }
 2280:         }
 2281:     }
 2282:     return;
 2283: }
 2284: 
 2285: function changed_text(choice,currentform) {
 2286:     var choicearg = choice + 'arg';
 2287:     if (currentform.elements[choicearg].value !='') {
 2288:         $Javascript_toUpperCase
 2289:         // clear old field
 2290:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2291:             currentform.elements[current.argfield].value = '';
 2292:         }
 2293:         current.argfield = choicearg;
 2294:     }
 2295:     set_auth_radio_buttons(choice,currentform);
 2296:     return;
 2297: }
 2298: 
 2299: function set_auth_radio_buttons(newvalue,currentform) {
 2300:     var numauthchoices = currentform.login.length;
 2301:     if (typeof numauthchoices  == "undefined") {
 2302:         return;
 2303:     } 
 2304:     var i=0;
 2305:     while (i < numauthchoices) {
 2306:         if (currentform.login[i].value == newvalue) { break; }
 2307:         i++;
 2308:     }
 2309:     if (i == numauthchoices) {
 2310:         return;
 2311:     }
 2312:     current.radiovalue = newvalue;
 2313:     currentform.login[i].checked = true;
 2314:     return;
 2315: }
 2316: END
 2317:     return $result;
 2318: }
 2319: 
 2320: sub authform_authorwarning{
 2321:     my $result='';
 2322:     $result='<i>'.
 2323:         &mt('As a general rule, only authors or co-authors should be '.
 2324:             'filesystem authenticated '.
 2325:             '(which allows access to the server filesystem).')."</i>\n";
 2326:     return $result;
 2327: }
 2328: 
 2329: sub authform_nochange{  
 2330:     my %in = (
 2331:               formname => 'document.cu',
 2332:               kerb_def_dom => 'MSU.EDU',
 2333:               @_,
 2334:           );
 2335:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2336:     my $result;
 2337:     if (keys(%can_assign) == 0) {
 2338:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2339:     } else {
 2340:         $result = '<label>'.&mt('[_1] Do not change login data',
 2341:                   '<input type="radio" name="login" value="nochange" '.
 2342:                   'checked="checked" onclick="'.
 2343:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2344: 	    '</label>';
 2345:     }
 2346:     return $result;
 2347: }
 2348: 
 2349: sub authform_kerberos {
 2350:     my %in = (
 2351:               formname => 'document.cu',
 2352:               kerb_def_dom => 'MSU.EDU',
 2353:               kerb_def_auth => 'krb4',
 2354:               @_,
 2355:               );
 2356:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2357:         $autharg,$jscall);
 2358:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2359:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2360:        $check5 = ' checked="checked"';
 2361:     } else {
 2362:        $check4 = ' checked="checked"';
 2363:     }
 2364:     $krbarg = $in{'kerb_def_dom'};
 2365:     if (defined($in{'curr_authtype'})) {
 2366:         if ($in{'curr_authtype'} eq 'krb') {
 2367:             $krbcheck = ' checked="checked"';
 2368:             if (defined($in{'mode'})) {
 2369:                 if ($in{'mode'} eq 'modifyuser') {
 2370:                     $krbcheck = '';
 2371:                 }
 2372:             }
 2373:             if (defined($in{'curr_kerb_ver'})) {
 2374:                 if ($in{'curr_krb_ver'} eq '5') {
 2375:                     $check5 = ' checked="checked"';
 2376:                     $check4 = '';
 2377:                 } else {
 2378:                     $check4 = ' checked="checked"';
 2379:                     $check5 = '';
 2380:                 }
 2381:             }
 2382:             if (defined($in{'curr_autharg'})) {
 2383:                 $krbarg = $in{'curr_autharg'};
 2384:             }
 2385:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2386:                 if (defined($in{'curr_autharg'})) {
 2387:                     $result = 
 2388:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2389:         $in{'curr_autharg'},$krbver);
 2390:                 } else {
 2391:                     $result =
 2392:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2393:                 }
 2394:                 return $result; 
 2395:             }
 2396:         }
 2397:     } else {
 2398:         if ($authnum == 1) {
 2399:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2400:         }
 2401:     }
 2402:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2403:         return;
 2404:     } elsif ($authtype eq '') {
 2405:         if (defined($in{'mode'})) {
 2406:             if ($in{'mode'} eq 'modifycourse') {
 2407:                 if ($authnum == 1) {
 2408:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2409:                 }
 2410:             }
 2411:         }
 2412:     }
 2413:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2414:     if ($authtype eq '') {
 2415:         $authtype = '<input type="radio" name="login" value="krb" '.
 2416:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2417:                     $krbcheck.' />';
 2418:     }
 2419:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2420:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2421:          $in{'curr_authtype'} eq 'krb5') ||
 2422:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2423:          $in{'curr_authtype'} eq 'krb4')) {
 2424:         $result .= &mt
 2425:         ('[_1] Kerberos authenticated with domain [_2] '.
 2426:          '[_3] Version 4 [_4] Version 5 [_5]',
 2427:          '<label>'.$authtype,
 2428:          '</label><input type="text" size="10" name="krbarg" '.
 2429:              'value="'.$krbarg.'" '.
 2430:              'onchange="'.$jscall.'" />',
 2431:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2432:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2433: 	 '</label>');
 2434:     } elsif ($can_assign{'krb4'}) {
 2435:         $result .= &mt
 2436:         ('[_1] Kerberos authenticated with domain [_2] '.
 2437:          '[_3] Version 4 [_4]',
 2438:          '<label>'.$authtype,
 2439:          '</label><input type="text" size="10" name="krbarg" '.
 2440:              'value="'.$krbarg.'" '.
 2441:              'onchange="'.$jscall.'" />',
 2442:          '<label><input type="hidden" name="krbver" value="4" />',
 2443:          '</label>');
 2444:     } elsif ($can_assign{'krb5'}) {
 2445:         $result .= &mt
 2446:         ('[_1] Kerberos authenticated with domain [_2] '.
 2447:          '[_3] Version 5 [_4]',
 2448:          '<label>'.$authtype,
 2449:          '</label><input type="text" size="10" name="krbarg" '.
 2450:              'value="'.$krbarg.'" '.
 2451:              'onchange="'.$jscall.'" />',
 2452:          '<label><input type="hidden" name="krbver" value="5" />',
 2453:          '</label>');
 2454:     }
 2455:     return $result;
 2456: }
 2457: 
 2458: sub authform_internal{  
 2459:     my %in = (
 2460:                 formname => 'document.cu',
 2461:                 kerb_def_dom => 'MSU.EDU',
 2462:                 @_,
 2463:                 );
 2464:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2465:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2466:     if (defined($in{'curr_authtype'})) {
 2467:         if ($in{'curr_authtype'} eq 'int') {
 2468:             if ($can_assign{'int'}) {
 2469:                 $intcheck = 'checked="checked" ';
 2470:                 if (defined($in{'mode'})) {
 2471:                     if ($in{'mode'} eq 'modifyuser') {
 2472:                         $intcheck = '';
 2473:                     }
 2474:                 }
 2475:                 if (defined($in{'curr_autharg'})) {
 2476:                     $intarg = $in{'curr_autharg'};
 2477:                 }
 2478:             } else {
 2479:                 $result = &mt('Currently internally authenticated.');
 2480:                 return $result;
 2481:             }
 2482:         }
 2483:     } else {
 2484:         if ($authnum == 1) {
 2485:             $authtype = '<input type="hidden" name="login" value="int" />';
 2486:         }
 2487:     }
 2488:     if (!$can_assign{'int'}) {
 2489:         return;
 2490:     } elsif ($authtype eq '') {
 2491:         if (defined($in{'mode'})) {
 2492:             if ($in{'mode'} eq 'modifycourse') {
 2493:                 if ($authnum == 1) {
 2494:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2495:                 }
 2496:             }
 2497:         }
 2498:     }
 2499:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2500:     if ($authtype eq '') {
 2501:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2502:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2503:     }
 2504:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2505:                $intarg.'" onchange="'.$jscall.'" />';
 2506:     $result = &mt
 2507:         ('[_1] Internally authenticated (with initial password [_2])',
 2508:          '<label>'.$authtype,'</label>'.$autharg);
 2509:     $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>';
 2510:     return $result;
 2511: }
 2512: 
 2513: sub authform_local{  
 2514:     my %in = (
 2515:               formname => 'document.cu',
 2516:               kerb_def_dom => 'MSU.EDU',
 2517:               @_,
 2518:               );
 2519:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2520:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2521:     if (defined($in{'curr_authtype'})) {
 2522:         if ($in{'curr_authtype'} eq 'loc') {
 2523:             if ($can_assign{'loc'}) {
 2524:                 $loccheck = 'checked="checked" ';
 2525:                 if (defined($in{'mode'})) {
 2526:                     if ($in{'mode'} eq 'modifyuser') {
 2527:                         $loccheck = '';
 2528:                     }
 2529:                 }
 2530:                 if (defined($in{'curr_autharg'})) {
 2531:                     $locarg = $in{'curr_autharg'};
 2532:                 }
 2533:             } else {
 2534:                 $result = &mt('Currently using local (institutional) authentication.');
 2535:                 return $result;
 2536:             }
 2537:         }
 2538:     } else {
 2539:         if ($authnum == 1) {
 2540:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2541:         }
 2542:     }
 2543:     if (!$can_assign{'loc'}) {
 2544:         return;
 2545:     } elsif ($authtype eq '') {
 2546:         if (defined($in{'mode'})) {
 2547:             if ($in{'mode'} eq 'modifycourse') {
 2548:                 if ($authnum == 1) {
 2549:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2550:                 }
 2551:             }
 2552:         }
 2553:     }
 2554:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2555:     if ($authtype eq '') {
 2556:         $authtype = '<input type="radio" name="login" value="loc" '.
 2557:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2558:                     $jscall.'" />';
 2559:     }
 2560:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2561:                $locarg.'" onchange="'.$jscall.'" />';
 2562:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2563:                   '<label>'.$authtype,'</label>'.$autharg);
 2564:     return $result;
 2565: }
 2566: 
 2567: sub authform_filesystem{  
 2568:     my %in = (
 2569:               formname => 'document.cu',
 2570:               kerb_def_dom => 'MSU.EDU',
 2571:               @_,
 2572:               );
 2573:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2574:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2575:     if (defined($in{'curr_authtype'})) {
 2576:         if ($in{'curr_authtype'} eq 'fsys') {
 2577:             if ($can_assign{'fsys'}) {
 2578:                 $fsyscheck = 'checked="checked" ';
 2579:                 if (defined($in{'mode'})) {
 2580:                     if ($in{'mode'} eq 'modifyuser') {
 2581:                         $fsyscheck = '';
 2582:                     }
 2583:                 }
 2584:             } else {
 2585:                 $result = &mt('Currently Filesystem Authenticated.');
 2586:                 return $result;
 2587:             }           
 2588:         }
 2589:     } else {
 2590:         if ($authnum == 1) {
 2591:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2592:         }
 2593:     }
 2594:     if (!$can_assign{'fsys'}) {
 2595:         return;
 2596:     } elsif ($authtype eq '') {
 2597:         if (defined($in{'mode'})) {
 2598:             if ($in{'mode'} eq 'modifycourse') {
 2599:                 if ($authnum == 1) {
 2600:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2601:                 }
 2602:             }
 2603:         }
 2604:     }
 2605:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2606:     if ($authtype eq '') {
 2607:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2608:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2609:                     $jscall.'" />';
 2610:     }
 2611:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2612:                ' onchange="'.$jscall.'" />';
 2613:     $result = &mt
 2614:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2615:          '<label><input type="radio" name="login" value="fsys" '.
 2616:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2617:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2618:                   'onchange="'.$jscall.'" />');
 2619:     return $result;
 2620: }
 2621: 
 2622: sub get_assignable_auth {
 2623:     my ($dom) = @_;
 2624:     if ($dom eq '') {
 2625:         $dom = $env{'request.role.domain'};
 2626:     }
 2627:     my %can_assign = (
 2628:                           krb4 => 1,
 2629:                           krb5 => 1,
 2630:                           int  => 1,
 2631:                           loc  => 1,
 2632:                      );
 2633:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2634:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2635:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2636:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2637:             my $context;
 2638:             if ($env{'request.role'} =~ /^au/) {
 2639:                 $context = 'author';
 2640:             } elsif ($env{'request.role'} =~ /^dc/) {
 2641:                 $context = 'domain';
 2642:             } elsif ($env{'request.course.id'}) {
 2643:                 $context = 'course';
 2644:             }
 2645:             if ($context) {
 2646:                 if (ref($authhash->{$context}) eq 'HASH') {
 2647:                    %can_assign = %{$authhash->{$context}}; 
 2648:                 }
 2649:             }
 2650:         }
 2651:     }
 2652:     my $authnum = 0;
 2653:     foreach my $key (keys(%can_assign)) {
 2654:         if ($can_assign{$key}) {
 2655:             $authnum ++;
 2656:         }
 2657:     }
 2658:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2659:         $authnum --;
 2660:     }
 2661:     return ($authnum,%can_assign);
 2662: }
 2663: 
 2664: ###############################################################
 2665: ##    Get Kerberos Defaults for Domain                 ##
 2666: ###############################################################
 2667: ##
 2668: ## Returns default kerberos version and an associated argument
 2669: ## as listed in file domain.tab. If not listed, provides
 2670: ## appropriate default domain and kerberos version.
 2671: ##
 2672: #-------------------------------------------
 2673: 
 2674: =pod
 2675: 
 2676: =item * &get_kerberos_defaults()
 2677: 
 2678: get_kerberos_defaults($target_domain) returns the default kerberos
 2679: version and domain. If not found, it defaults to version 4 and the 
 2680: domain of the server.
 2681: 
 2682: =over 4
 2683: 
 2684: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2685: 
 2686: =back
 2687: 
 2688: =back
 2689: 
 2690: =cut
 2691: 
 2692: #-------------------------------------------
 2693: sub get_kerberos_defaults {
 2694:     my $domain=shift;
 2695:     my ($krbdef,$krbdefdom);
 2696:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2697:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2698:         $krbdef = $domdefaults{'auth_def'};
 2699:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2700:     } else {
 2701:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2702:         my $krbdefdom=$1;
 2703:         $krbdefdom=~tr/a-z/A-Z/;
 2704:         $krbdef = "krb4";
 2705:     }
 2706:     return ($krbdef,$krbdefdom);
 2707: }
 2708: 
 2709: 
 2710: ###############################################################
 2711: ##                Thesaurus Functions                        ##
 2712: ###############################################################
 2713: 
 2714: =pod
 2715: 
 2716: =head1 Thesaurus Functions
 2717: 
 2718: =over 4
 2719: 
 2720: =item * &initialize_keywords()
 2721: 
 2722: Initializes the package variable %Keywords if it is empty.  Uses the
 2723: package variable $thesaurus_db_file.
 2724: 
 2725: =cut
 2726: 
 2727: ###################################################
 2728: 
 2729: sub initialize_keywords {
 2730:     return 1 if (scalar keys(%Keywords));
 2731:     # If we are here, %Keywords is empty, so fill it up
 2732:     #   Make sure the file we need exists...
 2733:     if (! -e $thesaurus_db_file) {
 2734:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2735:                                  " failed because it does not exist");
 2736:         return 0;
 2737:     }
 2738:     #   Set up the hash as a database
 2739:     my %thesaurus_db;
 2740:     if (! tie(%thesaurus_db,'GDBM_File',
 2741:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2742:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2743:                                  $thesaurus_db_file);
 2744:         return 0;
 2745:     } 
 2746:     #  Get the average number of appearances of a word.
 2747:     my $avecount = $thesaurus_db{'average.count'};
 2748:     #  Put keywords (those that appear > average) into %Keywords
 2749:     while (my ($word,$data)=each (%thesaurus_db)) {
 2750:         my ($count,undef) = split /:/,$data;
 2751:         $Keywords{$word}++ if ($count > $avecount);
 2752:     }
 2753:     untie %thesaurus_db;
 2754:     # Remove special values from %Keywords.
 2755:     foreach my $value ('total.count','average.count') {
 2756:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2757:   }
 2758:     return 1;
 2759: }
 2760: 
 2761: ###################################################
 2762: 
 2763: =pod
 2764: 
 2765: =item * &keyword($word)
 2766: 
 2767: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2768: than the average number of times in the thesaurus database.  Calls 
 2769: &initialize_keywords
 2770: 
 2771: =cut
 2772: 
 2773: ###################################################
 2774: 
 2775: sub keyword {
 2776:     return if (!&initialize_keywords());
 2777:     my $word=lc(shift());
 2778:     $word=~s/\W//g;
 2779:     return exists($Keywords{$word});
 2780: }
 2781: 
 2782: ###############################################################
 2783: 
 2784: =pod 
 2785: 
 2786: =item * &get_related_words()
 2787: 
 2788: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2789: an array of words.  If the keyword is not in the thesaurus, an empty array
 2790: will be returned.  The order of the words returned is determined by the
 2791: database which holds them.
 2792: 
 2793: Uses global $thesaurus_db_file.
 2794: 
 2795: =cut
 2796: 
 2797: ###############################################################
 2798: sub get_related_words {
 2799:     my $keyword = shift;
 2800:     my %thesaurus_db;
 2801:     if (! -e $thesaurus_db_file) {
 2802:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2803:                                  "failed because the file does not exist");
 2804:         return ();
 2805:     }
 2806:     if (! tie(%thesaurus_db,'GDBM_File',
 2807:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2808:         return ();
 2809:     } 
 2810:     my @Words=();
 2811:     my $count=0;
 2812:     if (exists($thesaurus_db{$keyword})) {
 2813: 	# The first element is the number of times
 2814: 	# the word appears.  We do not need it now.
 2815: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2816: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2817: 	my $threshold=$mostfrequentcount/10;
 2818:         foreach my $possibleword (@RelatedWords) {
 2819:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2820:             if ($wordcount>$threshold) {
 2821: 		push(@Words,$word);
 2822:                 $count++;
 2823:                 if ($count>10) { last; }
 2824: 	    }
 2825:         }
 2826:     }
 2827:     untie %thesaurus_db;
 2828:     return @Words;
 2829: }
 2830: 
 2831: =pod
 2832: 
 2833: =back
 2834: 
 2835: =cut
 2836: 
 2837: # -------------------------------------------------------------- Plaintext name
 2838: =pod
 2839: 
 2840: =head1 User Name Functions
 2841: 
 2842: =over 4
 2843: 
 2844: =item * &plainname($uname,$udom,$first)
 2845: 
 2846: Takes a users logon name and returns it as a string in
 2847: "first middle last generation" form 
 2848: if $first is set to 'lastname' then it returns it as
 2849: 'lastname generation, firstname middlename' if their is a lastname
 2850: 
 2851: =cut
 2852: 
 2853: 
 2854: ###############################################################
 2855: sub plainname {
 2856:     my ($uname,$udom,$first)=@_;
 2857:     return if (!defined($uname) || !defined($udom));
 2858:     my %names=&getnames($uname,$udom);
 2859:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2860: 					  $names{'middlename'},
 2861: 					  $names{'lastname'},
 2862: 					  $names{'generation'},$first);
 2863:     $name=~s/^\s+//;
 2864:     $name=~s/\s+$//;
 2865:     $name=~s/\s+/ /g;
 2866:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2867:     return $name;
 2868: }
 2869: 
 2870: # -------------------------------------------------------------------- Nickname
 2871: =pod
 2872: 
 2873: =item * &nickname($uname,$udom)
 2874: 
 2875: Gets a users name and returns it as a string as
 2876: 
 2877: "&quot;nickname&quot;"
 2878: 
 2879: if the user has a nickname or
 2880: 
 2881: "first middle last generation"
 2882: 
 2883: if the user does not
 2884: 
 2885: =cut
 2886: 
 2887: sub nickname {
 2888:     my ($uname,$udom)=@_;
 2889:     return if (!defined($uname) || !defined($udom));
 2890:     my %names=&getnames($uname,$udom);
 2891:     my $name=$names{'nickname'};
 2892:     if ($name) {
 2893:        $name='&quot;'.$name.'&quot;'; 
 2894:     } else {
 2895:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2896: 	     $names{'lastname'}.' '.$names{'generation'};
 2897:        $name=~s/\s+$//;
 2898:        $name=~s/\s+/ /g;
 2899:     }
 2900:     return $name;
 2901: }
 2902: 
 2903: sub getnames {
 2904:     my ($uname,$udom)=@_;
 2905:     return if (!defined($uname) || !defined($udom));
 2906:     if ($udom eq 'public' && $uname eq 'public') {
 2907: 	return ('lastname' => &mt('Public'));
 2908:     }
 2909:     my $id=$uname.':'.$udom;
 2910:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2911:     if ($cached) {
 2912: 	return %{$names};
 2913:     } else {
 2914: 	my %loadnames=&Apache::lonnet::get('environment',
 2915:                     ['firstname','middlename','lastname','generation','nickname'],
 2916: 					 $udom,$uname);
 2917: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2918: 	return %loadnames;
 2919:     }
 2920: }
 2921: 
 2922: # -------------------------------------------------------------------- getemails
 2923: 
 2924: =pod
 2925: 
 2926: =item * &getemails($uname,$udom)
 2927: 
 2928: Gets a user's email information and returns it as a hash with keys:
 2929: notification, critnotification, permanentemail
 2930: 
 2931: For notification and critnotification, values are comma-separated lists 
 2932: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2933:  
 2934: 
 2935: =cut
 2936: 
 2937: 
 2938: sub getemails {
 2939:     my ($uname,$udom)=@_;
 2940:     if ($udom eq 'public' && $uname eq 'public') {
 2941: 	return;
 2942:     }
 2943:     if (!$udom) { $udom=$env{'user.domain'}; }
 2944:     if (!$uname) { $uname=$env{'user.name'}; }
 2945:     my $id=$uname.':'.$udom;
 2946:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2947:     if ($cached) {
 2948: 	return %{$names};
 2949:     } else {
 2950: 	my %loadnames=&Apache::lonnet::get('environment',
 2951:                     			   ['notification','critnotification',
 2952: 					    'permanentemail'],
 2953: 					   $udom,$uname);
 2954: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2955: 	return %loadnames;
 2956:     }
 2957: }
 2958: 
 2959: sub flush_email_cache {
 2960:     my ($uname,$udom)=@_;
 2961:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2962:     if (!$uname) { $uname=$env{'user.name'};   }
 2963:     return if ($udom eq 'public' && $uname eq 'public');
 2964:     my $id=$uname.':'.$udom;
 2965:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2966: }
 2967: 
 2968: # -------------------------------------------------------------------- getlangs
 2969: 
 2970: =pod
 2971: 
 2972: =item * &getlangs($uname,$udom)
 2973: 
 2974: Gets a user's language preference and returns it as a hash with key:
 2975: language.
 2976: 
 2977: =cut
 2978: 
 2979: 
 2980: sub getlangs {
 2981:     my ($uname,$udom) = @_;
 2982:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2983:     if (!$uname) { $uname=$env{'user.name'};   }
 2984:     my $id=$uname.':'.$udom;
 2985:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2986:     if ($cached) {
 2987:         return %{$langs};
 2988:     } else {
 2989:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2990:                                            $udom,$uname);
 2991:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2992:         return %loadlangs;
 2993:     }
 2994: }
 2995: 
 2996: sub flush_langs_cache {
 2997:     my ($uname,$udom)=@_;
 2998:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2999:     if (!$uname) { $uname=$env{'user.name'};   }
 3000:     return if ($udom eq 'public' && $uname eq 'public');
 3001:     my $id=$uname.':'.$udom;
 3002:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3003: }
 3004: 
 3005: # ------------------------------------------------------------------ Screenname
 3006: 
 3007: =pod
 3008: 
 3009: =item * &screenname($uname,$udom)
 3010: 
 3011: Gets a users screenname and returns it as a string
 3012: 
 3013: =cut
 3014: 
 3015: sub screenname {
 3016:     my ($uname,$udom)=@_;
 3017:     if ($uname eq $env{'user.name'} &&
 3018: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3019:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3020:     return $names{'screenname'};
 3021: }
 3022: 
 3023: 
 3024: # ------------------------------------------------------------- Confirm Wrapper
 3025: =pod
 3026: 
 3027: =item confirmwrapper
 3028: 
 3029: Wrap messages about completion of operation in box
 3030: 
 3031: =cut
 3032: 
 3033: sub confirmwrapper {
 3034:     my ($message)=@_;
 3035:     if ($message) {
 3036:         return "\n".'<div class="LC_confirm_box">'."\n"
 3037:                .$message."\n"
 3038:                .'</div>'."\n";
 3039:     } else {
 3040:         return $message;
 3041:     }
 3042: }
 3043: 
 3044: # ------------------------------------------------------------- Message Wrapper
 3045: 
 3046: sub messagewrapper {
 3047:     my ($link,$username,$domain,$subject,$text)=@_;
 3048:     return 
 3049:         '<a href="/adm/email?compose=individual&amp;'.
 3050:         'recname='.$username.'&amp;recdom='.$domain.
 3051: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3052:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3053: }
 3054: 
 3055: # --------------------------------------------------------------- Notes Wrapper
 3056: 
 3057: sub noteswrapper {
 3058:     my ($link,$un,$do)=@_;
 3059:     return 
 3060: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3061: }
 3062: 
 3063: # ------------------------------------------------------------- Aboutme Wrapper
 3064: 
 3065: sub aboutmewrapper {
 3066:     my ($link,$username,$domain,$target)=@_;
 3067:     if (!defined($username)  && !defined($domain)) {
 3068:         return;
 3069:     }
 3070:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3071: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3072: }
 3073: 
 3074: # ------------------------------------------------------------ Syllabus Wrapper
 3075: 
 3076: sub syllabuswrapper {
 3077:     my ($linktext,$coursedir,$domain)=@_;
 3078:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3079: }
 3080: 
 3081: # -----------------------------------------------------------------------------
 3082: 
 3083: sub track_student_link {
 3084:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3085:     my $link ="/adm/trackstudent?";
 3086:     my $title = 'View recent activity';
 3087:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3088:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3089:         $link .= "selected_student=$sname:$sdom";
 3090:         $title .= ' of this student';
 3091:     } 
 3092:     if (defined($target) && $target !~ /^\s*$/) {
 3093:         $target = qq{target="$target"};
 3094:     } else {
 3095:         $target = '';
 3096:     }
 3097:     if ($start) { $link.='&amp;start='.$start; }
 3098:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3099:     $title = &mt($title);
 3100:     $linktext = &mt($linktext);
 3101:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3102: 	&help_open_topic('View_recent_activity');
 3103: }
 3104: 
 3105: sub slot_reservations_link {
 3106:     my ($linktext,$sname,$sdom,$target) = @_;
 3107:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3108:     my $title = 'View slot reservation history';
 3109:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3110:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3111:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3112:         $title .= ' of this student';
 3113:     }
 3114:     if (defined($target) && $target !~ /^\s*$/) {
 3115:         $target = qq{target="$target"};
 3116:     } else {
 3117:         $target = '';
 3118:     }
 3119:     $title = &mt($title);
 3120:     $linktext = &mt($linktext);
 3121:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3122: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3123: 
 3124: }
 3125: 
 3126: # ===================================================== Display a student photo
 3127: 
 3128: 
 3129: sub student_image_tag {
 3130:     my ($domain,$user)=@_;
 3131:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3132:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3133: 	return '<img src="'.$imgsrc.'" align="right" />';
 3134:     } else {
 3135: 	return '';
 3136:     }
 3137: }
 3138: 
 3139: =pod
 3140: 
 3141: =back
 3142: 
 3143: =head1 Access .tab File Data
 3144: 
 3145: =over 4
 3146: 
 3147: =item * &languageids() 
 3148: 
 3149: returns list of all language ids
 3150: 
 3151: =cut
 3152: 
 3153: sub languageids {
 3154:     return sort(keys(%language));
 3155: }
 3156: 
 3157: =pod
 3158: 
 3159: =item * &languagedescription() 
 3160: 
 3161: returns description of a specified language id
 3162: 
 3163: =cut
 3164: 
 3165: sub languagedescription {
 3166:     my $code=shift;
 3167:     return  ($supported_language{$code}?'* ':'').
 3168:             $language{$code}.
 3169: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3170: }
 3171: 
 3172: sub plainlanguagedescription {
 3173:     my $code=shift;
 3174:     return $language{$code};
 3175: }
 3176: 
 3177: sub supportedlanguagecode {
 3178:     my $code=shift;
 3179:     return $supported_language{$code};
 3180: }
 3181: 
 3182: =pod
 3183: 
 3184: =item * &copyrightids() 
 3185: 
 3186: returns list of all copyrights
 3187: 
 3188: =cut
 3189: 
 3190: sub copyrightids {
 3191:     return sort(keys(%cprtag));
 3192: }
 3193: 
 3194: =pod
 3195: 
 3196: =item * &copyrightdescription() 
 3197: 
 3198: returns description of a specified copyright id
 3199: 
 3200: =cut
 3201: 
 3202: sub copyrightdescription {
 3203:     return &mt($cprtag{shift(@_)});
 3204: }
 3205: 
 3206: =pod
 3207: 
 3208: =item * &source_copyrightids() 
 3209: 
 3210: returns list of all source copyrights
 3211: 
 3212: =cut
 3213: 
 3214: sub source_copyrightids {
 3215:     return sort(keys(%scprtag));
 3216: }
 3217: 
 3218: =pod
 3219: 
 3220: =item * &source_copyrightdescription() 
 3221: 
 3222: returns description of a specified source copyright id
 3223: 
 3224: =cut
 3225: 
 3226: sub source_copyrightdescription {
 3227:     return &mt($scprtag{shift(@_)});
 3228: }
 3229: 
 3230: =pod
 3231: 
 3232: =item * &filecategories() 
 3233: 
 3234: returns list of all file categories
 3235: 
 3236: =cut
 3237: 
 3238: sub filecategories {
 3239:     return sort(keys(%category_extensions));
 3240: }
 3241: 
 3242: =pod
 3243: 
 3244: =item * &filecategorytypes() 
 3245: 
 3246: returns list of file types belonging to a given file
 3247: category
 3248: 
 3249: =cut
 3250: 
 3251: sub filecategorytypes {
 3252:     my ($cat) = @_;
 3253:     return @{$category_extensions{lc($cat)}};
 3254: }
 3255: 
 3256: =pod
 3257: 
 3258: =item * &fileembstyle() 
 3259: 
 3260: returns embedding style for a specified file type
 3261: 
 3262: =cut
 3263: 
 3264: sub fileembstyle {
 3265:     return $fe{lc(shift(@_))};
 3266: }
 3267: 
 3268: sub filemimetype {
 3269:     return $fm{lc(shift(@_))};
 3270: }
 3271: 
 3272: 
 3273: sub filecategoryselect {
 3274:     my ($name,$value)=@_;
 3275:     return &select_form($value,$name,
 3276:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3277: }
 3278: 
 3279: =pod
 3280: 
 3281: =item * &filedescription() 
 3282: 
 3283: returns description for a specified file type
 3284: 
 3285: =cut
 3286: 
 3287: sub filedescription {
 3288:     my $file_description = $fd{lc(shift())};
 3289:     $file_description =~ s:([\[\]]):~$1:g;
 3290:     return &mt($file_description);
 3291: }
 3292: 
 3293: =pod
 3294: 
 3295: =item * &filedescriptionex() 
 3296: 
 3297: returns description for a specified file type with
 3298: extra formatting
 3299: 
 3300: =cut
 3301: 
 3302: sub filedescriptionex {
 3303:     my $ex=shift;
 3304:     my $file_description = $fd{lc($ex)};
 3305:     $file_description =~ s:([\[\]]):~$1:g;
 3306:     return '.'.$ex.' '.&mt($file_description);
 3307: }
 3308: 
 3309: # End of .tab access
 3310: =pod
 3311: 
 3312: =back
 3313: 
 3314: =cut
 3315: 
 3316: # ------------------------------------------------------------------ File Types
 3317: sub fileextensions {
 3318:     return sort(keys(%fe));
 3319: }
 3320: 
 3321: # ----------------------------------------------------------- Display Languages
 3322: # returns a hash with all desired display languages
 3323: #
 3324: 
 3325: sub display_languages {
 3326:     my %languages=();
 3327:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3328: 	$languages{$lang}=1;
 3329:     }
 3330:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3331:     if ($env{'form.displaylanguage'}) {
 3332: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3333: 	    $languages{$lang}=1;
 3334:         }
 3335:     }
 3336:     return %languages;
 3337: }
 3338: 
 3339: sub languages {
 3340:     my ($possible_langs) = @_;
 3341:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3342:     if (!ref($possible_langs)) {
 3343: 	if( wantarray ) {
 3344: 	    return @preferred_langs;
 3345: 	} else {
 3346: 	    return $preferred_langs[0];
 3347: 	}
 3348:     }
 3349:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3350:     my @preferred_possibilities;
 3351:     foreach my $preferred_lang (@preferred_langs) {
 3352: 	if (exists($possibilities{$preferred_lang})) {
 3353: 	    push(@preferred_possibilities, $preferred_lang);
 3354: 	}
 3355:     }
 3356:     if( wantarray ) {
 3357: 	return @preferred_possibilities;
 3358:     }
 3359:     return $preferred_possibilities[0];
 3360: }
 3361: 
 3362: sub user_lang {
 3363:     my ($touname,$toudom,$fromcid) = @_;
 3364:     my @userlangs;
 3365:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3366:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3367:                     $env{'course.'.$fromcid.'.languages'}));
 3368:     } else {
 3369:         my %langhash = &getlangs($touname,$toudom);
 3370:         if ($langhash{'languages'} ne '') {
 3371:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3372:         } else {
 3373:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3374:             if ($domdefs{'lang_def'} ne '') {
 3375:                 @userlangs = ($domdefs{'lang_def'});
 3376:             }
 3377:         }
 3378:     }
 3379:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3380:     my $user_lh = Apache::localize->get_handle(@languages);
 3381:     return $user_lh;
 3382: }
 3383: 
 3384: 
 3385: ###############################################################
 3386: ##               Student Answer Attempts                     ##
 3387: ###############################################################
 3388: 
 3389: =pod
 3390: 
 3391: =head1 Alternate Problem Views
 3392: 
 3393: =over 4
 3394: 
 3395: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3396:     $getattempt, $regexp, $gradesub)
 3397: 
 3398: Return string with previous attempt on problem. Arguments:
 3399: 
 3400: =over 4
 3401: 
 3402: =item * $symb: Problem, including path
 3403: 
 3404: =item * $username: username of the desired student
 3405: 
 3406: =item * $domain: domain of the desired student
 3407: 
 3408: =item * $course: Course ID
 3409: 
 3410: =item * $getattempt: Leave blank for all attempts, otherwise put
 3411:     something
 3412: 
 3413: =item * $regexp: if string matches this regexp, the string will be
 3414:     sent to $gradesub
 3415: 
 3416: =item * $gradesub: routine that processes the string if it matches $regexp
 3417: 
 3418: =back
 3419: 
 3420: The output string is a table containing all desired attempts, if any.
 3421: 
 3422: =cut
 3423: 
 3424: sub get_previous_attempt {
 3425:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3426:   my $prevattempts='';
 3427:   no strict 'refs';
 3428:   if ($symb) {
 3429:     my (%returnhash)=
 3430:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3431:     if ($returnhash{'version'}) {
 3432:       my %lasthash=();
 3433:       my $version;
 3434:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3435:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3436: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3437:         }
 3438:       }
 3439:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3440:       $prevattempts.='<th>'.&mt('History').'</th>';
 3441:       my (%typeparts,%lasthidden);
 3442:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3443:       foreach my $key (sort(keys(%lasthash))) {
 3444: 	my ($ign,@parts) = split(/\./,$key);
 3445: 	if ($#parts > 0) {
 3446: 	  my $data=$parts[-1];
 3447:           next if ($data eq 'foilorder');
 3448: 	  pop(@parts);
 3449:           if ($data eq 'type') {
 3450:               unless ($showsurv) {
 3451:                   my $id = join(',',@parts);
 3452:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3453:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3454:                       $lasthidden{$ign.'.'.$id} = 1;
 3455:                   }
 3456:               }
 3457:               delete($lasthash{$key});
 3458:           } else {
 3459: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3460:           }
 3461: 	} else {
 3462: 	  if ($#parts == 0) {
 3463: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3464: 	  } else {
 3465: 	    $prevattempts.='<th>'.$ign.'</th>';
 3466: 	  }
 3467: 	}
 3468:       }
 3469:       $prevattempts.=&end_data_table_header_row();
 3470:       if ($getattempt eq '') {
 3471: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3472:             my @hidden;
 3473:             if (%typeparts) {
 3474:                 foreach my $id (keys(%typeparts)) {
 3475:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3476:                         push(@hidden,$id);
 3477:                     }
 3478:                 }
 3479:             }
 3480:             $prevattempts.=&start_data_table_row().
 3481:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3482:             if (@hidden) {
 3483:                 foreach my $key (sort(keys(%lasthash))) {
 3484:                     next if ($key =~ /\.foilorder$/);
 3485:                     my $hide;
 3486:                     foreach my $id (@hidden) {
 3487:                         if ($key =~ /^\Q$id\E/) {
 3488:                             $hide = 1;
 3489:                             last;
 3490:                         }
 3491:                     }
 3492:                     if ($hide) {
 3493:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3494:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3495:                             my $value = &format_previous_attempt_value($key,
 3496:                                              $returnhash{$version.':'.$key});
 3497:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3498:                         } else {
 3499:                             $prevattempts.='<td>&nbsp;</td>';
 3500:                         }
 3501:                     } else {
 3502:                         if ($key =~ /\./) {
 3503:                             my $value = &format_previous_attempt_value($key,
 3504:                                               $returnhash{$version.':'.$key});
 3505:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3506:                         } else {
 3507:                             $prevattempts.='<td>&nbsp;</td>';
 3508:                         }
 3509:                     }
 3510:                 }
 3511:             } else {
 3512: 	        foreach my $key (sort(keys(%lasthash))) {
 3513:                     next if ($key =~ /\.foilorder$/);
 3514: 		    my $value = &format_previous_attempt_value($key,
 3515: 			            $returnhash{$version.':'.$key});
 3516: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3517: 	        }
 3518:             }
 3519: 	    $prevattempts.=&end_data_table_row();
 3520: 	 }
 3521:       }
 3522:       my @currhidden = keys(%lasthidden);
 3523:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3524:       foreach my $key (sort(keys(%lasthash))) {
 3525:           next if ($key =~ /\.foilorder$/);
 3526:           if (%typeparts) {
 3527:               my $hidden;
 3528:               foreach my $id (@currhidden) {
 3529:                   if ($key =~ /^\Q$id\E/) {
 3530:                       $hidden = 1;
 3531:                       last;
 3532:                   }
 3533:               }
 3534:               if ($hidden) {
 3535:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3536:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3537:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3538:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3539:                           $value = &$gradesub($value);
 3540:                       }
 3541:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3542:                   } else {
 3543:                       $prevattempts.='<td>&nbsp;</td>';
 3544:                   }
 3545:               } else {
 3546:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3547:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3548:                       $value = &$gradesub($value);
 3549:                   }
 3550:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3551:               }
 3552:           } else {
 3553: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3554: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3555:                   $value = &$gradesub($value);
 3556:               }
 3557: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3558:           }
 3559:       }
 3560:       $prevattempts.= &end_data_table_row().&end_data_table();
 3561:     } else {
 3562:       $prevattempts=
 3563: 	  &start_data_table().&start_data_table_row().
 3564: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3565: 	  &end_data_table_row().&end_data_table();
 3566:     }
 3567:   } else {
 3568:     $prevattempts=
 3569: 	  &start_data_table().&start_data_table_row().
 3570: 	  '<td>'.&mt('No data.').'</td>'.
 3571: 	  &end_data_table_row().&end_data_table();
 3572:   }
 3573: }
 3574: 
 3575: sub format_previous_attempt_value {
 3576:     my ($key,$value) = @_;
 3577:     if ($key =~ /timestamp/) {
 3578: 	$value = &Apache::lonlocal::locallocaltime($value);
 3579:     } elsif (ref($value) eq 'ARRAY') {
 3580: 	$value = '('.join(', ', @{ $value }).')';
 3581:     } elsif ($key =~ /answerstring$/) {
 3582:         my %answers = &Apache::lonnet::str2hash($value);
 3583:         my @anskeys = sort(keys(%answers));
 3584:         if (@anskeys == 1) {
 3585:             my $answer = $answers{$anskeys[0]};
 3586:             if ($answer =~ m{\0}) {
 3587:                 $answer =~ s{\0}{,}g;
 3588:             }
 3589:             my $tag_internal_answer_name = 'INTERNAL';
 3590:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3591:                 $value = $answer; 
 3592:             } else {
 3593:                 $value = $anskeys[0].'='.$answer;
 3594:             }
 3595:         } else {
 3596:             foreach my $ans (@anskeys) {
 3597:                 my $answer = $answers{$ans};
 3598:                 if ($answer =~ m{\0}) {
 3599:                     $answer =~ s{\0}{,}g;
 3600:                 }
 3601:                 $value .=  $ans.'='.$answer.'<br />';;
 3602:             } 
 3603:         }
 3604:     } else {
 3605: 	$value = &unescape($value);
 3606:     }
 3607:     return $value;
 3608: }
 3609: 
 3610: 
 3611: sub relative_to_absolute {
 3612:     my ($url,$output)=@_;
 3613:     my $parser=HTML::TokeParser->new(\$output);
 3614:     my $token;
 3615:     my $thisdir=$url;
 3616:     my @rlinks=();
 3617:     while ($token=$parser->get_token) {
 3618: 	if ($token->[0] eq 'S') {
 3619: 	    if ($token->[1] eq 'a') {
 3620: 		if ($token->[2]->{'href'}) {
 3621: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3622: 		}
 3623: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3624: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3625: 	    } elsif ($token->[1] eq 'base') {
 3626: 		$thisdir=$token->[2]->{'href'};
 3627: 	    }
 3628: 	}
 3629:     }
 3630:     $thisdir=~s-/[^/]*$--;
 3631:     foreach my $link (@rlinks) {
 3632: 	unless (($link=~/^https?\:\/\//i) ||
 3633: 		($link=~/^\//) ||
 3634: 		($link=~/^javascript:/i) ||
 3635: 		($link=~/^mailto:/i) ||
 3636: 		($link=~/^\#/)) {
 3637: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3638: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3639: 	}
 3640:     }
 3641: # -------------------------------------------------- Deal with Applet codebases
 3642:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3643:     return $output;
 3644: }
 3645: 
 3646: =pod
 3647: 
 3648: =item * &get_student_view()
 3649: 
 3650: show a snapshot of what student was looking at
 3651: 
 3652: =cut
 3653: 
 3654: sub get_student_view {
 3655:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3656:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3657:   my (%form);
 3658:   my @elements=('symb','courseid','domain','username');
 3659:   foreach my $element (@elements) {
 3660:       $form{'grade_'.$element}=eval '$'.$element #'
 3661:   }
 3662:   if (defined($moreenv)) {
 3663:       %form=(%form,%{$moreenv});
 3664:   }
 3665:   if (defined($target)) { $form{'grade_target'} = $target; }
 3666:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3667:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3668:   $userview=~s/\<body[^\>]*\>//gi;
 3669:   $userview=~s/\<\/body\>//gi;
 3670:   $userview=~s/\<html\>//gi;
 3671:   $userview=~s/\<\/html\>//gi;
 3672:   $userview=~s/\<head\>//gi;
 3673:   $userview=~s/\<\/head\>//gi;
 3674:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3675:   $userview=&relative_to_absolute($feedurl,$userview);
 3676:   if (wantarray) {
 3677:      return ($userview,$response);
 3678:   } else {
 3679:      return $userview;
 3680:   }
 3681: }
 3682: 
 3683: sub get_student_view_with_retries {
 3684:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3685: 
 3686:     my $ok = 0;                 # True if we got a good response.
 3687:     my $content;
 3688:     my $response;
 3689: 
 3690:     # Try to get the student_view done. within the retries count:
 3691:     
 3692:     do {
 3693:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3694:          $ok      = $response->is_success;
 3695:          if (!$ok) {
 3696:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3697:          }
 3698:          $retries--;
 3699:     } while (!$ok && ($retries > 0));
 3700:     
 3701:     if (!$ok) {
 3702:        $content = '';          # On error return an empty content.
 3703:     }
 3704:     if (wantarray) {
 3705:        return ($content, $response);
 3706:     } else {
 3707:        return $content;
 3708:     }
 3709: }
 3710: 
 3711: =pod
 3712: 
 3713: =item * &get_student_answers() 
 3714: 
 3715: show a snapshot of how student was answering problem
 3716: 
 3717: =cut
 3718: 
 3719: sub get_student_answers {
 3720:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3721:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3722:   my (%moreenv);
 3723:   my @elements=('symb','courseid','domain','username');
 3724:   foreach my $element (@elements) {
 3725:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3726:   }
 3727:   $moreenv{'grade_target'}='answer';
 3728:   %moreenv=(%form,%moreenv);
 3729:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3730:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3731:   return $userview;
 3732: }
 3733: 
 3734: =pod
 3735: 
 3736: =item * &submlink()
 3737: 
 3738: Inputs: $text $uname $udom $symb $target
 3739: 
 3740: Returns: A link to grades.pm such as to see the SUBM view of a student
 3741: 
 3742: =cut
 3743: 
 3744: ###############################################
 3745: sub submlink {
 3746:     my ($text,$uname,$udom,$symb,$target)=@_;
 3747:     if (!($uname && $udom)) {
 3748: 	(my $cursymb, my $courseid,$udom,$uname)=
 3749: 	    &Apache::lonnet::whichuser($symb);
 3750: 	if (!$symb) { $symb=$cursymb; }
 3751:     }
 3752:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3753:     $symb=&escape($symb);
 3754:     if ($target) { $target=" target=\"$target\""; }
 3755:     return
 3756:         '<a href="/adm/grades?command=submission'.
 3757:         '&amp;symb='.$symb.
 3758:         '&amp;student='.$uname.
 3759:         '&amp;userdom='.$udom.'"'.
 3760:         $target.'>'.$text.'</a>';
 3761: }
 3762: ##############################################
 3763: 
 3764: =pod
 3765: 
 3766: =item * &pgrdlink()
 3767: 
 3768: Inputs: $text $uname $udom $symb $target
 3769: 
 3770: Returns: A link to grades.pm such as to see the PGRD view of a student
 3771: 
 3772: =cut
 3773: 
 3774: ###############################################
 3775: sub pgrdlink {
 3776:     my $link=&submlink(@_);
 3777:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3778:     return $link;
 3779: }
 3780: ##############################################
 3781: 
 3782: =pod
 3783: 
 3784: =item * &pprmlink()
 3785: 
 3786: Inputs: $text $uname $udom $symb $target
 3787: 
 3788: Returns: A link to parmset.pm such as to see the PPRM view of a
 3789: student and a specific resource
 3790: 
 3791: =cut
 3792: 
 3793: ###############################################
 3794: sub pprmlink {
 3795:     my ($text,$uname,$udom,$symb,$target)=@_;
 3796:     if (!($uname && $udom)) {
 3797: 	(my $cursymb, my $courseid,$udom,$uname)=
 3798: 	    &Apache::lonnet::whichuser($symb);
 3799: 	if (!$symb) { $symb=$cursymb; }
 3800:     }
 3801:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3802:     $symb=&escape($symb);
 3803:     if ($target) { $target="target=\"$target\""; }
 3804:     return '<a href="/adm/parmset?command=set&amp;'.
 3805: 	'symb='.$symb.'&amp;uname='.$uname.
 3806: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3807: }
 3808: ##############################################
 3809: 
 3810: =pod
 3811: 
 3812: =back
 3813: 
 3814: =cut
 3815: 
 3816: ###############################################
 3817: 
 3818: 
 3819: sub timehash {
 3820:     my ($thistime) = @_;
 3821:     my $timezone = &Apache::lonlocal::gettimezone();
 3822:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3823:                      ->set_time_zone($timezone);
 3824:     my $wday = $dt->day_of_week();
 3825:     if ($wday == 7) { $wday = 0; }
 3826:     return ( 'second' => $dt->second(),
 3827:              'minute' => $dt->minute(),
 3828:              'hour'   => $dt->hour(),
 3829:              'day'     => $dt->day_of_month(),
 3830:              'month'   => $dt->month(),
 3831:              'year'    => $dt->year(),
 3832:              'weekday' => $wday,
 3833:              'dayyear' => $dt->day_of_year(),
 3834:              'dlsav'   => $dt->is_dst() );
 3835: }
 3836: 
 3837: sub utc_string {
 3838:     my ($date)=@_;
 3839:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3840: }
 3841: 
 3842: sub maketime {
 3843:     my %th=@_;
 3844:     my ($epoch_time,$timezone,$dt);
 3845:     $timezone = &Apache::lonlocal::gettimezone();
 3846:     eval {
 3847:         $dt = DateTime->new( year   => $th{'year'},
 3848:                              month  => $th{'month'},
 3849:                              day    => $th{'day'},
 3850:                              hour   => $th{'hour'},
 3851:                              minute => $th{'minute'},
 3852:                              second => $th{'second'},
 3853:                              time_zone => $timezone,
 3854:                          );
 3855:     };
 3856:     if (!$@) {
 3857:         $epoch_time = $dt->epoch;
 3858:         if ($epoch_time) {
 3859:             return $epoch_time;
 3860:         }
 3861:     }
 3862:     return POSIX::mktime(
 3863:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3864:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3865: }
 3866: 
 3867: #########################################
 3868: 
 3869: sub findallcourses {
 3870:     my ($roles,$uname,$udom) = @_;
 3871:     my %roles;
 3872:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3873:     my %courses;
 3874:     my $now=time;
 3875:     if (!defined($uname)) {
 3876:         $uname = $env{'user.name'};
 3877:     }
 3878:     if (!defined($udom)) {
 3879:         $udom = $env{'user.domain'};
 3880:     }
 3881:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3882:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3883:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3884:                                               $extra);
 3885:         if (!%roles) {
 3886:             %roles = (
 3887:                        cc => 1,
 3888:                        co => 1,
 3889:                        in => 1,
 3890:                        ep => 1,
 3891:                        ta => 1,
 3892:                        cr => 1,
 3893:                        st => 1,
 3894:              );
 3895:         }
 3896:         foreach my $entry (keys(%roleshash)) {
 3897:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3898:             if ($trole =~ /^cr/) { 
 3899:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3900:             } else {
 3901:                 next if (!exists($roles{$trole}));
 3902:             }
 3903:             if ($tend) {
 3904:                 next if ($tend < $now);
 3905:             }
 3906:             if ($tstart) {
 3907:                 next if ($tstart > $now);
 3908:             }
 3909:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3910:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3911:             if ($secpart eq '') {
 3912:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3913:                 $sec = 'none';
 3914:                 $realsec = '';
 3915:             } else {
 3916:                 $cnum = $cnumpart;
 3917:                 ($sec,$role) = split(/_/,$secpart);
 3918:                 $realsec = $sec;
 3919:             }
 3920:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3921:         }
 3922:     } else {
 3923:         foreach my $key (keys(%env)) {
 3924: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3925:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3926: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3927: 	        next if ($role eq 'ca' || $role eq 'aa');
 3928: 	        next if (%roles && !exists($roles{$role}));
 3929: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3930:                 my $active=1;
 3931:                 if ($starttime) {
 3932: 		    if ($now<$starttime) { $active=0; }
 3933:                 }
 3934:                 if ($endtime) {
 3935:                     if ($now>$endtime) { $active=0; }
 3936:                 }
 3937:                 if ($active) {
 3938:                     if ($sec eq '') {
 3939:                         $sec = 'none';
 3940:                     }
 3941:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3942:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3943:                 }
 3944:             }
 3945:         }
 3946:     }
 3947:     return %courses;
 3948: }
 3949: 
 3950: ###############################################
 3951: 
 3952: sub blockcheck {
 3953:     my ($setters,$activity,$uname,$udom) = @_;
 3954: 
 3955:     if (!defined($udom)) {
 3956:         $udom = $env{'user.domain'};
 3957:     }
 3958:     if (!defined($uname)) {
 3959:         $uname = $env{'user.name'};
 3960:     }
 3961: 
 3962:     # If uname and udom are for a course, check for blocks in the course.
 3963: 
 3964:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3965:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3966:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3967:         return ($startblock,$endblock);
 3968:     }
 3969: 
 3970:     my $startblock = 0;
 3971:     my $endblock = 0;
 3972:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3973: 
 3974:     # If uname is for a user, and activity is course-specific, i.e.,
 3975:     # boards, chat or groups, check for blocking in current course only.
 3976: 
 3977:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3978:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3979:         foreach my $key (keys(%live_courses)) {
 3980:             if ($key ne $env{'request.course.id'}) {
 3981:                 delete($live_courses{$key});
 3982:             }
 3983:         }
 3984:     }
 3985: 
 3986:     my $otheruser = 0;
 3987:     my %own_courses;
 3988:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3989:         # Resource belongs to user other than current user.
 3990:         $otheruser = 1;
 3991:         # Gather courses for current user
 3992:         %own_courses = 
 3993:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3994:     }
 3995: 
 3996:     # Gather active course roles - course coordinator, instructor, 
 3997:     # exam proctor, ta, student, or custom role.
 3998: 
 3999:     foreach my $course (keys(%live_courses)) {
 4000:         my ($cdom,$cnum);
 4001:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4002:             $cdom = $env{'course.'.$course.'.domain'};
 4003:             $cnum = $env{'course.'.$course.'.num'};
 4004:         } else {
 4005:             ($cdom,$cnum) = split(/_/,$course); 
 4006:         }
 4007:         my $no_ownblock = 0;
 4008:         my $no_userblock = 0;
 4009:         if ($otheruser && $activity ne 'com') {
 4010:             # Check if current user has 'evb' priv for this
 4011:             if (defined($own_courses{$course})) {
 4012:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4013:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4014:                     if ($sec ne 'none') {
 4015:                         $checkrole .= '/'.$sec;
 4016:                     }
 4017:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4018:                         $no_ownblock = 1;
 4019:                         last;
 4020:                     }
 4021:                 }
 4022:             }
 4023:             # if they have 'evb' priv and are currently not playing student
 4024:             next if (($no_ownblock) &&
 4025:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4026:         }
 4027:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4028:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4029:             if ($sec ne 'none') {
 4030:                 $checkrole .= '/'.$sec;
 4031:             }
 4032:             if ($otheruser) {
 4033:                 # Resource belongs to user other than current user.
 4034:                 # Assemble privs for that user, and check for 'evb' priv.
 4035:                 my ($trole,$tdom,$tnum,$tsec);
 4036:                 my $entry = $live_courses{$course}{$sec};
 4037:                 if ($entry =~ /^cr/) {
 4038:                     ($trole,$tdom,$tnum,$tsec) = 
 4039:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4040:                 } else {
 4041:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4042:                 }
 4043:                 my ($spec,$area,$trest,%allroles,%userroles);
 4044:                 $area = '/'.$tdom.'/'.$tnum;
 4045:                 $trest = $tnum;
 4046:                 if ($tsec ne '') {
 4047:                     $area .= '/'.$tsec;
 4048:                     $trest .= '/'.$tsec;
 4049:                 }
 4050:                 $spec = $trole.'.'.$area;
 4051:                 if ($trole =~ /^cr/) {
 4052:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4053:                                                       $tdom,$spec,$trest,$area);
 4054:                 } else {
 4055:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4056:                                                        $tdom,$spec,$trest,$area);
 4057:                 }
 4058:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4059:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4060:                     if ($1) {
 4061:                         $no_userblock = 1;
 4062:                         last;
 4063:                     }
 4064:                 }
 4065:             } else {
 4066:                 # Resource belongs to current user
 4067:                 # Check for 'evb' priv via lonnet::allowed().
 4068:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4069:                     $no_ownblock = 1;
 4070:                     last;
 4071:                 }
 4072:             }
 4073:         }
 4074:         # if they have the evb priv and are currently not playing student
 4075:         next if (($no_ownblock) &&
 4076:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4077:         next if ($no_userblock);
 4078: 
 4079:         # Retrieve blocking times and identity of locker for course
 4080:         # of specified user, unless user has 'evb' privilege.
 4081:         
 4082:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4083:         if (($start != 0) && 
 4084:             (($startblock == 0) || ($startblock > $start))) {
 4085:             $startblock = $start;
 4086:         }
 4087:         if (($end != 0)  &&
 4088:             (($endblock == 0) || ($endblock < $end))) {
 4089:             $endblock = $end;
 4090:         }
 4091:     }
 4092:     return ($startblock,$endblock);
 4093: }
 4094: 
 4095: sub get_blocks {
 4096:     my ($setters,$activity,$cdom,$cnum) = @_;
 4097:     my $startblock = 0;
 4098:     my $endblock = 0;
 4099:     my $course = $cdom.'_'.$cnum;
 4100:     $setters->{$course} = {};
 4101:     $setters->{$course}{'staff'} = [];
 4102:     $setters->{$course}{'times'} = [];
 4103:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4104:     foreach my $record (keys(%records)) {
 4105:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4106:         if ($start <= time && $end >= time) {
 4107:             my ($staff_name,$staff_dom,$title,$blocks) =
 4108:                 &parse_block_record($records{$record});
 4109:             if ($blocks->{$activity} eq 'on') {
 4110:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4111:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4112:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4113:                     $startblock = $start;
 4114:                 }
 4115:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4116:                     $endblock = $end;
 4117:                 }
 4118:             }
 4119:         }
 4120:     }
 4121:     return ($startblock,$endblock);
 4122: }
 4123: 
 4124: sub parse_block_record {
 4125:     my ($record) = @_;
 4126:     my ($setuname,$setudom,$title,$blocks);
 4127:     if (ref($record) eq 'HASH') {
 4128:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4129:         $title = &unescape($record->{'event'});
 4130:         $blocks = $record->{'blocks'};
 4131:     } else {
 4132:         my @data = split(/:/,$record,3);
 4133:         if (scalar(@data) eq 2) {
 4134:             $title = $data[1];
 4135:             ($setuname,$setudom) = split(/@/,$data[0]);
 4136:         } else {
 4137:             ($setuname,$setudom,$title) = @data;
 4138:         }
 4139:         $blocks = { 'com' => 'on' };
 4140:     }
 4141:     return ($setuname,$setudom,$title,$blocks);
 4142: }
 4143: 
 4144: sub blocking_status {
 4145:   my ($activity,$uname,$udom) = @_;
 4146:   my %setters;
 4147: 
 4148:   # check for active blocking
 4149:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4150: 
 4151:   my $blocked = $startblock && $endblock ? 1 : 0;
 4152: 
 4153:   # caller just wants to know whether a block is active
 4154:   if (!wantarray) { return $blocked; }
 4155: 
 4156:   # build a link to a popup window containing the details
 4157:   my $querystring  = "?activity=$activity";
 4158:   # $uname and $udom decide whose portfolio the user is trying to look at
 4159:      $querystring .= "&amp;udom=$udom"      if $udom;
 4160:      $querystring .= "&amp;uname=$uname"    if $uname;
 4161: 
 4162:   my $output .= <<'END_MYBLOCK';
 4163:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4164:         var options = "width=" + w + ",height=" + h + ",";
 4165:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4166:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4167:         var newWin = window.open(url, wdwName, options);
 4168:         newWin.focus();
 4169:     }
 4170: END_MYBLOCK
 4171: 
 4172:   $output = Apache::lonhtmlcommon::scripttag($output);
 4173:   
 4174:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4175:   my $text = mt('Communication Blocked');
 4176: 
 4177:   $output .= <<"END_BLOCK";
 4178: <div class='LC_comblock'>
 4179:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4180:   title='$text'>
 4181:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4182:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4183:   title='$text'>$text</a>
 4184: </div>
 4185: 
 4186: END_BLOCK
 4187: 
 4188:   return ($blocked, $output);
 4189: }
 4190: 
 4191: ###############################################
 4192: 
 4193: sub check_ip_acc {
 4194:     my ($acc)=@_;
 4195:     &Apache::lonxml::debug("acc is $acc");
 4196:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4197:         return 1;
 4198:     }
 4199:     my $allowed=0;
 4200:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4201: 
 4202:     my $name;
 4203:     foreach my $pattern (split(',',$acc)) {
 4204:         $pattern =~ s/^\s*//;
 4205:         $pattern =~ s/\s*$//;
 4206:         if ($pattern =~ /\*$/) {
 4207:             #35.8.*
 4208:             $pattern=~s/\*//;
 4209:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4210:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4211:             #35.8.3.[34-56]
 4212:             my $low=$2;
 4213:             my $high=$3;
 4214:             $pattern=$1;
 4215:             if ($ip =~ /^\Q$pattern\E/) {
 4216:                 my $last=(split(/\./,$ip))[3];
 4217:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4218:             }
 4219:         } elsif ($pattern =~ /^\*/) {
 4220:             #*.msu.edu
 4221:             $pattern=~s/\*//;
 4222:             if (!defined($name)) {
 4223:                 use Socket;
 4224:                 my $netaddr=inet_aton($ip);
 4225:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4226:             }
 4227:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4228:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4229:             #127.0.0.1
 4230:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4231:         } else {
 4232:             #some.name.com
 4233:             if (!defined($name)) {
 4234:                 use Socket;
 4235:                 my $netaddr=inet_aton($ip);
 4236:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4237:             }
 4238:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4239:         }
 4240:         if ($allowed) { last; }
 4241:     }
 4242:     return $allowed;
 4243: }
 4244: 
 4245: ###############################################
 4246: 
 4247: =pod
 4248: 
 4249: =head1 Domain Template Functions
 4250: 
 4251: =over 4
 4252: 
 4253: =item * &determinedomain()
 4254: 
 4255: Inputs: $domain (usually will be undef)
 4256: 
 4257: Returns: Determines which domain should be used for designs
 4258: 
 4259: =cut
 4260: 
 4261: ###############################################
 4262: sub determinedomain {
 4263:     my $domain=shift;
 4264:     if (! $domain) {
 4265:         # Determine domain if we have not been given one
 4266:         $domain = &Apache::lonnet::default_login_domain();
 4267:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4268:         if ($env{'request.role.domain'}) { 
 4269:             $domain=$env{'request.role.domain'}; 
 4270:         }
 4271:     }
 4272:     return $domain;
 4273: }
 4274: ###############################################
 4275: 
 4276: sub devalidate_domconfig_cache {
 4277:     my ($udom)=@_;
 4278:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4279: }
 4280: 
 4281: # ---------------------- Get domain configuration for a domain
 4282: sub get_domainconf {
 4283:     my ($udom) = @_;
 4284:     my $cachetime=1800;
 4285:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4286:     if (defined($cached)) { return %{$result}; }
 4287: 
 4288:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4289: 					     ['login','rolecolors','autoenroll'],$udom);
 4290:     my (%designhash,%legacy);
 4291:     if (keys(%domconfig) > 0) {
 4292:         if (ref($domconfig{'login'}) eq 'HASH') {
 4293:             if (keys(%{$domconfig{'login'}})) {
 4294:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4295:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4296:                         if ($key eq 'loginvia') {
 4297:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4298:                                 my @ids = &Apache::lonnet::current_machine_ids();
 4299:                                 foreach my $hostname (@ids) {
 4300:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4301:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4302:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4303:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4304:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4305: 
 4306:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4307:                                             } else {
 4308:                                                  $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4309:                                             }
 4310:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4311:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4312:                                             }
 4313:                                         }
 4314:                                     }
 4315:                                 }
 4316:                             }
 4317:                         } else {
 4318:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4319:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4320:                                     $domconfig{'login'}{$key}{$img};
 4321:                             }
 4322:                         }
 4323:                     } else {
 4324:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4325:                     }
 4326:                 }
 4327:             } else {
 4328:                 $legacy{'login'} = 1;
 4329:             }
 4330:         } else {
 4331:             $legacy{'login'} = 1;
 4332:         }
 4333:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4334:             if (keys(%{$domconfig{'rolecolors'}})) {
 4335:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4336:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4337:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4338:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4339:                         }
 4340:                     }
 4341:                 }
 4342:             } else {
 4343:                 $legacy{'rolecolors'} = 1;
 4344:             }
 4345:         } else {
 4346:             $legacy{'rolecolors'} = 1;
 4347:         }
 4348:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4349:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4350:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4351:             }
 4352:         }
 4353:         if (keys(%legacy) > 0) {
 4354:             my %legacyhash = &get_legacy_domconf($udom);
 4355:             foreach my $item (keys(%legacyhash)) {
 4356:                 if ($item =~ /^\Q$udom\E\.login/) {
 4357:                     if ($legacy{'login'}) { 
 4358:                         $designhash{$item} = $legacyhash{$item};
 4359:                     }
 4360:                 } else {
 4361:                     if ($legacy{'rolecolors'}) {
 4362:                         $designhash{$item} = $legacyhash{$item};
 4363:                     }
 4364:                 }
 4365:             }
 4366:         }
 4367:     } else {
 4368:         %designhash = &get_legacy_domconf($udom); 
 4369:     }
 4370:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4371: 				  $cachetime);
 4372:     return %designhash;
 4373: }
 4374: 
 4375: sub get_legacy_domconf {
 4376:     my ($udom) = @_;
 4377:     my %legacyhash;
 4378:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4379:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4380:     if (-e $designfile) {
 4381:         if ( open (my $fh,"<$designfile") ) {
 4382:             while (my $line = <$fh>) {
 4383:                 next if ($line =~ /^\#/);
 4384:                 chomp($line);
 4385:                 my ($key,$val)=(split(/\=/,$line));
 4386:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4387:             }
 4388:             close($fh);
 4389:         }
 4390:     }
 4391:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4392:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4393:     }
 4394:     return %legacyhash;
 4395: }
 4396: 
 4397: =pod
 4398: 
 4399: =item * &domainlogo()
 4400: 
 4401: Inputs: $domain (usually will be undef)
 4402: 
 4403: Returns: A link to a domain logo, if the domain logo exists.
 4404: If the domain logo does not exist, a description of the domain.
 4405: 
 4406: =cut
 4407: 
 4408: ###############################################
 4409: sub domainlogo {
 4410:     my $domain = &determinedomain(shift);
 4411:     my %designhash = &get_domainconf($domain);    
 4412:     # See if there is a logo
 4413:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4414:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4415:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4416: 	    if ($imgsrc =~ m{^/res/}) {
 4417: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4418: 		&Apache::lonnet::repcopy($local_name);
 4419: 	    }
 4420: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4421:         } 
 4422:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4423:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4424:         return &Apache::lonnet::domain($domain,'description');
 4425:     } else {
 4426:         return '';
 4427:     }
 4428: }
 4429: ##############################################
 4430: 
 4431: =pod
 4432: 
 4433: =item * &designparm()
 4434: 
 4435: Inputs: $which parameter; $domain (usually will be undef)
 4436: 
 4437: Returns: value of designparamter $which
 4438: 
 4439: =cut
 4440: 
 4441: 
 4442: ##############################################
 4443: sub designparm {
 4444:     my ($which,$domain)=@_;
 4445:     if (exists($env{'environment.color.'.$which})) {
 4446:         return $env{'environment.color.'.$which};
 4447:     }
 4448:     $domain=&determinedomain($domain);
 4449:     my %domdesign = &get_domainconf($domain);
 4450:     my $output;
 4451:     if ($domdesign{$domain.'.'.$which} ne '') {
 4452:         $output = $domdesign{$domain.'.'.$which};
 4453:     } else {
 4454:         $output = $defaultdesign{$which};
 4455:     }
 4456:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4457:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4458:         if ($output =~ m{^/(adm|res)/}) {
 4459:             if ($output =~ m{^/res/}) {
 4460:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4461:                 &Apache::lonnet::repcopy($local_name);
 4462:             }
 4463:             $output = &lonhttpdurl($output);
 4464:         }
 4465:     }
 4466:     return $output;
 4467: }
 4468: 
 4469: ##############################################
 4470: =pod
 4471: 
 4472: =item * &authorspace()
 4473: 
 4474: Inputs: ./.
 4475: 
 4476: Returns: Path to the Construction Space of the current user's
 4477:          accessed author space
 4478:          The author space will be that of the current user
 4479:          when accessing the own author space
 4480:          and that of the co-author/assistent co-author
 4481:          when accessing the co-author's/assistent co-author's
 4482:          space
 4483: 
 4484: =cut
 4485: 
 4486: sub authorspace {
 4487:     my $caname = '';
 4488:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4489:         (undef,$caname) =
 4490:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4491:     } else {
 4492:         $caname = $env{'user.name'};
 4493:     }
 4494:     return '/priv/'.$caname.'/';
 4495: }
 4496: 
 4497: ##############################################
 4498: =pod
 4499: 
 4500: =item * &head_subbox()
 4501: 
 4502: Inputs: $content (contains HTML code with page functions, etc.)
 4503: 
 4504: Returns: HTML div with $content
 4505:          To be included in page header
 4506: 
 4507: =cut
 4508: 
 4509: sub head_subbox {
 4510:     my ($content)=@_;
 4511:     my $output =
 4512:         '<div class="LC_head_subbox">'
 4513:        .$content
 4514:        .'</div>'
 4515: }
 4516: 
 4517: ##############################################
 4518: =pod
 4519: 
 4520: =item * &CSTR_pageheader()
 4521: 
 4522: Inputs: ./.
 4523: 
 4524: Returns: HTML div with CSTR path and recent box
 4525:          To be included on Construction Space pages
 4526: 
 4527: =cut
 4528: 
 4529: sub CSTR_pageheader {
 4530:     # this is for resources; directories have customtitle, and crumbs
 4531:             # and select recent are created in lonpubdir.pm  
 4532:     my ($uname,$thisdisfn)=
 4533:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4534:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4535:     $formaction=~s/\/+/\//g;
 4536: 
 4537:     my $parentpath = '';
 4538:     my $lastitem = '';
 4539:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4540:         $parentpath = $1;
 4541:         $lastitem = $2;
 4542:     } else {
 4543:         $lastitem = $thisdisfn;
 4544:     }
 4545: 
 4546:     my $output =
 4547:          '<div>'
 4548:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4549:         .'<b>'.&mt('Construction Space:').'</b> '
 4550:         .'<form name="dirs" method="post" action="'.$formaction
 4551:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4552:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4553: 
 4554:     if ($lastitem) {
 4555:         $output .=
 4556:              '<span class="LC_filename">'
 4557:             .$lastitem
 4558:             .'</span>';
 4559:     }
 4560:     $output .=
 4561:          '<br />'
 4562:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4563:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4564:         .'</form>'
 4565:         .&Apache::lonmenu::constspaceform()
 4566:         .'</div>';
 4567: 
 4568:     return $output;
 4569: }
 4570: 
 4571: ###############################################
 4572: ###############################################
 4573: 
 4574: =pod
 4575: 
 4576: =back
 4577: 
 4578: =head1 HTML Helpers
 4579: 
 4580: =over 4
 4581: 
 4582: =item * &bodytag()
 4583: 
 4584: Returns a uniform header for LON-CAPA web pages.
 4585: 
 4586: Inputs: 
 4587: 
 4588: =over 4
 4589: 
 4590: =item * $title, A title to be displayed on the page.
 4591: 
 4592: =item * $function, the current role (can be undef).
 4593: 
 4594: =item * $addentries, extra parameters for the <body> tag.
 4595: 
 4596: =item * $bodyonly, if defined, only return the <body> tag.
 4597: 
 4598: =item * $domain, if defined, force a given domain.
 4599: 
 4600: =item * $forcereg, if page should register as content page (relevant for 
 4601:             text interface only)
 4602: 
 4603: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4604:                      navigational links
 4605: 
 4606: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4607: 
 4608: =item * $args, optional argument valid values are
 4609:             no_auto_mt_title -> prevents &mt()ing the title arg
 4610:             inherit_jsmath -> when creating popup window in a page,
 4611:                               should it have jsmath forced on by the
 4612:                               current page
 4613: 
 4614: =back
 4615: 
 4616: Returns: A uniform header for LON-CAPA web pages.  
 4617: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4618: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4619: other decorations will be returned.
 4620: 
 4621: =cut
 4622: 
 4623: sub bodytag {
 4624:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4625:         $no_nav_bar,$bgcolor,$args)=@_;
 4626: 
 4627:     my $public;
 4628:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4629:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4630:         $public = 1;
 4631:     }
 4632:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4633: 
 4634:     $function = &get_users_function() if (!$function);
 4635:     my $img =    &designparm($function.'.img',$domain);
 4636:     my $font =   &designparm($function.'.font',$domain);
 4637:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4638: 
 4639:     my %design = ( 'style'   => 'margin-top: 0',
 4640: 		   'bgcolor' => $pgbg,
 4641: 		   'text'    => $font,
 4642:                    'alink'   => &designparm($function.'.alink',$domain),
 4643: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4644: 		   'link'    => &designparm($function.'.link',$domain),);
 4645:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4646: 
 4647:  # role and realm
 4648:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4649:     if ($role  eq 'ca') {
 4650:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4651:         $realm = &plainname($rname,$rdom);
 4652:     } 
 4653: # realm
 4654:     if ($env{'request.course.id'}) {
 4655:         if ($env{'request.role'} !~ /^cr/) {
 4656:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4657:         }
 4658:         if ($env{'request.course.sec'}) {
 4659:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4660:         }   
 4661: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4662:     } else {
 4663:         $role = &Apache::lonnet::plaintext($role);
 4664:     }
 4665: 
 4666:     if (!$realm) { $realm='&nbsp;'; }
 4667: 
 4668:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4669: 
 4670: # construct main body tag
 4671:     my $bodytag = "<body $extra_body_attr>".
 4672: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4673: 
 4674:     if ($bodyonly) {
 4675:         return $bodytag;
 4676:     } 
 4677: 
 4678:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4679:     if ($public) {
 4680: 	undef($role);
 4681:     } else {
 4682: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4683:     }
 4684:     
 4685:     my $titleinfo = '<h1>'.$title.'</h1>';
 4686:     #
 4687:     # Extra info if you are the DC
 4688:     my $dc_info = '';
 4689:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4690:                         $env{'course.'.$env{'request.course.id'}.
 4691:                                  '.domain'}.'/'})) {
 4692:         my $cid = $env{'request.course.id'};
 4693:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4694:         $dc_info =~ s/\s+$//;
 4695:     }
 4696: 
 4697:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4698:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4699: 
 4700:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4701:             return $bodytag; 
 4702:         } 
 4703: 
 4704:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4705: 
 4706:         #    if ($env{'request.state'} eq 'construct') {
 4707:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4708:         #    }
 4709: 
 4710: 
 4711: 
 4712:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4713:              if ($dc_info) {
 4714:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4715:              }
 4716:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4717:                 <em>$realm</em> $dc_info</div>|;
 4718:             return $bodytag;
 4719:         }
 4720: 
 4721:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4722:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4723:         }
 4724: 
 4725:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4726:             Apache::lonmenu::utilityfunctions(), 'start');
 4727: 
 4728:         $bodytag .= Apache::lonmenu::primary_menu();
 4729: 
 4730:         if ($dc_info) {
 4731:             $dc_info = &dc_courseid_toggle($dc_info);
 4732:         }
 4733:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4734: 
 4735:         #don't show menus for public users
 4736:         if (!$public){
 4737:             $bodytag .= Apache::lonmenu::secondary_menu();
 4738:             $bodytag .= Apache::lonmenu::serverform();
 4739:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4740:             if ($env{'request.state'} eq 'construct') {
 4741:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 4742:                                 $args->{'bread_crumbs'});
 4743:             } elsif ($forcereg) { 
 4744:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4745:             }
 4746:         }else{
 4747:             # this is to seperate menu from content when there's no secondary
 4748:             # menu. Especially needed for public accessible ressources.
 4749:             $bodytag .= '<hr style="clear:both" />';
 4750:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4751:         }
 4752: 
 4753:         return $bodytag;
 4754: }
 4755: 
 4756: sub dc_courseid_toggle {
 4757:     my ($dc_info) = @_;
 4758:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4759:            '<a href="javascript:showCourseID();">'.
 4760:            &mt('(More ...)').'</a></span>'.
 4761:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4762: }
 4763: 
 4764: sub make_attr_string {
 4765:     my ($register,$attr_ref) = @_;
 4766: 
 4767:     if ($attr_ref && !ref($attr_ref)) {
 4768: 	die("addentries Must be a hash ref ".
 4769: 	    join(':',caller(1))." ".
 4770: 	    join(':',caller(0))." ");
 4771:     }
 4772: 
 4773:     if ($register) {
 4774: 	my ($on_load,$on_unload);
 4775: 	foreach my $key (keys(%{$attr_ref})) {
 4776: 	    if      (lc($key) eq 'onload') {
 4777: 		$on_load.=$attr_ref->{$key}.';';
 4778: 		delete($attr_ref->{$key});
 4779: 
 4780: 	    } elsif (lc($key) eq 'onunload') {
 4781: 		$on_unload.=$attr_ref->{$key}.';';
 4782: 		delete($attr_ref->{$key});
 4783: 	    }
 4784: 	}
 4785: 	$attr_ref->{'onload'}  = $on_load;
 4786: 	$attr_ref->{'onunload'}= $on_unload;
 4787:     }
 4788: 
 4789:     my $attr_string;
 4790:     foreach my $attr (keys(%$attr_ref)) {
 4791: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4792:     }
 4793:     return $attr_string;
 4794: }
 4795: 
 4796: 
 4797: ###############################################
 4798: ###############################################
 4799: 
 4800: =pod
 4801: 
 4802: =item * &endbodytag()
 4803: 
 4804: Returns a uniform footer for LON-CAPA web pages.
 4805: 
 4806: Inputs: 1 - optional reference to an args hash
 4807: If in the hash, key for noredirectlink has a value which evaluates to true,
 4808: a 'Continue' link is not displayed if the page contains an
 4809: internal redirect in the <head></head> section,
 4810: i.e., $env{'internal.head.redirect'} exists   
 4811: 
 4812: =cut
 4813: 
 4814: sub endbodytag {
 4815:     my ($args) = @_;
 4816:     my $endbodytag='</body>';
 4817:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4818:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4819:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4820: 	    $endbodytag=
 4821: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4822: 	        &mt('Continue').'</a>'.
 4823: 	        $endbodytag;
 4824:         }
 4825:     }
 4826:     return $endbodytag;
 4827: }
 4828: 
 4829: =pod
 4830: 
 4831: =item * &standard_css()
 4832: 
 4833: Returns a style sheet
 4834: 
 4835: Inputs: (all optional)
 4836:             domain         -> force to color decorate a page for a specific
 4837:                                domain
 4838:             function       -> force usage of a specific rolish color scheme
 4839:             bgcolor        -> override the default page bgcolor
 4840: 
 4841: =cut
 4842: 
 4843: sub standard_css {
 4844:     my ($function,$domain,$bgcolor) = @_;
 4845:     $function  = &get_users_function() if (!$function);
 4846:     my $img    = &designparm($function.'.img',   $domain);
 4847:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4848:     my $font   = &designparm($function.'.font',  $domain);
 4849:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4850: #second colour for later usage
 4851:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4852:     my $pgbg_or_bgcolor =
 4853: 	         $bgcolor ||
 4854: 	         &designparm($function.'.pgbg',  $domain);
 4855:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4856:     my $alink  = &designparm($function.'.alink', $domain);
 4857:     my $vlink  = &designparm($function.'.vlink', $domain);
 4858:     my $link   = &designparm($function.'.link',  $domain);
 4859: 
 4860:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4861:     my $mono                 = 'monospace';
 4862:     my $data_table_head      = $sidebg;
 4863:     my $data_table_light     = '#FAFAFA';
 4864:     my $data_table_dark      = '#F0F0F0';
 4865:     my $data_table_darker    = '#CCCCCC';
 4866:     my $data_table_highlight = '#FFFF00';
 4867:     my $mail_new             = '#FFBB77';
 4868:     my $mail_new_hover       = '#DD9955';
 4869:     my $mail_read            = '#BBBB77';
 4870:     my $mail_read_hover      = '#999944';
 4871:     my $mail_replied         = '#AAAA88';
 4872:     my $mail_replied_hover   = '#888855';
 4873:     my $mail_other           = '#99BBBB';
 4874:     my $mail_other_hover     = '#669999';
 4875:     my $table_header         = '#DDDDDD';
 4876:     my $feedback_link_bg     = '#BBBBBB';
 4877:     my $lg_border_color      = '#C8C8C8';
 4878:     my $button_hover         = '#BF2317';
 4879: 
 4880:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4881:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4882:                                              : '0 3px 0 4px';
 4883: 
 4884: 
 4885:     return <<END;
 4886: 
 4887: /* needed for iframe to allow 100% height in FF */
 4888: body, html { 
 4889:     margin: 0;
 4890:     padding: 0 0.5%;
 4891:     height: 99%; /* to avoid scrollbars */
 4892: }
 4893: 
 4894: body {
 4895:   font-family: $sans;
 4896:   line-height:130%;
 4897:   font-size:0.83em;
 4898:   color:$font;
 4899: }
 4900: 
 4901: a:focus,
 4902: a:focus img {
 4903:   color: red;
 4904:   background: yellow;
 4905: }
 4906: 
 4907: form, .inline {
 4908:   display: inline;
 4909: }
 4910: 
 4911: .LC_right {
 4912:   text-align:right;
 4913: }
 4914: 
 4915: .LC_middle {
 4916:   vertical-align:middle;
 4917: }
 4918: 
 4919: .LC_400Box {
 4920:   width:400px;
 4921: }
 4922: 
 4923: .LC_iframecontainer {
 4924:     width: 98%;
 4925:     margin: 0;
 4926:     position: fixed;
 4927:     top: 8.5em;
 4928:     bottom: 0;
 4929: }
 4930: 
 4931: .LC_iframecontainer iframe{
 4932:     border: none;
 4933:     width: 100%;
 4934:     height: 100%;
 4935: }
 4936: 
 4937: .LC_filename {
 4938:   font-family: $mono;
 4939:   white-space:pre;
 4940:   font-size: 120%;
 4941: }
 4942: 
 4943: .LC_fileicon {
 4944:   border: none;
 4945:   height: 1.3em;
 4946:   vertical-align: text-bottom;
 4947:   margin-right: 0.3em;
 4948:   text-decoration:none;
 4949: }
 4950: 
 4951: .LC_error {
 4952:   color: red;
 4953:   font-size: larger;
 4954: }
 4955: 
 4956: .LC_warning,
 4957: .LC_diff_removed {
 4958:   color: red;
 4959: }
 4960: 
 4961: .LC_info,
 4962: .LC_success,
 4963: .LC_diff_added {
 4964:   color: green;
 4965: }
 4966: 
 4967: div.LC_confirm_box {
 4968:   background-color: #FAFAFA;
 4969:   border: 1px solid $lg_border_color;
 4970:   margin-right: 0;
 4971:   padding: 5px;
 4972: }
 4973: 
 4974: div.LC_confirm_box .LC_error img,
 4975: div.LC_confirm_box .LC_success img {
 4976:   vertical-align: middle;
 4977: }
 4978: 
 4979: .LC_icon {
 4980:   border: none;
 4981:   vertical-align: middle;
 4982: }
 4983: 
 4984: .LC_docs_spacer {
 4985:   width: 25px;
 4986:   height: 1px;
 4987:   border: none;
 4988: }
 4989: 
 4990: .LC_internal_info {
 4991:   color: #999999;
 4992: }
 4993: 
 4994: .LC_discussion {
 4995:   background: $tabbg;
 4996:   border: 1px solid black;
 4997:   margin: 2px;
 4998: }
 4999: 
 5000: .LC_disc_action_links_bar {
 5001:   background: $tabbg;
 5002:   border: none;
 5003:   margin: 4px;
 5004: }
 5005: 
 5006: .LC_disc_action_left {
 5007:   text-align: left;
 5008: }
 5009: 
 5010: .LC_disc_action_right {
 5011:   text-align: right;
 5012: }
 5013: 
 5014: .LC_disc_new_item {
 5015:   background: white;
 5016:   border: 2px solid red;
 5017:   margin: 2px;
 5018: }
 5019: 
 5020: .LC_disc_old_item {
 5021:   background: white;
 5022:   border: 1px solid black;
 5023:   margin: 2px;
 5024: }
 5025: 
 5026: table.LC_pastsubmission {
 5027:   border: 1px solid black;
 5028:   margin: 2px;
 5029: }
 5030: 
 5031: table#LC_menubuttons {
 5032:   width: 100%;
 5033:   background: $pgbg;
 5034:   border: 2px;
 5035:   border-collapse: separate;
 5036:   padding: 0;
 5037: }
 5038: 
 5039: table#LC_title_bar a {
 5040:   color: $fontmenu;
 5041: }
 5042: 
 5043: table#LC_title_bar {
 5044:   clear: both;
 5045:   display: none;
 5046: }
 5047: 
 5048: table#LC_title_bar,
 5049: table.LC_breadcrumbs, /* obsolete? */
 5050: table#LC_title_bar.LC_with_remote {
 5051:   width: 100%;
 5052:   border-color: $pgbg;
 5053:   border-style: solid;
 5054:   border-width: $border;
 5055:   background: $pgbg;
 5056:   color: $fontmenu;
 5057:   border-collapse: collapse;
 5058:   padding: 0;
 5059:   margin: 0;
 5060: }
 5061: 
 5062: ul.LC_breadcrumb_tools_outerlist {
 5063:     margin: 0;
 5064:     padding: 0;
 5065:     position: relative;
 5066:     list-style: none;
 5067: }
 5068: ul.LC_breadcrumb_tools_outerlist li {
 5069:     display: inline;
 5070: }
 5071: 
 5072: .LC_breadcrumb_tools_navigation {
 5073:     padding: 0;
 5074:     margin: 0;
 5075:     float: left;
 5076: }
 5077: .LC_breadcrumb_tools_tools {
 5078:     padding: 0;
 5079:     margin: 0;
 5080:     float: right;
 5081: }
 5082: 
 5083: table#LC_title_bar td {
 5084:   background: $tabbg;
 5085: }
 5086: 
 5087: table#LC_menubuttons img {
 5088:   border: none;
 5089: }
 5090: 
 5091: .LC_breadcrumbs_component {
 5092:   float: right;
 5093:   margin: 0 1em;
 5094: }
 5095: .LC_breadcrumbs_component img {
 5096:   vertical-align: middle;
 5097: }
 5098: 
 5099: td.LC_table_cell_checkbox {
 5100:   text-align: center;
 5101: }
 5102: 
 5103: .LC_fontsize_small {
 5104:   font-size: 70%;
 5105: }
 5106: 
 5107: #LC_breadcrumbs {
 5108:   clear:both;
 5109:   background: $sidebg;
 5110:   border-bottom: 1px solid $lg_border_color;
 5111:   line-height: 2.5em;
 5112:   overflow: hidden;
 5113:   margin: 0;
 5114:   padding: 0;
 5115:   text-align: left;
 5116: }
 5117: 
 5118: .LC_head_subbox {
 5119:   clear:both;
 5120:   background: #F8F8F8; /* $sidebg; */
 5121:   border: 1px solid $sidebg;
 5122:   margin: 0 0 10px 0;      
 5123:   padding: 3px;
 5124:   text-align: left;
 5125: }
 5126: 
 5127: .LC_fontsize_medium {
 5128:   font-size: 85%;
 5129: }
 5130: 
 5131: .LC_fontsize_large {
 5132:   font-size: 120%;
 5133: }
 5134: 
 5135: .LC_menubuttons_inline_text {
 5136:   color: $font;
 5137:   font-size: 90%;
 5138:   padding-left:3px;
 5139: }
 5140: 
 5141: .LC_menubuttons_inline_text img{
 5142:   vertical-align: middle;
 5143: }
 5144: 
 5145: li.LC_menubuttons_inline_text img,a {
 5146:   cursor:pointer;
 5147:   text-decoration: none;
 5148: }
 5149: 
 5150: .LC_menubuttons_link {
 5151:   text-decoration: none;
 5152: }
 5153: 
 5154: .LC_menubuttons_category {
 5155:   color: $font;
 5156:   background: $pgbg;
 5157:   font-size: larger;
 5158:   font-weight: bold;
 5159: }
 5160: 
 5161: td.LC_menubuttons_text {
 5162:   color: $font;
 5163: }
 5164: 
 5165: .LC_current_location {
 5166:   background: $tabbg;
 5167: }
 5168: 
 5169: table.LC_data_table {
 5170:   border: 1px solid #000000;
 5171:   border-collapse: separate;
 5172:   border-spacing: 1px;
 5173:   background: $pgbg;
 5174: }
 5175: 
 5176: .LC_data_table_dense {
 5177:   font-size: small;
 5178: }
 5179: 
 5180: table.LC_nested_outer {
 5181:   border: 1px solid #000000;
 5182:   border-collapse: collapse;
 5183:   border-spacing: 0;
 5184:   width: 100%;
 5185: }
 5186: 
 5187: table.LC_innerpickbox,
 5188: table.LC_nested {
 5189:   border: none;
 5190:   border-collapse: collapse;
 5191:   border-spacing: 0;
 5192:   width: 100%;
 5193: }
 5194: 
 5195: .ui-accordion,
 5196: .ui-accordion table.LC_data_table,
 5197: .ui-accordion table.LC_nested_outer{
 5198:   border: 0px;
 5199:   border-spacing: 0px;
 5200:   margin: 3px;
 5201: }
 5202: 
 5203: table.LC_data_table tr th,
 5204: table.LC_calendar tr th,
 5205: table.LC_prior_tries tr th,
 5206: table.LC_innerpickbox tr th {
 5207:   font-weight: bold;
 5208:   background-color: $data_table_head;
 5209:   color:$fontmenu;
 5210:   font-size:90%;
 5211: }
 5212: 
 5213: table.LC_innerpickbox tr th,
 5214: table.LC_innerpickbox tr td {
 5215:   vertical-align: top;
 5216: }
 5217: 
 5218: table.LC_data_table tr.LC_info_row > td {
 5219:   background-color: #CCCCCC;
 5220:   font-weight: bold;
 5221:   text-align: left;
 5222: }
 5223: 
 5224: table.LC_data_table tr.LC_odd_row > td {
 5225:   background-color: $data_table_light;
 5226:   padding: 2px;
 5227:   vertical-align: top;
 5228: }
 5229: 
 5230: table.LC_pick_box tr > td.LC_odd_row {
 5231:   background-color: $data_table_light;
 5232:   vertical-align: top;
 5233: }
 5234: 
 5235: table.LC_data_table tr.LC_even_row > td {
 5236:   background-color: $data_table_dark;
 5237:   padding: 2px;
 5238:   vertical-align: top;
 5239: }
 5240: 
 5241: table.LC_pick_box tr > td.LC_even_row {
 5242:   background-color: $data_table_dark;
 5243:   vertical-align: top;
 5244: }
 5245: 
 5246: table.LC_data_table tr.LC_data_table_highlight td {
 5247:   background-color: $data_table_darker;
 5248: }
 5249: 
 5250: table.LC_data_table tr td.LC_leftcol_header {
 5251:   background-color: $data_table_head;
 5252:   font-weight: bold;
 5253: }
 5254: 
 5255: table.LC_data_table tr.LC_empty_row td,
 5256: table.LC_nested tr.LC_empty_row td {
 5257:   font-weight: bold;
 5258:   font-style: italic;
 5259:   text-align: center;
 5260:   padding: 8px;
 5261: }
 5262: 
 5263: table.LC_data_table tr.LC_empty_row td {
 5264:   background-color: $sidebg;
 5265: }
 5266: 
 5267: table.LC_nested tr.LC_empty_row td {
 5268:   background-color: #FFFFFF;
 5269: }
 5270: 
 5271: table.LC_caption {
 5272: }
 5273: 
 5274: table.LC_nested tr.LC_empty_row td {
 5275:   padding: 4ex
 5276: }
 5277: 
 5278: table.LC_nested_outer tr th {
 5279:   font-weight: bold;
 5280:   color:$fontmenu;
 5281:   background-color: $data_table_head;
 5282:   font-size: small;
 5283:   border-bottom: 1px solid #000000;
 5284: }
 5285: 
 5286: table.LC_nested_outer tr td.LC_subheader {
 5287:   background-color: $data_table_head;
 5288:   font-weight: bold;
 5289:   font-size: small;
 5290:   border-bottom: 1px solid #000000;
 5291:   text-align: right;
 5292: }
 5293: 
 5294: table.LC_nested tr.LC_info_row td {
 5295:   background-color: #CCCCCC;
 5296:   font-weight: bold;
 5297:   font-size: small;
 5298:   text-align: center;
 5299: }
 5300: 
 5301: table.LC_nested tr.LC_info_row td.LC_left_item,
 5302: table.LC_nested_outer tr th.LC_left_item {
 5303:   text-align: left;
 5304: }
 5305: 
 5306: table.LC_nested td {
 5307:   background-color: #FFFFFF;
 5308:   font-size: small;
 5309: }
 5310: 
 5311: table.LC_nested_outer tr th.LC_right_item,
 5312: table.LC_nested tr.LC_info_row td.LC_right_item,
 5313: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5314: table.LC_nested tr td.LC_right_item {
 5315:   text-align: right;
 5316: }
 5317: 
 5318: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
 5319: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
 5320:   text-align: right;
 5321:   width: 40%;
 5322:   padding-right:10px;
 5323:   vertical-align: top;
 5324:   padding: 5px;
 5325: }
 5326: 
 5327: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
 5328: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
 5329:   text-align: left;
 5330:   width: 60%;
 5331:   padding: 2px 4px;
 5332: }
 5333: 
 5334: table.LC_nested tr.LC_odd_row td {
 5335:   background-color: #EEEEEE;
 5336: }
 5337: 
 5338: table.LC_createuser {
 5339: }
 5340: 
 5341: table.LC_createuser tr.LC_section_row td {
 5342:   font-size: small;
 5343: }
 5344: 
 5345: table.LC_createuser tr.LC_info_row td  {
 5346:   background-color: #CCCCCC;
 5347:   font-weight: bold;
 5348:   text-align: center;
 5349: }
 5350: 
 5351: table.LC_calendar {
 5352:   border: 1px solid #000000;
 5353:   border-collapse: collapse;
 5354:   width: 98%;
 5355: }
 5356: 
 5357: table.LC_calendar_pickdate {
 5358:   font-size: xx-small;
 5359: }
 5360: 
 5361: table.LC_calendar tr td {
 5362:   border: 1px solid #000000;
 5363:   vertical-align: top;
 5364:   width: 14%;
 5365: }
 5366: 
 5367: table.LC_calendar tr td.LC_calendar_day_empty {
 5368:   background-color: $data_table_dark;
 5369: }
 5370: 
 5371: table.LC_calendar tr td.LC_calendar_day_current {
 5372:   background-color: $data_table_highlight;
 5373: }
 5374: 
 5375: table.LC_data_table tr td.LC_mail_new {
 5376:   background-color: $mail_new;
 5377: }
 5378: 
 5379: table.LC_data_table tr.LC_mail_new:hover {
 5380:   background-color: $mail_new_hover;
 5381: }
 5382: 
 5383: table.LC_data_table tr td.LC_mail_read {
 5384:   background-color: $mail_read;
 5385: }
 5386: 
 5387: /*
 5388: table.LC_data_table tr.LC_mail_read:hover {
 5389:   background-color: $mail_read_hover;
 5390: }
 5391: */
 5392: 
 5393: table.LC_data_table tr td.LC_mail_replied {
 5394:   background-color: $mail_replied;
 5395: }
 5396: 
 5397: /*
 5398: table.LC_data_table tr.LC_mail_replied:hover {
 5399:   background-color: $mail_replied_hover;
 5400: }
 5401: */
 5402: 
 5403: table.LC_data_table tr td.LC_mail_other {
 5404:   background-color: $mail_other;
 5405: }
 5406: 
 5407: /*
 5408: table.LC_data_table tr.LC_mail_other:hover {
 5409:   background-color: $mail_other_hover;
 5410: }
 5411: */
 5412: 
 5413: table.LC_data_table tr > td.LC_browser_file,
 5414: table.LC_data_table tr > td.LC_browser_file_published {
 5415:   background: #AAEE77;
 5416: }
 5417: 
 5418: table.LC_data_table tr > td.LC_browser_file_locked,
 5419: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5420:   background: #FFAA99;
 5421: }
 5422: 
 5423: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5424:   background: #888888;
 5425: }
 5426: 
 5427: table.LC_data_table tr > td.LC_browser_file_modified,
 5428: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5429:   background: #F8F866;
 5430: }
 5431: 
 5432: table.LC_data_table tr.LC_browser_folder > td {
 5433:   background: #E0E8FF;
 5434: }
 5435: 
 5436: table.LC_data_table tr > td.LC_roles_is {
 5437:   /* background: #77FF77; */
 5438: }
 5439: 
 5440: table.LC_data_table tr > td.LC_roles_future {
 5441:   border-right: 8px solid #FFFF77;
 5442: }
 5443: 
 5444: table.LC_data_table tr > td.LC_roles_will {
 5445:   border-right: 8px solid #FFAA77;
 5446: }
 5447: 
 5448: table.LC_data_table tr > td.LC_roles_expired {
 5449:   border-right: 8px solid #FF7777;
 5450: }
 5451: 
 5452: table.LC_data_table tr > td.LC_roles_will_not {
 5453:   border-right: 8px solid #AAFF77;
 5454: }
 5455: 
 5456: table.LC_data_table tr > td.LC_roles_selected {
 5457:   border-right: 8px solid #11CC55;
 5458: }
 5459: 
 5460: span.LC_current_location {
 5461:   font-size:larger;
 5462:   background: $pgbg;
 5463: }
 5464: 
 5465: span.LC_parm_menu_item {
 5466:   font-size: larger;
 5467: }
 5468: 
 5469: span.LC_parm_scope_all {
 5470:   color: red;
 5471: }
 5472: 
 5473: span.LC_parm_scope_folder {
 5474:   color: green;
 5475: }
 5476: 
 5477: span.LC_parm_scope_resource {
 5478:   color: orange;
 5479: }
 5480: 
 5481: span.LC_parm_part {
 5482:   color: blue;
 5483: }
 5484: 
 5485: span.LC_parm_folder,
 5486: span.LC_parm_symb {
 5487:   font-size: x-small;
 5488:   font-family: $mono;
 5489:   color: #AAAAAA;
 5490: }
 5491: 
 5492: ul.LC_parm_parmlist li {
 5493:   display: inline-block;
 5494:   padding: 0.3em 0.8em;
 5495:   vertical-align: top;
 5496:   width: 150px;
 5497:   border-top:1px solid $lg_border_color;
 5498: }
 5499: 
 5500: td.LC_parm_overview_level_menu,
 5501: td.LC_parm_overview_map_menu,
 5502: td.LC_parm_overview_parm_selectors,
 5503: td.LC_parm_overview_restrictions  {
 5504:   border: 1px solid black;
 5505:   border-collapse: collapse;
 5506: }
 5507: 
 5508: table.LC_parm_overview_restrictions td {
 5509:   border-width: 1px 4px 1px 4px;
 5510:   border-style: solid;
 5511:   border-color: $pgbg;
 5512:   text-align: center;
 5513: }
 5514: 
 5515: table.LC_parm_overview_restrictions th {
 5516:   background: $tabbg;
 5517:   border-width: 1px 4px 1px 4px;
 5518:   border-style: solid;
 5519:   border-color: $pgbg;
 5520: }
 5521: 
 5522: table#LC_helpmenu {
 5523:   border: none;
 5524:   height: 55px;
 5525:   border-spacing: 0;
 5526: }
 5527: 
 5528: table#LC_helpmenu fieldset legend {
 5529:   font-size: larger;
 5530: }
 5531: 
 5532: table#LC_helpmenu_links {
 5533:   width: 100%;
 5534:   border: 1px solid black;
 5535:   background: $pgbg;
 5536:   padding: 0;
 5537:   border-spacing: 1px;
 5538: }
 5539: 
 5540: table#LC_helpmenu_links tr td {
 5541:   padding: 1px;
 5542:   background: $tabbg;
 5543:   text-align: center;
 5544:   font-weight: bold;
 5545: }
 5546: 
 5547: table#LC_helpmenu_links a:link,
 5548: table#LC_helpmenu_links a:visited,
 5549: table#LC_helpmenu_links a:active {
 5550:   text-decoration: none;
 5551:   color: $font;
 5552: }
 5553: 
 5554: table#LC_helpmenu_links a:hover {
 5555:   text-decoration: underline;
 5556:   color: $vlink;
 5557: }
 5558: 
 5559: .LC_chrt_popup_exists {
 5560:   border: 1px solid #339933;
 5561:   margin: -1px;
 5562: }
 5563: 
 5564: .LC_chrt_popup_up {
 5565:   border: 1px solid yellow;
 5566:   margin: -1px;
 5567: }
 5568: 
 5569: .LC_chrt_popup {
 5570:   border: 1px solid #8888FF;
 5571:   background: #CCCCFF;
 5572: }
 5573: 
 5574: table.LC_pick_box {
 5575:   border-collapse: separate;
 5576:   background: white;
 5577:   border: 1px solid black;
 5578:   border-spacing: 1px;
 5579: }
 5580: 
 5581: table.LC_pick_box td.LC_pick_box_title {
 5582:   background: $sidebg;
 5583:   font-weight: bold;
 5584:   text-align: left;
 5585:   vertical-align: top;
 5586:   width: 184px;
 5587:   padding: 8px;
 5588: }
 5589: 
 5590: table.LC_pick_box td.LC_pick_box_value {
 5591:   text-align: left;
 5592:   padding: 8px;
 5593: }
 5594: 
 5595: table.LC_pick_box td.LC_pick_box_select {
 5596:   text-align: left;
 5597:   padding: 8px;
 5598: }
 5599: 
 5600: table.LC_pick_box td.LC_pick_box_separator {
 5601:   padding: 0;
 5602:   height: 1px;
 5603:   background: black;
 5604: }
 5605: 
 5606: table.LC_pick_box td.LC_pick_box_submit {
 5607:   text-align: right;
 5608: }
 5609: 
 5610: table.LC_pick_box td.LC_evenrow_value {
 5611:   text-align: left;
 5612:   padding: 8px;
 5613:   background-color: $data_table_light;
 5614: }
 5615: 
 5616: table.LC_pick_box td.LC_oddrow_value {
 5617:   text-align: left;
 5618:   padding: 8px;
 5619:   background-color: $data_table_light;
 5620: }
 5621: 
 5622: span.LC_helpform_receipt_cat {
 5623:   font-weight: bold;
 5624: }
 5625: 
 5626: table.LC_group_priv_box {
 5627:   background: white;
 5628:   border: 1px solid black;
 5629:   border-spacing: 1px;
 5630: }
 5631: 
 5632: table.LC_group_priv_box td.LC_pick_box_title {
 5633:   background: $tabbg;
 5634:   font-weight: bold;
 5635:   text-align: right;
 5636:   width: 184px;
 5637: }
 5638: 
 5639: table.LC_group_priv_box td.LC_groups_fixed {
 5640:   background: $data_table_light;
 5641:   text-align: center;
 5642: }
 5643: 
 5644: table.LC_group_priv_box td.LC_groups_optional {
 5645:   background: $data_table_dark;
 5646:   text-align: center;
 5647: }
 5648: 
 5649: table.LC_group_priv_box td.LC_groups_functionality {
 5650:   background: $data_table_darker;
 5651:   text-align: center;
 5652:   font-weight: bold;
 5653: }
 5654: 
 5655: table.LC_group_priv td {
 5656:   text-align: left;
 5657:   padding: 0;
 5658: }
 5659: 
 5660: .LC_navbuttons {
 5661:   margin: 2ex 0ex 2ex 0ex;
 5662: }
 5663: 
 5664: .LC_topic_bar {
 5665:   font-weight: bold;
 5666:   background: $tabbg;
 5667:   margin: 1em 0em 1em 2em;
 5668:   padding: 3px;
 5669:   font-size: 1.2em;
 5670: }
 5671: 
 5672: .LC_topic_bar span {
 5673:   left: 0.5em;
 5674:   position: absolute;
 5675:   vertical-align: middle;
 5676:   font-size: 1.2em;
 5677: }
 5678: 
 5679: table.LC_course_group_status {
 5680:   margin: 20px;
 5681: }
 5682: 
 5683: table.LC_status_selector td {
 5684:   vertical-align: top;
 5685:   text-align: center;
 5686:   padding: 4px;
 5687: }
 5688: 
 5689: div.LC_feedback_link {
 5690:   clear: both;
 5691:   background: $sidebg;
 5692:   width: 100%;
 5693:   padding-bottom: 10px;
 5694:   border: 1px $tabbg solid;
 5695:   height: 22px;
 5696:   line-height: 22px;
 5697:   padding-top: 5px;
 5698: }
 5699: 
 5700: div.LC_feedback_link img {
 5701:   height: 22px;
 5702:   vertical-align:middle;
 5703: }
 5704: 
 5705: div.LC_feedback_link a {
 5706:   text-decoration: none;
 5707: }
 5708: 
 5709: div.LC_comblock {
 5710:   display:inline;
 5711:   color:$font;
 5712:   font-size:90%;
 5713: }
 5714: 
 5715: div.LC_feedback_link div.LC_comblock {
 5716:   padding-left:5px;
 5717: }
 5718: 
 5719: div.LC_feedback_link div.LC_comblock a {
 5720:   color:$font;
 5721: }
 5722: 
 5723: span.LC_feedback_link {
 5724:   /* background: $feedback_link_bg; */
 5725:   font-size: larger;
 5726: }
 5727: 
 5728: span.LC_message_link {
 5729:   /* background: $feedback_link_bg; */
 5730:   font-size: larger;
 5731:   position: absolute;
 5732:   right: 1em;
 5733: }
 5734: 
 5735: table.LC_prior_tries {
 5736:   border: 1px solid #000000;
 5737:   border-collapse: separate;
 5738:   border-spacing: 1px;
 5739: }
 5740: 
 5741: table.LC_prior_tries td {
 5742:   padding: 2px;
 5743: }
 5744: 
 5745: .LC_answer_correct {
 5746:   background: lightgreen;
 5747:   color: darkgreen;
 5748:   padding: 6px;
 5749: }
 5750: 
 5751: .LC_answer_charged_try {
 5752:   background: #FFAAAA;
 5753:   color: darkred;
 5754:   padding: 6px;
 5755: }
 5756: 
 5757: .LC_answer_not_charged_try,
 5758: .LC_answer_no_grade,
 5759: .LC_answer_late {
 5760:   background: lightyellow;
 5761:   color: black;
 5762:   padding: 6px;
 5763: }
 5764: 
 5765: .LC_answer_previous {
 5766:   background: lightblue;
 5767:   color: darkblue;
 5768:   padding: 6px;
 5769: }
 5770: 
 5771: .LC_answer_no_message {
 5772:   background: #FFFFFF;
 5773:   color: black;
 5774:   padding: 6px;
 5775: }
 5776: 
 5777: .LC_answer_unknown {
 5778:   background: orange;
 5779:   color: black;
 5780:   padding: 6px;
 5781: }
 5782: 
 5783: span.LC_prior_numerical,
 5784: span.LC_prior_string,
 5785: span.LC_prior_custom,
 5786: span.LC_prior_reaction,
 5787: span.LC_prior_math {
 5788:   font-family: $mono;
 5789:   white-space: pre;
 5790: }
 5791: 
 5792: span.LC_prior_string {
 5793:   font-family: $mono;
 5794:   white-space: pre;
 5795: }
 5796: 
 5797: table.LC_prior_option {
 5798:   width: 100%;
 5799:   border-collapse: collapse;
 5800: }
 5801: 
 5802: table.LC_prior_rank,
 5803: table.LC_prior_match {
 5804:   border-collapse: collapse;
 5805: }
 5806: 
 5807: table.LC_prior_option tr td,
 5808: table.LC_prior_rank tr td,
 5809: table.LC_prior_match tr td {
 5810:   border: 1px solid #000000;
 5811: }
 5812: 
 5813: .LC_nobreak {
 5814:   white-space: nowrap;
 5815: }
 5816: 
 5817: span.LC_cusr_emph {
 5818:   font-style: italic;
 5819: }
 5820: 
 5821: span.LC_cusr_subheading {
 5822:   font-weight: normal;
 5823:   font-size: 85%;
 5824: }
 5825: 
 5826: div.LC_docs_entry_move {
 5827:   border: 1px solid #BBBBBB;
 5828:   background: #DDDDDD;
 5829:   width: 22px;
 5830:   padding: 1px;
 5831:   margin: 0;
 5832: }
 5833: 
 5834: table.LC_data_table tr > td.LC_docs_entry_commands,
 5835: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5836:   background: #DDDDDD;
 5837:   font-size: x-small;
 5838: }
 5839: 
 5840: .LC_docs_entry_parameter {
 5841:   white-space: nowrap;
 5842: }
 5843: 
 5844: .LC_docs_copy {
 5845:   color: #000099;
 5846: }
 5847: 
 5848: .LC_docs_cut {
 5849:   color: #550044;
 5850: }
 5851: 
 5852: .LC_docs_rename {
 5853:   color: #009900;
 5854: }
 5855: 
 5856: .LC_docs_remove {
 5857:   color: #990000;
 5858: }
 5859: 
 5860: .LC_docs_reinit_warn,
 5861: .LC_docs_ext_edit {
 5862:   font-size: x-small;
 5863: }
 5864: 
 5865: table.LC_docs_adddocs td,
 5866: table.LC_docs_adddocs th {
 5867:   border: 1px solid #BBBBBB;
 5868:   padding: 4px;
 5869:   background: #DDDDDD;
 5870: }
 5871: 
 5872: table.LC_sty_begin {
 5873:   background: #BBFFBB;
 5874: }
 5875: 
 5876: table.LC_sty_end {
 5877:   background: #FFBBBB;
 5878: }
 5879: 
 5880: table.LC_double_column {
 5881:   border-width: 0;
 5882:   border-collapse: collapse;
 5883:   width: 100%;
 5884:   padding: 2px;
 5885: }
 5886: 
 5887: table.LC_double_column tr td.LC_left_col {
 5888:   top: 2px;
 5889:   left: 2px;
 5890:   width: 47%;
 5891:   vertical-align: top;
 5892: }
 5893: 
 5894: table.LC_double_column tr td.LC_right_col {
 5895:   top: 2px;
 5896:   right: 2px;
 5897:   width: 47%;
 5898:   vertical-align: top;
 5899: }
 5900: 
 5901: div.LC_left_float {
 5902:   float: left;
 5903:   padding-right: 5%;
 5904:   padding-bottom: 4px;
 5905: }
 5906: 
 5907: div.LC_clear_float_header {
 5908:   padding-bottom: 2px;
 5909: }
 5910: 
 5911: div.LC_clear_float_footer {
 5912:   padding-top: 10px;
 5913:   clear: both;
 5914: }
 5915: 
 5916: div.LC_grade_show_user {
 5917: /*  border-left: 5px solid $sidebg; */
 5918:   border-top: 5px solid #000000;
 5919:   margin: 50px 0 0 0;
 5920:   padding: 15px 0 5px 10px;
 5921: }
 5922: 
 5923: div.LC_grade_show_user_odd_row {
 5924: /*  border-left: 5px solid #000000; */
 5925: }
 5926: 
 5927: div.LC_grade_show_user div.LC_Box {
 5928:   margin-right: 50px;
 5929: }
 5930: 
 5931: div.LC_grade_submissions,
 5932: div.LC_grade_message_center,
 5933: div.LC_grade_info_links {
 5934:   margin: 5px;
 5935:   width: 99%;
 5936:   background: #FFFFFF;
 5937: }
 5938: 
 5939: div.LC_grade_submissions_header,
 5940: div.LC_grade_message_center_header {
 5941:   font-weight: bold;
 5942:   font-size: large;
 5943: }
 5944: 
 5945: div.LC_grade_submissions_body,
 5946: div.LC_grade_message_center_body {
 5947:   border: 1px solid black;
 5948:   width: 99%;
 5949:   background: #FFFFFF;
 5950: }
 5951: 
 5952: table.LC_scantron_action {
 5953:   width: 100%;
 5954: }
 5955: 
 5956: table.LC_scantron_action tr th {
 5957:   font-weight:bold;
 5958:   font-style:normal;
 5959: }
 5960: 
 5961: .LC_edit_problem_header,
 5962: div.LC_edit_problem_footer {
 5963:   font-weight: normal;
 5964:   font-size:  medium;
 5965:   margin: 2px;
 5966: }
 5967: 
 5968: div.LC_edit_problem_header,
 5969: div.LC_edit_problem_header div,
 5970: div.LC_edit_problem_footer,
 5971: div.LC_edit_problem_footer div,
 5972: div.LC_edit_problem_editxml_header,
 5973: div.LC_edit_problem_editxml_header div {
 5974:   margin-top: 5px;
 5975: }
 5976: 
 5977: div.LC_edit_problem_header_title {
 5978:   font-weight: bold;
 5979:   font-size: larger;
 5980:   background: $tabbg;
 5981:   padding: 3px;
 5982: }
 5983: 
 5984: table.LC_edit_problem_header_title {
 5985:   width: 100%;
 5986:   background: $tabbg;
 5987: }
 5988: 
 5989: div.LC_edit_problem_discards {
 5990:   float: left;
 5991:   padding-bottom: 5px;
 5992: }
 5993: 
 5994: div.LC_edit_problem_saves {
 5995:   float: right;
 5996:   padding-bottom: 5px;
 5997: }
 5998: 
 5999: img.stift {
 6000:   border-width: 0;
 6001:   vertical-align: middle;
 6002: }
 6003: 
 6004: table td.LC_mainmenu_col_fieldset {
 6005:   vertical-align: top;
 6006: }
 6007: 
 6008: div.LC_createcourse {
 6009:   margin: 10px 10px 10px 10px;
 6010: }
 6011: 
 6012: .LC_dccid {
 6013:   margin: 0.2em 0 0 0;
 6014:   padding: 0;
 6015:   font-size: 90%;
 6016:   display:none;
 6017: }
 6018: 
 6019: a:hover,
 6020: ol.LC_primary_menu a:hover,
 6021: ol#LC_MenuBreadcrumbs a:hover,
 6022: ol#LC_PathBreadcrumbs a:hover,
 6023: ul#LC_secondary_menu a:hover,
 6024: .LC_FormSectionClearButton input:hover
 6025: ul.LC_TabContent   li:hover a {
 6026:   color:$button_hover;
 6027:   text-decoration:none;
 6028: }
 6029: 
 6030: h1 {
 6031:   padding: 0;
 6032:   line-height:130%;
 6033: }
 6034: 
 6035: h2,
 6036: h3,
 6037: h4,
 6038: h5,
 6039: h6 {
 6040:   margin: 5px 0 5px 0;
 6041:   padding: 0;
 6042:   line-height:130%;
 6043: }
 6044: 
 6045: .LC_hcell {
 6046:   padding:3px 15px 3px 15px;
 6047:   margin: 0;
 6048:   background-color:$tabbg;
 6049:   color:$fontmenu;
 6050:   border-bottom:solid 1px $lg_border_color;
 6051: }
 6052: 
 6053: .LC_Box > .LC_hcell {
 6054:   margin: 0 -10px 10px -10px;
 6055: }
 6056: 
 6057: .LC_noBorder {
 6058:   border: 0;
 6059: }
 6060: 
 6061: .LC_FormSectionClearButton input {
 6062:   background-color:transparent;
 6063:   border: none;
 6064:   cursor:pointer;
 6065:   text-decoration:underline;
 6066: }
 6067: 
 6068: .LC_help_open_topic {
 6069:   color: #FFFFFF;
 6070:   background-color: #EEEEFF;
 6071:   margin: 1px;
 6072:   padding: 4px;
 6073:   border: 1px solid #000033;
 6074:   white-space: nowrap;
 6075:   /* vertical-align: middle; */
 6076: }
 6077: 
 6078: dl,
 6079: ul,
 6080: div,
 6081: fieldset {
 6082:   margin: 10px 10px 10px 0;
 6083:   /* overflow: hidden; */
 6084: }
 6085: 
 6086: fieldset > legend {
 6087:   font-weight: bold;
 6088:   padding: 0 5px 0 5px;
 6089: }
 6090: 
 6091: #LC_nav_bar {
 6092:   float: left;
 6093:   background-color: $pgbg_or_bgcolor;
 6094:   margin: 0 0 2px 0;
 6095: }
 6096: 
 6097: #LC_realm {
 6098:   margin: 0.2em 0 0 0;
 6099:   padding: 0;
 6100:   font-weight: bold;
 6101:   text-align: center;
 6102:   background-color: $pgbg_or_bgcolor;
 6103: }
 6104: 
 6105: #LC_nav_bar em {
 6106:   font-weight: bold;
 6107:   font-style: normal;
 6108: }
 6109: 
 6110: ol.LC_primary_menu {
 6111:   float: right;
 6112:   margin: 0;
 6113:   background-color: $pgbg_or_bgcolor;
 6114: }
 6115: 
 6116: ol#LC_PathBreadcrumbs {
 6117:   margin: 0;
 6118: }
 6119: 
 6120: ol.LC_primary_menu li {
 6121:   display: inline;
 6122:   padding: 5px 5px 0 10px;
 6123:   vertical-align: top;
 6124: }
 6125: 
 6126: ol.LC_primary_menu li img {
 6127:   vertical-align: bottom;
 6128:   height: 1.1em;
 6129: }
 6130: 
 6131: ol.LC_primary_menu a {
 6132:   color: RGB(80, 80, 80);
 6133:   text-decoration: none;
 6134: }
 6135: 
 6136: ol.LC_primary_menu a.LC_new_message {
 6137:   font-weight:bold;
 6138:   color: darkred;
 6139: }
 6140: 
 6141: ol.LC_docs_parameters {
 6142:   margin-left: 0;
 6143:   padding: 0;
 6144:   list-style: none;
 6145: }
 6146: 
 6147: ol.LC_docs_parameters li {
 6148:   margin: 0;
 6149:   padding-right: 20px;
 6150:   display: inline;
 6151: }
 6152: 
 6153: ol.LC_docs_parameters li:before {
 6154:   content: "\\002022 \\0020";
 6155: }
 6156: 
 6157: li.LC_docs_parameters_title {
 6158:   font-weight: bold;
 6159: }
 6160: 
 6161: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6162:   content: "";
 6163: }
 6164: 
 6165: ul#LC_secondary_menu {
 6166:   clear: both;
 6167:   color: $fontmenu;
 6168:   background: $tabbg;
 6169:   list-style: none;
 6170:   padding: 0;
 6171:   margin: 0;
 6172:   width: 100%;
 6173:   text-align: left;
 6174: }
 6175: 
 6176: ul#LC_secondary_menu li {
 6177:   font-weight: bold;
 6178:   line-height: 1.8em;
 6179:   padding: 0 0.8em;
 6180:   border-right: 1px solid black;
 6181:   display: inline;
 6182:   vertical-align: middle;
 6183: }
 6184: 
 6185: ul.LC_TabContent {
 6186:   display:block;
 6187:   background: $sidebg;
 6188:   border-bottom: solid 1px $lg_border_color;
 6189:   list-style:none;
 6190:   margin: 0 -10px;
 6191:   padding: 0;
 6192: }
 6193: 
 6194: ul.LC_TabContent li,
 6195: ul.LC_TabContentBigger li {
 6196:   float:left;
 6197: }
 6198: 
 6199: ul#LC_secondary_menu li a {
 6200:   color: $fontmenu;
 6201:   text-decoration: none;
 6202: }
 6203: 
 6204: ul.LC_TabContent {
 6205:   min-height:20px;
 6206: }
 6207: 
 6208: ul.LC_TabContent li {
 6209:   vertical-align:middle;
 6210:   padding: 0 16px 0 10px;
 6211:   background-color:$tabbg;
 6212:   border-bottom:solid 1px $lg_border_color;
 6213:   border-right: solid 1px $font;
 6214: }
 6215: 
 6216: ul.LC_TabContent .right {
 6217:   float:right;
 6218: }
 6219: 
 6220: ul.LC_TabContent li a,
 6221: ul.LC_TabContent li {
 6222:   color:rgb(47,47,47);
 6223:   text-decoration:none;
 6224:   font-size:95%;
 6225:   font-weight:bold;
 6226:   min-height:20px;
 6227: }
 6228: 
 6229: ul.LC_TabContent li a:hover,
 6230: ul.LC_TabContent li a:focus {
 6231:   color: $button_hover;
 6232:   background:none;
 6233:   outline:none;
 6234: }
 6235: 
 6236: ul.LC_TabContent li:hover {
 6237:   color: $button_hover;
 6238:   cursor:pointer;
 6239: }
 6240: 
 6241: ul.LC_TabContent li.active {
 6242:   color: $font;
 6243:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6244:   border-bottom:solid 1px #FFFFFF;
 6245:   cursor: default;
 6246: }
 6247: 
 6248: ul.LC_TabContent li.active a {
 6249:   color:$font;
 6250:   background:#FFFFFF;
 6251:   outline: none;
 6252: }
 6253: #maincoursedoc {
 6254:   clear:both;
 6255: }
 6256: 
 6257: ul.LC_TabContentBigger {
 6258:   display:block;
 6259:   list-style:none;
 6260:   padding: 0;
 6261: }
 6262: 
 6263: ul.LC_TabContentBigger li {
 6264:   vertical-align:bottom;
 6265:   height: 30px;
 6266:   font-size:110%;
 6267:   font-weight:bold;
 6268:   color: #737373;
 6269: }
 6270: 
 6271: ul.LC_TabContentBigger li.active {
 6272:   position: relative;
 6273:   top: 1px;
 6274: }
 6275: 
 6276: ul.LC_TabContentBigger li a {
 6277:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6278:   height: 30px;
 6279:   line-height: 30px;
 6280:   text-align: center;
 6281:   display: block;
 6282:   text-decoration: none;
 6283:   outline: none;  
 6284: }
 6285: 
 6286: ul.LC_TabContentBigger li.active a {
 6287:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6288:   color:$font;
 6289: }
 6290: 
 6291: ul.LC_TabContentBigger li b {
 6292:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6293:   display: block;
 6294:   float: left;
 6295:   padding: 0 30px;
 6296:   border-bottom: 1px solid $lg_border_color;
 6297: }
 6298: 
 6299: ul.LC_TabContentBigger li:hover b {
 6300:   color:$button_hover;
 6301: }
 6302: 
 6303: ul.LC_TabContentBigger li.active b {
 6304:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6305:   color:$font;
 6306:   border: 0;
 6307: }
 6308: 
 6309: 
 6310: ul.LC_CourseBreadcrumbs {
 6311:   background: $sidebg;
 6312:   line-height: 32px;
 6313:   padding-left: 10px;
 6314:   margin: 0 0 10px 0;
 6315:   list-style-position: inside;
 6316: 
 6317: }
 6318: 
 6319: ol#LC_MenuBreadcrumbs,
 6320: ol#LC_PathBreadcrumbs {
 6321:   padding-left: 10px;
 6322:   margin: 0;
 6323:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6324: }
 6325: 
 6326: ol#LC_MenuBreadcrumbs li,
 6327: ol#LC_PathBreadcrumbs li,
 6328: ul.LC_CourseBreadcrumbs li {
 6329:   display: inline;
 6330:   white-space: normal;  
 6331: }
 6332: 
 6333: ol#LC_MenuBreadcrumbs li a,
 6334: ul.LC_CourseBreadcrumbs li a {
 6335:   text-decoration: none;
 6336:   font-size:90%;
 6337: }
 6338: 
 6339: ol#LC_MenuBreadcrumbs h1 {
 6340:   display: inline;
 6341:   font-size: 90%;
 6342:   line-height: 2.5em;
 6343:   margin: 0;
 6344:   padding: 0;
 6345: }
 6346: 
 6347: ol#LC_PathBreadcrumbs li a {
 6348:   text-decoration:none;
 6349:   font-size:100%;
 6350:   font-weight:bold;
 6351: }
 6352: 
 6353: .LC_Box {
 6354:   border: solid 1px $lg_border_color;
 6355:   padding: 0 10px 10px 10px;
 6356: }
 6357: 
 6358: .LC_AboutMe_Image {
 6359:   float:left;
 6360:   margin-right:10px;
 6361: }
 6362: 
 6363: .LC_Clear_AboutMe_Image {
 6364:   clear:left;
 6365: }
 6366: 
 6367: dl.LC_ListStyleClean dt {
 6368:   padding-right: 5px;
 6369:   display: table-header-group;
 6370: }
 6371: 
 6372: dl.LC_ListStyleClean dd {
 6373:   display: table-row;
 6374: }
 6375: 
 6376: .LC_ListStyleClean,
 6377: .LC_ListStyleSimple,
 6378: .LC_ListStyleNormal,
 6379: .LC_ListStyleSpecial {
 6380:   /* display:block; */
 6381:   list-style-position: inside;
 6382:   list-style-type: none;
 6383:   overflow: hidden;
 6384:   padding: 0;
 6385: }
 6386: 
 6387: .LC_ListStyleSimple li,
 6388: .LC_ListStyleSimple dd,
 6389: .LC_ListStyleNormal li,
 6390: .LC_ListStyleNormal dd,
 6391: .LC_ListStyleSpecial li,
 6392: .LC_ListStyleSpecial dd {
 6393:   margin: 0;
 6394:   padding: 5px 5px 5px 10px;
 6395:   clear: both;
 6396: }
 6397: 
 6398: .LC_ListStyleClean li,
 6399: .LC_ListStyleClean dd {
 6400:   padding-top: 0;
 6401:   padding-bottom: 0;
 6402: }
 6403: 
 6404: .LC_ListStyleSimple dd,
 6405: .LC_ListStyleSimple li {
 6406:   border-bottom: solid 1px $lg_border_color;
 6407: }
 6408: 
 6409: .LC_ListStyleSpecial li,
 6410: .LC_ListStyleSpecial dd {
 6411:   list-style-type: none;
 6412:   background-color: RGB(220, 220, 220);
 6413:   margin-bottom: 4px;
 6414: }
 6415: 
 6416: table.LC_SimpleTable {
 6417:   margin:5px;
 6418:   border:solid 1px $lg_border_color;
 6419: }
 6420: 
 6421: table.LC_SimpleTable tr {
 6422:   padding: 0;
 6423:   border:solid 1px $lg_border_color;
 6424: }
 6425: 
 6426: table.LC_SimpleTable thead {
 6427:   background:rgb(220,220,220);
 6428: }
 6429: 
 6430: div.LC_columnSection {
 6431:   display: block;
 6432:   clear: both;
 6433:   overflow: hidden;
 6434:   margin: 0;
 6435: }
 6436: 
 6437: div.LC_columnSection>* {
 6438:   float: left;
 6439:   margin: 10px 20px 10px 0;
 6440:   overflow:hidden;
 6441: }
 6442: 
 6443: table em {
 6444:   font-weight: bold;
 6445:   font-style: normal;
 6446: }
 6447: 
 6448: table.LC_tableBrowseRes,
 6449: table.LC_tableOfContent {
 6450:   border:none;
 6451:   border-spacing: 1px;
 6452:   padding: 3px;
 6453:   background-color: #FFFFFF;
 6454:   font-size: 90%;
 6455: }
 6456: 
 6457: table.LC_tableOfContent {
 6458:   border-collapse: collapse;
 6459: }
 6460: 
 6461: table.LC_tableBrowseRes a,
 6462: table.LC_tableOfContent a {
 6463:   background-color: transparent;
 6464:   text-decoration: none;
 6465: }
 6466: 
 6467: table.LC_tableOfContent img {
 6468:   border: none;
 6469:   height: 1.3em;
 6470:   vertical-align: text-bottom;
 6471:   margin-right: 0.3em;
 6472: }
 6473: 
 6474: a#LC_content_toolbar_firsthomework {
 6475:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6476: }
 6477: 
 6478: a#LC_content_toolbar_everything {
 6479:   background-image:url(/res/adm/pages/show-all.gif);
 6480: }
 6481: 
 6482: a#LC_content_toolbar_uncompleted {
 6483:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6484: }
 6485: 
 6486: #LC_content_toolbar_clearbubbles {
 6487:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6488: }
 6489: 
 6490: a#LC_content_toolbar_changefolder {
 6491:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6492: }
 6493: 
 6494: a#LC_content_toolbar_changefolder_toggled {
 6495:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6496: }
 6497: 
 6498: ul#LC_toolbar li a:hover {
 6499:   background-position: bottom center;
 6500: }
 6501: 
 6502: ul#LC_toolbar {
 6503:   padding: 0;
 6504:   margin: 2px;
 6505:   list-style:none;
 6506:   position:relative;
 6507:   background-color:white;
 6508: }
 6509: 
 6510: ul#LC_toolbar li {
 6511:   border:1px solid white;
 6512:   padding: 0;
 6513:   margin: 0;
 6514:   float: left;
 6515:   display:inline;
 6516:   vertical-align:middle;
 6517: }
 6518: 
 6519: 
 6520: a.LC_toolbarItem {
 6521:   display:block;
 6522:   padding: 0;
 6523:   margin: 0;
 6524:   height: 32px;
 6525:   width: 32px;
 6526:   color:white;
 6527:   border: none;
 6528:   background-repeat:no-repeat;
 6529:   background-color:transparent;
 6530: }
 6531: 
 6532: ul.LC_funclist {
 6533:     margin: 0;
 6534:     padding: 0.5em 1em 0.5em 0;
 6535: }
 6536: 
 6537: ul.LC_funclist > li:first-child {
 6538:     font-weight:bold; 
 6539:     margin-left:0.8em;
 6540: }
 6541: 
 6542: ul.LC_funclist + ul.LC_funclist {
 6543:     /* 
 6544:        left border as a seperator if we have more than
 6545:        one list 
 6546:     */
 6547:     border-left: 1px solid $sidebg;
 6548:     /* 
 6549:        this hides the left border behind the border of the 
 6550:        outer box if element is wrapped to the next 'line' 
 6551:     */
 6552:     margin-left: -1px;
 6553: }
 6554: 
 6555: ul.LC_funclist li {
 6556:   display: inline;
 6557:   white-space: nowrap;
 6558:   margin: 0 0 0 25px;
 6559:   line-height: 150%;
 6560: }
 6561: 
 6562: .ui-accordion .LC_advanced_toggle {
 6563:   float: right;
 6564:   font-size: 90%;
 6565:   padding: 0px 4px
 6566: }
 6567: 
 6568: .LC_hidden {
 6569:   display: none;
 6570: }
 6571: 
 6572: END
 6573: }
 6574: 
 6575: =pod
 6576: 
 6577: =item * &headtag()
 6578: 
 6579: Returns a uniform footer for LON-CAPA web pages.
 6580: 
 6581: Inputs: $title - optional title for the head
 6582:         $head_extra - optional extra HTML to put inside the <head>
 6583:         $args - optional arguments
 6584:             force_register - if is true call registerurl so the remote is 
 6585:                              informed
 6586:             redirect       -> array ref of
 6587:                                    1- seconds before redirect occurs
 6588:                                    2- url to redirect to
 6589:                                    3- whether the side effect should occur
 6590:                            (side effect of setting 
 6591:                                $env{'internal.head.redirect'} to the url 
 6592:                                redirected too)
 6593:             domain         -> force to color decorate a page for a specific
 6594:                                domain
 6595:             function       -> force usage of a specific rolish color scheme
 6596:             bgcolor        -> override the default page bgcolor
 6597:             no_auto_mt_title
 6598:                            -> prevent &mt()ing the title arg
 6599: 
 6600: =cut
 6601: 
 6602: sub headtag {
 6603:     my ($title,$head_extra,$args) = @_;
 6604:     
 6605:     my $function = $args->{'function'} || &get_users_function();
 6606:     my $domain   = $args->{'domain'}   || &determinedomain();
 6607:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6608:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6609: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6610: 		   #time(),
 6611: 		   $env{'environment.color.timestamp'},
 6612: 		   $function,$domain,$bgcolor);
 6613: 
 6614:     $url = '/adm/css/'.&escape($url).'.css';
 6615: 
 6616:     my $result =
 6617: 	'<head>'.
 6618: 	&font_settings();
 6619: 
 6620:     if (!$args->{'frameset'}) {
 6621: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6622:     }
 6623:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 6624:         $result .= Apache::lonxml::display_title();
 6625:     }
 6626:     if (!$args->{'no_nav_bar'} 
 6627: 	&& !$args->{'only_body'}
 6628: 	&& !$args->{'frameset'}) {
 6629: 	$result .= &help_menu_js();
 6630:     }
 6631: 
 6632:     if (ref($args->{'redirect'})) {
 6633: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6634: 	$url = &Apache::lonenc::check_encrypt($url);
 6635: 	if (!$inhibit_continue) {
 6636: 	    $env{'internal.head.redirect'} = $url;
 6637: 	}
 6638: 	$result.=<<ADDMETA
 6639: <meta http-equiv="pragma" content="no-cache" />
 6640: <meta http-equiv="Refresh" content="$time; url=$url" />
 6641: ADDMETA
 6642:     }
 6643:     if (!defined($title)) {
 6644: 	$title = 'The LearningOnline Network with CAPA';
 6645:     }
 6646:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6647:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6648: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6649: 	.$head_extra;
 6650:     return $result.'</head>';
 6651: }
 6652: 
 6653: =pod
 6654: 
 6655: =item * &font_settings()
 6656: 
 6657: Returns neccessary <meta> to set the proper encoding
 6658: 
 6659: Inputs: none
 6660: 
 6661: =cut
 6662: 
 6663: sub font_settings {
 6664:     my $headerstring='';
 6665:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6666: 	$headerstring.=
 6667: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6668:     }
 6669:     return $headerstring;
 6670: }
 6671: 
 6672: =pod
 6673: 
 6674: =item * &xml_begin()
 6675: 
 6676: Returns the needed doctype and <html>
 6677: 
 6678: Inputs: none
 6679: 
 6680: =cut
 6681: 
 6682: sub xml_begin {
 6683:     my $output='';
 6684: 
 6685:     if ($env{'browser.mathml'}) {
 6686: 	$output='<?xml version="1.0"?>'
 6687:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6688: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6689:             
 6690: #	    .'<!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">] >'
 6691: 	    .'<!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">'
 6692:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6693: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6694:     } else {
 6695: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6696:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6697:     }
 6698:     return $output;
 6699: }
 6700: 
 6701: =pod
 6702: 
 6703: =item * &start_page()
 6704: 
 6705: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6706: 
 6707: Inputs:
 6708: 
 6709: =over 4
 6710: 
 6711: $title - optional title for the page
 6712: 
 6713: $head_extra - optional extra HTML to incude inside the <head>
 6714: 
 6715: $args - additional optional args supported are:
 6716: 
 6717: =over 8
 6718: 
 6719:              only_body      -> is true will set &bodytag() onlybodytag
 6720:                                     arg on
 6721:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6722:              add_entries    -> additional attributes to add to the  <body>
 6723:              domain         -> force to color decorate a page for a 
 6724:                                     specific domain
 6725:              function       -> force usage of a specific rolish color
 6726:                                     scheme
 6727:              redirect       -> see &headtag()
 6728:              bgcolor        -> override the default page bg color
 6729:              js_ready       -> return a string ready for being used in 
 6730:                                     a javascript writeln
 6731:              html_encode    -> return a string ready for being used in 
 6732:                                     a html attribute
 6733:              force_register -> if is true will turn on the &bodytag()
 6734:                                     $forcereg arg
 6735:              frameset       -> if true will start with a <frameset>
 6736:                                     rather than <body>
 6737:              skip_phases    -> hash ref of 
 6738:                                     head -> skip the <html><head> generation
 6739:                                     body -> skip all <body> generation
 6740:              no_auto_mt_title -> prevent &mt()ing the title arg
 6741:              inherit_jsmath -> when creating popup window in a page,
 6742:                                     should it have jsmath forced on by the
 6743:                                     current page
 6744:              bread_crumbs ->             Array containing breadcrumbs
 6745:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 6746: 
 6747: =back
 6748: 
 6749: =back
 6750: 
 6751: =cut
 6752: 
 6753: sub start_page {
 6754:     my ($title,$head_extra,$args) = @_;
 6755:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6756: #SD
 6757: #I don't see why we copy certain elements of %$args to %head_args
 6758: #head args is passed to headtag() and this routine only reads those
 6759: #keys that are needed. There doesn't happen any writes or any processing
 6760: #of other keys.
 6761: #proposal: just pass $args to headtag instead of \%head_args and delete 
 6762: #marked lines
 6763: #<- MARK
 6764:     my %head_args;
 6765:     foreach my $arg ('redirect','force_register','domain','function',
 6766: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6767: 		     'no_auto_mt_title') {
 6768: 	if (defined($args->{$arg})) {
 6769: 	    $head_args{$arg} = $args->{$arg};
 6770: 	}
 6771:     }
 6772: #MARK ->
 6773: 
 6774:     $env{'internal.start_page'}++;
 6775:     my $result;
 6776: 
 6777:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6778:         $result .= 
 6779:                   &xml_begin() . &headtag($title,$head_extra,\%head_args);
 6780: #replace prev line by
 6781: #                 &xml_begin() . &headtag($title, $head_extra, $args);
 6782:     }
 6783:     
 6784:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6785: 	if ($args->{'frameset'}) {
 6786: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6787: 						$args->{'add_entries'});
 6788: 	    $result .= "\n<frameset $attr_string>\n";
 6789:         } else {
 6790:             $result .=
 6791:                 &bodytag($title, 
 6792:                          $args->{'function'},       $args->{'add_entries'},
 6793:                          $args->{'only_body'},      $args->{'domain'},
 6794:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6795:                          $args->{'bgcolor'},        $args);
 6796:         }
 6797:     }
 6798: 
 6799:     if ($args->{'js_ready'}) {
 6800: 		$result = &js_ready($result);
 6801:     }
 6802:     if ($args->{'html_encode'}) {
 6803: 		$result = &html_encode($result);
 6804:     }
 6805: 
 6806:     # Preparation for new and consistent functionlist at top of screen
 6807:     # if ($args->{'functionlist'}) {
 6808:     #            $result .= &build_functionlist();
 6809:     #}
 6810: 
 6811:     # Don't add anything more if only_body wanted or in const space
 6812:     return $result if    $args->{'only_body'} 
 6813:                       || $env{'request.state'} eq 'construct';
 6814: 
 6815:     #Breadcrumbs
 6816:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6817: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6818: 		#if any br links exists, add them to the breadcrumbs
 6819: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6820: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6821: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6822: 			}
 6823: 		}
 6824: 
 6825: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6826: 		if(exists($args->{'bread_crumbs_component'})){
 6827: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6828: 		}else{
 6829: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6830: 		}
 6831:     }
 6832:     return $result;
 6833: }
 6834: 
 6835: sub end_page {
 6836:     my ($args) = @_;
 6837:     $env{'internal.end_page'}++;
 6838:     my $result;
 6839:     if ($args->{'discussion'}) {
 6840: 	my ($target,$parser);
 6841: 	if (ref($args->{'discussion'})) {
 6842: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6843: 				$args->{'discussion'}{'parser'});
 6844: 	}
 6845: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6846:     }
 6847: 
 6848:     if ($args->{'frameset'}) {
 6849: 	$result .= '</frameset>';
 6850:     } else {
 6851: 	$result .= &endbodytag($args);
 6852:     }
 6853:     $result .= "\n</html>";
 6854: 
 6855:     if ($args->{'js_ready'}) {
 6856: 	$result = &js_ready($result);
 6857:     }
 6858: 
 6859:     if ($args->{'html_encode'}) {
 6860: 	$result = &html_encode($result);
 6861:     }
 6862: 
 6863:     return $result;
 6864: }
 6865: 
 6866: sub html_encode {
 6867:     my ($result) = @_;
 6868: 
 6869:     $result = &HTML::Entities::encode($result,'<>&"');
 6870:     
 6871:     return $result;
 6872: }
 6873: sub js_ready {
 6874:     my ($result) = @_;
 6875: 
 6876:     $result =~ s/[\n\r]/ /xmsg;
 6877:     $result =~ s/\\/\\\\/xmsg;
 6878:     $result =~ s/'/\\'/xmsg;
 6879:     $result =~ s{</}{<\\/}xmsg;
 6880:     
 6881:     return $result;
 6882: }
 6883: 
 6884: sub validate_page {
 6885:     if (  exists($env{'internal.start_page'})
 6886: 	  &&     $env{'internal.start_page'} > 1) {
 6887: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6888: 				 $env{'internal.start_page'}.' '.
 6889: 				 $ENV{'request.filename'});
 6890:     }
 6891:     if (  exists($env{'internal.end_page'})
 6892: 	  &&     $env{'internal.end_page'} > 1) {
 6893: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6894: 				 $env{'internal.end_page'}.' '.
 6895: 				 $env{'request.filename'});
 6896:     }
 6897:     if (     exists($env{'internal.start_page'})
 6898: 	&& ! exists($env{'internal.end_page'})) {
 6899: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6900: 				 $env{'request.filename'});
 6901:     }
 6902:     if (   ! exists($env{'internal.start_page'})
 6903: 	&&   exists($env{'internal.end_page'})) {
 6904: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6905: 				 $env{'request.filename'});
 6906:     }
 6907: }
 6908: 
 6909: 
 6910: sub start_scrollbox {
 6911:     my ($outerwidth,$width,$height)=@_;
 6912:     unless ($outerwidth) { $outerwidth='520px'; }
 6913:     unless ($width) { $width='500px'; }
 6914:     unless ($height) { $height='200px'; }
 6915:     return "<table style='width: $outerwidth; border: 1px solid black;'><tr><td style='width: $width;' bgcolor='#FFFFFF'><div style='overflow:auto; width:$width; height: $height;'>";
 6916: }
 6917: 
 6918: sub end_scrollbox {
 6919:     return '</td></tr></table>';
 6920: }
 6921: 
 6922: sub simple_error_page {
 6923:     my ($r,$title,$msg) = @_;
 6924:     my $page =
 6925: 	&Apache::loncommon::start_page($title).
 6926: 	&mt($msg).
 6927: 	&Apache::loncommon::end_page();
 6928:     if (ref($r)) {
 6929: 	$r->print($page);
 6930: 	return;
 6931:     }
 6932:     return $page;
 6933: }
 6934: 
 6935: {
 6936:     my @row_count;
 6937: 
 6938:     sub start_data_table_count {
 6939:         unshift(@row_count, 0);
 6940:         return;
 6941:     }
 6942: 
 6943:     sub end_data_table_count {
 6944:         shift(@row_count);
 6945:         return;
 6946:     }
 6947: 
 6948:     sub start_data_table {
 6949: 	my ($add_class) = @_;
 6950: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6951: 	&start_data_table_count();
 6952: 	return '<table class="'.$css_class.'">'."\n";
 6953:     }
 6954: 
 6955:     sub end_data_table {
 6956: 	&end_data_table_count();
 6957: 	return '</table>'."\n";;
 6958:     }
 6959: 
 6960:     sub start_data_table_row {
 6961: 	my ($add_class, $id) = @_;
 6962: 	$row_count[0]++;
 6963: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6964: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6965:         $id = (' id="'.$id.'"') unless ($id eq '');
 6966:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6967:     }
 6968:     
 6969:     sub continue_data_table_row {
 6970: 	my ($add_class, $id) = @_;
 6971: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6972: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6973:         $id = (' id="'.$id.'"') unless ($id eq '');
 6974:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6975:     }
 6976: 
 6977:     sub end_data_table_row {
 6978: 	return '</tr>'."\n";;
 6979:     }
 6980: 
 6981:     sub start_data_table_empty_row {
 6982: #	$row_count[0]++;
 6983: 	return  '<tr class="LC_empty_row" >'."\n";;
 6984:     }
 6985: 
 6986:     sub end_data_table_empty_row {
 6987: 	return '</tr>'."\n";;
 6988:     }
 6989: 
 6990:     sub start_data_table_header_row {
 6991: 	return  '<tr class="LC_header_row">'."\n";;
 6992:     }
 6993: 
 6994:     sub end_data_table_header_row {
 6995: 	return '</tr>'."\n";;
 6996:     }
 6997: 
 6998:     sub data_table_caption {
 6999:         my $caption = shift;
 7000:         return "<caption class=\"LC_caption\">$caption</caption>";
 7001:     }
 7002: }
 7003: 
 7004: =pod
 7005: 
 7006: =item * &inhibit_menu_check($arg)
 7007: 
 7008: Checks for a inhibitmenu state and generates output to preserve it
 7009: 
 7010: Inputs:         $arg - can be any of
 7011:                      - undef - in which case the return value is a string 
 7012:                                to add  into arguments list of a uri
 7013:                      - 'input' - in which case the return value is a HTML
 7014:                                  <form> <input> field of type hidden to
 7015:                                  preserve the value
 7016:                      - a url - in which case the return value is the url with
 7017:                                the neccesary cgi args added to preserve the
 7018:                                inhibitmenu state
 7019:                      - a ref to a url - no return value, but the string is
 7020:                                         updated to include the neccessary cgi
 7021:                                         args to preserve the inhibitmenu state
 7022: 
 7023: =cut
 7024: 
 7025: sub inhibit_menu_check {
 7026:     my ($arg) = @_;
 7027:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 7028:     if ($arg eq 'input') {
 7029: 	if ($env{'form.inhibitmenu'}) {
 7030: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 7031: 	} else {
 7032: 	    return
 7033: 	}
 7034:     }
 7035:     if ($env{'form.inhibitmenu'}) {
 7036: 	if (ref($arg)) {
 7037: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7038: 	} elsif ($arg eq '') {
 7039: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 7040: 	} else {
 7041: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 7042: 	}
 7043:     }
 7044:     if (!ref($arg)) {
 7045: 	return $arg;
 7046:     }
 7047: }
 7048: 
 7049: ###############################################
 7050: 
 7051: =pod
 7052: 
 7053: =back
 7054: 
 7055: =head1 User Information Routines
 7056: 
 7057: =over 4
 7058: 
 7059: =item * &get_users_function()
 7060: 
 7061: Used by &bodytag to determine the current users primary role.
 7062: Returns either 'student','coordinator','admin', or 'author'.
 7063: 
 7064: =cut
 7065: 
 7066: ###############################################
 7067: sub get_users_function {
 7068:     my $function = 'norole';
 7069:     if ($env{'request.role'}=~/^(st)/) {
 7070:         $function='student';
 7071:     }
 7072:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7073:         $function='coordinator';
 7074:     }
 7075:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7076:         $function='admin';
 7077:     }
 7078:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7079:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7080:         $function='author';
 7081:     }
 7082:     return $function;
 7083: }
 7084: 
 7085: ###############################################
 7086: 
 7087: =pod
 7088: 
 7089: =item * &show_course()
 7090: 
 7091: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7092: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7093: 
 7094: Inputs:
 7095: None
 7096: 
 7097: Outputs:
 7098: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7099: 
 7100: =cut
 7101: 
 7102: ###############################################
 7103: sub show_course {
 7104:     my $course = !$env{'user.adv'};
 7105:     if (!$env{'user.adv'}) {
 7106:         foreach my $env (keys(%env)) {
 7107:             next if ($env !~ m/^user\.priv\./);
 7108:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7109:                 $course = 0;
 7110:                 last;
 7111:             }
 7112:         }
 7113:     }
 7114:     return $course;
 7115: }
 7116: 
 7117: ###############################################
 7118: 
 7119: =pod
 7120: 
 7121: =item * &check_user_status()
 7122: 
 7123: Determines current status of supplied role for a
 7124: specific user. Roles can be active, previous or future.
 7125: 
 7126: Inputs: 
 7127: user's domain, user's username, course's domain,
 7128: course's number, optional section ID.
 7129: 
 7130: Outputs:
 7131: role status: active, previous or future. 
 7132: 
 7133: =cut
 7134: 
 7135: sub check_user_status {
 7136:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7137:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7138:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7139:     my @uroles = keys %userinfo;
 7140:     my $srchstr;
 7141:     my $active_chk = 'none';
 7142:     my $now = time;
 7143:     if (@uroles > 0) {
 7144:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7145:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7146:         } else {
 7147:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7148:         }
 7149:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7150:             my $role_end = 0;
 7151:             my $role_start = 0;
 7152:             $active_chk = 'active';
 7153:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7154:                 $role_end = $1;
 7155:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7156:                     $role_start = $1;
 7157:                 }
 7158:             }
 7159:             if ($role_start > 0) {
 7160:                 if ($now < $role_start) {
 7161:                     $active_chk = 'future';
 7162:                 }
 7163:             }
 7164:             if ($role_end > 0) {
 7165:                 if ($now > $role_end) {
 7166:                     $active_chk = 'previous';
 7167:                 }
 7168:             }
 7169:         }
 7170:     }
 7171:     return $active_chk;
 7172: }
 7173: 
 7174: ###############################################
 7175: 
 7176: =pod
 7177: 
 7178: =item * &get_sections()
 7179: 
 7180: Determines all the sections for a course including
 7181: sections with students and sections containing other roles.
 7182: Incoming parameters: 
 7183: 
 7184: 1. domain
 7185: 2. course number 
 7186: 3. reference to array containing roles for which sections should 
 7187: be gathered (optional).
 7188: 4. reference to array containing status types for which sections 
 7189: should be gathered (optional).
 7190: 
 7191: If the third argument is undefined, sections are gathered for any role. 
 7192: If the fourth argument is undefined, sections are gathered for any status.
 7193: Permissible values are 'active' or 'future' or 'previous'.
 7194:  
 7195: Returns section hash (keys are section IDs, values are
 7196: number of users in each section), subject to the
 7197: optional roles filter, optional status filter 
 7198: 
 7199: =cut
 7200: 
 7201: ###############################################
 7202: sub get_sections {
 7203:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7204:     if (!defined($cdom) || !defined($cnum)) {
 7205:         my $cid =  $env{'request.course.id'};
 7206: 
 7207: 	return if (!defined($cid));
 7208: 
 7209:         $cdom = $env{'course.'.$cid.'.domain'};
 7210:         $cnum = $env{'course.'.$cid.'.num'};
 7211:     }
 7212: 
 7213:     my %sectioncount;
 7214:     my $now = time;
 7215: 
 7216:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7217: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7218: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7219: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7220:         my $start_index = &Apache::loncoursedata::CL_START();
 7221:         my $end_index = &Apache::loncoursedata::CL_END();
 7222:         my $status;
 7223: 	while (my ($student,$data) = each(%$classlist)) {
 7224: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7225: 				                     $data->[$status_index],
 7226:                                                      $data->[$start_index],
 7227:                                                      $data->[$end_index]);
 7228:             if ($stu_status eq 'Active') {
 7229:                 $status = 'active';
 7230:             } elsif ($end < $now) {
 7231:                 $status = 'previous';
 7232:             } elsif ($start > $now) {
 7233:                 $status = 'future';
 7234:             } 
 7235: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7236:                 if ((!defined($possible_status)) || (($status ne '') && 
 7237:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7238: 		    $sectioncount{$section}++;
 7239:                 }
 7240: 	    }
 7241: 	}
 7242:     }
 7243:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7244:     foreach my $user (sort(keys(%courseroles))) {
 7245: 	if ($user !~ /^(\w{2})/) { next; }
 7246: 	my ($role) = ($user =~ /^(\w{2})/);
 7247: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7248: 	my ($section,$status);
 7249: 	if ($role eq 'cr' &&
 7250: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7251: 	    $section=$1;
 7252: 	}
 7253: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7254: 	if (!defined($section) || $section eq '-1') { next; }
 7255:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7256:         if ($end == -1 && $start == -1) {
 7257:             next; #deleted role
 7258:         }
 7259:         if (!defined($possible_status)) { 
 7260:             $sectioncount{$section}++;
 7261:         } else {
 7262:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7263:                 $status = 'active';
 7264:             } elsif ($end < $now) {
 7265:                 $status = 'future';
 7266:             } elsif ($start > $now) {
 7267:                 $status = 'previous';
 7268:             }
 7269:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7270:                 $sectioncount{$section}++;
 7271:             }
 7272:         }
 7273:     }
 7274:     return %sectioncount;
 7275: }
 7276: 
 7277: ###############################################
 7278: 
 7279: =pod
 7280: 
 7281: =item * &get_course_users()
 7282: 
 7283: Retrieves usernames:domains for users in the specified course
 7284: with specific role(s), and access status. 
 7285: 
 7286: Incoming parameters:
 7287: 1. course domain
 7288: 2. course number
 7289: 3. access status: users must have - either active, 
 7290: previous, future, or all.
 7291: 4. reference to array of permissible roles
 7292: 5. reference to array of section restrictions (optional)
 7293: 6. reference to results object (hash of hashes).
 7294: 7. reference to optional userdata hash
 7295: 8. reference to optional statushash
 7296: 9. flag if privileged users (except those set to unhide in
 7297:    course settings) should be excluded    
 7298: Keys of top level results hash are roles.
 7299: Keys of inner hashes are username:domain, with 
 7300: values set to access type.
 7301: Optional userdata hash returns an array with arguments in the 
 7302: same order as loncoursedata::get_classlist() for student data.
 7303: 
 7304: Optional statushash returns
 7305: 
 7306: Entries for end, start, section and status are blank because
 7307: of the possibility of multiple values for non-student roles.
 7308: 
 7309: =cut
 7310: 
 7311: ###############################################
 7312: 
 7313: sub get_course_users {
 7314:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7315:     my %idx = ();
 7316:     my %seclists;
 7317: 
 7318:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7319:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7320:     $idx{end} = &Apache::loncoursedata::CL_END();
 7321:     $idx{start} = &Apache::loncoursedata::CL_START();
 7322:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7323:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7324:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7325:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7326: 
 7327:     if (grep(/^st$/,@{$roles})) {
 7328:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7329:         my $now = time;
 7330:         foreach my $student (keys(%{$classlist})) {
 7331:             my $match = 0;
 7332:             my $secmatch = 0;
 7333:             my $section = $$classlist{$student}[$idx{section}];
 7334:             my $status = $$classlist{$student}[$idx{status}];
 7335:             if ($section eq '') {
 7336:                 $section = 'none';
 7337:             }
 7338:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7339:                 if (grep(/^all$/,@{$sections})) {
 7340:                     $secmatch = 1;
 7341:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7342:                     if (grep(/^none$/,@{$sections})) {
 7343:                         $secmatch = 1;
 7344:                     }
 7345:                 } else {  
 7346: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7347: 		        $secmatch = 1;
 7348:                     }
 7349: 		}
 7350:                 if (!$secmatch) {
 7351:                     next;
 7352:                 }
 7353:             }
 7354:             if (defined($$types{'active'})) {
 7355:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7356:                     push(@{$$users{st}{$student}},'active');
 7357:                     $match = 1;
 7358:                 }
 7359:             }
 7360:             if (defined($$types{'previous'})) {
 7361:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7362:                     push(@{$$users{st}{$student}},'previous');
 7363:                     $match = 1;
 7364:                 }
 7365:             }
 7366:             if (defined($$types{'future'})) {
 7367:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7368:                     push(@{$$users{st}{$student}},'future');
 7369:                     $match = 1;
 7370:                 }
 7371:             }
 7372:             if ($match) {
 7373:                 push(@{$seclists{$student}},$section);
 7374:                 if (ref($userdata) eq 'HASH') {
 7375:                     $$userdata{$student} = $$classlist{$student};
 7376:                 }
 7377:                 if (ref($statushash) eq 'HASH') {
 7378:                     $statushash->{$student}{'st'}{$section} = $status;
 7379:                 }
 7380:             }
 7381:         }
 7382:     }
 7383:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7384:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7385:         my $now = time;
 7386:         my %displaystatus = ( previous => 'Expired',
 7387:                               active   => 'Active',
 7388:                               future   => 'Future',
 7389:                             );
 7390:         my %nothide;
 7391:         if ($hidepriv) {
 7392:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7393:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7394:                 if ($user !~ /:/) {
 7395:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7396:                 } else {
 7397:                     $nothide{$user} = 1;
 7398:                 }
 7399:             }
 7400:         }
 7401:         foreach my $person (sort(keys(%coursepersonnel))) {
 7402:             my $match = 0;
 7403:             my $secmatch = 0;
 7404:             my $status;
 7405:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7406:             $user =~ s/:$//;
 7407:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7408:             if ($end == -1 || $start == -1) {
 7409:                 next;
 7410:             }
 7411:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7412:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7413:                 my ($uname,$udom) = split(/:/,$user);
 7414:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7415:                     if (grep(/^all$/,@{$sections})) {
 7416:                         $secmatch = 1;
 7417:                     } elsif ($usec eq '') {
 7418:                         if (grep(/^none$/,@{$sections})) {
 7419:                             $secmatch = 1;
 7420:                         }
 7421:                     } else {
 7422:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7423:                             $secmatch = 1;
 7424:                         }
 7425:                     }
 7426:                     if (!$secmatch) {
 7427:                         next;
 7428:                     }
 7429:                 }
 7430:                 if ($usec eq '') {
 7431:                     $usec = 'none';
 7432:                 }
 7433:                 if ($uname ne '' && $udom ne '') {
 7434:                     if ($hidepriv) {
 7435:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7436:                             (!$nothide{$uname.':'.$udom})) {
 7437:                             next;
 7438:                         }
 7439:                     }
 7440:                     if ($end > 0 && $end < $now) {
 7441:                         $status = 'previous';
 7442:                     } elsif ($start > $now) {
 7443:                         $status = 'future';
 7444:                     } else {
 7445:                         $status = 'active';
 7446:                     }
 7447:                     foreach my $type (keys(%{$types})) { 
 7448:                         if ($status eq $type) {
 7449:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7450:                                 push(@{$$users{$role}{$user}},$type);
 7451:                             }
 7452:                             $match = 1;
 7453:                         }
 7454:                     }
 7455:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7456:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7457: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7458:                         }
 7459:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7460:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7461:                         }
 7462:                         if (ref($statushash) eq 'HASH') {
 7463:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7464:                         }
 7465:                     }
 7466:                 }
 7467:             }
 7468:         }
 7469:         if (grep(/^ow$/,@{$roles})) {
 7470:             if ((defined($cdom)) && (defined($cnum))) {
 7471:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7472:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7473:                     my $owner = $csettings{'internal.courseowner'};
 7474:                     next if ($owner eq '');
 7475:                     my ($ownername,$ownerdom);
 7476:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7477:                         $ownername = $1;
 7478:                         $ownerdom = $2;
 7479:                     } else {
 7480:                         $ownername = $owner;
 7481:                         $ownerdom = $cdom;
 7482:                         $owner = $ownername.':'.$ownerdom;
 7483:                     }
 7484:                     @{$$users{'ow'}{$owner}} = 'any';
 7485:                     if (defined($userdata) && 
 7486: 			!exists($$userdata{$owner})) {
 7487: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7488:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7489:                             push(@{$seclists{$owner}},'none');
 7490:                         }
 7491:                         if (ref($statushash) eq 'HASH') {
 7492:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7493:                         }
 7494: 		    }
 7495:                 }
 7496:             }
 7497:         }
 7498:         foreach my $user (keys(%seclists)) {
 7499:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7500:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7501:         }
 7502:     }
 7503:     return;
 7504: }
 7505: 
 7506: sub get_user_info {
 7507:     my ($udom,$uname,$idx,$userdata) = @_;
 7508:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7509: 	&plainname($uname,$udom,'lastname');
 7510:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7511:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7512:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7513:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7514:     return;
 7515: }
 7516: 
 7517: ###############################################
 7518: 
 7519: =pod
 7520: 
 7521: =item * &get_user_quota()
 7522: 
 7523: Retrieves quota assigned for storage of portfolio files for a user  
 7524: 
 7525: Incoming parameters:
 7526: 1. user's username
 7527: 2. user's domain
 7528: 
 7529: Returns:
 7530: 1. Disk quota (in Mb) assigned to student.
 7531: 2. (Optional) Type of setting: custom or default
 7532:    (individually assigned or default for user's 
 7533:    institutional status).
 7534: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7535:    or student - types as defined in localenroll::inst_usertypes 
 7536:    for user's domain, which determines default quota for user.
 7537: 4. (Optional) - Default quota which would apply to the user.
 7538: 
 7539: If a value has been stored in the user's environment, 
 7540: it will return that, otherwise it returns the maximal default
 7541: defined for the user's instituional status(es) in the domain.
 7542: 
 7543: =cut
 7544: 
 7545: ###############################################
 7546: 
 7547: 
 7548: sub get_user_quota {
 7549:     my ($uname,$udom) = @_;
 7550:     my ($quota,$quotatype,$settingstatus,$defquota);
 7551:     if (!defined($udom)) {
 7552:         $udom = $env{'user.domain'};
 7553:     }
 7554:     if (!defined($uname)) {
 7555:         $uname = $env{'user.name'};
 7556:     }
 7557:     if (($udom eq '' || $uname eq '') ||
 7558:         ($udom eq 'public') && ($uname eq 'public')) {
 7559:         $quota = 0;
 7560:         $quotatype = 'default';
 7561:         $defquota = 0; 
 7562:     } else {
 7563:         my $inststatus;
 7564:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7565:             $quota = $env{'environment.portfolioquota'};
 7566:             $inststatus = $env{'environment.inststatus'};
 7567:         } else {
 7568:             my %userenv = 
 7569:                 &Apache::lonnet::get('environment',['portfolioquota',
 7570:                                      'inststatus'],$udom,$uname);
 7571:             my ($tmp) = keys(%userenv);
 7572:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7573:                 $quota = $userenv{'portfolioquota'};
 7574:                 $inststatus = $userenv{'inststatus'};
 7575:             } else {
 7576:                 undef(%userenv);
 7577:             }
 7578:         }
 7579:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7580:         if ($quota eq '') {
 7581:             $quota = $defquota;
 7582:             $quotatype = 'default';
 7583:         } else {
 7584:             $quotatype = 'custom';
 7585:         }
 7586:     }
 7587:     if (wantarray) {
 7588:         return ($quota,$quotatype,$settingstatus,$defquota);
 7589:     } else {
 7590:         return $quota;
 7591:     }
 7592: }
 7593: 
 7594: ###############################################
 7595: 
 7596: =pod
 7597: 
 7598: =item * &default_quota()
 7599: 
 7600: Retrieves default quota assigned for storage of user portfolio files,
 7601: given an (optional) user's institutional status.
 7602: 
 7603: Incoming parameters:
 7604: 1. domain
 7605: 2. (Optional) institutional status(es).  This is a : separated list of 
 7606:    status types (e.g., faculty, staff, student etc.)
 7607:    which apply to the user for whom the default is being retrieved.
 7608:    If the institutional status string in undefined, the domain
 7609:    default quota will be returned. 
 7610: 
 7611: Returns:
 7612: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7613: 2. (Optional) institutional type which determined the value of the
 7614:    default quota.
 7615: 
 7616: If a value has been stored in the domain's configuration db,
 7617: it will return that, otherwise it returns 20 (for backwards 
 7618: compatibility with domains which have not set up a configuration
 7619: db file; the original statically defined portfolio quota was 20 Mb). 
 7620: 
 7621: If the user's status includes multiple types (e.g., staff and student),
 7622: the largest default quota which applies to the user determines the
 7623: default quota returned.
 7624: 
 7625: =back
 7626: 
 7627: =cut
 7628: 
 7629: ###############################################
 7630: 
 7631: 
 7632: sub default_quota {
 7633:     my ($udom,$inststatus) = @_;
 7634:     my ($defquota,$settingstatus);
 7635:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7636:                                             ['quotas'],$udom);
 7637:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7638:         if ($inststatus ne '') {
 7639:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7640:             foreach my $item (@statuses) {
 7641:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7642:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7643:                         if ($defquota eq '') {
 7644:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7645:                             $settingstatus = $item;
 7646:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7647:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7648:                             $settingstatus = $item;
 7649:                         }
 7650:                     }
 7651:                 } else {
 7652:                     if ($quotahash{'quotas'}{$item} ne '') {
 7653:                         if ($defquota eq '') {
 7654:                             $defquota = $quotahash{'quotas'}{$item};
 7655:                             $settingstatus = $item;
 7656:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7657:                             $defquota = $quotahash{'quotas'}{$item};
 7658:                             $settingstatus = $item;
 7659:                         }
 7660:                     }
 7661:                 }
 7662:             }
 7663:         }
 7664:         if ($defquota eq '') {
 7665:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7666:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7667:             } else {
 7668:                 $defquota = $quotahash{'quotas'}{'default'};
 7669:             }
 7670:             $settingstatus = 'default';
 7671:         }
 7672:     } else {
 7673:         $settingstatus = 'default';
 7674:         $defquota = 20;
 7675:     }
 7676:     if (wantarray) {
 7677:         return ($defquota,$settingstatus);
 7678:     } else {
 7679:         return $defquota;
 7680:     }
 7681: }
 7682: 
 7683: sub get_secgrprole_info {
 7684:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7685:     my %sections_count = &get_sections($cdom,$cnum);
 7686:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7687:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7688:     my @groups = sort(keys(%curr_groups));
 7689:     my $allroles = [];
 7690:     my $rolehash;
 7691:     my $accesshash = {
 7692:                      active => 'Currently has access',
 7693:                      future => 'Will have future access',
 7694:                      previous => 'Previously had access',
 7695:                   };
 7696:     if ($needroles) {
 7697:         $rolehash = {'all' => 'all'};
 7698:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7699: 	if (&Apache::lonnet::error(%user_roles)) {
 7700: 	    undef(%user_roles);
 7701: 	}
 7702:         foreach my $item (keys(%user_roles)) {
 7703:             my ($role)=split(/\:/,$item,2);
 7704:             if ($role eq 'cr') { next; }
 7705:             if ($role =~ /^cr/) {
 7706:                 $$rolehash{$role} = (split('/',$role))[3];
 7707:             } else {
 7708:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7709:             }
 7710:         }
 7711:         foreach my $key (sort(keys(%{$rolehash}))) {
 7712:             push(@{$allroles},$key);
 7713:         }
 7714:         push (@{$allroles},'st');
 7715:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7716:     }
 7717:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7718: }
 7719: 
 7720: sub user_picker {
 7721:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 7722:     my $currdom = $dom;
 7723:     my %curr_selected = (
 7724:                         srchin => 'dom',
 7725:                         srchby => 'lastname',
 7726:                       );
 7727:     my $srchterm;
 7728:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7729:         if ($srch->{'srchby'} ne '') {
 7730:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7731:         }
 7732:         if ($srch->{'srchin'} ne '') {
 7733:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7734:         }
 7735:         if ($srch->{'srchtype'} ne '') {
 7736:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7737:         }
 7738:         if ($srch->{'srchdomain'} ne '') {
 7739:             $currdom = $srch->{'srchdomain'};
 7740:         }
 7741:         $srchterm = $srch->{'srchterm'};
 7742:     }
 7743:     my %lt=&Apache::lonlocal::texthash(
 7744:                     'usr'       => 'Search criteria',
 7745:                     'doma'      => 'Domain/institution to search',
 7746:                     'uname'     => 'username',
 7747:                     'lastname'  => 'last name',
 7748:                     'lastfirst' => 'last name, first name',
 7749:                     'crs'       => 'in this course',
 7750:                     'dom'       => 'in selected LON-CAPA domain', 
 7751:                     'alc'       => 'all LON-CAPA',
 7752:                     'instd'     => 'in institutional directory for selected domain',
 7753:                     'exact'     => 'is',
 7754:                     'contains'  => 'contains',
 7755:                     'begins'    => 'begins with',
 7756:                     'youm'      => "You must include some text to search for.",
 7757:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7758:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7759:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7760:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7761:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7762:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7763:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7764:                                        );
 7765:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7766:     my $srchinsel = ' <select name="srchin">';
 7767: 
 7768:     my @srchins = ('crs','dom','alc','instd');
 7769: 
 7770:     foreach my $option (@srchins) {
 7771:         # FIXME 'alc' option unavailable until 
 7772:         #       loncreateuser::print_user_query_page()
 7773:         #       has been completed.
 7774:         next if ($option eq 'alc');
 7775:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7776:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7777:         if ($curr_selected{'srchin'} eq $option) {
 7778:             $srchinsel .= ' 
 7779:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7780:         } else {
 7781:             $srchinsel .= '
 7782:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7783:         }
 7784:     }
 7785:     $srchinsel .= "\n  </select>\n";
 7786: 
 7787:     my $srchbysel =  ' <select name="srchby">';
 7788:     foreach my $option ('lastname','lastfirst','uname') {
 7789:         if ($curr_selected{'srchby'} eq $option) {
 7790:             $srchbysel .= '
 7791:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7792:         } else {
 7793:             $srchbysel .= '
 7794:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7795:          }
 7796:     }
 7797:     $srchbysel .= "\n  </select>\n";
 7798: 
 7799:     my $srchtypesel = ' <select name="srchtype">';
 7800:     foreach my $option ('begins','contains','exact') {
 7801:         if ($curr_selected{'srchtype'} eq $option) {
 7802:             $srchtypesel .= '
 7803:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7804:         } else {
 7805:             $srchtypesel .= '
 7806:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7807:         }
 7808:     }
 7809:     $srchtypesel .= "\n  </select>\n";
 7810: 
 7811:     my ($newuserscript,$new_user_create);
 7812:     my $context_dom = $env{'request.role.domain'};
 7813:     if ($context eq 'requestcrs') {
 7814:         if ($env{'form.coursedom'} ne '') { 
 7815:             $context_dom = $env{'form.coursedom'};
 7816:         }
 7817:     }
 7818:     if ($forcenewuser) {
 7819:         if (ref($srch) eq 'HASH') {
 7820:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 7821:                 if ($cancreate) {
 7822:                     $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>';
 7823:                 } else {
 7824:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7825:                     my %usertypetext = (
 7826:                         official   => 'institutional',
 7827:                         unofficial => 'non-institutional',
 7828:                     );
 7829:                     $new_user_create = '<p class="LC_warning">'
 7830:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7831:                                       .' '
 7832:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7833:                                           ,'<a href="'.$helplink.'">','</a>')
 7834:                                       .'</p><br />';
 7835:                 }
 7836:             }
 7837:         }
 7838: 
 7839:         $newuserscript = <<"ENDSCRIPT";
 7840: 
 7841: function setSearch(createnew,callingForm) {
 7842:     if (createnew == 1) {
 7843:         for (var i=0; i<callingForm.srchby.length; i++) {
 7844:             if (callingForm.srchby.options[i].value == 'uname') {
 7845:                 callingForm.srchby.selectedIndex = i;
 7846:             }
 7847:         }
 7848:         for (var i=0; i<callingForm.srchin.length; i++) {
 7849:             if ( callingForm.srchin.options[i].value == 'dom') {
 7850: 		callingForm.srchin.selectedIndex = i;
 7851:             }
 7852:         }
 7853:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7854:             if (callingForm.srchtype.options[i].value == 'exact') {
 7855:                 callingForm.srchtype.selectedIndex = i;
 7856:             }
 7857:         }
 7858:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7859:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 7860:                 callingForm.srchdomain.selectedIndex = i;
 7861:             }
 7862:         }
 7863:     }
 7864: }
 7865: ENDSCRIPT
 7866: 
 7867:     }
 7868: 
 7869:     my $output = <<"END_BLOCK";
 7870: <script type="text/javascript">
 7871: // <![CDATA[
 7872: function validateEntry(callingForm) {
 7873: 
 7874:     var checkok = 1;
 7875:     var srchin;
 7876:     for (var i=0; i<callingForm.srchin.length; i++) {
 7877: 	if ( callingForm.srchin[i].checked ) {
 7878: 	    srchin = callingForm.srchin[i].value;
 7879: 	}
 7880:     }
 7881: 
 7882:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7883:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7884:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7885:     var srchterm =  callingForm.srchterm.value;
 7886:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7887:     var msg = "";
 7888: 
 7889:     if (srchterm == "") {
 7890:         checkok = 0;
 7891:         msg += "$lt{'youm'}\\n";
 7892:     }
 7893: 
 7894:     if (srchtype== 'begins') {
 7895:         if (srchterm.length < 2) {
 7896:             checkok = 0;
 7897:             msg += "$lt{'thte'}\\n";
 7898:         }
 7899:     }
 7900: 
 7901:     if (srchtype== 'contains') {
 7902:         if (srchterm.length < 3) {
 7903:             checkok = 0;
 7904:             msg += "$lt{'thet'}\\n";
 7905:         }
 7906:     }
 7907:     if (srchin == 'instd') {
 7908:         if (srchdomain == '') {
 7909:             checkok = 0;
 7910:             msg += "$lt{'yomc'}\\n";
 7911:         }
 7912:     }
 7913:     if (srchin == 'dom') {
 7914:         if (srchdomain == '') {
 7915:             checkok = 0;
 7916:             msg += "$lt{'ymcd'}\\n";
 7917:         }
 7918:     }
 7919:     if (srchby == 'lastfirst') {
 7920:         if (srchterm.indexOf(",") == -1) {
 7921:             checkok = 0;
 7922:             msg += "$lt{'whus'}\\n";
 7923:         }
 7924:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7925:             checkok = 0;
 7926:             msg += "$lt{'whse'}\\n";
 7927:         }
 7928:     }
 7929:     if (checkok == 0) {
 7930:         alert("$lt{'thfo'}\\n"+msg);
 7931:         return;
 7932:     }
 7933:     if (checkok == 1) {
 7934:         callingForm.submit();
 7935:     }
 7936: }
 7937: 
 7938: $newuserscript
 7939: 
 7940: // ]]>
 7941: </script>
 7942: 
 7943: $new_user_create
 7944: 
 7945: END_BLOCK
 7946: 
 7947:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7948:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7949:                $domform.
 7950:                &Apache::lonhtmlcommon::row_closure().
 7951:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7952:                $srchbysel.
 7953:                $srchtypesel. 
 7954:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7955:                $srchinsel.
 7956:                &Apache::lonhtmlcommon::row_closure(1). 
 7957:                &Apache::lonhtmlcommon::end_pick_box().
 7958:                '<br />';
 7959:     return $output;
 7960: }
 7961: 
 7962: sub user_rule_check {
 7963:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7964:     my $response;
 7965:     if (ref($usershash) eq 'HASH') {
 7966:         foreach my $user (keys(%{$usershash})) {
 7967:             my ($uname,$udom) = split(/:/,$user);
 7968:             next if ($udom eq '' || $uname eq '');
 7969:             my ($id,$newuser);
 7970:             if (ref($usershash->{$user}) eq 'HASH') {
 7971:                 $newuser = $usershash->{$user}->{'newuser'};
 7972:                 $id = $usershash->{$user}->{'id'};
 7973:             }
 7974:             my $inst_response;
 7975:             if (ref($checks) eq 'HASH') {
 7976:                 if (defined($checks->{'username'})) {
 7977:                     ($inst_response,%{$inst_results->{$user}}) = 
 7978:                         &Apache::lonnet::get_instuser($udom,$uname);
 7979:                 } elsif (defined($checks->{'id'})) {
 7980:                     ($inst_response,%{$inst_results->{$user}}) =
 7981:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7982:                 }
 7983:             } else {
 7984:                 ($inst_response,%{$inst_results->{$user}}) =
 7985:                     &Apache::lonnet::get_instuser($udom,$uname);
 7986:                 return;
 7987:             }
 7988:             if (!$got_rules->{$udom}) {
 7989:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7990:                                                   ['usercreation'],$udom);
 7991:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7992:                     foreach my $item ('username','id') {
 7993:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7994:                             $$curr_rules{$udom}{$item} = 
 7995:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7996:                         }
 7997:                     }
 7998:                 }
 7999:                 $got_rules->{$udom} = 1;  
 8000:             }
 8001:             foreach my $item (keys(%{$checks})) {
 8002:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8003:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8004:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8005:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8006:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8007:                                 if ($rule_check{$rule}) {
 8008:                                     $$rulematch{$user}{$item} = $rule;
 8009:                                     if ($inst_response eq 'ok') {
 8010:                                         if (ref($inst_results) eq 'HASH') {
 8011:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 8012:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 8013:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 8014:                                                 }
 8015:                                             }
 8016:                                         }
 8017:                                     }
 8018:                                     last;
 8019:                                 }
 8020:                             }
 8021:                         }
 8022:                     }
 8023:                 }
 8024:             }
 8025:         }
 8026:     }
 8027:     return;
 8028: }
 8029: 
 8030: sub user_rule_formats {
 8031:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 8032:     my %text = ( 
 8033:                  'username' => 'Usernames',
 8034:                  'id'       => 'IDs',
 8035:                );
 8036:     my $output;
 8037:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 8038:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 8039:         if (@{$ruleorder} > 0) {
 8040:             $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>';
 8041:             foreach my $rule (@{$ruleorder}) {
 8042:                 if (ref($curr_rules) eq 'ARRAY') {
 8043:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 8044:                         if (ref($rules->{$rule}) eq 'HASH') {
 8045:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 8046:                                         $rules->{$rule}{'desc'}.'</li>';
 8047:                         }
 8048:                     }
 8049:                 }
 8050:             }
 8051:             $output .= '</ul>';
 8052:         }
 8053:     }
 8054:     return $output;
 8055: }
 8056: 
 8057: sub instrule_disallow_msg {
 8058:     my ($checkitem,$domdesc,$count,$mode) = @_;
 8059:     my $response;
 8060:     my %text = (
 8061:                   item   => 'username',
 8062:                   items  => 'usernames',
 8063:                   match  => 'matches',
 8064:                   do     => 'does',
 8065:                   action => 'a username',
 8066:                   one    => 'one',
 8067:                );
 8068:     if ($count > 1) {
 8069:         $text{'item'} = 'usernames';
 8070:         $text{'match'} ='match';
 8071:         $text{'do'} = 'do';
 8072:         $text{'action'} = 'usernames',
 8073:         $text{'one'} = 'ones';
 8074:     }
 8075:     if ($checkitem eq 'id') {
 8076:         $text{'items'} = 'IDs';
 8077:         $text{'item'} = 'ID';
 8078:         $text{'action'} = 'an ID';
 8079:         if ($count > 1) {
 8080:             $text{'item'} = 'IDs';
 8081:             $text{'action'} = 'IDs';
 8082:         }
 8083:     }
 8084:     $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 />';
 8085:     if ($mode eq 'upload') {
 8086:         if ($checkitem eq 'username') {
 8087:             $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'}.");
 8088:         } elsif ($checkitem eq 'id') {
 8089:             $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.");
 8090:         }
 8091:     } elsif ($mode eq 'selfcreate') {
 8092:         if ($checkitem eq 'id') {
 8093:             $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.");
 8094:         }
 8095:     } else {
 8096:         if ($checkitem eq 'username') {
 8097:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8098:         } elsif ($checkitem eq 'id') {
 8099:             $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.");
 8100:         }
 8101:     }
 8102:     return $response;
 8103: }
 8104: 
 8105: sub personal_data_fieldtitles {
 8106:     my %fieldtitles = &Apache::lonlocal::texthash (
 8107:                         id => 'Student/Employee ID',
 8108:                         permanentemail => 'E-mail address',
 8109:                         lastname => 'Last Name',
 8110:                         firstname => 'First Name',
 8111:                         middlename => 'Middle Name',
 8112:                         generation => 'Generation',
 8113:                         gen => 'Generation',
 8114:                         inststatus => 'Affiliation',
 8115:                    );
 8116:     return %fieldtitles;
 8117: }
 8118: 
 8119: sub sorted_inst_types {
 8120:     my ($dom) = @_;
 8121:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8122:     my $othertitle = &mt('All users');
 8123:     if ($env{'request.course.id'}) {
 8124:         $othertitle  = &mt('Any users');
 8125:     }
 8126:     my @types;
 8127:     if (ref($order) eq 'ARRAY') {
 8128:         @types = @{$order};
 8129:     }
 8130:     if (@types == 0) {
 8131:         if (ref($usertypes) eq 'HASH') {
 8132:             @types = sort(keys(%{$usertypes}));
 8133:         }
 8134:     }
 8135:     if (keys(%{$usertypes}) > 0) {
 8136:         $othertitle = &mt('Other users');
 8137:     }
 8138:     return ($othertitle,$usertypes,\@types);
 8139: }
 8140: 
 8141: sub get_institutional_codes {
 8142:     my ($settings,$allcourses,$LC_code) = @_;
 8143: # Get complete list of course sections to update
 8144:     my @currsections = ();
 8145:     my @currxlists = ();
 8146:     my $coursecode = $$settings{'internal.coursecode'};
 8147: 
 8148:     if ($$settings{'internal.sectionnums'} ne '') {
 8149:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8150:     }
 8151: 
 8152:     if ($$settings{'internal.crosslistings'} ne '') {
 8153:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8154:     }
 8155: 
 8156:     if (@currxlists > 0) {
 8157:         foreach (@currxlists) {
 8158:             if (m/^([^:]+):(\w*)$/) {
 8159:                 unless (grep/^$1$/,@{$allcourses}) {
 8160:                     push @{$allcourses},$1;
 8161:                     $$LC_code{$1} = $2;
 8162:                 }
 8163:             }
 8164:         }
 8165:     }
 8166:  
 8167:     if (@currsections > 0) {
 8168:         foreach (@currsections) {
 8169:             if (m/^(\w+):(\w*)$/) {
 8170:                 my $sec = $coursecode.$1;
 8171:                 my $lc_sec = $2;
 8172:                 unless (grep/^$sec$/,@{$allcourses}) {
 8173:                     push @{$allcourses},$sec;
 8174:                     $$LC_code{$sec} = $lc_sec;
 8175:                 }
 8176:             }
 8177:         }
 8178:     }
 8179:     return;
 8180: }
 8181: 
 8182: sub get_standard_codeitems {
 8183:     return ('Year','Semester','Department','Number','Section');
 8184: }
 8185: 
 8186: =pod
 8187: 
 8188: =head1 Slot Helpers
 8189: 
 8190: =over 4
 8191: 
 8192: =item * sorted_slots()
 8193: 
 8194: Sorts an array of slot names in order of slot start time (earliest first). 
 8195: 
 8196: Inputs:
 8197: 
 8198: =over 4
 8199: 
 8200: slotsarr  - Reference to array of unsorted slot names.
 8201: 
 8202: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8203: 
 8204: =back
 8205: 
 8206: Returns:
 8207: 
 8208: =over 4
 8209: 
 8210: sorted   - An array of slot names sorted by the start time of the slot.
 8211: 
 8212: =back
 8213: 
 8214: =back
 8215: 
 8216: =cut
 8217: 
 8218: 
 8219: sub sorted_slots {
 8220:     my ($slotsarr,$slots) = @_;
 8221:     my @sorted;
 8222:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8223:         @sorted =
 8224:             sort {
 8225:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8226:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8227:                      }
 8228:                      if (ref($slots->{$a})) { return -1;}
 8229:                      if (ref($slots->{$b})) { return 1;}
 8230:                      return 0;
 8231:                  } @{$slotsarr};
 8232:     }
 8233:     return @sorted;
 8234: }
 8235: 
 8236: 
 8237: =pod
 8238: 
 8239: =head1 HTTP Helpers
 8240: 
 8241: =over 4
 8242: 
 8243: =item * &get_unprocessed_cgi($query,$possible_names)
 8244: 
 8245: Modify the %env hash to contain unprocessed CGI form parameters held in
 8246: $query.  The parameters listed in $possible_names (an array reference),
 8247: will be set in $env{'form.name'} if they do not already exist.
 8248: 
 8249: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8250: $possible_names is an ref to an array of form element names.  As an example:
 8251: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8252: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8253: 
 8254: =cut
 8255: 
 8256: sub get_unprocessed_cgi {
 8257:   my ($query,$possible_names)= @_;
 8258:   # $Apache::lonxml::debug=1;
 8259:   foreach my $pair (split(/&/,$query)) {
 8260:     my ($name, $value) = split(/=/,$pair);
 8261:     $name = &unescape($name);
 8262:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8263:       $value =~ tr/+/ /;
 8264:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8265:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8266:     }
 8267:   }
 8268: }
 8269: 
 8270: =pod
 8271: 
 8272: =item * &cacheheader() 
 8273: 
 8274: returns cache-controlling header code
 8275: 
 8276: =cut
 8277: 
 8278: sub cacheheader {
 8279:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8280:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8281:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8282:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8283:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8284:     return $output;
 8285: }
 8286: 
 8287: =pod
 8288: 
 8289: =item * &no_cache($r) 
 8290: 
 8291: specifies header code to not have cache
 8292: 
 8293: =cut
 8294: 
 8295: sub no_cache {
 8296:     my ($r) = @_;
 8297:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8298: 	$env{'request.method'} ne 'GET') { return ''; }
 8299:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8300:     $r->no_cache(1);
 8301:     $r->header_out("Expires" => $date);
 8302:     $r->header_out("Pragma" => "no-cache");
 8303: }
 8304: 
 8305: sub content_type {
 8306:     my ($r,$type,$charset) = @_;
 8307:     if ($r) {
 8308: 	#  Note that printout.pl calls this with undef for $r.
 8309: 	&no_cache($r);
 8310:     }
 8311:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8312:     unless ($charset) {
 8313: 	$charset=&Apache::lonlocal::current_encoding;
 8314:     }
 8315:     if ($charset) { $type.='; charset='.$charset; }
 8316:     if ($r) {
 8317: 	$r->content_type($type);
 8318:     } else {
 8319: 	print("Content-type: $type\n\n");
 8320:     }
 8321: }
 8322: 
 8323: =pod
 8324: 
 8325: =item * &add_to_env($name,$value) 
 8326: 
 8327: adds $name to the %env hash with value
 8328: $value, if $name already exists, the entry is converted to an array
 8329: reference and $value is added to the array.
 8330: 
 8331: =cut
 8332: 
 8333: sub add_to_env {
 8334:   my ($name,$value)=@_;
 8335:   if (defined($env{$name})) {
 8336:     if (ref($env{$name})) {
 8337:       #already have multiple values
 8338:       push(@{ $env{$name} },$value);
 8339:     } else {
 8340:       #first time seeing multiple values, convert hash entry to an arrayref
 8341:       my $first=$env{$name};
 8342:       undef($env{$name});
 8343:       push(@{ $env{$name} },$first,$value);
 8344:     }
 8345:   } else {
 8346:     $env{$name}=$value;
 8347:   }
 8348: }
 8349: 
 8350: =pod
 8351: 
 8352: =item * &get_env_multiple($name) 
 8353: 
 8354: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8355: values may be defined and end up as an array ref.
 8356: 
 8357: returns an array of values
 8358: 
 8359: =cut
 8360: 
 8361: sub get_env_multiple {
 8362:     my ($name) = @_;
 8363:     my @values;
 8364:     if (defined($env{$name})) {
 8365:         # exists is it an array
 8366:         if (ref($env{$name})) {
 8367:             @values=@{ $env{$name} };
 8368:         } else {
 8369:             $values[0]=$env{$name};
 8370:         }
 8371:     }
 8372:     return(@values);
 8373: }
 8374: 
 8375: sub ask_for_embedded_content {
 8376:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8377:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges);
 8378:     my $num = 0;
 8379:     my $numremref = 0;
 8380:     my $numinvalid = 0;
 8381:     my $numpathchg = 0;
 8382:     my $numexisting = 0;
 8383:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath);
 8384:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8385:         my $current_path='/';
 8386:         if ($env{'form.currentpath'}) {
 8387:             $current_path = $env{'form.currentpath'};
 8388:         }
 8389:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 8390:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8391:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 8392:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 8393:         } else {
 8394:             $udom = $env{'user.domain'};
 8395:             $uname = $env{'user.name'};
 8396:             $url = '/userfiles/portfolio';
 8397:         }
 8398:         $toplevel = $url.'/';
 8399:         $url .= $current_path;
 8400:         $getpropath = 1;
 8401:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 8402:              ($actionurl eq '/adm/imsimport')) { 
 8403:         ($uname,my $rest) = ($args->{'current_path'} =~ m{/priv/($match_username)/?(.*)$});
 8404:         $url = '/home/'.$uname.'/public_html/';
 8405:         $toplevel = $url;
 8406:         if ($rest ne '') {
 8407:             $url .= $rest;
 8408:         }
 8409:     } elsif ($actionurl eq '/adm/coursedocs') {
 8410:         if (ref($args) eq 'HASH') {
 8411:            $url = $args->{'docs_url'};
 8412:            $toplevel = $url;
 8413:         }
 8414:     }
 8415:     my $now = time();
 8416:     foreach my $embed_file (keys(%{$allfiles})) {
 8417:         my $absolutepath;
 8418:         if ($embed_file =~ m{^\w+://}) {
 8419:             $newfiles{$embed_file} = 1;
 8420:             $mapping{$embed_file} = $embed_file;
 8421:         } else {
 8422:             if ($embed_file =~ m{^/}) {
 8423:                 $absolutepath = $embed_file;
 8424:                 $embed_file =~ s{^(/+)}{};
 8425:             }
 8426:             if ($embed_file =~ m{/}) {
 8427:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 8428:                 $path = &check_for_traversal($path,$url,$toplevel);
 8429:                 my $item = $fname;
 8430:                 if ($path ne '') {
 8431:                     $item = $path.'/'.$fname;
 8432:                     $subdependencies{$path}{$fname} = 1;
 8433:                 } else {
 8434:                     $dependencies{$item} = 1;
 8435:                 }
 8436:                 if ($absolutepath) {
 8437:                     $mapping{$item} = $absolutepath;
 8438:                 } else {
 8439:                     $mapping{$item} = $embed_file;
 8440:                 }
 8441:             } else {
 8442:                 $dependencies{$embed_file} = 1;
 8443:                 if ($absolutepath) {
 8444:                     $mapping{$embed_file} = $absolutepath;
 8445:                 } else {
 8446:                     $mapping{$embed_file} = $embed_file;
 8447:                 }
 8448:             }
 8449:         }
 8450:     }
 8451:     foreach my $path (keys(%subdependencies)) {
 8452:         my %currsubfile;
 8453:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 8454:             my @subdir_list = &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 8455:             foreach my $line (@subdir_list) {
 8456:                 my ($file_name,$rest) = split(/\&/,$line,2);
 8457:                 $currsubfile{$file_name} = 1;
 8458:             }
 8459:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8460:             if (opendir(my $dir,$url.'/'.$path)) {
 8461:                 my @subdir_list = grep(!/^\./,readdir($dir));
 8462:                 map {$currsubfile{$_} = 1;} @subdir_list;
 8463:             }
 8464:         }
 8465:         foreach my $file (keys(%{$subdependencies{$path}})) {
 8466:             if ($currsubfile{$file}) {
 8467:                 my $item = $path.'/'.$file;
 8468:                 unless ($mapping{$item} eq $item) {
 8469:                     $pathchanges{$item} = 1;
 8470:                 }
 8471:                 $existing{$item} = 1;
 8472:                 $numexisting ++;
 8473:             } else {
 8474:                 $newfiles{$path.'/'.$file} = 1;
 8475:             }
 8476:         }
 8477:     }
 8478:     my %currfile;
 8479:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8480:         my @dir_list = &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 8481:         foreach my $line (@dir_list) {
 8482:             my ($file_name,$rest) = split(/\&/,$line,2);
 8483:             $currfile{$file_name} = 1;
 8484:         }
 8485:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8486:         if (opendir(my $dir,$url)) {
 8487:             my @dir_list = grep(!/^\./,readdir($dir));
 8488:             map {$currfile{$_} = 1;} @dir_list;
 8489:         }
 8490:     }
 8491:     foreach my $file (keys(%dependencies)) {
 8492:         if ($currfile{$file}) {
 8493:             unless ($mapping{$file} eq $file) {
 8494:                 $pathchanges{$file} = 1;
 8495:             }
 8496:             $existing{$file} = 1;
 8497:             $numexisting ++;
 8498:         } else {
 8499:             $newfiles{$file} = 1;
 8500:         }
 8501:     }
 8502:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 8503:         $upload_output .= &start_data_table_row().
 8504:                           '<td><span class="LC_filename">'.$embed_file.'</span>';
 8505:         unless ($mapping{$embed_file} eq $embed_file) {
 8506:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 8507:         }
 8508:         $upload_output .= '</td><td>';
 8509:         if ($args->{'ignore_remote_references'}
 8510:             && $embed_file =~ m{^\w+://}) {
 8511:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8512:             $numremref++;
 8513:         } elsif ($args->{'error_on_invalid_names'}
 8514:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8515: 
 8516:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 8517:             $numinvalid++;
 8518:         } else {
 8519:             $upload_output .= &embedded_file_element('upload_embedded',$num,
 8520:                                                      $embed_file,\%mapping,
 8521:                                                      $allfiles,$codebase);
 8522:             $num++;
 8523:         }
 8524:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 8525:     }
 8526:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 8527:         $upload_output .= &start_data_table_row().
 8528:                           '<td><span class="LC_filename">'.$embed_file.'</span></td>'.
 8529:                           '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 8530:                           &Apache::loncommon::end_data_table_row()."\n";
 8531:     }
 8532:     if ($upload_output) {
 8533:         $upload_output = &start_data_table().
 8534:                          $upload_output.
 8535:                          &end_data_table()."\n";
 8536:     }
 8537:     my $applies = 0;
 8538:     if ($numremref) {
 8539:         $applies ++;
 8540:     }
 8541:     if ($numinvalid) {
 8542:         $applies ++;
 8543:     }
 8544:     if ($numexisting) {
 8545:         $applies ++;
 8546:     }
 8547:     if ($num) {
 8548:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 8549:                   ' method="post" enctype="multipart/form-data">'."\n".
 8550:                   $state.
 8551:                   '<h3>'.&mt('Upload embedded files').
 8552:                   ':</h3>'.$upload_output.'<br />'."\n".
 8553:                   '<input type ="hidden" name="number_embedded_items" value="'.
 8554:                   $num.'" />'."\n";
 8555:         if ($actionurl eq '') {
 8556:             $output .=  '<input type="hidden" name="phase" value="three" />';
 8557:         }
 8558:     } elsif ($applies) {
 8559:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 8560:         if ($applies > 1) {
 8561:             $output .=  
 8562:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 8563:             if ($numremref) {
 8564:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 8565:             }
 8566:             if ($numinvalid) {
 8567:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 8568:             }
 8569:             if ($numexisting) {
 8570:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 8571:             }
 8572:             $output .= '</ul><br />';
 8573:         } elsif ($numremref) {
 8574:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 8575:         } elsif ($numinvalid) {
 8576:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 8577:         } elsif ($numexisting) {
 8578:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 8579:         }
 8580:         $output .= $upload_output.'<br />';
 8581:     }
 8582:     my ($pathchange_output,$chgcount);
 8583:     $chgcount = $num;
 8584:     if (keys(%pathchanges) > 0) {
 8585:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 8586:             if ($num) {
 8587:                 $output .= &embedded_file_element('pathchange',$chgcount,
 8588:                                                   $embed_file,\%mapping,
 8589:                                                   $allfiles,$codebase);
 8590:             } else {
 8591:                 $pathchange_output .= 
 8592:                     &start_data_table_row().
 8593:                     '<td><input type ="checkbox" name="namechange" value="'.
 8594:                     $chgcount.'" checked="checked" /></td>'.
 8595:                     '<td>'.$mapping{$embed_file}.'</td>'.
 8596:                     '<td>'.$embed_file.
 8597:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 8598:                                            \%mapping,$allfiles,$codebase).
 8599:                     '</td>'.&end_data_table_row();
 8600:             }
 8601:             $numpathchg ++;
 8602:             $chgcount ++;
 8603:         }
 8604:     }
 8605:     if ($num) {
 8606:         if ($numpathchg) {
 8607:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 8608:                        $numpathchg.'" />'."\n";
 8609:         }
 8610:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 8611:             ($actionurl eq '/adm/imsimport')) {
 8612:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 8613:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 8614:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 8615:         }
 8616:         $output .=  '<input type ="submit" value="'.&mt('Upload Listed Files').'" />'."\n".
 8617:                     &mt('(only files for which a location has been provided will be uploaded)').'</form>'."\n";
 8618:     } elsif ($numpathchg) {
 8619:         my %pathchange = ();
 8620:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 8621:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8622:             $output .= '<p>'.&mt('or').'</p>'; 
 8623:         } 
 8624:     }
 8625:     return ($output,$num,$numpathchg);
 8626: }
 8627: 
 8628: sub embedded_file_element {
 8629:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase) = @_;
 8630:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 8631:                    (ref($codebase) eq 'HASH'));
 8632:     my $output;
 8633:     if ($context eq 'upload_embedded') {
 8634:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 8635:     }
 8636:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 8637:                &escape($embed_file).'" />';
 8638:     unless (($context eq 'upload_embedded') && 
 8639:             ($mapping->{$embed_file} eq $embed_file)) {
 8640:         $output .='
 8641:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 8642:     }
 8643:     my $attrib;
 8644:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 8645:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 8646:     }
 8647:     $output .=
 8648:         "\n\t\t".
 8649:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8650:         $attrib.'" />';
 8651:     if (exists($codebase->{$mapping->{$embed_file}})) {
 8652:         $output .=
 8653:             "\n\t\t".
 8654:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 8655:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 8656:     }
 8657:     return $output;
 8658: }
 8659: 
 8660: sub upload_embedded {
 8661:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8662:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
 8663:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
 8664:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8665:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8666:         my $orig_uploaded_filename =
 8667:             $env{'form.embedded_item_'.$i.'.filename'};
 8668:         foreach my $type ('orig','ref','attrib','codebase') {
 8669:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
 8670:                 $env{'form.embedded_'.$type.'_'.$i} =
 8671:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
 8672:             }
 8673:         }
 8674:         my ($path,$fname) =
 8675:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8676:         # no path, whole string is fname
 8677:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8678:         $fname = &Apache::lonnet::clean_filename($fname);
 8679:         # See if there is anything left
 8680:         next if ($fname eq '');
 8681: 
 8682:         # Check if file already exists as a file or directory.
 8683:         my ($state,$msg);
 8684:         if ($context eq 'portfolio') {
 8685:             my $port_path = $dirpath;
 8686:             if ($group ne '') {
 8687:                 $port_path = "groups/$group/$port_path";
 8688:             }
 8689:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
 8690:                                               $fname,$group,'embedded_item_'.$i,
 8691:                                               $dir_root,$port_path,$disk_quota,
 8692:                                               $current_disk_usage,$uname,$udom);
 8693:             if ($state eq 'will_exceed_quota'
 8694:                 || $state eq 'file_locked') {
 8695:                 $output .= $msg;
 8696:                 next;
 8697:             }
 8698:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8699:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8700:             if ($state eq 'exists') {
 8701:                 $output .= $msg;
 8702:                 next;
 8703:             }
 8704:         }
 8705:         # Check if extension is valid
 8706:         if (($fname =~ /\.(\w+)$/) &&
 8707:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8708:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
 8709:             next;
 8710:         } elsif (($fname =~ /\.(\w+)$/) &&
 8711:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8712:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
 8713:             next;
 8714:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8715:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
 8716:             next;
 8717:         }
 8718: 
 8719:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8720:         if ($context eq 'portfolio') {
 8721:             my $result;
 8722:             if ($state eq 'existingfile') {
 8723:                 $result=
 8724:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
 8725:                                                     $dirpath.$env{'form.currentpath'}.$path);
 8726:             } else {
 8727:                 $result=
 8728:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8729:                                                     $dirpath.
 8730:                                                     $env{'form.currentpath'}.$path);
 8731:                 if ($result !~ m|^/uploaded/|) {
 8732:                     $output .= '<span class="LC_error">'
 8733:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8734:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8735:                                .'</span><br />';
 8736:                     next;
 8737:                 } else {
 8738:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8739:                                $path.$fname.'</span>').'<br />';     
 8740:                 }
 8741:             }
 8742:         } elsif ($context eq 'coursedoc') {
 8743:             my $result =
 8744:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
 8745:                                                 $dirpath.'/'.$path);
 8746:             if ($result !~ m|^/uploaded/|) {
 8747:                 $output .= '<span class="LC_error">'
 8748:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8749:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8750:                            .'</span><br />';
 8751:                     next;
 8752:             } else {
 8753:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8754:                            $path.$fname.'</span>').'<br />';
 8755:             }
 8756:         } else {
 8757: # Save the file
 8758:             my $target = $env{'form.embedded_item_'.$i};
 8759:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8760:             my $dest = $fullpath.$fname;
 8761:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8762:             my @parts=split(/\//,$fullpath);
 8763:             my $count;
 8764:             my $filepath = $dir_root;
 8765:             for ($count=4;$count<=$#parts;$count++) {
 8766:                 $filepath .= "/$parts[$count]";
 8767:                 if ((-e $filepath)!=1) {
 8768:                     mkdir($filepath,0770);
 8769:                 }
 8770:             }
 8771:             my $fh;
 8772:             if (!open($fh,'>'.$dest)) {
 8773:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8774:                 $output .= '<span class="LC_error">'.
 8775:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8776:                            '</span><br />';
 8777:             } else {
 8778:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8779:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8780:                     $output .= '<span class="LC_error">'.
 8781:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8782:                               '</span><br />';
 8783:                 } else {
 8784:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
 8785:                                $url.'</span>').'<br />';
 8786:                     unless ($context eq 'testbank') {
 8787:                         $footer .= &mt('View embedded file: [_1]',
 8788:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
 8789:                     }
 8790:                 }
 8791:                 close($fh);
 8792:             }
 8793:         }
 8794:         if ($env{'form.embedded_ref_'.$i}) {
 8795:             $pathchange{$i} = 1;
 8796:         }
 8797:     }
 8798:     if ($output) {
 8799:         $output = '<p>'.$output.'</p>';
 8800:     }
 8801:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
 8802:     $returnflag = 'ok';
 8803:     if (keys(%pathchange) > 0) {
 8804:         if ($context eq 'portfolio') {
 8805:             $output .= '<p>'.&mt('or').'</p>';
 8806:         } elsif ($context eq 'testbank') {
 8807:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).','<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
 8808:             $returnflag = 'modify_orightml';
 8809:         }
 8810:     }
 8811:     return ($output.$footer,$returnflag);
 8812: }
 8813: 
 8814: sub modify_html_form {
 8815:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
 8816:     my $end = 0;
 8817:     my $modifyform;
 8818:     if ($context eq 'upload_embedded') {
 8819:         return unless (ref($pathchange) eq 'HASH');
 8820:         if ($env{'form.number_embedded_items'}) {
 8821:             $end += $env{'form.number_embedded_items'};
 8822:         }
 8823:         if ($env{'form.number_pathchange_items'}) {
 8824:             $end += $env{'form.number_pathchange_items'};
 8825:         }
 8826:         if ($end) {
 8827:             for (my $i=0; $i<$end; $i++) {
 8828:                 if ($i < $env{'form.number_embedded_items'}) {
 8829:                     next unless($pathchange->{$i});
 8830:                 }
 8831:                 $modifyform .=
 8832:                     &start_data_table_row().
 8833:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
 8834:                     'checked="checked" /></td>'.
 8835:                     '<td>'.$env{'form.embedded_ref_'.$i}.
 8836:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
 8837:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
 8838:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
 8839:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
 8840:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
 8841:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
 8842:                     '<td>'.$env{'form.embedded_orig_'.$i}.
 8843:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
 8844:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
 8845:                     &end_data_table_row();
 8846:             } 
 8847:         }
 8848:     } else {
 8849:         $modifyform = $pathchgtable;
 8850:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 8851:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
 8852:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 8853:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
 8854:         }
 8855:     }
 8856:     if ($modifyform) {
 8857:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
 8858:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
 8859:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
 8860:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
 8861:                '</ol></p>'."\n".'<p>'.
 8862:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
 8863:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
 8864:                &start_data_table()."\n".
 8865:                &start_data_table_header_row().
 8866:                '<th>'.&mt('Change?').'</th>'.
 8867:                '<th>'.&mt('Current reference').'</th>'.
 8868:                '<th>'.&mt('Required reference').'</th>'.
 8869:                &end_data_table_header_row()."\n".
 8870:                $modifyform.
 8871:                &end_data_table().'<br />'."\n".$hiddenstate.
 8872:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
 8873:                '</form>'."\n";
 8874:     }
 8875:     return;
 8876: }
 8877: 
 8878: sub modify_html_refs {
 8879:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
 8880:     my $container;
 8881:     if ($context eq 'portfolio') {
 8882:         $container = $env{'form.container'};
 8883:     } elsif ($context eq 'coursedoc') {
 8884:         $container = $env{'form.primaryurl'};
 8885:     } else {
 8886:         $container = $env{'form.filename'};
 8887:         $container =~ s{^/priv/(\Q$uname\E)/(.*)}{/home/$1/public_html/$2};
 8888:     }
 8889:     my (%allfiles,%codebase,$output,$content);
 8890:     my @changes = &get_env_multiple('form.namechange');
 8891:     return unless (@changes > 0);
 8892:     if (($context eq 'portfolio') || ($context eq 'coursedoc')) {
 8893:         return unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/});
 8894:         $content = &Apache::lonnet::getfile($container);
 8895:         return if ($content eq '-1');
 8896:     } else {
 8897:         return unless ($container =~ /^\Q$dir_root\E/); 
 8898:         if (open(my $fh,"<$container")) {
 8899:             $content = join('', <$fh>);
 8900:             close($fh);
 8901:         } else {
 8902:             return;
 8903:         }
 8904:     }
 8905:     my ($count,$codebasecount) = (0,0);
 8906:     my $mm = new File::MMagic;
 8907:     my $mime_type = $mm->checktype_contents($content);
 8908:     if ($mime_type eq 'text/html') {
 8909:         my $parse_result = 
 8910:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
 8911:                                                     \%codebase,\$content);
 8912:         if ($parse_result eq 'ok') {
 8913:             foreach my $i (@changes) {
 8914:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
 8915:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
 8916:                 if ($allfiles{$ref}) {
 8917:                     my $newname =  $orig;
 8918:                     my ($attrib_regexp,$codebase);
 8919:                     my $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
 8920:                     if ($attrib_regexp =~ /:/) {
 8921:                         $attrib_regexp =~ s/\:/|/g;
 8922:                     }
 8923:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
 8924:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
 8925:                         $count += $numchg;
 8926:                     }
 8927:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
 8928:                         my $codebase = &unescape($env{'form.embedded_codebase_'.$i});
 8929:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
 8930:                         $codebasecount ++;
 8931:                     }
 8932:                 }
 8933:             }
 8934:             if ($count || $codebasecount) {
 8935:                 my $saveresult;
 8936:                 if ($context eq 'portfolio' || $context eq 'coursedoc') {
 8937:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
 8938:                     if ($url eq $container) {
 8939:                         my ($fname) = ($container =~ m{/([^/]+)$});
 8940:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 8941:                                             $count,'<span class="LC_filename">'.
 8942:                                             $fname.'</span>').'</p>'; 
 8943:                     } else {
 8944:                          $output = '<p class="LC_error">'.
 8945:                                    &mt('Error: update failed for: [_1].',
 8946:                                    '<span class="LC_filename">'.
 8947:                                    $container.'</span>').'</p>';
 8948:                     }
 8949:                 } else {
 8950:                     if (open(my $fh,">$container")) {
 8951:                         print $fh $content;
 8952:                         close($fh);
 8953:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
 8954:                                   $count,'<span class="LC_filename">'.
 8955:                                   $container.'</span>').'</p>';
 8956:                     } else {
 8957:                          $output = '<p class="LC_error">'.
 8958:                                    &mt('Error: could not update [_1].',
 8959:                                    '<span class="LC_filename">'.
 8960:                                    $container.'</span>').'</p>';
 8961:                     }
 8962:                 }
 8963:             }
 8964:         } else {
 8965:             &logthis('Failed to parse '.$container.
 8966:                      ' to modify references: '.$parse_result);
 8967:         }
 8968:     }
 8969:     return $output;
 8970: }
 8971: 
 8972: sub check_for_existing {
 8973:     my ($path,$fname,$element) = @_;
 8974:     my ($state,$msg);
 8975:     if (-d $path.'/'.$fname) {
 8976:         $state = 'exists';
 8977:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8978:     } elsif (-e $path.'/'.$fname) {
 8979:         $state = 'exists';
 8980:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8981:     }
 8982:     if ($state eq 'exists') {
 8983:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8984:     }
 8985:     return ($state,$msg);
 8986: }
 8987: 
 8988: sub check_for_upload {
 8989:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8990:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8991:     my $filesize = length($env{'form.'.$element});
 8992:     if (!$filesize) {
 8993:         my $msg = '<span class="LC_error">'.
 8994:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
 8995:                       '<span class="LC_filename">'.$fname.'</span>',
 8996:                       $filesize).'<br />'.
 8997:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />';
 8998:                   '</span>';
 8999:         return ('zero_bytes',$msg);
 9000:     }
 9001:     $filesize =  $filesize/1000; #express in k (1024?)
 9002:     my $getpropath = 1;
 9003:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 9004:                                             $getpropath);
 9005:     my $found_file = 0;
 9006:     my $locked_file = 0;
 9007:     my @lockers;
 9008:     my $navmap;
 9009:     if ($env{'request.course.id'}) {
 9010:         $navmap = Apache::lonnavmaps::navmap->new();
 9011:     }
 9012:     foreach my $line (@dir_list) {
 9013:         my ($file_name,$rest)=split(/\&/,$line,2);
 9014:         if ($file_name eq $fname){
 9015:             $file_name = $path.$file_name;
 9016:             if ($group ne '') {
 9017:                 $file_name = $group.$file_name;
 9018:             }
 9019:             $found_file = 1;
 9020:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
 9021:                 foreach my $lock (@lockers) {
 9022:                     if (ref($lock) eq 'ARRAY') {
 9023:                         my ($symb,$crsid) = @{$lock};
 9024:                         if ($crsid eq $env{'request.course.id'}) {
 9025:                             if (ref($navmap)) {
 9026:                                 my $res = $navmap->getBySymb($symb);
 9027:                                 foreach my $part (@{$res->parts()}) { 
 9028:                                     my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
 9029:                                     unless (($slot_status == $res->RESERVED) ||
 9030:                                             ($slot_status == $res->RESERVED_LOCATION)) {
 9031:                                         $locked_file = 1;
 9032:                                     }
 9033:                                 }
 9034:                             } else {
 9035:                                 $locked_file = 1;
 9036:                             }
 9037:                         } else {
 9038:                             $locked_file = 1;
 9039:                         }
 9040:                     }
 9041:                 }
 9042:             } else {
 9043:                 my @info = split(/\&/,$rest);
 9044:                 my $currsize = $info[6]/1000;
 9045:                 if ($currsize < $filesize) {
 9046:                     my $extra = $filesize - $currsize;
 9047:                     if (($current_disk_usage + $extra) > $disk_quota) {
 9048:                         my $msg = '<span class="LC_error">'.
 9049:                                   &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
 9050:                                       '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
 9051:                                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9052:                                                $disk_quota,$current_disk_usage);
 9053:                         return ('will_exceed_quota',$msg);
 9054:                     }
 9055:                 }
 9056:             }
 9057:         }
 9058:     }
 9059:     if (($current_disk_usage + $filesize) > $disk_quota){
 9060:         my $msg = '<span class="LC_error">'.
 9061:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 9062:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 9063:         return ('will_exceed_quota',$msg);
 9064:     } elsif ($found_file) {
 9065:         if ($locked_file) {
 9066:             my $msg = '<span class="LC_error">';
 9067:             $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>');
 9068:             $msg .= '</span><br />';
 9069:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 9070:             return ('file_locked',$msg);
 9071:         } else {
 9072:             my $msg = '<span class="LC_error">';
 9073:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 9074:             $msg .= '</span>';
 9075:             return ('existingfile',$msg);
 9076:         }
 9077:     }
 9078: }
 9079: 
 9080: sub check_for_traversal {
 9081:     my ($path,$url,$toplevel) = @_;
 9082:     my @parts=split(/\//,$path);
 9083:     my $cleanpath;
 9084:     my $fullpath = $url;
 9085:     for (my $i=0;$i<@parts;$i++) {
 9086:         next if ($parts[$i] eq '.');
 9087:         if ($parts[$i] eq '..') {
 9088:             $fullpath =~ s{([^/]+/)$}{};
 9089:         } else {
 9090:             $fullpath .= $parts[$i].'/';
 9091:         }
 9092:     }
 9093:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
 9094:         $cleanpath = $1;
 9095:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
 9096:         my $curr_toprel = $1;
 9097:         my @parts = split(/\//,$curr_toprel);
 9098:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
 9099:         my @urlparts = split(/\//,$url_toprel);
 9100:         my $doubledots;
 9101:         my $startdiff = -1;
 9102:         for (my $i=0; $i<@urlparts; $i++) {
 9103:             if ($startdiff == -1) {
 9104:                 unless ($urlparts[$i] eq $parts[$i]) {
 9105:                     $startdiff = $i;
 9106:                     $doubledots .= '../';
 9107:                 }
 9108:             } else {
 9109:                 $doubledots .= '../';
 9110:             }
 9111:         }
 9112:         if ($startdiff > -1) {
 9113:             $cleanpath = $doubledots;
 9114:             for (my $i=$startdiff; $i<@parts; $i++) {
 9115:                 $cleanpath .= $parts[$i].'/';
 9116:             }
 9117:         }
 9118:     }
 9119:     $cleanpath =~ s{(/)$}{};
 9120:     return $cleanpath;
 9121: }
 9122: 
 9123: =pod
 9124: 
 9125: =back
 9126: 
 9127: =head1 CSV Upload/Handling functions
 9128: 
 9129: =over 4
 9130: 
 9131: =item * &upfile_store($r)
 9132: 
 9133: Store uploaded file, $r should be the HTTP Request object,
 9134: needs $env{'form.upfile'}
 9135: returns $datatoken to be put into hidden field
 9136: 
 9137: =cut
 9138: 
 9139: sub upfile_store {
 9140:     my $r=shift;
 9141:     $env{'form.upfile'}=~s/\r/\n/gs;
 9142:     $env{'form.upfile'}=~s/\f/\n/gs;
 9143:     $env{'form.upfile'}=~s/\n+/\n/gs;
 9144:     $env{'form.upfile'}=~s/\n+$//gs;
 9145: 
 9146:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 9147: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 9148:     {
 9149:         my $datafile = $r->dir_config('lonDaemons').
 9150:                            '/tmp/'.$datatoken.'.tmp';
 9151:         if ( open(my $fh,">$datafile") ) {
 9152:             print $fh $env{'form.upfile'};
 9153:             close($fh);
 9154:         }
 9155:     }
 9156:     return $datatoken;
 9157: }
 9158: 
 9159: =pod
 9160: 
 9161: =item * &load_tmp_file($r)
 9162: 
 9163: Load uploaded file from tmp, $r should be the HTTP Request object,
 9164: needs $env{'form.datatoken'},
 9165: sets $env{'form.upfile'} to the contents of the file
 9166: 
 9167: =cut
 9168: 
 9169: sub load_tmp_file {
 9170:     my $r=shift;
 9171:     my @studentdata=();
 9172:     {
 9173:         my $studentfile = $r->dir_config('lonDaemons').
 9174:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 9175:         if ( open(my $fh,"<$studentfile") ) {
 9176:             @studentdata=<$fh>;
 9177:             close($fh);
 9178:         }
 9179:     }
 9180:     $env{'form.upfile'}=join('',@studentdata);
 9181: }
 9182: 
 9183: =pod
 9184: 
 9185: =item * &upfile_record_sep()
 9186: 
 9187: Separate uploaded file into records
 9188: returns array of records,
 9189: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 9190: 
 9191: =cut
 9192: 
 9193: sub upfile_record_sep {
 9194:     if ($env{'form.upfiletype'} eq 'xml') {
 9195:     } else {
 9196: 	my @records;
 9197: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 9198: 	    if ($line=~/^\s*$/) { next; }
 9199: 	    push(@records,$line);
 9200: 	}
 9201: 	return @records;
 9202:     }
 9203: }
 9204: 
 9205: =pod
 9206: 
 9207: =item * &record_sep($record)
 9208: 
 9209: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 9210: 
 9211: =cut
 9212: 
 9213: sub takeleft {
 9214:     my $index=shift;
 9215:     return substr('0000'.$index,-4,4);
 9216: }
 9217: 
 9218: sub record_sep {
 9219:     my $record=shift;
 9220:     my %components=();
 9221:     if ($env{'form.upfiletype'} eq 'xml') {
 9222:     } elsif ($env{'form.upfiletype'} eq 'space') {
 9223:         my $i=0;
 9224:         foreach my $field (split(/\s+/,$record)) {
 9225:             $field=~s/^(\"|\')//;
 9226:             $field=~s/(\"|\')$//;
 9227:             $components{&takeleft($i)}=$field;
 9228:             $i++;
 9229:         }
 9230:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 9231:         my $i=0;
 9232:         foreach my $field (split(/\t/,$record)) {
 9233:             $field=~s/^(\"|\')//;
 9234:             $field=~s/(\"|\')$//;
 9235:             $components{&takeleft($i)}=$field;
 9236:             $i++;
 9237:         }
 9238:     } else {
 9239:         my $separator=',';
 9240:         if ($env{'form.upfiletype'} eq 'semisv') {
 9241:             $separator=';';
 9242:         }
 9243:         my $i=0;
 9244: # the character we are looking for to indicate the end of a quote or a record 
 9245:         my $looking_for=$separator;
 9246: # do not add the characters to the fields
 9247:         my $ignore=0;
 9248: # we just encountered a separator (or the beginning of the record)
 9249:         my $just_found_separator=1;
 9250: # store the field we are working on here
 9251:         my $field='';
 9252: # work our way through all characters in record
 9253:         foreach my $character ($record=~/(.)/g) {
 9254:             if ($character eq $looking_for) {
 9255:                if ($character ne $separator) {
 9256: # Found the end of a quote, again looking for separator
 9257:                   $looking_for=$separator;
 9258:                   $ignore=1;
 9259:                } else {
 9260: # Found a separator, store away what we got
 9261:                   $components{&takeleft($i)}=$field;
 9262: 	          $i++;
 9263:                   $just_found_separator=1;
 9264:                   $ignore=0;
 9265:                   $field='';
 9266:                }
 9267:                next;
 9268:             }
 9269: # single or double quotation marks after a separator indicate beginning of a quote
 9270: # we are now looking for the end of the quote and need to ignore separators
 9271:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 9272:                $looking_for=$character;
 9273:                next;
 9274:             }
 9275: # ignore would be true after we reached the end of a quote
 9276:             if ($ignore) { next; }
 9277:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 9278:             $field.=$character;
 9279:             $just_found_separator=0; 
 9280:         }
 9281: # catch the very last entry, since we never encountered the separator
 9282:         $components{&takeleft($i)}=$field;
 9283:     }
 9284:     return %components;
 9285: }
 9286: 
 9287: ######################################################
 9288: ######################################################
 9289: 
 9290: =pod
 9291: 
 9292: =item * &upfile_select_html()
 9293: 
 9294: Return HTML code to select a file from the users machine and specify 
 9295: the file type.
 9296: 
 9297: =cut
 9298: 
 9299: ######################################################
 9300: ######################################################
 9301: sub upfile_select_html {
 9302:     my %Types = (
 9303:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 9304:                  semisv => &mt('Semicolon separated values'),
 9305:                  space => &mt('Space separated'),
 9306:                  tab   => &mt('Tabulator separated'),
 9307: #                 xml   => &mt('HTML/XML'),
 9308:                  );
 9309:     my $Str = '<input type="file" name="upfile" size="50" />'.
 9310:         '<br />'.&mt('Type').': <select name="upfiletype">';
 9311:     foreach my $type (sort(keys(%Types))) {
 9312:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 9313:     }
 9314:     $Str .= "</select>\n";
 9315:     return $Str;
 9316: }
 9317: 
 9318: sub get_samples {
 9319:     my ($records,$toget) = @_;
 9320:     my @samples=({});
 9321:     my $got=0;
 9322:     foreach my $rec (@$records) {
 9323: 	my %temp = &record_sep($rec);
 9324: 	if (! grep(/\S/, values(%temp))) { next; }
 9325: 	if (%temp) {
 9326: 	    $samples[$got]=\%temp;
 9327: 	    $got++;
 9328: 	    if ($got == $toget) { last; }
 9329: 	}
 9330:     }
 9331:     return \@samples;
 9332: }
 9333: 
 9334: ######################################################
 9335: ######################################################
 9336: 
 9337: =pod
 9338: 
 9339: =item * &csv_print_samples($r,$records)
 9340: 
 9341: Prints a table of sample values from each column uploaded $r is an
 9342: Apache Request ref, $records is an arrayref from
 9343: &Apache::loncommon::upfile_record_sep
 9344: 
 9345: =cut
 9346: 
 9347: ######################################################
 9348: ######################################################
 9349: sub csv_print_samples {
 9350:     my ($r,$records) = @_;
 9351:     my $samples = &get_samples($records,5);
 9352: 
 9353:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 9354:               &start_data_table_header_row());
 9355:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 9356:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 9357:     $r->print(&end_data_table_header_row());
 9358:     foreach my $hash (@$samples) {
 9359: 	$r->print(&start_data_table_row());
 9360: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9361: 	    $r->print('<td>');
 9362: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 9363: 	    $r->print('</td>');
 9364: 	}
 9365: 	$r->print(&end_data_table_row());
 9366:     }
 9367:     $r->print(&end_data_table().'<br />'."\n");
 9368: }
 9369: 
 9370: ######################################################
 9371: ######################################################
 9372: 
 9373: =pod
 9374: 
 9375: =item * &csv_print_select_table($r,$records,$d)
 9376: 
 9377: Prints a table to create associations between values and table columns.
 9378: 
 9379: $r is an Apache Request ref,
 9380: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9381: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 9382: 
 9383: =cut
 9384: 
 9385: ######################################################
 9386: ######################################################
 9387: sub csv_print_select_table {
 9388:     my ($r,$records,$d) = @_;
 9389:     my $i=0;
 9390:     my $samples = &get_samples($records,1);
 9391:     $r->print(&mt('Associate columns with student attributes.')."\n".
 9392: 	      &start_data_table().&start_data_table_header_row().
 9393:               '<th>'.&mt('Attribute').'</th>'.
 9394:               '<th>'.&mt('Column').'</th>'.
 9395:               &end_data_table_header_row()."\n");
 9396:     foreach my $array_ref (@$d) {
 9397: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 9398: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 9399: 
 9400: 	$r->print('<td><select name="f'.$i.'"'.
 9401: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9402: 	$r->print('<option value="none"></option>');
 9403: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 9404: 	    $r->print('<option value="'.$sample.'"'.
 9405:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 9406:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 9407: 	}
 9408: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 9409: 	$i++;
 9410:     }
 9411:     $r->print(&end_data_table());
 9412:     $i--;
 9413:     return $i;
 9414: }
 9415: 
 9416: ######################################################
 9417: ######################################################
 9418: 
 9419: =pod
 9420: 
 9421: =item * &csv_samples_select_table($r,$records,$d)
 9422: 
 9423: Prints a table of sample values from the upload and can make associate samples to internal names.
 9424: 
 9425: $r is an Apache Request ref,
 9426: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 9427: $d is an array of 2 element arrays (internal name, displayed name)
 9428: 
 9429: =cut
 9430: 
 9431: ######################################################
 9432: ######################################################
 9433: sub csv_samples_select_table {
 9434:     my ($r,$records,$d) = @_;
 9435:     my $i=0;
 9436:     #
 9437:     my $max_samples = 5;
 9438:     my $samples = &get_samples($records,$max_samples);
 9439:     $r->print(&start_data_table().
 9440:               &start_data_table_header_row().'<th>'.
 9441:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 9442:               &end_data_table_header_row());
 9443: 
 9444:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 9445: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 9446: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 9447: 	foreach my $option (@$d) {
 9448: 	    my ($value,$display,$defaultcol)=@{ $option };
 9449: 	    $r->print('<option value="'.$value.'"'.
 9450:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 9451:                       $display.'</option>');
 9452: 	}
 9453: 	$r->print('</select></td><td>');
 9454: 	foreach my $line (0..($max_samples-1)) {
 9455: 	    if (defined($samples->[$line]{$key})) { 
 9456: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 9457: 	    }
 9458: 	}
 9459: 	$r->print('</td>'.&end_data_table_row());
 9460: 	$i++;
 9461:     }
 9462:     $r->print(&end_data_table());
 9463:     $i--;
 9464:     return($i);
 9465: }
 9466: 
 9467: ######################################################
 9468: ######################################################
 9469: 
 9470: =pod
 9471: 
 9472: =item * &clean_excel_name($name)
 9473: 
 9474: Returns a replacement for $name which does not contain any illegal characters.
 9475: 
 9476: =cut
 9477: 
 9478: ######################################################
 9479: ######################################################
 9480: sub clean_excel_name {
 9481:     my ($name) = @_;
 9482:     $name =~ s/[:\*\?\/\\]//g;
 9483:     if (length($name) > 31) {
 9484:         $name = substr($name,0,31);
 9485:     }
 9486:     return $name;
 9487: }
 9488: 
 9489: =pod
 9490: 
 9491: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 9492: 
 9493: Returns either 1 or undef
 9494: 
 9495: 1 if the part is to be hidden, undef if it is to be shown
 9496: 
 9497: Arguments are:
 9498: 
 9499: $id the id of the part to be checked
 9500: $symb, optional the symb of the resource to check
 9501: $udom, optional the domain of the user to check for
 9502: $uname, optional the username of the user to check for
 9503: 
 9504: =cut
 9505: 
 9506: sub check_if_partid_hidden {
 9507:     my ($id,$symb,$udom,$uname) = @_;
 9508:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 9509: 					 $symb,$udom,$uname);
 9510:     my $truth=1;
 9511:     #if the string starts with !, then the list is the list to show not hide
 9512:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 9513:     my @hiddenlist=split(/,/,$hiddenparts);
 9514:     foreach my $checkid (@hiddenlist) {
 9515: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 9516:     }
 9517:     return !$truth;
 9518: }
 9519: 
 9520: 
 9521: ############################################################
 9522: ############################################################
 9523: 
 9524: =pod
 9525: 
 9526: =back 
 9527: 
 9528: =head1 cgi-bin script and graphing routines
 9529: 
 9530: =over 4
 9531: 
 9532: =item * &get_cgi_id()
 9533: 
 9534: Inputs: none
 9535: 
 9536: Returns an id which can be used to pass environment variables
 9537: to various cgi-bin scripts.  These environment variables will
 9538: be removed from the users environment after a given time by
 9539: the routine &Apache::lonnet::transfer_profile_to_env.
 9540: 
 9541: =cut
 9542: 
 9543: ############################################################
 9544: ############################################################
 9545: my $uniq=0;
 9546: sub get_cgi_id {
 9547:     $uniq=($uniq+1)%100000;
 9548:     return (time.'_'.$$.'_'.$uniq);
 9549: }
 9550: 
 9551: ############################################################
 9552: ############################################################
 9553: 
 9554: =pod
 9555: 
 9556: =item * &DrawBarGraph()
 9557: 
 9558: Facilitates the plotting of data in a (stacked) bar graph.
 9559: Puts plot definition data into the users environment in order for 
 9560: graph.png to plot it.  Returns an <img> tag for the plot.
 9561: The bars on the plot are labeled '1','2',...,'n'.
 9562: 
 9563: Inputs:
 9564: 
 9565: =over 4
 9566: 
 9567: =item $Title: string, the title of the plot
 9568: 
 9569: =item $xlabel: string, text describing the X-axis of the plot
 9570: 
 9571: =item $ylabel: string, text describing the Y-axis of the plot
 9572: 
 9573: =item $Max: scalar, the maximum Y value to use in the plot
 9574: If $Max is < any data point, the graph will not be rendered.
 9575: 
 9576: =item $colors: array ref holding the colors to be used for the data sets when
 9577: they are plotted.  If undefined, default values will be used.
 9578: 
 9579: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 9580: 
 9581: =item @Values: An array of array references.  Each array reference holds data
 9582: to be plotted in a stacked bar chart.
 9583: 
 9584: =item If the final element of @Values is a hash reference the key/value
 9585: pairs will be added to the graph definition.
 9586: 
 9587: =back
 9588: 
 9589: Returns:
 9590: 
 9591: An <img> tag which references graph.png and the appropriate identifying
 9592: information for the plot.
 9593: 
 9594: =cut
 9595: 
 9596: ############################################################
 9597: ############################################################
 9598: sub DrawBarGraph {
 9599:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9600:     #
 9601:     if (! defined($colors)) {
 9602:         $colors = ['#33ff00', 
 9603:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9604:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9605:                   ]; 
 9606:     }
 9607:     my $extra_settings = {};
 9608:     if (ref($Values[-1]) eq 'HASH') {
 9609:         $extra_settings = pop(@Values);
 9610:     }
 9611:     #
 9612:     my $identifier = &get_cgi_id();
 9613:     my $id = 'cgi.'.$identifier;        
 9614:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9615:         return '';
 9616:     }
 9617:     #
 9618:     my @Labels;
 9619:     if (defined($labels)) {
 9620:         @Labels = @$labels;
 9621:     } else {
 9622:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9623:             push (@Labels,$i+1);
 9624:         }
 9625:     }
 9626:     #
 9627:     my $NumBars = scalar(@{$Values[0]});
 9628:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9629:     my %ValuesHash;
 9630:     my $NumSets=1;
 9631:     foreach my $array (@Values) {
 9632:         next if (! ref($array));
 9633:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9634:             join(',',@$array);
 9635:     }
 9636:     #
 9637:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9638:     if ($NumBars < 3) {
 9639:         $width = 120+$NumBars*32;
 9640:         $xskip = 1;
 9641:         $bar_width = 30;
 9642:     } elsif ($NumBars < 5) {
 9643:         $width = 120+$NumBars*20;
 9644:         $xskip = 1;
 9645:         $bar_width = 20;
 9646:     } elsif ($NumBars < 10) {
 9647:         $width = 120+$NumBars*15;
 9648:         $xskip = 1;
 9649:         $bar_width = 15;
 9650:     } elsif ($NumBars <= 25) {
 9651:         $width = 120+$NumBars*11;
 9652:         $xskip = 5;
 9653:         $bar_width = 8;
 9654:     } elsif ($NumBars <= 50) {
 9655:         $width = 120+$NumBars*8;
 9656:         $xskip = 5;
 9657:         $bar_width = 4;
 9658:     } else {
 9659:         $width = 120+$NumBars*8;
 9660:         $xskip = 5;
 9661:         $bar_width = 4;
 9662:     }
 9663:     #
 9664:     $Max = 1 if ($Max < 1);
 9665:     if ( int($Max) < $Max ) {
 9666:         $Max++;
 9667:         $Max = int($Max);
 9668:     }
 9669:     $Title  = '' if (! defined($Title));
 9670:     $xlabel = '' if (! defined($xlabel));
 9671:     $ylabel = '' if (! defined($ylabel));
 9672:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9673:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9674:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9675:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9676:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9677:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9678:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9679:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9680:     $ValuesHash{$id.'.height'}   = $height;
 9681:     $ValuesHash{$id.'.width'}    = $width;
 9682:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9683:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9684:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9685:     #
 9686:     # Deal with other parameters
 9687:     while (my ($key,$value) = each(%$extra_settings)) {
 9688:         $ValuesHash{$id.'.'.$key} = $value;
 9689:     }
 9690:     #
 9691:     &Apache::lonnet::appenv(\%ValuesHash);
 9692:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9693: }
 9694: 
 9695: ############################################################
 9696: ############################################################
 9697: 
 9698: =pod
 9699: 
 9700: =item * &DrawXYGraph()
 9701: 
 9702: Facilitates the plotting of data in an XY graph.
 9703: Puts plot definition data into the users environment in order for 
 9704: graph.png to plot it.  Returns an <img> tag for the plot.
 9705: 
 9706: Inputs:
 9707: 
 9708: =over 4
 9709: 
 9710: =item $Title: string, the title of the plot
 9711: 
 9712: =item $xlabel: string, text describing the X-axis of the plot
 9713: 
 9714: =item $ylabel: string, text describing the Y-axis of the plot
 9715: 
 9716: =item $Max: scalar, the maximum Y value to use in the plot
 9717: If $Max is < any data point, the graph will not be rendered.
 9718: 
 9719: =item $colors: Array ref containing the hex color codes for the data to be 
 9720: plotted in.  If undefined, default values will be used.
 9721: 
 9722: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9723: 
 9724: =item $Ydata: Array ref containing Array refs.  
 9725: Each of the contained arrays will be plotted as a separate curve.
 9726: 
 9727: =item %Values: hash indicating or overriding any default values which are 
 9728: passed to graph.png.  
 9729: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9730: 
 9731: =back
 9732: 
 9733: Returns:
 9734: 
 9735: An <img> tag which references graph.png and the appropriate identifying
 9736: information for the plot.
 9737: 
 9738: =cut
 9739: 
 9740: ############################################################
 9741: ############################################################
 9742: sub DrawXYGraph {
 9743:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9744:     #
 9745:     # Create the identifier for the graph
 9746:     my $identifier = &get_cgi_id();
 9747:     my $id = 'cgi.'.$identifier;
 9748:     #
 9749:     $Title  = '' if (! defined($Title));
 9750:     $xlabel = '' if (! defined($xlabel));
 9751:     $ylabel = '' if (! defined($ylabel));
 9752:     my %ValuesHash = 
 9753:         (
 9754:          $id.'.title'  => &escape($Title),
 9755:          $id.'.xlabel' => &escape($xlabel),
 9756:          $id.'.ylabel' => &escape($ylabel),
 9757:          $id.'.y_max_value'=> $Max,
 9758:          $id.'.labels'     => join(',',@$Xlabels),
 9759:          $id.'.PlotType'   => 'XY',
 9760:          );
 9761:     #
 9762:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9763:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9764:     }
 9765:     #
 9766:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9767:         return '';
 9768:     }
 9769:     my $NumSets=1;
 9770:     foreach my $array (@{$Ydata}){
 9771:         next if (! ref($array));
 9772:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9773:     }
 9774:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9775:     #
 9776:     # Deal with other parameters
 9777:     while (my ($key,$value) = each(%Values)) {
 9778:         $ValuesHash{$id.'.'.$key} = $value;
 9779:     }
 9780:     #
 9781:     &Apache::lonnet::appenv(\%ValuesHash);
 9782:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9783: }
 9784: 
 9785: ############################################################
 9786: ############################################################
 9787: 
 9788: =pod
 9789: 
 9790: =item * &DrawXYYGraph()
 9791: 
 9792: Facilitates the plotting of data in an XY graph with two Y axes.
 9793: Puts plot definition data into the users environment in order for 
 9794: graph.png to plot it.  Returns an <img> tag for the plot.
 9795: 
 9796: Inputs:
 9797: 
 9798: =over 4
 9799: 
 9800: =item $Title: string, the title of the plot
 9801: 
 9802: =item $xlabel: string, text describing the X-axis of the plot
 9803: 
 9804: =item $ylabel: string, text describing the Y-axis of the plot
 9805: 
 9806: =item $colors: Array ref containing the hex color codes for the data to be 
 9807: plotted in.  If undefined, default values will be used.
 9808: 
 9809: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9810: 
 9811: =item $Ydata1: The first data set
 9812: 
 9813: =item $Min1: The minimum value of the left Y-axis
 9814: 
 9815: =item $Max1: The maximum value of the left Y-axis
 9816: 
 9817: =item $Ydata2: The second data set
 9818: 
 9819: =item $Min2: The minimum value of the right Y-axis
 9820: 
 9821: =item $Max2: The maximum value of the left Y-axis
 9822: 
 9823: =item %Values: hash indicating or overriding any default values which are 
 9824: passed to graph.png.  
 9825: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9826: 
 9827: =back
 9828: 
 9829: Returns:
 9830: 
 9831: An <img> tag which references graph.png and the appropriate identifying
 9832: information for the plot.
 9833: 
 9834: =cut
 9835: 
 9836: ############################################################
 9837: ############################################################
 9838: sub DrawXYYGraph {
 9839:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9840:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9841:     #
 9842:     # Create the identifier for the graph
 9843:     my $identifier = &get_cgi_id();
 9844:     my $id = 'cgi.'.$identifier;
 9845:     #
 9846:     $Title  = '' if (! defined($Title));
 9847:     $xlabel = '' if (! defined($xlabel));
 9848:     $ylabel = '' if (! defined($ylabel));
 9849:     my %ValuesHash = 
 9850:         (
 9851:          $id.'.title'  => &escape($Title),
 9852:          $id.'.xlabel' => &escape($xlabel),
 9853:          $id.'.ylabel' => &escape($ylabel),
 9854:          $id.'.labels' => join(',',@$Xlabels),
 9855:          $id.'.PlotType' => 'XY',
 9856:          $id.'.NumSets' => 2,
 9857:          $id.'.two_axes' => 1,
 9858:          $id.'.y1_max_value' => $Max1,
 9859:          $id.'.y1_min_value' => $Min1,
 9860:          $id.'.y2_max_value' => $Max2,
 9861:          $id.'.y2_min_value' => $Min2,
 9862:          );
 9863:     #
 9864:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9865:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9866:     }
 9867:     #
 9868:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9869:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9870:         return '';
 9871:     }
 9872:     my $NumSets=1;
 9873:     foreach my $array ($Ydata1,$Ydata2){
 9874:         next if (! ref($array));
 9875:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9876:     }
 9877:     #
 9878:     # Deal with other parameters
 9879:     while (my ($key,$value) = each(%Values)) {
 9880:         $ValuesHash{$id.'.'.$key} = $value;
 9881:     }
 9882:     #
 9883:     &Apache::lonnet::appenv(\%ValuesHash);
 9884:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9885: }
 9886: 
 9887: ############################################################
 9888: ############################################################
 9889: 
 9890: =pod
 9891: 
 9892: =back 
 9893: 
 9894: =head1 Statistics helper routines?  
 9895: 
 9896: Bad place for them but what the hell.
 9897: 
 9898: =over 4
 9899: 
 9900: =item * &chartlink()
 9901: 
 9902: Returns a link to the chart for a specific student.  
 9903: 
 9904: Inputs:
 9905: 
 9906: =over 4
 9907: 
 9908: =item $linktext: The text of the link
 9909: 
 9910: =item $sname: The students username
 9911: 
 9912: =item $sdomain: The students domain
 9913: 
 9914: =back
 9915: 
 9916: =back
 9917: 
 9918: =cut
 9919: 
 9920: ############################################################
 9921: ############################################################
 9922: sub chartlink {
 9923:     my ($linktext, $sname, $sdomain) = @_;
 9924:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9925:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9926:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9927:        '">'.$linktext.'</a>';
 9928: }
 9929: 
 9930: #######################################################
 9931: #######################################################
 9932: 
 9933: =pod
 9934: 
 9935: =head1 Course Environment Routines
 9936: 
 9937: =over 4
 9938: 
 9939: =item * &restore_course_settings()
 9940: 
 9941: =item * &store_course_settings()
 9942: 
 9943: Restores/Store indicated form parameters from the course environment.
 9944: Will not overwrite existing values of the form parameters.
 9945: 
 9946: Inputs: 
 9947: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9948: 
 9949: a hash ref describing the data to be stored.  For example:
 9950:    
 9951: %Save_Parameters = ('Status' => 'scalar',
 9952:     'chartoutputmode' => 'scalar',
 9953:     'chartoutputdata' => 'scalar',
 9954:     'Section' => 'array',
 9955:     'Group' => 'array',
 9956:     'StudentData' => 'array',
 9957:     'Maps' => 'array');
 9958: 
 9959: Returns: both routines return nothing
 9960: 
 9961: =back
 9962: 
 9963: =cut
 9964: 
 9965: #######################################################
 9966: #######################################################
 9967: sub store_course_settings {
 9968:     return &store_settings($env{'request.course.id'},@_);
 9969: }
 9970: 
 9971: sub store_settings {
 9972:     # save to the environment
 9973:     # appenv the same items, just to be safe
 9974:     my $udom  = $env{'user.domain'};
 9975:     my $uname = $env{'user.name'};
 9976:     my ($context,$prefix,$Settings) = @_;
 9977:     my %SaveHash;
 9978:     my %AppHash;
 9979:     while (my ($setting,$type) = each(%$Settings)) {
 9980:         my $basename = join('.','internal',$context,$prefix,$setting);
 9981:         my $envname = 'environment.'.$basename;
 9982:         if (exists($env{'form.'.$setting})) {
 9983:             # Save this value away
 9984:             if ($type eq 'scalar' &&
 9985:                 (! exists($env{$envname}) || 
 9986:                  $env{$envname} ne $env{'form.'.$setting})) {
 9987:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9988:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9989:             } elsif ($type eq 'array') {
 9990:                 my $stored_form;
 9991:                 if (ref($env{'form.'.$setting})) {
 9992:                     $stored_form = join(',',
 9993:                                         map {
 9994:                                             &escape($_);
 9995:                                         } sort(@{$env{'form.'.$setting}}));
 9996:                 } else {
 9997:                     $stored_form = 
 9998:                         &escape($env{'form.'.$setting});
 9999:                 }
10000:                 # Determine if the array contents are the same.
10001:                 if ($stored_form ne $env{$envname}) {
10002:                     $SaveHash{$basename} = $stored_form;
10003:                     $AppHash{$envname}   = $stored_form;
10004:                 }
10005:             }
10006:         }
10007:     }
10008:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
10009:                                           $udom,$uname);
10010:     if ($put_result !~ /^(ok|delayed)/) {
10011:         &Apache::lonnet::logthis('unable to save form parameters, '.
10012:                                  'got error:'.$put_result);
10013:     }
10014:     # Make sure these settings stick around in this session, too
10015:     &Apache::lonnet::appenv(\%AppHash);
10016:     return;
10017: }
10018: 
10019: sub restore_course_settings {
10020:     return &restore_settings($env{'request.course.id'},@_);
10021: }
10022: 
10023: sub restore_settings {
10024:     my ($context,$prefix,$Settings) = @_;
10025:     while (my ($setting,$type) = each(%$Settings)) {
10026:         next if (exists($env{'form.'.$setting}));
10027:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
10028:             '.'.$setting;
10029:         if (exists($env{$envname})) {
10030:             if ($type eq 'scalar') {
10031:                 $env{'form.'.$setting} = $env{$envname};
10032:             } elsif ($type eq 'array') {
10033:                 $env{'form.'.$setting} = [ 
10034:                                            map { 
10035:                                                &unescape($_); 
10036:                                            } split(',',$env{$envname})
10037:                                            ];
10038:             }
10039:         }
10040:     }
10041: }
10042: 
10043: #######################################################
10044: #######################################################
10045: 
10046: =pod
10047: 
10048: =head1 Domain E-mail Routines  
10049: 
10050: =over 4
10051: 
10052: =item * &build_recipient_list()
10053: 
10054: Build recipient lists for five types of e-mail:
10055: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
10056: (d) Help requests, (e) Course requests needing approval,  generated by
10057: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
10058: loncoursequeueadmin.pm respectively.
10059: 
10060: Inputs:
10061: defmail (scalar - email address of default recipient), 
10062: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
10063: defdom (domain for which to retrieve configuration settings),
10064: origmail (scalar - email address of recipient from loncapa.conf, 
10065: i.e., predates configuration by DC via domainprefs.pm 
10066: 
10067: Returns: comma separated list of addresses to which to send e-mail.
10068: 
10069: =back
10070: 
10071: =cut
10072: 
10073: ############################################################
10074: ############################################################
10075: sub build_recipient_list {
10076:     my ($defmail,$mailing,$defdom,$origmail) = @_;
10077:     my @recipients;
10078:     my $otheremails;
10079:     my %domconfig =
10080:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
10081:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10082:         if (exists($domconfig{'contacts'}{$mailing})) {
10083:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
10084:                 my @contacts = ('adminemail','supportemail');
10085:                 foreach my $item (@contacts) {
10086:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
10087:                         my $addr = $domconfig{'contacts'}{$item}; 
10088:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
10089:                             push(@recipients,$addr);
10090:                         }
10091:                     }
10092:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
10093:                 }
10094:             }
10095:         } elsif ($origmail ne '') {
10096:             push(@recipients,$origmail);
10097:         }
10098:     } elsif ($origmail ne '') {
10099:         push(@recipients,$origmail);
10100:     }
10101:     if (defined($defmail)) {
10102:         if ($defmail ne '') {
10103:             push(@recipients,$defmail);
10104:         }
10105:     }
10106:     if ($otheremails) {
10107:         my @others;
10108:         if ($otheremails =~ /,/) {
10109:             @others = split(/,/,$otheremails);
10110:         } else {
10111:             push(@others,$otheremails);
10112:         }
10113:         foreach my $addr (@others) {
10114:             if (!grep(/^\Q$addr\E$/,@recipients)) {
10115:                 push(@recipients,$addr);
10116:             }
10117:         }
10118:     }
10119:     my $recipientlist = join(',',@recipients); 
10120:     return $recipientlist;
10121: }
10122: 
10123: ############################################################
10124: ############################################################
10125: 
10126: =pod
10127: 
10128: =head1 Course Catalog Routines
10129: 
10130: =over 4
10131: 
10132: =item * &gather_categories()
10133: 
10134: Converts category definitions - keys of categories hash stored in  
10135: coursecategories in configuration.db on the primary library server in a 
10136: domain - to an array.  Also generates javascript and idx hash used to 
10137: generate Domain Coordinator interface for editing Course Categories.
10138: 
10139: Inputs:
10140: 
10141: categories (reference to hash of category definitions).
10142: 
10143: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10144:       categories and subcategories).
10145: 
10146: idx (reference to hash of counters used in Domain Coordinator interface for 
10147:       editing Course Categories).
10148: 
10149: jsarray (reference to array of categories used to create Javascript arrays for
10150:          Domain Coordinator interface for editing Course Categories).
10151: 
10152: Returns: nothing
10153: 
10154: Side effects: populates cats, idx and jsarray. 
10155: 
10156: =cut
10157: 
10158: sub gather_categories {
10159:     my ($categories,$cats,$idx,$jsarray) = @_;
10160:     my %counters;
10161:     my $num = 0;
10162:     foreach my $item (keys(%{$categories})) {
10163:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10164:         if ($container eq '' && $depth == 0) {
10165:             $cats->[$depth][$categories->{$item}] = $cat;
10166:         } else {
10167:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
10168:         }
10169:         my ($escitem,$tail) = split(/:/,$item,2);
10170:         if ($counters{$tail} eq '') {
10171:             $counters{$tail} = $num;
10172:             $num ++;
10173:         }
10174:         if (ref($idx) eq 'HASH') {
10175:             $idx->{$item} = $counters{$tail};
10176:         }
10177:         if (ref($jsarray) eq 'ARRAY') {
10178:             push(@{$jsarray->[$counters{$tail}]},$item);
10179:         }
10180:     }
10181:     return;
10182: }
10183: 
10184: =pod
10185: 
10186: =item * &extract_categories()
10187: 
10188: Used to generate breadcrumb trails for course categories.
10189: 
10190: Inputs:
10191: 
10192: categories (reference to hash of category definitions).
10193: 
10194: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10195:       categories and subcategories).
10196: 
10197: trails (reference to array of breacrumb trails for each category).
10198: 
10199: allitems (reference to hash - key is category key 
10200:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10201: 
10202: idx (reference to hash of counters used in Domain Coordinator interface for
10203:       editing Course Categories).
10204: 
10205: jsarray (reference to array of categories used to create Javascript arrays for
10206:          Domain Coordinator interface for editing Course Categories).
10207: 
10208: subcats (reference to hash of arrays containing all subcategories within each 
10209:          category, -recursive)
10210: 
10211: Returns: nothing
10212: 
10213: Side effects: populates trails and allitems hash references.
10214: 
10215: =cut
10216: 
10217: sub extract_categories {
10218:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
10219:     if (ref($categories) eq 'HASH') {
10220:         &gather_categories($categories,$cats,$idx,$jsarray);
10221:         if (ref($cats->[0]) eq 'ARRAY') {
10222:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
10223:                 my $name = $cats->[0][$i];
10224:                 my $item = &escape($name).'::0';
10225:                 my $trailstr;
10226:                 if ($name eq 'instcode') {
10227:                     $trailstr = &mt('Official courses (with institutional codes)');
10228:                 } elsif ($name eq 'communities') {
10229:                     $trailstr = &mt('Communities');
10230:                 } else {
10231:                     $trailstr = $name;
10232:                 }
10233:                 if ($allitems->{$item} eq '') {
10234:                     push(@{$trails},$trailstr);
10235:                     $allitems->{$item} = scalar(@{$trails})-1;
10236:                 }
10237:                 my @parents = ($name);
10238:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
10239:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
10240:                         my $category = $cats->[1]{$name}[$j];
10241:                         if (ref($subcats) eq 'HASH') {
10242:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
10243:                         }
10244:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
10245:                     }
10246:                 } else {
10247:                     if (ref($subcats) eq 'HASH') {
10248:                         $subcats->{$item} = [];
10249:                     }
10250:                 }
10251:             }
10252:         }
10253:     }
10254:     return;
10255: }
10256: 
10257: =pod
10258: 
10259: =item *&recurse_categories()
10260: 
10261: Recursively used to generate breadcrumb trails for course categories.
10262: 
10263: Inputs:
10264: 
10265: cats (reference to array of arrays/hashes which encapsulates hierarchy of
10266:       categories and subcategories).
10267: 
10268: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
10269: 
10270: category (current course category, for which breadcrumb trail is being generated).
10271: 
10272: trails (reference to array of breadcrumb trails for each category).
10273: 
10274: allitems (reference to hash - key is category key
10275:          (format: escaped(name):escaped(parent category):depth in hierarchy).
10276: 
10277: parents (array containing containers directories for current category, 
10278:          back to top level). 
10279: 
10280: Returns: nothing
10281: 
10282: Side effects: populates trails and allitems hash references
10283: 
10284: =cut
10285: 
10286: sub recurse_categories {
10287:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
10288:     my $shallower = $depth - 1;
10289:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
10290:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
10291:             my $name = $cats->[$depth]{$category}[$k];
10292:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10293:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
10294:             if ($allitems->{$item} eq '') {
10295:                 push(@{$trails},$trailstr);
10296:                 $allitems->{$item} = scalar(@{$trails})-1;
10297:             }
10298:             my $deeper = $depth+1;
10299:             push(@{$parents},$category);
10300:             if (ref($subcats) eq 'HASH') {
10301:                 my $subcat = &escape($name).':'.$category.':'.$depth;
10302:                 for (my $j=@{$parents}; $j>=0; $j--) {
10303:                     my $higher;
10304:                     if ($j > 0) {
10305:                         $higher = &escape($parents->[$j]).':'.
10306:                                   &escape($parents->[$j-1]).':'.$j;
10307:                     } else {
10308:                         $higher = &escape($parents->[$j]).'::'.$j;
10309:                     }
10310:                     push(@{$subcats->{$higher}},$subcat);
10311:                 }
10312:             }
10313:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
10314:                                 $subcats);
10315:             pop(@{$parents});
10316:         }
10317:     } else {
10318:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
10319:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
10320:         if ($allitems->{$item} eq '') {
10321:             push(@{$trails},$trailstr);
10322:             $allitems->{$item} = scalar(@{$trails})-1;
10323:         }
10324:     }
10325:     return;
10326: }
10327: 
10328: =pod
10329: 
10330: =item *&assign_categories_table()
10331: 
10332: Create a datatable for display of hierarchical categories in a domain,
10333: with checkboxes to allow a course to be categorized. 
10334: 
10335: Inputs:
10336: 
10337: cathash - reference to hash of categories defined for the domain (from
10338:           configuration.db)
10339: 
10340: currcat - scalar with an & separated list of categories assigned to a course. 
10341: 
10342: type    - scalar contains course type (Course or Community).
10343: 
10344: Returns: $output (markup to be displayed) 
10345: 
10346: =cut
10347: 
10348: sub assign_categories_table {
10349:     my ($cathash,$currcat,$type) = @_;
10350:     my $output;
10351:     if (ref($cathash) eq 'HASH') {
10352:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
10353:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
10354:         $maxdepth = scalar(@cats);
10355:         if (@cats > 0) {
10356:             my $itemcount = 0;
10357:             if (ref($cats[0]) eq 'ARRAY') {
10358:                 my @currcategories;
10359:                 if ($currcat ne '') {
10360:                     @currcategories = split('&',$currcat);
10361:                 }
10362:                 my $table;
10363:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
10364:                     my $parent = $cats[0][$i];
10365:                     next if ($parent eq 'instcode');
10366:                     if ($type eq 'Community') {
10367:                         next unless ($parent eq 'communities');
10368:                     } else {
10369:                         next if ($parent eq 'communities');
10370:                     }
10371:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10372:                     my $item = &escape($parent).'::0';
10373:                     my $checked = '';
10374:                     if (@currcategories > 0) {
10375:                         if (grep(/^\Q$item\E$/,@currcategories)) {
10376:                             $checked = ' checked="checked"';
10377:                         }
10378:                     }
10379:                     my $parent_title = $parent;
10380:                     if ($parent eq 'communities') {
10381:                         $parent_title = &mt('Communities');
10382:                     }
10383:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
10384:                               '<input type="checkbox" name="usecategory" value="'.
10385:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
10386:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
10387:                     my $depth = 1;
10388:                     push(@path,$parent);
10389:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
10390:                     pop(@path);
10391:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10392:                     $itemcount ++;
10393:                 }
10394:                 if ($itemcount) {
10395:                     $output = &Apache::loncommon::start_data_table().
10396:                               $table.
10397:                               &Apache::loncommon::end_data_table();
10398:                 }
10399:             }
10400:         }
10401:     }
10402:     return $output;
10403: }
10404: 
10405: =pod
10406: 
10407: =item *&assign_category_rows()
10408: 
10409: Create a datatable row for display of nested categories in a domain,
10410: with checkboxes to allow a course to be categorized,called recursively.
10411: 
10412: Inputs:
10413: 
10414: itemcount - track row number for alternating colors
10415: 
10416: cats - reference to array of arrays/hashes which encapsulates hierarchy of
10417:       categories and subcategories.
10418: 
10419: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
10420: 
10421: parent - parent of current category item
10422: 
10423: path - Array containing all categories back up through the hierarchy from the
10424:        current category to the top level.
10425: 
10426: currcategories - reference to array of current categories assigned to the course
10427: 
10428: Returns: $output (markup to be displayed).
10429: 
10430: =cut
10431: 
10432: sub assign_category_rows {
10433:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
10434:     my ($text,$name,$item,$chgstr);
10435:     if (ref($cats) eq 'ARRAY') {
10436:         my $maxdepth = scalar(@{$cats});
10437:         if (ref($cats->[$depth]) eq 'HASH') {
10438:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10439:                 my $numchildren = @{$cats->[$depth]{$parent}};
10440:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10441:                 $text .= '<td><table class="LC_datatable">';
10442:                 for (my $j=0; $j<$numchildren; $j++) {
10443:                     $name = $cats->[$depth]{$parent}[$j];
10444:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
10445:                     my $deeper = $depth+1;
10446:                     my $checked = '';
10447:                     if (ref($currcategories) eq 'ARRAY') {
10448:                         if (@{$currcategories} > 0) {
10449:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
10450:                                 $checked = ' checked="checked"';
10451:                             }
10452:                         }
10453:                     }
10454:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
10455:                              '<input type="checkbox" name="usecategory" value="'.
10456:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
10457:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
10458:                              '</td><td>';
10459:                     if (ref($path) eq 'ARRAY') {
10460:                         push(@{$path},$name);
10461:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
10462:                         pop(@{$path});
10463:                     }
10464:                     $text .= '</td></tr>';
10465:                 }
10466:                 $text .= '</table></td>';
10467:             }
10468:         }
10469:     }
10470:     return $text;
10471: }
10472: 
10473: ############################################################
10474: ############################################################
10475: 
10476: 
10477: sub commit_customrole {
10478:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
10479:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
10480:                          ($start?', '.&mt('starting').' '.localtime($start):'').
10481:                          ($end?', ending '.localtime($end):'').': <b>'.
10482:               &Apache::lonnet::assigncustomrole(
10483:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
10484:                  '</b><br />';
10485:     return $output;
10486: }
10487: 
10488: sub commit_standardrole {
10489:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10490:     my ($output,$logmsg,$linefeed);
10491:     if ($context eq 'auto') {
10492:         $linefeed = "\n";
10493:     } else {
10494:         $linefeed = "<br />\n";
10495:     }  
10496:     if ($three eq 'st') {
10497:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
10498:                                          $one,$two,$sec,$context);
10499:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
10500:             ($result eq 'unknown_course') || ($result eq 'refused')) {
10501:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
10502:         } else {
10503:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
10504:                ($start?', '.&mt('starting').' '.localtime($start):'').
10505:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10506:             if ($context eq 'auto') {
10507:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
10508:             } else {
10509:                $output .= '<b>'.$result.'</b>'.$linefeed.
10510:                &mt('Add to classlist').': <b>ok</b>';
10511:             }
10512:             $output .= $linefeed;
10513:         }
10514:     } else {
10515:         $output = &mt('Assigning').' '.$three.' in '.$url.
10516:                ($start?', '.&mt('starting').' '.localtime($start):'').
10517:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
10518:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
10519:         if ($context eq 'auto') {
10520:             $output .= $result.$linefeed;
10521:         } else {
10522:             $output .= '<b>'.$result.'</b>'.$linefeed;
10523:         }
10524:     }
10525:     return $output;
10526: }
10527: 
10528: sub commit_studentrole {
10529:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
10530:     my ($result,$linefeed,$oldsecurl,$newsecurl);
10531:     if ($context eq 'auto') {
10532:         $linefeed = "\n";
10533:     } else {
10534:         $linefeed = '<br />'."\n";
10535:     }
10536:     if (defined($one) && defined($two)) {
10537:         my $cid=$one.'_'.$two;
10538:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
10539:         my $secchange = 0;
10540:         my $expire_role_result;
10541:         my $modify_section_result;
10542:         if ($oldsec ne '-1') { 
10543:             if ($oldsec ne $sec) {
10544:                 $secchange = 1;
10545:                 my $now = time;
10546:                 my $uurl='/'.$cid;
10547:                 $uurl=~s/\_/\//g;
10548:                 if ($oldsec) {
10549:                     $uurl.='/'.$oldsec;
10550:                 }
10551:                 $oldsecurl = $uurl;
10552:                 $expire_role_result = 
10553:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
10554:                 if ($env{'request.course.sec'} ne '') { 
10555:                     if ($expire_role_result eq 'refused') {
10556:                         my @roles = ('st');
10557:                         my @statuses = ('previous');
10558:                         my @roledoms = ($one);
10559:                         my $withsec = 1;
10560:                         my %roleshash = 
10561:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
10562:                                               \@statuses,\@roles,\@roledoms,$withsec);
10563:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
10564:                             my ($oldstart,$oldend) = 
10565:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
10566:                             if ($oldend > 0 && $oldend <= $now) {
10567:                                 $expire_role_result = 'ok';
10568:                             }
10569:                         }
10570:                     }
10571:                 }
10572:                 $result = $expire_role_result;
10573:             }
10574:         }
10575:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
10576:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
10577:             if ($modify_section_result =~ /^ok/) {
10578:                 if ($secchange == 1) {
10579:                     if ($sec eq '') {
10580:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
10581:                     } else {
10582:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
10583:                     }
10584:                 } elsif ($oldsec eq '-1') {
10585:                     if ($sec eq '') {
10586:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
10587:                     } else {
10588:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10589:                     }
10590:                 } else {
10591:                     if ($sec eq '') {
10592:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
10593:                     } else {
10594:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
10595:                     }
10596:                 }
10597:             } else {
10598:                 if ($secchange) {       
10599:                     $$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;
10600:                 } else {
10601:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10602:                 }
10603:             }
10604:             $result = $modify_section_result;
10605:         } elsif ($secchange == 1) {
10606:             if ($oldsec eq '') {
10607:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10608:             } else {
10609:                 $$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;
10610:             }
10611:             if ($expire_role_result eq 'refused') {
10612:                 my $newsecurl = '/'.$cid;
10613:                 $newsecurl =~ s/\_/\//g;
10614:                 if ($sec ne '') {
10615:                     $newsecurl.='/'.$sec;
10616:                 }
10617:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10618:                     if ($sec eq '') {
10619:                         $$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;
10620:                     } else {
10621:                         $$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;
10622:                     }
10623:                 }
10624:             }
10625:         }
10626:     } else {
10627:         $$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;
10628:         $result = "error: incomplete course id\n";
10629:     }
10630:     return $result;
10631: }
10632: 
10633: ############################################################
10634: ############################################################
10635: 
10636: sub check_clone {
10637:     my ($args,$linefeed) = @_;
10638:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10639:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10640:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10641:     my $clonemsg;
10642:     my $can_clone = 0;
10643:     my $lctype = lc($args->{'crstype'});
10644:     if ($lctype ne 'community') {
10645:         $lctype = 'course';
10646:     }
10647:     if ($clonehome eq 'no_host') {
10648:         if ($args->{'crstype'} eq 'Community') {
10649:             $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'});
10650:         } else {
10651:             $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'});
10652:         }     
10653:     } else {
10654: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10655:         if ($args->{'crstype'} eq 'Community') {
10656:             if ($clonedesc{'type'} ne 'Community') {
10657:                  $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'});
10658:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10659:             }
10660:         }
10661: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10662:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10663: 	    $can_clone = 1;
10664: 	} else {
10665: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10666: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10667: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10668:             if (grep(/^\*$/,@cloners)) {
10669:                 $can_clone = 1;
10670:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10671:                 $can_clone = 1;
10672:             } else {
10673:                 my $ccrole = 'cc';
10674:                 if ($args->{'crstype'} eq 'Community') {
10675:                     $ccrole = 'co';
10676:                 }
10677: 	        my %roleshash =
10678: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10679: 					 $args->{'ccdomain'},
10680:                                          'userroles',['active'],[$ccrole],
10681: 					 [$args->{'clonedomain'}]);
10682: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10683:                     $can_clone = 1;
10684:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10685:                     $can_clone = 1;
10686:                 } else {
10687:                     if ($args->{'crstype'} eq 'Community') {
10688:                         $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'});
10689:                     } else {
10690:                         $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'});
10691:                     }
10692: 	        }
10693: 	    }
10694:         }
10695:     }
10696:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10697: }
10698: 
10699: sub construct_course {
10700:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10701:     my $outcome;
10702:     my $linefeed =  '<br />'."\n";
10703:     if ($context eq 'auto') {
10704:         $linefeed = "\n";
10705:     }
10706: 
10707: #
10708: # Are we cloning?
10709: #
10710:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10711:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10712: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10713: 	if ($context ne 'auto') {
10714:             if ($clonemsg ne '') {
10715: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10716:             }
10717: 	}
10718: 	$outcome .= $clonemsg.$linefeed;
10719: 
10720:         if (!$can_clone) {
10721: 	    return (0,$outcome);
10722: 	}
10723:     }
10724: 
10725: #
10726: # Open course
10727: #
10728:     my $crstype = lc($args->{'crstype'});
10729:     my %cenv=();
10730:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10731:                                              $args->{'cdescr'},
10732:                                              $args->{'curl'},
10733:                                              $args->{'course_home'},
10734:                                              $args->{'nonstandard'},
10735:                                              $args->{'crscode'},
10736:                                              $args->{'ccuname'}.':'.
10737:                                              $args->{'ccdomain'},
10738:                                              $args->{'crstype'},
10739:                                              $cnum,$context,$category);
10740: 
10741:     # Note: The testing routines depend on this being output; see 
10742:     # Utils::Course. This needs to at least be output as a comment
10743:     # if anyone ever decides to not show this, and Utils::Course::new
10744:     # will need to be suitably modified.
10745:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10746:     if ($$courseid =~ /^error:/) {
10747:         return (0,$outcome);
10748:     }
10749: 
10750: #
10751: # Check if created correctly
10752: #
10753:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10754:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10755:     if ($crsuhome eq 'no_host') {
10756:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10757:         return (0,$outcome);
10758:     }
10759:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10760: 
10761: #
10762: # Do the cloning
10763: #   
10764:     if ($can_clone && $cloneid) {
10765: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10766: 	if ($context ne 'auto') {
10767: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10768: 	}
10769: 	$outcome .= $clonemsg.$linefeed;
10770: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10771: # Copy all files
10772: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10773: # Restore URL
10774: 	$cenv{'url'}=$oldcenv{'url'};
10775: # Restore title
10776: 	$cenv{'description'}=$oldcenv{'description'};
10777: # Restore creation date, creator and creation context.
10778:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
10779:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10780:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10781: # Mark as cloned
10782: 	$cenv{'clonedfrom'}=$cloneid;
10783: # Need to clone grading mode
10784:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10785:         $cenv{'grading'}=$newenv{'grading'};
10786: # Do not clone these environment entries
10787:         &Apache::lonnet::del('environment',
10788:                   ['default_enrollment_start_date',
10789:                    'default_enrollment_end_date',
10790:                    'question.email',
10791:                    'policy.email',
10792:                    'comment.email',
10793:                    'pch.users.denied',
10794:                    'plc.users.denied',
10795:                    'hidefromcat',
10796:                    'categories'],
10797:                    $$crsudom,$$crsunum);
10798:     }
10799: 
10800: #
10801: # Set environment (will override cloned, if existing)
10802: #
10803:     my @sections = ();
10804:     my @xlists = ();
10805:     if ($args->{'crstype'}) {
10806:         $cenv{'type'}=$args->{'crstype'};
10807:     }
10808:     if ($args->{'crsid'}) {
10809:         $cenv{'courseid'}=$args->{'crsid'};
10810:     }
10811:     if ($args->{'crscode'}) {
10812:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10813:     }
10814:     if ($args->{'crsquota'} ne '') {
10815:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10816:     } else {
10817:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10818:     }
10819:     if ($args->{'ccuname'}) {
10820:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10821:                                         ':'.$args->{'ccdomain'};
10822:     } else {
10823:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10824:     }
10825:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10826:     if ($args->{'crssections'}) {
10827:         $cenv{'internal.sectionnums'} = '';
10828:         if ($args->{'crssections'} =~ m/,/) {
10829:             @sections = split/,/,$args->{'crssections'};
10830:         } else {
10831:             $sections[0] = $args->{'crssections'};
10832:         }
10833:         if (@sections > 0) {
10834:             foreach my $item (@sections) {
10835:                 my ($sec,$gp) = split/:/,$item;
10836:                 my $class = $args->{'crscode'}.$sec;
10837:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10838:                 $cenv{'internal.sectionnums'} .= $item.',';
10839:                 unless ($addcheck eq 'ok') {
10840:                     push @badclasses, $class;
10841:                 }
10842:             }
10843:             $cenv{'internal.sectionnums'} =~ s/,$//;
10844:         }
10845:     }
10846: # do not hide course coordinator from staff listing, 
10847: # even if privileged
10848:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10849: # add crosslistings
10850:     if ($args->{'crsxlist'}) {
10851:         $cenv{'internal.crosslistings'}='';
10852:         if ($args->{'crsxlist'} =~ m/,/) {
10853:             @xlists = split/,/,$args->{'crsxlist'};
10854:         } else {
10855:             $xlists[0] = $args->{'crsxlist'};
10856:         }
10857:         if (@xlists > 0) {
10858:             foreach my $item (@xlists) {
10859:                 my ($xl,$gp) = split/:/,$item;
10860:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10861:                 $cenv{'internal.crosslistings'} .= $item.',';
10862:                 unless ($addcheck eq 'ok') {
10863:                     push @badclasses, $xl;
10864:                 }
10865:             }
10866:             $cenv{'internal.crosslistings'} =~ s/,$//;
10867:         }
10868:     }
10869:     if ($args->{'autoadds'}) {
10870:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10871:     }
10872:     if ($args->{'autodrops'}) {
10873:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10874:     }
10875: # check for notification of enrollment changes
10876:     my @notified = ();
10877:     if ($args->{'notify_owner'}) {
10878:         if ($args->{'ccuname'} ne '') {
10879:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10880:         }
10881:     }
10882:     if ($args->{'notify_dc'}) {
10883:         if ($uname ne '') { 
10884:             push(@notified,$uname.':'.$udom);
10885:         }
10886:     }
10887:     if (@notified > 0) {
10888:         my $notifylist;
10889:         if (@notified > 1) {
10890:             $notifylist = join(',',@notified);
10891:         } else {
10892:             $notifylist = $notified[0];
10893:         }
10894:         $cenv{'internal.notifylist'} = $notifylist;
10895:     }
10896:     if (@badclasses > 0) {
10897:         my %lt=&Apache::lonlocal::texthash(
10898:                 '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',
10899:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10900:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10901:         );
10902:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10903:                            ' ('.$lt{'adby'}.')';
10904:         if ($context eq 'auto') {
10905:             $outcome .= $badclass_msg.$linefeed;
10906:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10907:             foreach my $item (@badclasses) {
10908:                 if ($context eq 'auto') {
10909:                     $outcome .= " - $item\n";
10910:                 } else {
10911:                     $outcome .= "<li>$item</li>\n";
10912:                 }
10913:             }
10914:             if ($context eq 'auto') {
10915:                 $outcome .= $linefeed;
10916:             } else {
10917:                 $outcome .= "</ul><br /><br /></div>\n";
10918:             }
10919:         } 
10920:     }
10921:     if ($args->{'no_end_date'}) {
10922:         $args->{'endaccess'} = 0;
10923:     }
10924:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10925:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10926:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10927:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10928:     if ($args->{'showphotos'}) {
10929:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10930:     }
10931:     $cenv{'internal.authtype'} = $args->{'authtype'};
10932:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10933:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10934:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10935:             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'); 
10936:             if ($context eq 'auto') {
10937:                 $outcome .= $krb_msg;
10938:             } else {
10939:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10940:             }
10941:             $outcome .= $linefeed;
10942:         }
10943:     }
10944:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10945:        if ($args->{'setpolicy'}) {
10946:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10947:        }
10948:        if ($args->{'setcontent'}) {
10949:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10950:        }
10951:     }
10952:     if ($args->{'reshome'}) {
10953: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10954: 	$cenv{'reshome'}=~s/\/+$/\//;
10955:     }
10956: #
10957: # course has keyed access
10958: #
10959:     if ($args->{'setkeys'}) {
10960:        $cenv{'keyaccess'}='yes';
10961:     }
10962: # if specified, key authority is not course, but user
10963: # only active if keyaccess is yes
10964:     if ($args->{'keyauth'}) {
10965: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10966: 	$user = &LONCAPA::clean_username($user);
10967: 	$domain = &LONCAPA::clean_username($domain);
10968: 	if ($user ne '' && $domain ne '') {
10969: 	    $cenv{'keyauth'}=$user.':'.$domain;
10970: 	}
10971:     }
10972: 
10973:     if ($args->{'disresdis'}) {
10974:         $cenv{'pch.roles.denied'}='st';
10975:     }
10976:     if ($args->{'disablechat'}) {
10977:         $cenv{'plc.roles.denied'}='st';
10978:     }
10979: 
10980:     # Record we've not yet viewed the Course Initialization Helper for this 
10981:     # course
10982:     $cenv{'course.helper.not.run'} = 1;
10983:     #
10984:     # Use new Randomseed
10985:     #
10986:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10987:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10988:     #
10989:     # The encryption code and receipt prefix for this course
10990:     #
10991:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10992:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10993:     #
10994:     # By default, use standard grading
10995:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10996: 
10997:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10998:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10999: #
11000: # Open all assignments
11001: #
11002:     if ($args->{'openall'}) {
11003:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
11004:        my %storecontent = ($storeunder         => time,
11005:                            $storeunder.'.type' => 'date_start');
11006:        
11007:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
11008:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
11009:    }
11010: #
11011: # Set first page
11012: #
11013:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
11014: 	    || ($cloneid)) {
11015: 	use LONCAPA::map;
11016: 	$outcome .= &mt('Setting first resource').': ';
11017: 
11018: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
11019:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
11020: 
11021:         $outcome .= ($fatal?$errtext:'read ok').' - ';
11022:         my $title; my $url;
11023:         if ($args->{'firstres'} eq 'syl') {
11024: 	    $title=&mt('Syllabus');
11025:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
11026:         } else {
11027:             $title=&mt('Table of Contents');
11028:             $url='/adm/navmaps';
11029:         }
11030: 
11031:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
11032: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
11033: 
11034: 	if ($errtext) { $fatal=2; }
11035:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
11036:     }
11037: 
11038:     return (1,$outcome);
11039: }
11040: 
11041: ############################################################
11042: ############################################################
11043: 
11044: #SD
11045: # only Community and Course, or anything else?
11046: sub course_type {
11047:     my ($cid) = @_;
11048:     if (!defined($cid)) {
11049:         $cid = $env{'request.course.id'};
11050:     }
11051:     if (defined($env{'course.'.$cid.'.type'})) {
11052:         return $env{'course.'.$cid.'.type'};
11053:     } else {
11054:         return 'Course';
11055:     }
11056: }
11057: 
11058: sub group_term {
11059:     my $crstype = &course_type();
11060:     my %names = (
11061:                   'Course' => 'group',
11062:                   'Community' => 'group',
11063:                 );
11064:     return $names{$crstype};
11065: }
11066: 
11067: sub course_types {
11068:     my @types = ('official','unofficial','community');
11069:     my %typename = (
11070:                          official   => 'Official course',
11071:                          unofficial => 'Unofficial course',
11072:                          community  => 'Community',
11073:                    );
11074:     return (\@types,\%typename);
11075: }
11076: 
11077: sub icon {
11078:     my ($file)=@_;
11079:     my $curfext = lc((split(/\./,$file))[-1]);
11080:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
11081:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
11082:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
11083: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
11084: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11085: 	            $curfext.".gif") {
11086: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
11087: 		$curfext.".gif";
11088: 	}
11089:     }
11090:     return &lonhttpdurl($iconname);
11091: } 
11092: 
11093: sub lonhttpdurl {
11094: #
11095: # Had been used for "small fry" static images on separate port 8080.
11096: # Modify here if lightweight http functionality desired again.
11097: # Currently eliminated due to increasing firewall issues.
11098: #
11099:     my ($url)=@_;
11100:     return $url;
11101: }
11102: 
11103: sub connection_aborted {
11104:     my ($r)=@_;
11105:     $r->print(" ");$r->rflush();
11106:     my $c = $r->connection;
11107:     return $c->aborted();
11108: }
11109: 
11110: #    Escapes strings that may have embedded 's that will be put into
11111: #    strings as 'strings'.
11112: sub escape_single {
11113:     my ($input) = @_;
11114:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
11115:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
11116:     return $input;
11117: }
11118: 
11119: #  Same as escape_single, but escape's "'s  This 
11120: #  can be used for  "strings"
11121: sub escape_double {
11122:     my ($input) = @_;
11123:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
11124:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
11125:     return $input;
11126: }
11127:  
11128: #   Escapes the last element of a full URL.
11129: sub escape_url {
11130:     my ($url)   = @_;
11131:     my @urlslices = split(/\//, $url,-1);
11132:     my $lastitem = &escape(pop(@urlslices));
11133:     return join('/',@urlslices).'/'.$lastitem;
11134: }
11135: 
11136: sub compare_arrays {
11137:     my ($arrayref1,$arrayref2) = @_;
11138:     my (@difference,%count);
11139:     @difference = ();
11140:     %count = ();
11141:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
11142:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
11143:         foreach my $element (keys(%count)) {
11144:             if ($count{$element} == 1) {
11145:                 push(@difference,$element);
11146:             }
11147:         }
11148:     }
11149:     return @difference;
11150: }
11151: 
11152: # -------------------------------------------------------- Initialize user login
11153: sub init_user_environment {
11154:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
11155:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
11156: 
11157:     my $public=($username eq 'public' && $domain eq 'public');
11158: 
11159: # See if old ID present, if so, remove
11160: 
11161:     my ($filename,$cookie,$userroles);
11162:     my $now=time;
11163: 
11164:     if ($public) {
11165: 	my $max_public=100;
11166: 	my $oldest;
11167: 	my $oldest_time=0;
11168: 	for(my $next=1;$next<=$max_public;$next++) {
11169: 	    if (-e $lonids."/publicuser_$next.id") {
11170: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
11171: 		if ($mtime<$oldest_time || !$oldest_time) {
11172: 		    $oldest_time=$mtime;
11173: 		    $oldest=$next;
11174: 		}
11175: 	    } else {
11176: 		$cookie="publicuser_$next";
11177: 		last;
11178: 	    }
11179: 	}
11180: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
11181:     } else {
11182: 	# if this isn't a robot, kill any existing non-robot sessions
11183: 	if (!$args->{'robot'}) {
11184: 	    opendir(DIR,$lonids);
11185: 	    while ($filename=readdir(DIR)) {
11186: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
11187: 		    unlink($lonids.'/'.$filename);
11188: 		}
11189: 	    }
11190: 	    closedir(DIR);
11191: 	}
11192: # Give them a new cookie
11193: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
11194: 		                   : $now.$$.int(rand(10000)));
11195: 	$cookie="$username\_$id\_$domain\_$authhost";
11196:     
11197: # Initialize roles
11198: 
11199: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
11200:     }
11201: # ------------------------------------ Check browser type and MathML capability
11202: 
11203:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
11204:         $clientunicode,$clientos) = &decode_user_agent($r);
11205: 
11206: # ------------------------------------------------------------- Get environment
11207: 
11208:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
11209:     my ($tmp) = keys(%userenv);
11210:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11211:     } else {
11212: 	undef(%userenv);
11213:     }
11214:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
11215: 	$form->{'interface'}=$userenv{'interface'};
11216:     }
11217:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
11218: 
11219: # --------------- Do not trust query string to be put directly into environment
11220:     foreach my $option ('interface','localpath','localres') {
11221:         $form->{$option}=~s/[\n\r\=]//gs;
11222:     }
11223: # --------------------------------------------------------- Write first profile
11224: 
11225:     {
11226: 	my %initial_env = 
11227: 	    ("user.name"          => $username,
11228: 	     "user.domain"        => $domain,
11229: 	     "user.home"          => $authhost,
11230: 	     "browser.type"       => $clientbrowser,
11231: 	     "browser.version"    => $clientversion,
11232: 	     "browser.mathml"     => $clientmathml,
11233: 	     "browser.unicode"    => $clientunicode,
11234: 	     "browser.os"         => $clientos,
11235: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
11236: 	     "request.course.fn"  => '',
11237: 	     "request.course.uri" => '',
11238: 	     "request.course.sec" => '',
11239: 	     "request.role"       => 'cm',
11240: 	     "request.role.adv"   => $env{'user.adv'},
11241: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
11242: 
11243:         if ($form->{'localpath'}) {
11244: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
11245: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
11246:         }
11247: 	
11248: 	if ($form->{'interface'}) {
11249: 	    $form->{'interface'}=~s/\W//gs;
11250: 	    $initial_env{"browser.interface"} = $form->{'interface'};
11251: 	    $env{'browser.interface'}=$form->{'interface'};
11252: 	}
11253: 
11254:         my %is_adv = ( is_adv => $env{'user.adv'} );
11255:         my %domdef = &Apache::lonnet::get_domain_defaults($domain);
11256: 
11257:         foreach my $tool ('aboutme','blog','portfolio') {
11258:             $userenv{'availabletools.'.$tool} = 
11259:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
11260:                                                   undef,\%userenv,\%domdef,\%is_adv);
11261:         }
11262: 
11263:         foreach my $crstype ('official','unofficial','community') {
11264:             $userenv{'canrequest.'.$crstype} =
11265:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
11266:                                                   'reload','requestcourses',
11267:                                                   \%userenv,\%domdef,\%is_adv);
11268:         }
11269: 
11270: 	$env{'user.environment'} = "$lonids/$cookie.id";
11271: 	
11272: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
11273: 		 &GDBM_WRCREAT(),0640)) {
11274: 	    &_add_to_env(\%disk_env,\%initial_env);
11275: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
11276: 	    &_add_to_env(\%disk_env,$userroles);
11277: 	    if (ref($args->{'extra_env'})) {
11278: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
11279: 	    }
11280: 	    untie(%disk_env);
11281: 	} else {
11282: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
11283: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
11284: 	    return 'error: '.$!;
11285: 	}
11286:     }
11287:     $env{'request.role'}='cm';
11288:     $env{'request.role.adv'}=$env{'user.adv'};
11289:     $env{'browser.type'}=$clientbrowser;
11290: 
11291:     return $cookie;
11292: 
11293: }
11294: 
11295: sub _add_to_env {
11296:     my ($idf,$env_data,$prefix) = @_;
11297:     if (ref($env_data) eq 'HASH') {
11298:         while (my ($key,$value) = each(%$env_data)) {
11299: 	    $idf->{$prefix.$key} = $value;
11300: 	    $env{$prefix.$key}   = $value;
11301:         }
11302:     }
11303: }
11304: 
11305: # --- Get the symbolic name of a problem and the url
11306: sub get_symb {
11307:     my ($request,$silent) = @_;
11308:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
11309:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
11310:     if ($symb eq '') {
11311:         if (!$silent) {
11312:             $request->print("Unable to handle ambiguous references:$url:.");
11313:             return ();
11314:         }
11315:     }
11316:     &Apache::lonenc::check_decrypt(\$symb);
11317:     return ($symb);
11318: }
11319: 
11320: # --------------------------------------------------------------Get annotation
11321: 
11322: sub get_annotation {
11323:     my ($symb,$enc) = @_;
11324: 
11325:     my $key = $symb;
11326:     if (!$enc) {
11327:         $key =
11328:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
11329:     }
11330:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
11331:     return $annotation{$key};
11332: }
11333: 
11334: sub clean_symb {
11335:     my ($symb,$delete_enc) = @_;
11336: 
11337:     &Apache::lonenc::check_decrypt(\$symb);
11338:     my $enc = $env{'request.enc'};
11339:     if ($delete_enc) {
11340:         delete($env{'request.enc'});
11341:     }
11342: 
11343:     return ($symb,$enc);
11344: }
11345: 
11346: sub build_release_hashes {
11347:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
11348:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
11349:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
11350:                   (ref($randomizetry) eq 'HASH'));
11351:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
11352:         my ($item,$name,$value) = split(/:/,$key);
11353:         if ($item eq 'parameter') {
11354:             if (ref($checkparms->{$name}) eq 'ARRAY') {
11355:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
11356:                     push(@{$checkparms->{$name}},$value);
11357:                 }
11358:             } else {
11359:                 push(@{$checkparms->{$name}},$value);
11360:             }
11361:         } elsif ($item eq 'resourcetag') {
11362:             if ($name eq 'responsetype') {
11363:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
11364:             }
11365:         } elsif ($item eq 'course') {
11366:             if ($name eq 'crstype') {
11367:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
11368:             }
11369:         }
11370:     }
11371:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
11372:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
11373:     return;
11374: }
11375: 
11376: =pod
11377: 
11378: =back
11379: 
11380: =cut
11381: 
11382: 1;
11383: __END__;
11384: 

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