File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.982: download - view: text, annotated - select for diffs
Sun Sep 26 01:57:21 2010 UTC (13 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- skip check for loncapa version (via "extra" hashref passed to lonnet::dump)
  when getting dump of roles for purposes other than rolesinit.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.982 2010/09/26 01:57:21 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410: // <![CDATA[
  411:     var stdeditbrowser;
  412:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
  413:         var url = '/adm/pickstudent?';
  414:         var filter;
  415: 	if (!ignorefilter) {
  416: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  417: 	}
  418:         if (filter != null) {
  419:            if (filter != '') {
  420:                url += 'filter='+filter+'&';
  421: 	   }
  422:         }
  423:         url += 'form=' + formname + '&unameelement='+uname+
  424:                                     '&udomelement='+udom;
  425: 	if (roleflag) { url+="&roles=1"; }
  426:         if (courseadvonly) { url+="&courseadvonly=1"; }
  427:         var title = 'Student_Browser';
  428:         var options = 'scrollbars=1,resizable=1,menubar=0';
  429:         options += ',width=700,height=600';
  430:         stdeditbrowser = open(url,title,options,'1');
  431:         stdeditbrowser.focus();
  432:     }
  433: // ]]>
  434: </script>
  435: ENDSTDBRW
  436: }
  437: 
  438: sub selectstudent_link {
  439:    my ($form,$unameele,$udomele,$courseadvonly)=@_;
  440:    my $callargs = "'".$form."','".$unameele."','".$udomele."'";
  441:    if ($env{'request.course.id'}) {  
  442:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  443: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  444: 					'/'.$env{'request.course.sec'})) {
  445: 	   return '';
  446:        }
  447:        if ($courseadvonly)  {
  448:            $callargs .= ",'',1,1";
  449:        }
  450:        return '<span class="LC_nobreak">'.
  451:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  452:               &mt('Select User').'</a></span>';
  453:    }
  454:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  455:        $callargs .= ",1"; 
  456:        return '<span class="LC_nobreak">'.
  457:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  458:               &mt('Select User').'</a></span>';
  459:    }
  460:    return '';
  461: }
  462: 
  463: sub authorbrowser_javascript {
  464:     return <<"ENDAUTHORBRW";
  465: <script type="text/javascript" language="JavaScript">
  466: // <![CDATA[
  467: var stdeditbrowser;
  468: 
  469: function openauthorbrowser(formname,udom) {
  470:     var url = '/adm/pickauthor?';
  471:     url += 'form='+formname+'&roledom='+udom;
  472:     var title = 'Author_Browser';
  473:     var options = 'scrollbars=1,resizable=1,menubar=0';
  474:     options += ',width=700,height=600';
  475:     stdeditbrowser = open(url,title,options,'1');
  476:     stdeditbrowser.focus();
  477: }
  478: 
  479: // ]]>
  480: </script>
  481: ENDAUTHORBRW
  482: }
  483: 
  484: sub coursebrowser_javascript {
  485:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  486:     my $wintitle = 'Course_Browser';
  487:     if ($crstype eq 'Community') {
  488:         $wintitle = 'Community_Browser';
  489:     }
  490:     my $id_functions = &javascript_index_functions();
  491:     my $output = '
  492: <script type="text/javascript" language="JavaScript">
  493: // <![CDATA[
  494:     var stdeditbrowser;'."\n";
  495: 
  496:     $output .= <<"ENDSTDBRW";
  497:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  498:         var url = '/adm/pickcourse?';
  499:         var formid = getFormIdByName(formname);
  500:         var domainfilter = getDomainFromSelectbox(formname,udom);
  501:         if (domainfilter != null) {
  502:            if (domainfilter != '') {
  503:                url += 'domainfilter='+domainfilter+'&';
  504: 	   }
  505:         }
  506:         url += 'form=' + formname + '&cnumelement='+uname+
  507: 	                            '&cdomelement='+udom+
  508:                                     '&cnameelement='+desc;
  509:         if (extra_element !=null && extra_element != '') {
  510:             if (formname == 'rolechoice' || formname == 'studentform') {
  511:                 url += '&roleelement='+extra_element;
  512:                 if (domainfilter == null || domainfilter == '') {
  513:                     url += '&domainfilter='+extra_element;
  514:                 }
  515:             }
  516:             else {
  517:                 if (formname == 'portform') {
  518:                     url += '&setroles='+extra_element;
  519:                 } else {
  520:                     if (formname == 'rules') {
  521:                         url += '&fixeddom='+extra_element; 
  522:                     }
  523:                 }
  524:             }     
  525:         }
  526:         if (type != null && type != '') {
  527:             url += '&type='+type;
  528:         }
  529:         if (type_elem != null && type_elem != '') {
  530:             url += '&typeelement='+type_elem;
  531:         }
  532:         if (formname == 'ccrs') {
  533:             var ownername = document.forms[formid].ccuname.value;
  534:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  535:             url += '&cloner='+ownername+':'+ownerdom;
  536:         }
  537:         if (multflag !=null && multflag != '') {
  538:             url += '&multiple='+multflag;
  539:         }
  540:         var title = '$wintitle';
  541:         var options = 'scrollbars=1,resizable=1,menubar=0';
  542:         options += ',width=700,height=600';
  543:         stdeditbrowser = open(url,title,options,'1');
  544:         stdeditbrowser.focus();
  545:     }
  546: $id_functions
  547: ENDSTDBRW
  548:     if (($sec_element ne '') || ($role_element ne '')) {
  549:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  550:     }
  551:     $output .= '
  552: // ]]>
  553: </script>';
  554:     return $output;
  555: }
  556: 
  557: sub javascript_index_functions {
  558:     return <<"ENDJS";
  559: 
  560: function getFormIdByName(formname) {
  561:     for (var i=0;i<document.forms.length;i++) {
  562:         if (document.forms[i].name == formname) {
  563:             return i;
  564:         }
  565:     }
  566:     return -1;
  567: }
  568: 
  569: function getIndexByName(formid,item) {
  570:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  571:         if (document.forms[formid].elements[i].name == item) {
  572:             return i;
  573:         }
  574:     }
  575:     return -1;
  576: }
  577: 
  578: function getDomainFromSelectbox(formname,udom) {
  579:     var userdom;
  580:     var formid = getFormIdByName(formname);
  581:     if (formid > -1) {
  582:         var domid = getIndexByName(formid,udom);
  583:         if (domid > -1) {
  584:             if (document.forms[formid].elements[domid].type == 'select-one') {
  585:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  586:             }
  587:             if (document.forms[formid].elements[domid].type == 'hidden') {
  588:                 userdom=document.forms[formid].elements[domid].value;
  589:             }
  590:         }
  591:     }
  592:     return userdom;
  593: }
  594: 
  595: ENDJS
  596: 
  597: }
  598: 
  599: sub userbrowser_javascript {
  600:     my $id_functions = &javascript_index_functions();
  601:     return <<"ENDUSERBRW";
  602: 
  603: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  604:     var url = '/adm/pickuser?';
  605:     var userdom = getDomainFromSelectbox(formname,udom);
  606:     if (userdom != null) {
  607:        if (userdom != '') {
  608:            url += 'srchdom='+userdom+'&';
  609:        }
  610:     }
  611:     url += 'form=' + formname + '&unameelement='+uname+
  612:                                 '&udomelement='+udom+
  613:                                 '&ulastelement='+ulast+
  614:                                 '&ufirstelement='+ufirst+
  615:                                 '&uemailelement='+uemail+
  616:                                 '&hideudomelement='+hideudom+
  617:                                 '&coursedom='+crsdom;
  618:     if ((caller != null) && (caller != undefined)) {
  619:         url += '&caller='+caller;
  620:     }
  621:     var title = 'User_Browser';
  622:     var options = 'scrollbars=1,resizable=1,menubar=0';
  623:     options += ',width=700,height=600';
  624:     var stdeditbrowser = open(url,title,options,'1');
  625:     stdeditbrowser.focus();
  626: }
  627: 
  628: function fix_domain (formname,udom,origdom,uname) {
  629:     var formid = getFormIdByName(formname);
  630:     if (formid > -1) {
  631:         var unameid = getIndexByName(formid,uname);
  632:         var domid = getIndexByName(formid,udom);
  633:         var hidedomid = getIndexByName(formid,origdom);
  634:         if (hidedomid > -1) {
  635:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  636:             var unameval = document.forms[formid].elements[unameid].value;
  637:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  638:                 if (domid > -1) {
  639:                     var slct = document.forms[formid].elements[domid];
  640:                     if (slct.type == 'select-one') {
  641:                         var i;
  642:                         for (i=0;i<slct.length;i++) {
  643:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  644:                         }
  645:                     }
  646:                     if (slct.type == 'hidden') {
  647:                         slct.value = fixeddom;
  648:                     }
  649:                 }
  650:             }
  651:         }
  652:     }
  653:     return;
  654: }
  655: 
  656: $id_functions
  657: ENDUSERBRW
  658: }
  659: 
  660: sub setsec_javascript {
  661:     my ($sec_element,$formname,$role_element) = @_;
  662:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  663:         $communityrolestr);
  664:     if ($role_element ne '') {
  665:         my @allroles = ('st','ta','ep','in','ad');
  666:         foreach my $crstype ('Course','Community') {
  667:             if ($crstype eq 'Community') {
  668:                 foreach my $role (@allroles) {
  669:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  670:                 }
  671:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  672:             } else {
  673:                 foreach my $role (@allroles) {
  674:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  675:                 }
  676:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  677:             }
  678:         }
  679:         $rolestr = '"'.join('","',@allroles).'"';
  680:         $courserolestr = '"'.join('","',@courserolenames).'"';
  681:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  682:     }
  683:     my $setsections = qq|
  684: function setSect(sectionlist) {
  685:     var sectionsArray = new Array();
  686:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  687:         sectionsArray = sectionlist.split(",");
  688:     }
  689:     var numSections = sectionsArray.length;
  690:     document.$formname.$sec_element.length = 0;
  691:     if (numSections == 0) {
  692:         document.$formname.$sec_element.multiple=false;
  693:         document.$formname.$sec_element.size=1;
  694:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  695:     } else {
  696:         if (numSections == 1) {
  697:             document.$formname.$sec_element.multiple=false;
  698:             document.$formname.$sec_element.size=1;
  699:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  700:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  701:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  702:         } else {
  703:             for (var i=0; i<numSections; i++) {
  704:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  705:             }
  706:             document.$formname.$sec_element.multiple=true
  707:             if (numSections < 3) {
  708:                 document.$formname.$sec_element.size=numSections;
  709:             } else {
  710:                 document.$formname.$sec_element.size=3;
  711:             }
  712:             document.$formname.$sec_element.options[0].selected = false
  713:         }
  714:     }
  715: }
  716: 
  717: function setRole(crstype) {
  718: |;
  719:     if ($role_element eq '') {
  720:         $setsections .= '    return;
  721: }
  722: ';
  723:     } else {
  724:         $setsections .= qq|
  725:     var elementLength = document.$formname.$role_element.length;
  726:     var allroles = Array($rolestr);
  727:     var courserolenames = Array($courserolestr);
  728:     var communityrolenames = Array($communityrolestr);
  729:     if (elementLength != undefined) {
  730:         if (document.$formname.$role_element.options[5].value == 'cc') {
  731:             if (crstype == 'Course') {
  732:                 return;
  733:             } else {
  734:                 allroles[5] = 'co';
  735:                 for (var i=0; i<6; i++) {
  736:                     document.$formname.$role_element.options[i].value = allroles[i];
  737:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  738:                 }
  739:             }
  740:         } else {
  741:             if (crstype == 'Community') {
  742:                 return;
  743:             } else {
  744:                 allroles[5] = 'cc';
  745:                 for (var i=0; i<6; i++) {
  746:                     document.$formname.$role_element.options[i].value = allroles[i];
  747:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  748:                 }
  749:             }
  750:         }
  751:     }
  752:     return;
  753: }
  754: |;
  755:     }
  756:     return $setsections;
  757: }
  758: 
  759: sub selectcourse_link {
  760:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  761:        $typeelement) = @_;
  762:    my $type = $selecttype;
  763:    my $linktext = &mt('Select Course');
  764:    if ($selecttype eq 'Community') {
  765:        $linktext = &mt('Select Community');
  766:    } elsif ($selecttype eq 'Course/Community') {
  767:        $linktext = &mt('Select Course/Community');
  768:        $type = '';
  769:    }
  770:    return '<span class="LC_nobreak">'
  771:          ."<a href='"
  772:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  773:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  774:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  775:          ."'>".$linktext.'</a>'
  776:          .'</span>';
  777: }
  778: 
  779: sub selectauthor_link {
  780:    my ($form,$udom)=@_;
  781:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  782:           &mt('Select Author').'</a>';
  783: }
  784: 
  785: sub selectuser_link {
  786:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  787:         $coursedom,$linktext,$caller) = @_;
  788:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  789:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  790:            ');">'.$linktext.'</a>';
  791: }
  792: 
  793: sub check_uncheck_jscript {
  794:     my $jscript = <<"ENDSCRT";
  795: function checkAll(field) {
  796:     if (field.length > 0) {
  797:         for (i = 0; i < field.length; i++) {
  798:             field[i].checked = true ;
  799:         }
  800:     } else {
  801:         field.checked = true
  802:     }
  803: }
  804:  
  805: function uncheckAll(field) {
  806:     if (field.length > 0) {
  807:         for (i = 0; i < field.length; i++) {
  808:             field[i].checked = false ;
  809:         }
  810:     } else {
  811:         field.checked = false ;
  812:     }
  813: }
  814: ENDSCRT
  815:     return $jscript;
  816: }
  817: 
  818: sub select_timezone {
  819:    my ($name,$selected,$onchange,$includeempty)=@_;
  820:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  821:    if ($includeempty) {
  822:        $output .= '<option value=""';
  823:        if (($selected eq '') || ($selected eq 'local')) {
  824:            $output .= ' selected="selected" ';
  825:        }
  826:        $output .= '> </option>';
  827:    }
  828:    my @timezones = DateTime::TimeZone->all_names;
  829:    foreach my $tzone (@timezones) {
  830:        $output.= '<option value="'.$tzone.'"';
  831:        if ($tzone eq $selected) {
  832:            $output.=' selected="selected"';
  833:        }
  834:        $output.=">$tzone</option>\n";
  835:    }
  836:    $output.="</select>";
  837:    return $output;
  838: }
  839: 
  840: sub select_datelocale {
  841:     my ($name,$selected,$onchange,$includeempty)=@_;
  842:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  843:     if ($includeempty) {
  844:         $output .= '<option value=""';
  845:         if ($selected eq '') {
  846:             $output .= ' selected="selected" ';
  847:         }
  848:         $output .= '> </option>';
  849:     }
  850:     my (@possibles,%locale_names);
  851:     my @locales = DateTime::Locale::Catalog::Locales;
  852:     foreach my $locale (@locales) {
  853:         if (ref($locale) eq 'HASH') {
  854:             my $id = $locale->{'id'};
  855:             if ($id ne '') {
  856:                 my $en_terr = $locale->{'en_territory'};
  857:                 my $native_terr = $locale->{'native_territory'};
  858:                 my @languages = &Apache::lonlocal::preferred_languages();
  859:                 if (grep(/^en$/,@languages) || !@languages) {
  860:                     if ($en_terr ne '') {
  861:                         $locale_names{$id} = '('.$en_terr.')';
  862:                     } elsif ($native_terr ne '') {
  863:                         $locale_names{$id} = $native_terr;
  864:                     }
  865:                 } else {
  866:                     if ($native_terr ne '') {
  867:                         $locale_names{$id} = $native_terr.' ';
  868:                     } elsif ($en_terr ne '') {
  869:                         $locale_names{$id} = '('.$en_terr.')';
  870:                     }
  871:                 }
  872:                 push (@possibles,$id);
  873:             }
  874:         }
  875:     }
  876:     foreach my $item (sort(@possibles)) {
  877:         $output.= '<option value="'.$item.'"';
  878:         if ($item eq $selected) {
  879:             $output.=' selected="selected"';
  880:         }
  881:         $output.=">$item";
  882:         if ($locale_names{$item} ne '') {
  883:             $output.="  $locale_names{$item}</option>\n";
  884:         }
  885:         $output.="</option>\n";
  886:     }
  887:     $output.="</select>";
  888:     return $output;
  889: }
  890: 
  891: sub select_language {
  892:     my ($name,$selected,$includeempty) = @_;
  893:     my %langchoices;
  894:     if ($includeempty) {
  895:         %langchoices = ('' => 'No language preference');
  896:     }
  897:     foreach my $id (&languageids()) {
  898:         my $code = &supportedlanguagecode($id);
  899:         if ($code) {
  900:             $langchoices{$code} = &plainlanguagedescription($id);
  901:         }
  902:     }
  903:     return &select_form($selected,$name,\%langchoices);
  904: }
  905: 
  906: =pod
  907: 
  908: =item * &linked_select_forms(...)
  909: 
  910: linked_select_forms returns a string containing a <script></script> block
  911: and html for two <select> menus.  The select menus will be linked in that
  912: changing the value of the first menu will result in new values being placed
  913: in the second menu.  The values in the select menu will appear in alphabetical
  914: order unless a defined order is provided.
  915: 
  916: linked_select_forms takes the following ordered inputs:
  917: 
  918: =over 4
  919: 
  920: =item * $formname, the name of the <form> tag
  921: 
  922: =item * $middletext, the text which appears between the <select> tags
  923: 
  924: =item * $firstdefault, the default value for the first menu
  925: 
  926: =item * $firstselectname, the name of the first <select> tag
  927: 
  928: =item * $secondselectname, the name of the second <select> tag
  929: 
  930: =item * $hashref, a reference to a hash containing the data for the menus.
  931: 
  932: =item * $menuorder, the order of values in the first menu
  933: 
  934: =back 
  935: 
  936: Below is an example of such a hash.  Only the 'text', 'default', and 
  937: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  938: values for the first select menu.  The text that coincides with the 
  939: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  940: and text for the second menu are given in the hash pointed to by 
  941: $menu{$choice1}->{'select2'}.  
  942: 
  943:  my %menu = ( A1 => { text =>"Choice A1" ,
  944:                        default => "B3",
  945:                        select2 => { 
  946:                            B1 => "Choice B1",
  947:                            B2 => "Choice B2",
  948:                            B3 => "Choice B3",
  949:                            B4 => "Choice B4"
  950:                            },
  951:                        order => ['B4','B3','B1','B2'],
  952:                    },
  953:                A2 => { text =>"Choice A2" ,
  954:                        default => "C2",
  955:                        select2 => { 
  956:                            C1 => "Choice C1",
  957:                            C2 => "Choice C2",
  958:                            C3 => "Choice C3"
  959:                            },
  960:                        order => ['C2','C1','C3'],
  961:                    },
  962:                A3 => { text =>"Choice A3" ,
  963:                        default => "D6",
  964:                        select2 => { 
  965:                            D1 => "Choice D1",
  966:                            D2 => "Choice D2",
  967:                            D3 => "Choice D3",
  968:                            D4 => "Choice D4",
  969:                            D5 => "Choice D5",
  970:                            D6 => "Choice D6",
  971:                            D7 => "Choice D7"
  972:                            },
  973:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  974:                    }
  975:                );
  976: 
  977: =cut
  978: 
  979: sub linked_select_forms {
  980:     my ($formname,
  981:         $middletext,
  982:         $firstdefault,
  983:         $firstselectname,
  984:         $secondselectname, 
  985:         $hashref,
  986:         $menuorder,
  987:         ) = @_;
  988:     my $second = "document.$formname.$secondselectname";
  989:     my $first = "document.$formname.$firstselectname";
  990:     # output the javascript to do the changing
  991:     my $result = '';
  992:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  993:     $result.="// <![CDATA[\n";
  994:     $result.="var select2data = new Object();\n";
  995:     $" = '","';
  996:     my $debug = '';
  997:     foreach my $s1 (sort(keys(%$hashref))) {
  998:         $result.="select2data.d_$s1 = new Object();\n";        
  999:         $result.="select2data.d_$s1.def = new String('".
 1000:             $hashref->{$s1}->{'default'}."');\n";
 1001:         $result.="select2data.d_$s1.values = new Array(";
 1002:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1003:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1004:             @s2values = @{$hashref->{$s1}->{'order'}};
 1005:         }
 1006:         $result.="\"@s2values\");\n";
 1007:         $result.="select2data.d_$s1.texts = new Array(";        
 1008:         my @s2texts;
 1009:         foreach my $value (@s2values) {
 1010:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1011:         }
 1012:         $result.="\"@s2texts\");\n";
 1013:     }
 1014:     $"=' ';
 1015:     $result.= <<"END";
 1016: 
 1017: function select1_changed() {
 1018:     // Determine new choice
 1019:     var newvalue = "d_" + $first.value;
 1020:     // update select2
 1021:     var values     = select2data[newvalue].values;
 1022:     var texts      = select2data[newvalue].texts;
 1023:     var select2def = select2data[newvalue].def;
 1024:     var i;
 1025:     // out with the old
 1026:     for (i = 0; i < $second.options.length; i++) {
 1027:         $second.options[i] = null;
 1028:     }
 1029:     // in with the nuclear
 1030:     for (i=0;i<values.length; i++) {
 1031:         $second.options[i] = new Option(values[i]);
 1032:         $second.options[i].value = values[i];
 1033:         $second.options[i].text = texts[i];
 1034:         if (values[i] == select2def) {
 1035:             $second.options[i].selected = true;
 1036:         }
 1037:     }
 1038: }
 1039: // ]]>
 1040: </script>
 1041: END
 1042:     # output the initial values for the selection lists
 1043:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1044:     my @order = sort(keys(%{$hashref}));
 1045:     if (ref($menuorder) eq 'ARRAY') {
 1046:         @order = @{$menuorder};
 1047:     }
 1048:     foreach my $value (@order) {
 1049:         $result.="    <option value=\"$value\" ";
 1050:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1051:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1052:     }
 1053:     $result .= "</select>\n";
 1054:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1055:     $result .= $middletext;
 1056:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1057:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1058:     
 1059:     my @secondorder = sort(keys(%select2));
 1060:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1061:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1062:     }
 1063:     foreach my $value (@secondorder) {
 1064:         $result.="    <option value=\"$value\" ";        
 1065:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1066:         $result.=">".&mt($select2{$value})."</option>\n";
 1067:     }
 1068:     $result .= "</select>\n";
 1069:     #    return $debug;
 1070:     return $result;
 1071: }   #  end of sub linked_select_forms {
 1072: 
 1073: =pod
 1074: 
 1075: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1076: 
 1077: Returns a string corresponding to an HTML link to the given help
 1078: $topic, where $topic corresponds to the name of a .tex file in
 1079: /home/httpd/html/adm/help/tex, with underscores replaced by
 1080: spaces. 
 1081: 
 1082: $text will optionally be linked to the same topic, allowing you to
 1083: link text in addition to the graphic. If you do not want to link
 1084: text, but wish to specify one of the later parameters, pass an
 1085: empty string. 
 1086: 
 1087: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1088: the link will not open a new window. If false, the link will open
 1089: a new window using Javascript. (Default is false.) 
 1090: 
 1091: $width and $height are optional numerical parameters that will
 1092: override the width and height of the popped up window, which may
 1093: be useful for certain help topics with big pictures included.
 1094: 
 1095: $imgid is the id of the img tag used for the help icon. This may be
 1096: used in a javascript call to switch the image src.  See 
 1097: lonhtmlcommon::htmlareaselectactive() for an example.
 1098: 
 1099: =cut
 1100: 
 1101: sub help_open_topic {
 1102:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1103:     $text = "" if (not defined $text);
 1104:     $stayOnPage = 0 if (not defined $stayOnPage);
 1105:     $width = 350 if (not defined $width);
 1106:     $height = 400 if (not defined $height);
 1107:     my $filename = $topic;
 1108:     $filename =~ s/ /_/g;
 1109: 
 1110:     my $template = "";
 1111:     my $link;
 1112:     
 1113:     $topic=~s/\W/\_/g;
 1114: 
 1115:     if (!$stayOnPage) {
 1116: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1117:     } else {
 1118: 	$link = "/adm/help/${filename}.hlp";
 1119:     }
 1120: 
 1121:     # Add the text
 1122:     if ($text ne "") {	
 1123: 	$template.='<span class="LC_help_open_topic">'
 1124:                   .'<a target="_top" href="'.$link.'">'
 1125:                   .$text.'</a>';
 1126:     }
 1127: 
 1128:     # (Always) Add the graphic
 1129:     my $title = &mt('Online Help');
 1130:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1131:     if ($imgid ne '') {
 1132:         $imgid = ' id="'.$imgid.'"';
 1133:     }
 1134:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1135:               .'<img src="'.$helpicon.'" border="0"'
 1136:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1137:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1138:               .' /></a>';
 1139:     if ($text ne "") {	
 1140:         $template.='</span>';
 1141:     }
 1142:     return $template;
 1143: 
 1144: }
 1145: 
 1146: # This is a quicky function for Latex cheatsheet editing, since it 
 1147: # appears in at least four places
 1148: sub helpLatexCheatsheet {
 1149:     my ($topic,$text,$not_author) = @_;
 1150:     my $out;
 1151:     my $addOther = '';
 1152:     if ($topic) {
 1153: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1154: 							       undef, undef, 600).
 1155: 								   '</span> ';
 1156:     }
 1157:     $out = '<span>' # Start cheatsheet
 1158: 	  .$addOther
 1159:           .'<span>'
 1160: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1161: 					       undef,undef,600)
 1162: 	  .'</span> <span>'
 1163: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1164: 					       undef,undef,600)
 1165: 	  .'</span>';
 1166:     unless ($not_author) {
 1167:         $out .= ' <span>'
 1168: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1169: 	                                            undef,undef,600)
 1170: 	       .'</span>';
 1171:     }
 1172:     $out .= '</span>'; # End cheatsheet
 1173:     return $out;
 1174: }
 1175: 
 1176: sub general_help {
 1177:     my $helptopic='Student_Intro';
 1178:     if ($env{'request.role'}=~/^(ca|au)/) {
 1179: 	$helptopic='Authoring_Intro';
 1180:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1181: 	$helptopic='Course_Coordination_Intro';
 1182:     } elsif ($env{'request.role'}=~/^dc/) {
 1183:         $helptopic='Domain_Coordination_Intro';
 1184:     }
 1185:     return $helptopic;
 1186: }
 1187: 
 1188: sub update_help_link {
 1189:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1190:     my $origurl = $ENV{'REQUEST_URI'};
 1191:     $origurl=~s|^/~|/priv/|;
 1192:     my $timestamp = time;
 1193:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1194:         $$datum = &escape($$datum);
 1195:     }
 1196: 
 1197:     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";
 1198:     my $output .= <<"ENDOUTPUT";
 1199: <script type="text/javascript">
 1200: // <![CDATA[
 1201: banner_link = '$banner_link';
 1202: // ]]>
 1203: </script>
 1204: ENDOUTPUT
 1205:     return $output;
 1206: }
 1207: 
 1208: # now just updates the help link and generates a blue icon
 1209: sub help_open_menu {
 1210:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1211: 	= @_;    
 1212:     $stayOnPage = 1;
 1213:     my $output;
 1214:     if ($component_help) {
 1215: 	if (!$text) {
 1216: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1217: 				       $width,$height);
 1218: 	} else {
 1219: 	    my $help_text;
 1220: 	    $help_text=&unescape($topic);
 1221: 	    $output='<table><tr><td>'.
 1222: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1223: 				 $width,$height).'</td></tr></table>';
 1224: 	}
 1225:     }
 1226:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1227:     return $output.$banner_link;
 1228: }
 1229: 
 1230: sub top_nav_help {
 1231:     my ($text) = @_;
 1232:     $text = &mt($text);
 1233:     my $stay_on_page = 1;
 1234: 
 1235:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1236: 	                     : "javascript:helpMenu('open')";
 1237:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1238: 
 1239:     my $title = &mt('Get help');
 1240: 
 1241:     return <<"END";
 1242: $banner_link
 1243:  <a href="$link" title="$title">$text</a>
 1244: END
 1245: }
 1246: 
 1247: sub help_menu_js {
 1248:     my ($text) = @_;
 1249:     my $stayOnPage = 1;
 1250:     my $width = 620;
 1251:     my $height = 600;
 1252:     my $helptopic=&general_help();
 1253:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1254:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1255:     my $start_page =
 1256:         &Apache::loncommon::start_page('Help Menu', undef,
 1257: 				       {'frameset'    => 1,
 1258: 					'js_ready'    => 1,
 1259: 					'add_entries' => {
 1260: 					    'border' => '0',
 1261: 					    'rows'   => "110,*",},});
 1262:     my $end_page =
 1263:         &Apache::loncommon::end_page({'frameset' => 1,
 1264: 				      'js_ready' => 1,});
 1265: 
 1266:     my $template .= <<"ENDTEMPLATE";
 1267: <script type="text/javascript">
 1268: // <![CDATA[
 1269: // <!-- BEGIN LON-CAPA Internal
 1270: var banner_link = '';
 1271: function helpMenu(target) {
 1272:     var caller = this;
 1273:     if (target == 'open') {
 1274:         var newWindow = null;
 1275:         try {
 1276:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1277:         }
 1278:         catch(error) {
 1279:             writeHelp(caller);
 1280:             return;
 1281:         }
 1282:         if (newWindow) {
 1283:             caller = newWindow;
 1284:         }
 1285:     }
 1286:     writeHelp(caller);
 1287:     return;
 1288: }
 1289: function writeHelp(caller) {
 1290:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1291:     caller.document.close()
 1292:     caller.focus()
 1293: }
 1294: // END LON-CAPA Internal -->
 1295: // ]]>
 1296: </script>
 1297: ENDTEMPLATE
 1298:     return $template;
 1299: }
 1300: 
 1301: sub help_open_bug {
 1302:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1303:     unless ($env{'user.adv'}) { return ''; }
 1304:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1305:     $text = "" if (not defined $text);
 1306: 	$stayOnPage=1;
 1307:     $width = 600 if (not defined $width);
 1308:     $height = 600 if (not defined $height);
 1309: 
 1310:     $topic=~s/\W+/\+/g;
 1311:     my $link='';
 1312:     my $template='';
 1313:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1314: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1315:     if (!$stayOnPage)
 1316:     {
 1317: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1318:     }
 1319:     else
 1320:     {
 1321: 	$link = $url;
 1322:     }
 1323:     # Add the text
 1324:     if ($text ne "")
 1325:     {
 1326: 	$template .= 
 1327:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1328:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1329:     }
 1330: 
 1331:     # Add the graphic
 1332:     my $title = &mt('Report a Bug');
 1333:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1334:     $template .= <<"ENDTEMPLATE";
 1335:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1336: ENDTEMPLATE
 1337:     if ($text ne '') { $template.='</td></tr></table>' };
 1338:     return $template;
 1339: 
 1340: }
 1341: 
 1342: sub help_open_faq {
 1343:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1344:     unless ($env{'user.adv'}) { return ''; }
 1345:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1346:     $text = "" if (not defined $text);
 1347: 	$stayOnPage=1;
 1348:     $width = 350 if (not defined $width);
 1349:     $height = 400 if (not defined $height);
 1350: 
 1351:     $topic=~s/\W+/\+/g;
 1352:     my $link='';
 1353:     my $template='';
 1354:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1355:     if (!$stayOnPage)
 1356:     {
 1357: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1358:     }
 1359:     else
 1360:     {
 1361: 	$link = $url;
 1362:     }
 1363: 
 1364:     # Add the text
 1365:     if ($text ne "")
 1366:     {
 1367: 	$template .= 
 1368:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1369:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1370:     }
 1371: 
 1372:     # Add the graphic
 1373:     my $title = &mt('View the FAQ');
 1374:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1375:     $template .= <<"ENDTEMPLATE";
 1376:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1377: ENDTEMPLATE
 1378:     if ($text ne '') { $template.='</td></tr></table>' };
 1379:     return $template;
 1380: 
 1381: }
 1382: 
 1383: ###############################################################
 1384: ###############################################################
 1385: 
 1386: =pod
 1387: 
 1388: =item * &change_content_javascript():
 1389: 
 1390: This and the next function allow you to create small sections of an
 1391: otherwise static HTML page that you can update on the fly with
 1392: Javascript, even in Netscape 4.
 1393: 
 1394: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1395: must be written to the HTML page once. It will prove the Javascript
 1396: function "change(name, content)". Calling the change function with the
 1397: name of the section 
 1398: you want to update, matching the name passed to C<changable_area>, and
 1399: the new content you want to put in there, will put the content into
 1400: that area.
 1401: 
 1402: B<Note>: Netscape 4 only reserves enough space for the changable area
 1403: to contain room for the original contents. You need to "make space"
 1404: for whatever changes you wish to make, and be B<sure> to check your
 1405: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1406: it's adequate for updating a one-line status display, but little more.
 1407: This script will set the space to 100% width, so you only need to
 1408: worry about height in Netscape 4.
 1409: 
 1410: Modern browsers are much less limiting, and if you can commit to the
 1411: user not using Netscape 4, this feature may be used freely with
 1412: pretty much any HTML.
 1413: 
 1414: =cut
 1415: 
 1416: sub change_content_javascript {
 1417:     # If we're on Netscape 4, we need to use Layer-based code
 1418:     if ($env{'browser.type'} eq 'netscape' &&
 1419: 	$env{'browser.version'} =~ /^4\./) {
 1420: 	return (<<NETSCAPE4);
 1421: 	function change(name, content) {
 1422: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1423: 	    doc.open();
 1424: 	    doc.write(content);
 1425: 	    doc.close();
 1426: 	}
 1427: NETSCAPE4
 1428:     } else {
 1429: 	# Otherwise, we need to use semi-standards-compliant code
 1430: 	# (technically, "innerHTML" isn't standard but the equivalent
 1431: 	# is really scary, and every useful browser supports it
 1432: 	return (<<DOMBASED);
 1433: 	function change(name, content) {
 1434: 	    element = document.getElementById(name);
 1435: 	    element.innerHTML = content;
 1436: 	}
 1437: DOMBASED
 1438:     }
 1439: }
 1440: 
 1441: =pod
 1442: 
 1443: =item * &changable_area($name,$origContent):
 1444: 
 1445: This provides a "changable area" that can be modified on the fly via
 1446: the Javascript code provided in C<change_content_javascript>. $name is
 1447: the name you will use to reference the area later; do not repeat the
 1448: same name on a given HTML page more then once. $origContent is what
 1449: the area will originally contain, which can be left blank.
 1450: 
 1451: =cut
 1452: 
 1453: sub changable_area {
 1454:     my ($name, $origContent) = @_;
 1455: 
 1456:     if ($env{'browser.type'} eq 'netscape' &&
 1457: 	$env{'browser.version'} =~ /^4\./) {
 1458: 	# If this is netscape 4, we need to use the Layer tag
 1459: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1460:     } else {
 1461: 	return "<span id='$name'>$origContent</span>";
 1462:     }
 1463: }
 1464: 
 1465: =pod
 1466: 
 1467: =item * &viewport_geometry_js 
 1468: 
 1469: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1470: 
 1471: =cut
 1472: 
 1473: 
 1474: sub viewport_geometry_js { 
 1475:     return <<"GEOMETRY";
 1476: var Geometry = {};
 1477: function init_geometry() {
 1478:     if (Geometry.init) { return };
 1479:     Geometry.init=1;
 1480:     if (window.innerHeight) {
 1481:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1482:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1483:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1484:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1485:     }
 1486:     else if (document.documentElement && document.documentElement.clientHeight) {
 1487:         Geometry.getViewportHeight =
 1488:             function() { return document.documentElement.clientHeight; };
 1489:         Geometry.getViewportWidth =
 1490:             function() { return document.documentElement.clientWidth; };
 1491: 
 1492:         Geometry.getHorizontalScroll =
 1493:             function() { return document.documentElement.scrollLeft; };
 1494:         Geometry.getVerticalScroll =
 1495:             function() { return document.documentElement.scrollTop; };
 1496:     }
 1497:     else if (document.body.clientHeight) {
 1498:         Geometry.getViewportHeight =
 1499:             function() { return document.body.clientHeight; };
 1500:         Geometry.getViewportWidth =
 1501:             function() { return document.body.clientWidth; };
 1502:         Geometry.getHorizontalScroll =
 1503:             function() { return document.body.scrollLeft; };
 1504:         Geometry.getVerticalScroll =
 1505:             function() { return document.body.scrollTop; };
 1506:     }
 1507: }
 1508: 
 1509: GEOMETRY
 1510: }
 1511: 
 1512: =pod
 1513: 
 1514: =item * &viewport_size_js()
 1515: 
 1516: 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. 
 1517: 
 1518: =cut
 1519: 
 1520: sub viewport_size_js {
 1521:     my $geometry = &viewport_geometry_js();
 1522:     return <<"DIMS";
 1523: 
 1524: $geometry
 1525: 
 1526: function getViewportDims(width,height) {
 1527:     init_geometry();
 1528:     width.value = Geometry.getViewportWidth();
 1529:     height.value = Geometry.getViewportHeight();
 1530:     return;
 1531: }
 1532: 
 1533: DIMS
 1534: }
 1535: 
 1536: =pod
 1537: 
 1538: =item * &resize_textarea_js()
 1539: 
 1540: emits the needed javascript to resize a textarea to be as big as possible
 1541: 
 1542: creates a function resize_textrea that takes two IDs first should be
 1543: the id of the element to resize, second should be the id of a div that
 1544: surrounds everything that comes after the textarea, this routine needs
 1545: to be attached to the <body> for the onload and onresize events.
 1546: 
 1547: =back
 1548: 
 1549: =cut
 1550: 
 1551: sub resize_textarea_js {
 1552:     my $geometry = &viewport_geometry_js();
 1553:     return <<"RESIZE";
 1554:     <script type="text/javascript">
 1555: // <![CDATA[
 1556: $geometry
 1557: 
 1558: function getX(element) {
 1559:     var x = 0;
 1560:     while (element) {
 1561: 	x += element.offsetLeft;
 1562: 	element = element.offsetParent;
 1563:     }
 1564:     return x;
 1565: }
 1566: function getY(element) {
 1567:     var y = 0;
 1568:     while (element) {
 1569: 	y += element.offsetTop;
 1570: 	element = element.offsetParent;
 1571:     }
 1572:     return y;
 1573: }
 1574: 
 1575: 
 1576: function resize_textarea(textarea_id,bottom_id) {
 1577:     init_geometry();
 1578:     var textarea        = document.getElementById(textarea_id);
 1579:     //alert(textarea);
 1580: 
 1581:     var textarea_top    = getY(textarea);
 1582:     var textarea_height = textarea.offsetHeight;
 1583:     var bottom          = document.getElementById(bottom_id);
 1584:     var bottom_top      = getY(bottom);
 1585:     var bottom_height   = bottom.offsetHeight;
 1586:     var window_height   = Geometry.getViewportHeight();
 1587:     var fudge           = 23;
 1588:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1589:     if (new_height < 300) {
 1590: 	new_height = 300;
 1591:     }
 1592:     textarea.style.height=new_height+'px';
 1593: }
 1594: // ]]>
 1595: </script>
 1596: RESIZE
 1597: 
 1598: }
 1599: 
 1600: =pod
 1601: 
 1602: =head1 Excel and CSV file utility routines
 1603: 
 1604: =over 4
 1605: 
 1606: =cut
 1607: 
 1608: ###############################################################
 1609: ###############################################################
 1610: 
 1611: =pod
 1612: 
 1613: =item * &csv_translate($text) 
 1614: 
 1615: Translate $text to allow it to be output as a 'comma separated values' 
 1616: format.
 1617: 
 1618: =cut
 1619: 
 1620: ###############################################################
 1621: ###############################################################
 1622: sub csv_translate {
 1623:     my $text = shift;
 1624:     $text =~ s/\"/\"\"/g;
 1625:     $text =~ s/\n/ /g;
 1626:     return $text;
 1627: }
 1628: 
 1629: ###############################################################
 1630: ###############################################################
 1631: 
 1632: =pod
 1633: 
 1634: =item * &define_excel_formats()
 1635: 
 1636: Define some commonly used Excel cell formats.
 1637: 
 1638: Currently supported formats:
 1639: 
 1640: =over 4
 1641: 
 1642: =item header
 1643: 
 1644: =item bold
 1645: 
 1646: =item h1
 1647: 
 1648: =item h2
 1649: 
 1650: =item h3
 1651: 
 1652: =item h4
 1653: 
 1654: =item i
 1655: 
 1656: =item date
 1657: 
 1658: =back
 1659: 
 1660: Inputs: $workbook
 1661: 
 1662: Returns: $format, a hash reference.
 1663: 
 1664: =cut
 1665: 
 1666: ###############################################################
 1667: ###############################################################
 1668: sub define_excel_formats {
 1669:     my ($workbook) = @_;
 1670:     my $format;
 1671:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1672:                                                 bottom    => 1,
 1673:                                                 align     => 'center');
 1674:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1675:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1676:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1677:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1678:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1679:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1680:     $format->{'date'} = $workbook->add_format(num_format=>
 1681:                                             'mm/dd/yyyy hh:mm:ss');
 1682:     return $format;
 1683: }
 1684: 
 1685: ###############################################################
 1686: ###############################################################
 1687: 
 1688: =pod
 1689: 
 1690: =item * &create_workbook()
 1691: 
 1692: Create an Excel worksheet.  If it fails, output message on the
 1693: request object and return undefs.
 1694: 
 1695: Inputs: Apache request object
 1696: 
 1697: Returns (undef) on failure, 
 1698:     Excel worksheet object, scalar with filename, and formats 
 1699:     from &Apache::loncommon::define_excel_formats on success
 1700: 
 1701: =cut
 1702: 
 1703: ###############################################################
 1704: ###############################################################
 1705: sub create_workbook {
 1706:     my ($r) = @_;
 1707:         #
 1708:     # Create the excel spreadsheet
 1709:     my $filename = '/prtspool/'.
 1710:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1711:         time.'_'.rand(1000000000).'.xls';
 1712:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1713:     if (! defined($workbook)) {
 1714:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1715:         $r->print(
 1716:             '<p class="LC_error">'
 1717:            .&mt('Problems occurred in creating the new Excel file.')
 1718:            .' '.&mt('This error has been logged.')
 1719:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1720:            .'</p>'
 1721:         );
 1722:         return (undef);
 1723:     }
 1724:     #
 1725:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1726:     #
 1727:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1728:     return ($workbook,$filename,$format);
 1729: }
 1730: 
 1731: ###############################################################
 1732: ###############################################################
 1733: 
 1734: =pod
 1735: 
 1736: =item * &create_text_file()
 1737: 
 1738: Create a file to write to and eventually make available to the user.
 1739: If file creation fails, outputs an error message on the request object and 
 1740: return undefs.
 1741: 
 1742: Inputs: Apache request object, and file suffix
 1743: 
 1744: Returns (undef) on failure, 
 1745:     Filehandle and filename on success.
 1746: 
 1747: =cut
 1748: 
 1749: ###############################################################
 1750: ###############################################################
 1751: sub create_text_file {
 1752:     my ($r,$suffix) = @_;
 1753:     if (! defined($suffix)) { $suffix = 'txt'; };
 1754:     my $fh;
 1755:     my $filename = '/prtspool/'.
 1756:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1757:         time.'_'.rand(1000000000).'.'.$suffix;
 1758:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1759:     if (! defined($fh)) {
 1760:         $r->log_error("Couldn't open $filename for output $!");
 1761:         $r->print(
 1762:             '<p class="LC_error">'
 1763:            .&mt('Problems occurred in creating the output file.')
 1764:            .' '.&mt('This error has been logged.')
 1765:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1766:            .'</p>'
 1767:         );
 1768:     }
 1769:     return ($fh,$filename)
 1770: }
 1771: 
 1772: 
 1773: =pod 
 1774: 
 1775: =back
 1776: 
 1777: =cut
 1778: 
 1779: ###############################################################
 1780: ##        Home server <option> list generating code          ##
 1781: ###############################################################
 1782: 
 1783: # ------------------------------------------
 1784: 
 1785: sub domain_select {
 1786:     my ($name,$value,$multiple)=@_;
 1787:     my %domains=map { 
 1788: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1789:     } &Apache::lonnet::all_domains();
 1790:     if ($multiple) {
 1791: 	$domains{''}=&mt('Any domain');
 1792: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1793: 	return &multiple_select_form($name,$value,4,\%domains);
 1794:     } else {
 1795: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1796: 	return &select_form($name,$value,\%domains);
 1797:     }
 1798: }
 1799: 
 1800: #-------------------------------------------
 1801: 
 1802: =pod
 1803: 
 1804: =head1 Routines for form select boxes
 1805: 
 1806: =over 4
 1807: 
 1808: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1809: 
 1810: Returns a string containing a <select> element int multiple mode
 1811: 
 1812: 
 1813: Args:
 1814:   $name - name of the <select> element
 1815:   $value - scalar or array ref of values that should already be selected
 1816:   $size - number of rows long the select element is
 1817:   $hash - the elements should be 'option' => 'shown text'
 1818:           (shown text should already have been &mt())
 1819:   $order - (optional) array ref of the order to show the elements in
 1820: 
 1821: =cut
 1822: 
 1823: #-------------------------------------------
 1824: sub multiple_select_form {
 1825:     my ($name,$value,$size,$hash,$order)=@_;
 1826:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1827:     my $output='';
 1828:     if (! defined($size)) {
 1829:         $size = 4;
 1830:         if (scalar(keys(%$hash))<4) {
 1831:             $size = scalar(keys(%$hash));
 1832:         }
 1833:     }
 1834:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1835:     my @order;
 1836:     if (ref($order) eq 'ARRAY')  {
 1837:         @order = @{$order};
 1838:     } else {
 1839:         @order = sort(keys(%$hash));
 1840:     }
 1841:     if (exists($$hash{'select_form_order'})) {
 1842:         @order = @{$$hash{'select_form_order'}};
 1843:     }
 1844:         
 1845:     foreach my $key (@order) {
 1846:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1847:         $output.='selected="selected" ' if ($selected{$key});
 1848:         $output.='>'.$hash->{$key}."</option>\n";
 1849:     }
 1850:     $output.="</select>\n";
 1851:     return $output;
 1852: }
 1853: 
 1854: #-------------------------------------------
 1855: 
 1856: =pod
 1857: 
 1858: =item * &select_form($defdom,$name,$hashref,$onchange)
 1859: 
 1860: Returns a string containing a <select name='$name' size='1'> form to 
 1861: allow a user to select options from a ref to a hash containing:
 1862: option_name => displayed text. An optional $onchange can include
 1863: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1864: 
 1865: See lonrights.pm for an example invocation and use.
 1866: 
 1867: =cut
 1868: 
 1869: #-------------------------------------------
 1870: sub select_form {
 1871:     my ($def,$name,$hashref,$onchange) = @_;
 1872:     return unless (ref($hashref) eq 'HASH');
 1873:     if ($onchange) {
 1874:         $onchange = ' onchange="'.$onchange.'"';
 1875:     }
 1876:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1877:     my @keys;
 1878:     if (exists($hashref->{'select_form_order'})) {
 1879: 	@keys=@{$hashref->{'select_form_order'}};
 1880:     } else {
 1881: 	@keys=sort(keys(%{$hashref}));
 1882:     }
 1883:     foreach my $key (@keys) {
 1884:         $selectform.=
 1885: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1886:             ($key eq $def ? 'selected="selected" ' : '').
 1887:                 ">".$hashref->{$key}."</option>\n";
 1888:     }
 1889:     $selectform.="</select>";
 1890:     return $selectform;
 1891: }
 1892: 
 1893: # For display filters
 1894: 
 1895: sub display_filter {
 1896:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1897:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1898:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1899: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1900: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1901: 	   '</label></span> <span class="LC_nobreak">'.
 1902:            &mt('Filter [_1]',
 1903: 	   &select_form($env{'form.displayfilter'},
 1904: 			'displayfilter',
 1905: 			{'currentfolder' => 'Current folder/page',
 1906: 			 'containing' => 'Containing phrase',
 1907: 			 'none' => 'None'})).
 1908: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1909: }
 1910: 
 1911: sub gradeleveldescription {
 1912:     my $gradelevel=shift;
 1913:     my %gradelevels=(0 => 'Not specified',
 1914: 		     1 => 'Grade 1',
 1915: 		     2 => 'Grade 2',
 1916: 		     3 => 'Grade 3',
 1917: 		     4 => 'Grade 4',
 1918: 		     5 => 'Grade 5',
 1919: 		     6 => 'Grade 6',
 1920: 		     7 => 'Grade 7',
 1921: 		     8 => 'Grade 8',
 1922: 		     9 => 'Grade 9',
 1923: 		     10 => 'Grade 10',
 1924: 		     11 => 'Grade 11',
 1925: 		     12 => 'Grade 12',
 1926: 		     13 => 'Grade 13',
 1927: 		     14 => '100 Level',
 1928: 		     15 => '200 Level',
 1929: 		     16 => '300 Level',
 1930: 		     17 => '400 Level',
 1931: 		     18 => 'Graduate Level');
 1932:     return &mt($gradelevels{$gradelevel});
 1933: }
 1934: 
 1935: sub select_level_form {
 1936:     my ($deflevel,$name)=@_;
 1937:     unless ($deflevel) { $deflevel=0; }
 1938:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1939:     for (my $i=0; $i<=18; $i++) {
 1940:         $selectform.="<option value=\"$i\" ".
 1941:             ($i==$deflevel ? 'selected="selected" ' : '').
 1942:                 ">".&gradeleveldescription($i)."</option>\n";
 1943:     }
 1944:     $selectform.="</select>";
 1945:     return $selectform;
 1946: }
 1947: 
 1948: #-------------------------------------------
 1949: 
 1950: =pod
 1951: 
 1952: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 1953: 
 1954: Returns a string containing a <select name='$name' size='1'> form to 
 1955: allow a user to select the domain to preform an operation in.  
 1956: See loncreateuser.pm for an example invocation and use.
 1957: 
 1958: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1959: selected");
 1960: 
 1961: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1962: 
 1963: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 1964: 
 1965: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 1966: 
 1967: =cut
 1968: 
 1969: #-------------------------------------------
 1970: sub select_dom_form {
 1971:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 1972:     if ($onchange) {
 1973:         $onchange = ' onchange="'.$onchange.'"';
 1974:     }
 1975:     my @domains;
 1976:     if (ref($incdoms) eq 'ARRAY') {
 1977:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 1978:     } else {
 1979:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1980:     }
 1981:     if ($includeempty) { @domains=('',@domains); }
 1982:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1983:     foreach my $dom (@domains) {
 1984:         $selectdomain.="<option value=\"$dom\" ".
 1985:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1986:         if ($showdomdesc) {
 1987:             if ($dom ne '') {
 1988:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1989:                 if ($domdesc ne '') {
 1990:                     $selectdomain .= ' ('.$domdesc.')';
 1991:                 }
 1992:             } 
 1993:         }
 1994:         $selectdomain .= "</option>\n";
 1995:     }
 1996:     $selectdomain.="</select>";
 1997:     return $selectdomain;
 1998: }
 1999: 
 2000: #-------------------------------------------
 2001: 
 2002: =pod
 2003: 
 2004: =item * &home_server_form_item($domain,$name,$defaultflag)
 2005: 
 2006: input: 4 arguments (two required, two optional) - 
 2007:     $domain - domain of new user
 2008:     $name - name of form element
 2009:     $default - Value of 'default' causes a default item to be first 
 2010:                             option, and selected by default. 
 2011:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2012:                             if 1 server found, or default, if 0 found.
 2013: output: returns 2 items: 
 2014: (a) form element which contains either:
 2015:    (i) <select name="$name">
 2016:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2017:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2018:        </select>
 2019:        form item if there are multiple library servers in $domain, or
 2020:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2021:        if there is only one library server in $domain.
 2022: 
 2023: (b) number of library servers found.
 2024: 
 2025: See loncreateuser.pm for example of use.
 2026: 
 2027: =cut
 2028: 
 2029: #-------------------------------------------
 2030: sub home_server_form_item {
 2031:     my ($domain,$name,$default,$hide) = @_;
 2032:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2033:     my $result;
 2034:     my $numlib = keys(%servers);
 2035:     if ($numlib > 1) {
 2036:         $result .= '<select name="'.$name.'" />'."\n";
 2037:         if ($default) {
 2038:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2039:                        '</option>'."\n";
 2040:         }
 2041:         foreach my $hostid (sort(keys(%servers))) {
 2042:             $result.= '<option value="'.$hostid.'">'.
 2043: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2044:         }
 2045:         $result .= '</select>'."\n";
 2046:     } elsif ($numlib == 1) {
 2047:         my $hostid;
 2048:         foreach my $item (keys(%servers)) {
 2049:             $hostid = $item;
 2050:         }
 2051:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2052:                    $hostid.'" />';
 2053:                    if (!$hide) {
 2054:                        $result .= $hostid.' '.$servers{$hostid};
 2055:                    }
 2056:                    $result .= "\n";
 2057:     } elsif ($default) {
 2058:         $result .= '<input type="hidden" name="'.$name.
 2059:                    '" value="default" />';
 2060:                    if (!$hide) {
 2061:                        $result .= &mt('default');
 2062:                    }
 2063:                    $result .= "\n";
 2064:     }
 2065:     return ($result,$numlib);
 2066: }
 2067: 
 2068: =pod
 2069: 
 2070: =back 
 2071: 
 2072: =cut
 2073: 
 2074: ###############################################################
 2075: ##                  Decoding User Agent                      ##
 2076: ###############################################################
 2077: 
 2078: =pod
 2079: 
 2080: =head1 Decoding the User Agent
 2081: 
 2082: =over 4
 2083: 
 2084: =item * &decode_user_agent()
 2085: 
 2086: Inputs: $r
 2087: 
 2088: Outputs:
 2089: 
 2090: =over 4
 2091: 
 2092: =item * $httpbrowser
 2093: 
 2094: =item * $clientbrowser
 2095: 
 2096: =item * $clientversion
 2097: 
 2098: =item * $clientmathml
 2099: 
 2100: =item * $clientunicode
 2101: 
 2102: =item * $clientos
 2103: 
 2104: =back
 2105: 
 2106: =back 
 2107: 
 2108: =cut
 2109: 
 2110: ###############################################################
 2111: ###############################################################
 2112: sub decode_user_agent {
 2113:     my ($r)=@_;
 2114:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2115:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2116:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2117:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2118:     my $clientbrowser='unknown';
 2119:     my $clientversion='0';
 2120:     my $clientmathml='';
 2121:     my $clientunicode='0';
 2122:     for (my $i=0;$i<=$#browsertype;$i++) {
 2123:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2124: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2125: 	    $clientbrowser=$bname;
 2126:             $httpbrowser=~/$vreg/i;
 2127: 	    $clientversion=$1;
 2128:             $clientmathml=($clientversion>=$minv);
 2129:             $clientunicode=($clientversion>=$univ);
 2130: 	}
 2131:     }
 2132:     my $clientos='unknown';
 2133:     if (($httpbrowser=~/linux/i) ||
 2134:         ($httpbrowser=~/unix/i) ||
 2135:         ($httpbrowser=~/ux/i) ||
 2136:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2137:     if (($httpbrowser=~/vax/i) ||
 2138:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2139:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2140:     if (($httpbrowser=~/mac/i) ||
 2141:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2142:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2143:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2144:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2145:             $clientunicode,$clientos,);
 2146: }
 2147: 
 2148: ###############################################################
 2149: ##    Authentication changing form generation subroutines    ##
 2150: ###############################################################
 2151: ##
 2152: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2153: ## hash, and have reasonable default values.
 2154: ##
 2155: ##    formname = the name given in the <form> tag.
 2156: #-------------------------------------------
 2157: 
 2158: =pod
 2159: 
 2160: =head1 Authentication Routines
 2161: 
 2162: =over 4
 2163: 
 2164: =item * &authform_xxxxxx()
 2165: 
 2166: The authform_xxxxxx subroutines provide javascript and html forms which 
 2167: handle some of the conveniences required for authentication forms.  
 2168: This is not an optimal method, but it works.  
 2169: 
 2170: =over 4
 2171: 
 2172: =item * authform_header
 2173: 
 2174: =item * authform_authorwarning
 2175: 
 2176: =item * authform_nochange
 2177: 
 2178: =item * authform_kerberos
 2179: 
 2180: =item * authform_internal
 2181: 
 2182: =item * authform_filesystem
 2183: 
 2184: =back
 2185: 
 2186: See loncreateuser.pm for invocation and use examples.
 2187: 
 2188: =cut
 2189: 
 2190: #-------------------------------------------
 2191: sub authform_header{  
 2192:     my %in = (
 2193:         formname => 'cu',
 2194:         kerb_def_dom => '',
 2195:         @_,
 2196:     );
 2197:     $in{'formname'} = 'document.' . $in{'formname'};
 2198:     my $result='';
 2199: 
 2200: #---------------------------------------------- Code for upper case translation
 2201:     my $Javascript_toUpperCase;
 2202:     unless ($in{kerb_def_dom}) {
 2203:         $Javascript_toUpperCase =<<"END";
 2204:         switch (choice) {
 2205:            case 'krb': currentform.elements[choicearg].value =
 2206:                currentform.elements[choicearg].value.toUpperCase();
 2207:                break;
 2208:            default:
 2209:         }
 2210: END
 2211:     } else {
 2212:         $Javascript_toUpperCase = "";
 2213:     }
 2214: 
 2215:     my $radioval = "'nochange'";
 2216:     if (defined($in{'curr_authtype'})) {
 2217:         if ($in{'curr_authtype'} ne '') {
 2218:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2219:         }
 2220:     }
 2221:     my $argfield = 'null';
 2222:     if (defined($in{'mode'})) {
 2223:         if ($in{'mode'} eq 'modifycourse')  {
 2224:             if (defined($in{'curr_autharg'})) {
 2225:                 if ($in{'curr_autharg'} ne '') {
 2226:                     $argfield = "'$in{'curr_autharg'}'";
 2227:                 }
 2228:             }
 2229:         }
 2230:     }
 2231: 
 2232:     $result.=<<"END";
 2233: var current = new Object();
 2234: current.radiovalue = $radioval;
 2235: current.argfield = $argfield;
 2236: 
 2237: function changed_radio(choice,currentform) {
 2238:     var choicearg = choice + 'arg';
 2239:     // If a radio button in changed, we need to change the argfield
 2240:     if (current.radiovalue != choice) {
 2241:         current.radiovalue = choice;
 2242:         if (current.argfield != null) {
 2243:             currentform.elements[current.argfield].value = '';
 2244:         }
 2245:         if (choice == 'nochange') {
 2246:             current.argfield = null;
 2247:         } else {
 2248:             current.argfield = choicearg;
 2249:             switch(choice) {
 2250:                 case 'krb': 
 2251:                     currentform.elements[current.argfield].value = 
 2252:                         "$in{'kerb_def_dom'}";
 2253:                 break;
 2254:               default:
 2255:                 break;
 2256:             }
 2257:         }
 2258:     }
 2259:     return;
 2260: }
 2261: 
 2262: function changed_text(choice,currentform) {
 2263:     var choicearg = choice + 'arg';
 2264:     if (currentform.elements[choicearg].value !='') {
 2265:         $Javascript_toUpperCase
 2266:         // clear old field
 2267:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2268:             currentform.elements[current.argfield].value = '';
 2269:         }
 2270:         current.argfield = choicearg;
 2271:     }
 2272:     set_auth_radio_buttons(choice,currentform);
 2273:     return;
 2274: }
 2275: 
 2276: function set_auth_radio_buttons(newvalue,currentform) {
 2277:     var i=0;
 2278:     while (i < currentform.login.length) {
 2279:         if (currentform.login[i].value == newvalue) { break; }
 2280:         i++;
 2281:     }
 2282:     if (i == currentform.login.length) {
 2283:         return;
 2284:     }
 2285:     current.radiovalue = newvalue;
 2286:     currentform.login[i].checked = true;
 2287:     return;
 2288: }
 2289: END
 2290:     return $result;
 2291: }
 2292: 
 2293: sub authform_authorwarning{
 2294:     my $result='';
 2295:     $result='<i>'.
 2296:         &mt('As a general rule, only authors or co-authors should be '.
 2297:             'filesystem authenticated '.
 2298:             '(which allows access to the server filesystem).')."</i>\n";
 2299:     return $result;
 2300: }
 2301: 
 2302: sub authform_nochange{  
 2303:     my %in = (
 2304:               formname => 'document.cu',
 2305:               kerb_def_dom => 'MSU.EDU',
 2306:               @_,
 2307:           );
 2308:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2309:     my $result;
 2310:     if (keys(%can_assign) == 0) {
 2311:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2312:     } else {
 2313:         $result = '<label>'.&mt('[_1] Do not change login data',
 2314:                   '<input type="radio" name="login" value="nochange" '.
 2315:                   'checked="checked" onclick="'.
 2316:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2317: 	    '</label>';
 2318:     }
 2319:     return $result;
 2320: }
 2321: 
 2322: sub authform_kerberos {
 2323:     my %in = (
 2324:               formname => 'document.cu',
 2325:               kerb_def_dom => 'MSU.EDU',
 2326:               kerb_def_auth => 'krb4',
 2327:               @_,
 2328:               );
 2329:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2330:         $autharg,$jscall);
 2331:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2332:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2333:        $check5 = ' checked="checked"';
 2334:     } else {
 2335:        $check4 = ' checked="checked"';
 2336:     }
 2337:     $krbarg = $in{'kerb_def_dom'};
 2338:     if (defined($in{'curr_authtype'})) {
 2339:         if ($in{'curr_authtype'} eq 'krb') {
 2340:             $krbcheck = ' checked="checked"';
 2341:             if (defined($in{'mode'})) {
 2342:                 if ($in{'mode'} eq 'modifyuser') {
 2343:                     $krbcheck = '';
 2344:                 }
 2345:             }
 2346:             if (defined($in{'curr_kerb_ver'})) {
 2347:                 if ($in{'curr_krb_ver'} eq '5') {
 2348:                     $check5 = ' checked="checked"';
 2349:                     $check4 = '';
 2350:                 } else {
 2351:                     $check4 = ' checked="checked"';
 2352:                     $check5 = '';
 2353:                 }
 2354:             }
 2355:             if (defined($in{'curr_autharg'})) {
 2356:                 $krbarg = $in{'curr_autharg'};
 2357:             }
 2358:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2359:                 if (defined($in{'curr_autharg'})) {
 2360:                     $result = 
 2361:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2362:         $in{'curr_autharg'},$krbver);
 2363:                 } else {
 2364:                     $result =
 2365:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2366:                 }
 2367:                 return $result; 
 2368:             }
 2369:         }
 2370:     } else {
 2371:         if ($authnum == 1) {
 2372:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2373:         }
 2374:     }
 2375:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2376:         return;
 2377:     } elsif ($authtype eq '') {
 2378:         if (defined($in{'mode'})) {
 2379:             if ($in{'mode'} eq 'modifycourse') {
 2380:                 if ($authnum == 1) {
 2381:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2387:     if ($authtype eq '') {
 2388:         $authtype = '<input type="radio" name="login" value="krb" '.
 2389:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2390:                     $krbcheck.' />';
 2391:     }
 2392:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2393:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2394:          $in{'curr_authtype'} eq 'krb5') ||
 2395:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2396:          $in{'curr_authtype'} eq 'krb4')) {
 2397:         $result .= &mt
 2398:         ('[_1] Kerberos authenticated with domain [_2] '.
 2399:          '[_3] Version 4 [_4] Version 5 [_5]',
 2400:          '<label>'.$authtype,
 2401:          '</label><input type="text" size="10" name="krbarg" '.
 2402:              'value="'.$krbarg.'" '.
 2403:              'onchange="'.$jscall.'" />',
 2404:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2405:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2406: 	 '</label>');
 2407:     } elsif ($can_assign{'krb4'}) {
 2408:         $result .= &mt
 2409:         ('[_1] Kerberos authenticated with domain [_2] '.
 2410:          '[_3] Version 4 [_4]',
 2411:          '<label>'.$authtype,
 2412:          '</label><input type="text" size="10" name="krbarg" '.
 2413:              'value="'.$krbarg.'" '.
 2414:              'onchange="'.$jscall.'" />',
 2415:          '<label><input type="hidden" name="krbver" value="4" />',
 2416:          '</label>');
 2417:     } elsif ($can_assign{'krb5'}) {
 2418:         $result .= &mt
 2419:         ('[_1] Kerberos authenticated with domain [_2] '.
 2420:          '[_3] Version 5 [_4]',
 2421:          '<label>'.$authtype,
 2422:          '</label><input type="text" size="10" name="krbarg" '.
 2423:              'value="'.$krbarg.'" '.
 2424:              'onchange="'.$jscall.'" />',
 2425:          '<label><input type="hidden" name="krbver" value="5" />',
 2426:          '</label>');
 2427:     }
 2428:     return $result;
 2429: }
 2430: 
 2431: sub authform_internal{  
 2432:     my %in = (
 2433:                 formname => 'document.cu',
 2434:                 kerb_def_dom => 'MSU.EDU',
 2435:                 @_,
 2436:                 );
 2437:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2438:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2439:     if (defined($in{'curr_authtype'})) {
 2440:         if ($in{'curr_authtype'} eq 'int') {
 2441:             if ($can_assign{'int'}) {
 2442:                 $intcheck = 'checked="checked" ';
 2443:                 if (defined($in{'mode'})) {
 2444:                     if ($in{'mode'} eq 'modifyuser') {
 2445:                         $intcheck = '';
 2446:                     }
 2447:                 }
 2448:                 if (defined($in{'curr_autharg'})) {
 2449:                     $intarg = $in{'curr_autharg'};
 2450:                 }
 2451:             } else {
 2452:                 $result = &mt('Currently internally authenticated.');
 2453:                 return $result;
 2454:             }
 2455:         }
 2456:     } else {
 2457:         if ($authnum == 1) {
 2458:             $authtype = '<input type="hidden" name="login" value="int" />';
 2459:         }
 2460:     }
 2461:     if (!$can_assign{'int'}) {
 2462:         return;
 2463:     } elsif ($authtype eq '') {
 2464:         if (defined($in{'mode'})) {
 2465:             if ($in{'mode'} eq 'modifycourse') {
 2466:                 if ($authnum == 1) {
 2467:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2468:                 }
 2469:             }
 2470:         }
 2471:     }
 2472:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2473:     if ($authtype eq '') {
 2474:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2475:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2476:     }
 2477:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2478:                $intarg.'" onchange="'.$jscall.'" />';
 2479:     $result = &mt
 2480:         ('[_1] Internally authenticated (with initial password [_2])',
 2481:          '<label>'.$authtype,'</label>'.$autharg);
 2482:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2483:     return $result;
 2484: }
 2485: 
 2486: sub authform_local{  
 2487:     my %in = (
 2488:               formname => 'document.cu',
 2489:               kerb_def_dom => 'MSU.EDU',
 2490:               @_,
 2491:               );
 2492:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2493:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2494:     if (defined($in{'curr_authtype'})) {
 2495:         if ($in{'curr_authtype'} eq 'loc') {
 2496:             if ($can_assign{'loc'}) {
 2497:                 $loccheck = 'checked="checked" ';
 2498:                 if (defined($in{'mode'})) {
 2499:                     if ($in{'mode'} eq 'modifyuser') {
 2500:                         $loccheck = '';
 2501:                     }
 2502:                 }
 2503:                 if (defined($in{'curr_autharg'})) {
 2504:                     $locarg = $in{'curr_autharg'};
 2505:                 }
 2506:             } else {
 2507:                 $result = &mt('Currently using local (institutional) authentication.');
 2508:                 return $result;
 2509:             }
 2510:         }
 2511:     } else {
 2512:         if ($authnum == 1) {
 2513:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2514:         }
 2515:     }
 2516:     if (!$can_assign{'loc'}) {
 2517:         return;
 2518:     } elsif ($authtype eq '') {
 2519:         if (defined($in{'mode'})) {
 2520:             if ($in{'mode'} eq 'modifycourse') {
 2521:                 if ($authnum == 1) {
 2522:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2523:                 }
 2524:             }
 2525:         }
 2526:     }
 2527:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2528:     if ($authtype eq '') {
 2529:         $authtype = '<input type="radio" name="login" value="loc" '.
 2530:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2531:                     $jscall.'" />';
 2532:     }
 2533:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2534:                $locarg.'" onchange="'.$jscall.'" />';
 2535:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2536:                   '<label>'.$authtype,'</label>'.$autharg);
 2537:     return $result;
 2538: }
 2539: 
 2540: sub authform_filesystem{  
 2541:     my %in = (
 2542:               formname => 'document.cu',
 2543:               kerb_def_dom => 'MSU.EDU',
 2544:               @_,
 2545:               );
 2546:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2547:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2548:     if (defined($in{'curr_authtype'})) {
 2549:         if ($in{'curr_authtype'} eq 'fsys') {
 2550:             if ($can_assign{'fsys'}) {
 2551:                 $fsyscheck = 'checked="checked" ';
 2552:                 if (defined($in{'mode'})) {
 2553:                     if ($in{'mode'} eq 'modifyuser') {
 2554:                         $fsyscheck = '';
 2555:                     }
 2556:                 }
 2557:             } else {
 2558:                 $result = &mt('Currently Filesystem Authenticated.');
 2559:                 return $result;
 2560:             }           
 2561:         }
 2562:     } else {
 2563:         if ($authnum == 1) {
 2564:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2565:         }
 2566:     }
 2567:     if (!$can_assign{'fsys'}) {
 2568:         return;
 2569:     } elsif ($authtype eq '') {
 2570:         if (defined($in{'mode'})) {
 2571:             if ($in{'mode'} eq 'modifycourse') {
 2572:                 if ($authnum == 1) {
 2573:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2574:                 }
 2575:             }
 2576:         }
 2577:     }
 2578:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2579:     if ($authtype eq '') {
 2580:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2581:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2582:                     $jscall.'" />';
 2583:     }
 2584:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2585:                ' onchange="'.$jscall.'" />';
 2586:     $result = &mt
 2587:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2588:          '<label><input type="radio" name="login" value="fsys" '.
 2589:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2590:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2591:                   'onchange="'.$jscall.'" />');
 2592:     return $result;
 2593: }
 2594: 
 2595: sub get_assignable_auth {
 2596:     my ($dom) = @_;
 2597:     if ($dom eq '') {
 2598:         $dom = $env{'request.role.domain'};
 2599:     }
 2600:     my %can_assign = (
 2601:                           krb4 => 1,
 2602:                           krb5 => 1,
 2603:                           int  => 1,
 2604:                           loc  => 1,
 2605:                      );
 2606:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2607:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2608:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2609:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2610:             my $context;
 2611:             if ($env{'request.role'} =~ /^au/) {
 2612:                 $context = 'author';
 2613:             } elsif ($env{'request.role'} =~ /^dc/) {
 2614:                 $context = 'domain';
 2615:             } elsif ($env{'request.course.id'}) {
 2616:                 $context = 'course';
 2617:             }
 2618:             if ($context) {
 2619:                 if (ref($authhash->{$context}) eq 'HASH') {
 2620:                    %can_assign = %{$authhash->{$context}}; 
 2621:                 }
 2622:             }
 2623:         }
 2624:     }
 2625:     my $authnum = 0;
 2626:     foreach my $key (keys(%can_assign)) {
 2627:         if ($can_assign{$key}) {
 2628:             $authnum ++;
 2629:         }
 2630:     }
 2631:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2632:         $authnum --;
 2633:     }
 2634:     return ($authnum,%can_assign);
 2635: }
 2636: 
 2637: ###############################################################
 2638: ##    Get Kerberos Defaults for Domain                 ##
 2639: ###############################################################
 2640: ##
 2641: ## Returns default kerberos version and an associated argument
 2642: ## as listed in file domain.tab. If not listed, provides
 2643: ## appropriate default domain and kerberos version.
 2644: ##
 2645: #-------------------------------------------
 2646: 
 2647: =pod
 2648: 
 2649: =item * &get_kerberos_defaults()
 2650: 
 2651: get_kerberos_defaults($target_domain) returns the default kerberos
 2652: version and domain. If not found, it defaults to version 4 and the 
 2653: domain of the server.
 2654: 
 2655: =over 4
 2656: 
 2657: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2658: 
 2659: =back
 2660: 
 2661: =back
 2662: 
 2663: =cut
 2664: 
 2665: #-------------------------------------------
 2666: sub get_kerberos_defaults {
 2667:     my $domain=shift;
 2668:     my ($krbdef,$krbdefdom);
 2669:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2670:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2671:         $krbdef = $domdefaults{'auth_def'};
 2672:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2673:     } else {
 2674:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2675:         my $krbdefdom=$1;
 2676:         $krbdefdom=~tr/a-z/A-Z/;
 2677:         $krbdef = "krb4";
 2678:     }
 2679:     return ($krbdef,$krbdefdom);
 2680: }
 2681: 
 2682: 
 2683: ###############################################################
 2684: ##                Thesaurus Functions                        ##
 2685: ###############################################################
 2686: 
 2687: =pod
 2688: 
 2689: =head1 Thesaurus Functions
 2690: 
 2691: =over 4
 2692: 
 2693: =item * &initialize_keywords()
 2694: 
 2695: Initializes the package variable %Keywords if it is empty.  Uses the
 2696: package variable $thesaurus_db_file.
 2697: 
 2698: =cut
 2699: 
 2700: ###################################################
 2701: 
 2702: sub initialize_keywords {
 2703:     return 1 if (scalar keys(%Keywords));
 2704:     # If we are here, %Keywords is empty, so fill it up
 2705:     #   Make sure the file we need exists...
 2706:     if (! -e $thesaurus_db_file) {
 2707:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2708:                                  " failed because it does not exist");
 2709:         return 0;
 2710:     }
 2711:     #   Set up the hash as a database
 2712:     my %thesaurus_db;
 2713:     if (! tie(%thesaurus_db,'GDBM_File',
 2714:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2715:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2716:                                  $thesaurus_db_file);
 2717:         return 0;
 2718:     } 
 2719:     #  Get the average number of appearances of a word.
 2720:     my $avecount = $thesaurus_db{'average.count'};
 2721:     #  Put keywords (those that appear > average) into %Keywords
 2722:     while (my ($word,$data)=each (%thesaurus_db)) {
 2723:         my ($count,undef) = split /:/,$data;
 2724:         $Keywords{$word}++ if ($count > $avecount);
 2725:     }
 2726:     untie %thesaurus_db;
 2727:     # Remove special values from %Keywords.
 2728:     foreach my $value ('total.count','average.count') {
 2729:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2730:   }
 2731:     return 1;
 2732: }
 2733: 
 2734: ###################################################
 2735: 
 2736: =pod
 2737: 
 2738: =item * &keyword($word)
 2739: 
 2740: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2741: than the average number of times in the thesaurus database.  Calls 
 2742: &initialize_keywords
 2743: 
 2744: =cut
 2745: 
 2746: ###################################################
 2747: 
 2748: sub keyword {
 2749:     return if (!&initialize_keywords());
 2750:     my $word=lc(shift());
 2751:     $word=~s/\W//g;
 2752:     return exists($Keywords{$word});
 2753: }
 2754: 
 2755: ###############################################################
 2756: 
 2757: =pod 
 2758: 
 2759: =item * &get_related_words()
 2760: 
 2761: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2762: an array of words.  If the keyword is not in the thesaurus, an empty array
 2763: will be returned.  The order of the words returned is determined by the
 2764: database which holds them.
 2765: 
 2766: Uses global $thesaurus_db_file.
 2767: 
 2768: =cut
 2769: 
 2770: ###############################################################
 2771: sub get_related_words {
 2772:     my $keyword = shift;
 2773:     my %thesaurus_db;
 2774:     if (! -e $thesaurus_db_file) {
 2775:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2776:                                  "failed because the file does not exist");
 2777:         return ();
 2778:     }
 2779:     if (! tie(%thesaurus_db,'GDBM_File',
 2780:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2781:         return ();
 2782:     } 
 2783:     my @Words=();
 2784:     my $count=0;
 2785:     if (exists($thesaurus_db{$keyword})) {
 2786: 	# The first element is the number of times
 2787: 	# the word appears.  We do not need it now.
 2788: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2789: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2790: 	my $threshold=$mostfrequentcount/10;
 2791:         foreach my $possibleword (@RelatedWords) {
 2792:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2793:             if ($wordcount>$threshold) {
 2794: 		push(@Words,$word);
 2795:                 $count++;
 2796:                 if ($count>10) { last; }
 2797: 	    }
 2798:         }
 2799:     }
 2800:     untie %thesaurus_db;
 2801:     return @Words;
 2802: }
 2803: 
 2804: =pod
 2805: 
 2806: =back
 2807: 
 2808: =cut
 2809: 
 2810: # -------------------------------------------------------------- Plaintext name
 2811: =pod
 2812: 
 2813: =head1 User Name Functions
 2814: 
 2815: =over 4
 2816: 
 2817: =item * &plainname($uname,$udom,$first)
 2818: 
 2819: Takes a users logon name and returns it as a string in
 2820: "first middle last generation" form 
 2821: if $first is set to 'lastname' then it returns it as
 2822: 'lastname generation, firstname middlename' if their is a lastname
 2823: 
 2824: =cut
 2825: 
 2826: 
 2827: ###############################################################
 2828: sub plainname {
 2829:     my ($uname,$udom,$first)=@_;
 2830:     return if (!defined($uname) || !defined($udom));
 2831:     my %names=&getnames($uname,$udom);
 2832:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2833: 					  $names{'middlename'},
 2834: 					  $names{'lastname'},
 2835: 					  $names{'generation'},$first);
 2836:     $name=~s/^\s+//;
 2837:     $name=~s/\s+$//;
 2838:     $name=~s/\s+/ /g;
 2839:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2840:     return $name;
 2841: }
 2842: 
 2843: # -------------------------------------------------------------------- Nickname
 2844: =pod
 2845: 
 2846: =item * &nickname($uname,$udom)
 2847: 
 2848: Gets a users name and returns it as a string as
 2849: 
 2850: "&quot;nickname&quot;"
 2851: 
 2852: if the user has a nickname or
 2853: 
 2854: "first middle last generation"
 2855: 
 2856: if the user does not
 2857: 
 2858: =cut
 2859: 
 2860: sub nickname {
 2861:     my ($uname,$udom)=@_;
 2862:     return if (!defined($uname) || !defined($udom));
 2863:     my %names=&getnames($uname,$udom);
 2864:     my $name=$names{'nickname'};
 2865:     if ($name) {
 2866:        $name='&quot;'.$name.'&quot;'; 
 2867:     } else {
 2868:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2869: 	     $names{'lastname'}.' '.$names{'generation'};
 2870:        $name=~s/\s+$//;
 2871:        $name=~s/\s+/ /g;
 2872:     }
 2873:     return $name;
 2874: }
 2875: 
 2876: sub getnames {
 2877:     my ($uname,$udom)=@_;
 2878:     return if (!defined($uname) || !defined($udom));
 2879:     if ($udom eq 'public' && $uname eq 'public') {
 2880: 	return ('lastname' => &mt('Public'));
 2881:     }
 2882:     my $id=$uname.':'.$udom;
 2883:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2884:     if ($cached) {
 2885: 	return %{$names};
 2886:     } else {
 2887: 	my %loadnames=&Apache::lonnet::get('environment',
 2888:                     ['firstname','middlename','lastname','generation','nickname'],
 2889: 					 $udom,$uname);
 2890: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2891: 	return %loadnames;
 2892:     }
 2893: }
 2894: 
 2895: # -------------------------------------------------------------------- getemails
 2896: 
 2897: =pod
 2898: 
 2899: =item * &getemails($uname,$udom)
 2900: 
 2901: Gets a user's email information and returns it as a hash with keys:
 2902: notification, critnotification, permanentemail
 2903: 
 2904: For notification and critnotification, values are comma-separated lists 
 2905: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2906:  
 2907: 
 2908: =cut
 2909: 
 2910: 
 2911: sub getemails {
 2912:     my ($uname,$udom)=@_;
 2913:     if ($udom eq 'public' && $uname eq 'public') {
 2914: 	return;
 2915:     }
 2916:     if (!$udom) { $udom=$env{'user.domain'}; }
 2917:     if (!$uname) { $uname=$env{'user.name'}; }
 2918:     my $id=$uname.':'.$udom;
 2919:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2920:     if ($cached) {
 2921: 	return %{$names};
 2922:     } else {
 2923: 	my %loadnames=&Apache::lonnet::get('environment',
 2924:                     			   ['notification','critnotification',
 2925: 					    'permanentemail'],
 2926: 					   $udom,$uname);
 2927: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2928: 	return %loadnames;
 2929:     }
 2930: }
 2931: 
 2932: sub flush_email_cache {
 2933:     my ($uname,$udom)=@_;
 2934:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2935:     if (!$uname) { $uname=$env{'user.name'};   }
 2936:     return if ($udom eq 'public' && $uname eq 'public');
 2937:     my $id=$uname.':'.$udom;
 2938:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2939: }
 2940: 
 2941: # -------------------------------------------------------------------- getlangs
 2942: 
 2943: =pod
 2944: 
 2945: =item * &getlangs($uname,$udom)
 2946: 
 2947: Gets a user's language preference and returns it as a hash with key:
 2948: language.
 2949: 
 2950: =cut
 2951: 
 2952: 
 2953: sub getlangs {
 2954:     my ($uname,$udom) = @_;
 2955:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2956:     if (!$uname) { $uname=$env{'user.name'};   }
 2957:     my $id=$uname.':'.$udom;
 2958:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2959:     if ($cached) {
 2960:         return %{$langs};
 2961:     } else {
 2962:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2963:                                            $udom,$uname);
 2964:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2965:         return %loadlangs;
 2966:     }
 2967: }
 2968: 
 2969: sub flush_langs_cache {
 2970:     my ($uname,$udom)=@_;
 2971:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2972:     if (!$uname) { $uname=$env{'user.name'};   }
 2973:     return if ($udom eq 'public' && $uname eq 'public');
 2974:     my $id=$uname.':'.$udom;
 2975:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2976: }
 2977: 
 2978: # ------------------------------------------------------------------ Screenname
 2979: 
 2980: =pod
 2981: 
 2982: =item * &screenname($uname,$udom)
 2983: 
 2984: Gets a users screenname and returns it as a string
 2985: 
 2986: =cut
 2987: 
 2988: sub screenname {
 2989:     my ($uname,$udom)=@_;
 2990:     if ($uname eq $env{'user.name'} &&
 2991: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2992:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2993:     return $names{'screenname'};
 2994: }
 2995: 
 2996: 
 2997: # ------------------------------------------------------------- Confirm Wrapper
 2998: =pod
 2999: 
 3000: =item confirmwrapper
 3001: 
 3002: Wrap messages about completion of operation in box
 3003: 
 3004: =cut
 3005: 
 3006: sub confirmwrapper {
 3007:     my ($message)=@_;
 3008:     if ($message) {
 3009:         return "\n".'<div class="LC_confirm_box">'."\n"
 3010:                .$message."\n"
 3011:                .'</div>'."\n";
 3012:     } else {
 3013:         return $message;
 3014:     }
 3015: }
 3016: 
 3017: # ------------------------------------------------------------- Message Wrapper
 3018: 
 3019: sub messagewrapper {
 3020:     my ($link,$username,$domain,$subject,$text)=@_;
 3021:     return 
 3022:         '<a href="/adm/email?compose=individual&amp;'.
 3023:         'recname='.$username.'&amp;recdom='.$domain.
 3024: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3025:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3026: }
 3027: 
 3028: # --------------------------------------------------------------- Notes Wrapper
 3029: 
 3030: sub noteswrapper {
 3031:     my ($link,$un,$do)=@_;
 3032:     return 
 3033: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3034: }
 3035: 
 3036: # ------------------------------------------------------------- Aboutme Wrapper
 3037: 
 3038: sub aboutmewrapper {
 3039:     my ($link,$username,$domain,$target)=@_;
 3040:     if (!defined($username)  && !defined($domain)) {
 3041:         return;
 3042:     }
 3043:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 3044: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3045: }
 3046: 
 3047: # ------------------------------------------------------------ Syllabus Wrapper
 3048: 
 3049: sub syllabuswrapper {
 3050:     my ($linktext,$coursedir,$domain)=@_;
 3051:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3052: }
 3053: 
 3054: # -----------------------------------------------------------------------------
 3055: 
 3056: sub track_student_link {
 3057:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3058:     my $link ="/adm/trackstudent?";
 3059:     my $title = 'View recent activity';
 3060:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3061:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3062:         $link .= "selected_student=$sname:$sdom";
 3063:         $title .= ' of this student';
 3064:     } 
 3065:     if (defined($target) && $target !~ /^\s*$/) {
 3066:         $target = qq{target="$target"};
 3067:     } else {
 3068:         $target = '';
 3069:     }
 3070:     if ($start) { $link.='&amp;start='.$start; }
 3071:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3072:     $title = &mt($title);
 3073:     $linktext = &mt($linktext);
 3074:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3075: 	&help_open_topic('View_recent_activity');
 3076: }
 3077: 
 3078: sub slot_reservations_link {
 3079:     my ($linktext,$sname,$sdom,$target) = @_;
 3080:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3081:     my $title = 'View slot reservation history';
 3082:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3083:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3084:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3085:         $title .= ' of this student';
 3086:     }
 3087:     if (defined($target) && $target !~ /^\s*$/) {
 3088:         $target = qq{target="$target"};
 3089:     } else {
 3090:         $target = '';
 3091:     }
 3092:     $title = &mt($title);
 3093:     $linktext = &mt($linktext);
 3094:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3095: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3096: 
 3097: }
 3098: 
 3099: # ===================================================== Display a student photo
 3100: 
 3101: 
 3102: sub student_image_tag {
 3103:     my ($domain,$user)=@_;
 3104:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3105:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3106: 	return '<img src="'.$imgsrc.'" align="right" />';
 3107:     } else {
 3108: 	return '';
 3109:     }
 3110: }
 3111: 
 3112: =pod
 3113: 
 3114: =back
 3115: 
 3116: =head1 Access .tab File Data
 3117: 
 3118: =over 4
 3119: 
 3120: =item * &languageids() 
 3121: 
 3122: returns list of all language ids
 3123: 
 3124: =cut
 3125: 
 3126: sub languageids {
 3127:     return sort(keys(%language));
 3128: }
 3129: 
 3130: =pod
 3131: 
 3132: =item * &languagedescription() 
 3133: 
 3134: returns description of a specified language id
 3135: 
 3136: =cut
 3137: 
 3138: sub languagedescription {
 3139:     my $code=shift;
 3140:     return  ($supported_language{$code}?'* ':'').
 3141:             $language{$code}.
 3142: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3143: }
 3144: 
 3145: sub plainlanguagedescription {
 3146:     my $code=shift;
 3147:     return $language{$code};
 3148: }
 3149: 
 3150: sub supportedlanguagecode {
 3151:     my $code=shift;
 3152:     return $supported_language{$code};
 3153: }
 3154: 
 3155: =pod
 3156: 
 3157: =item * &copyrightids() 
 3158: 
 3159: returns list of all copyrights
 3160: 
 3161: =cut
 3162: 
 3163: sub copyrightids {
 3164:     return sort(keys(%cprtag));
 3165: }
 3166: 
 3167: =pod
 3168: 
 3169: =item * &copyrightdescription() 
 3170: 
 3171: returns description of a specified copyright id
 3172: 
 3173: =cut
 3174: 
 3175: sub copyrightdescription {
 3176:     return &mt($cprtag{shift(@_)});
 3177: }
 3178: 
 3179: =pod
 3180: 
 3181: =item * &source_copyrightids() 
 3182: 
 3183: returns list of all source copyrights
 3184: 
 3185: =cut
 3186: 
 3187: sub source_copyrightids {
 3188:     return sort(keys(%scprtag));
 3189: }
 3190: 
 3191: =pod
 3192: 
 3193: =item * &source_copyrightdescription() 
 3194: 
 3195: returns description of a specified source copyright id
 3196: 
 3197: =cut
 3198: 
 3199: sub source_copyrightdescription {
 3200:     return &mt($scprtag{shift(@_)});
 3201: }
 3202: 
 3203: =pod
 3204: 
 3205: =item * &filecategories() 
 3206: 
 3207: returns list of all file categories
 3208: 
 3209: =cut
 3210: 
 3211: sub filecategories {
 3212:     return sort(keys(%category_extensions));
 3213: }
 3214: 
 3215: =pod
 3216: 
 3217: =item * &filecategorytypes() 
 3218: 
 3219: returns list of file types belonging to a given file
 3220: category
 3221: 
 3222: =cut
 3223: 
 3224: sub filecategorytypes {
 3225:     my ($cat) = @_;
 3226:     return @{$category_extensions{lc($cat)}};
 3227: }
 3228: 
 3229: =pod
 3230: 
 3231: =item * &fileembstyle() 
 3232: 
 3233: returns embedding style for a specified file type
 3234: 
 3235: =cut
 3236: 
 3237: sub fileembstyle {
 3238:     return $fe{lc(shift(@_))};
 3239: }
 3240: 
 3241: sub filemimetype {
 3242:     return $fm{lc(shift(@_))};
 3243: }
 3244: 
 3245: 
 3246: sub filecategoryselect {
 3247:     my ($name,$value)=@_;
 3248:     return &select_form($value,$name,
 3249:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3250: }
 3251: 
 3252: =pod
 3253: 
 3254: =item * &filedescription() 
 3255: 
 3256: returns description for a specified file type
 3257: 
 3258: =cut
 3259: 
 3260: sub filedescription {
 3261:     my $file_description = $fd{lc(shift())};
 3262:     $file_description =~ s:([\[\]]):~$1:g;
 3263:     return &mt($file_description);
 3264: }
 3265: 
 3266: =pod
 3267: 
 3268: =item * &filedescriptionex() 
 3269: 
 3270: returns description for a specified file type with
 3271: extra formatting
 3272: 
 3273: =cut
 3274: 
 3275: sub filedescriptionex {
 3276:     my $ex=shift;
 3277:     my $file_description = $fd{lc($ex)};
 3278:     $file_description =~ s:([\[\]]):~$1:g;
 3279:     return '.'.$ex.' '.&mt($file_description);
 3280: }
 3281: 
 3282: # End of .tab access
 3283: =pod
 3284: 
 3285: =back
 3286: 
 3287: =cut
 3288: 
 3289: # ------------------------------------------------------------------ File Types
 3290: sub fileextensions {
 3291:     return sort(keys(%fe));
 3292: }
 3293: 
 3294: # ----------------------------------------------------------- Display Languages
 3295: # returns a hash with all desired display languages
 3296: #
 3297: 
 3298: sub display_languages {
 3299:     my %languages=();
 3300:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3301: 	$languages{$lang}=1;
 3302:     }
 3303:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3304:     if ($env{'form.displaylanguage'}) {
 3305: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3306: 	    $languages{$lang}=1;
 3307:         }
 3308:     }
 3309:     return %languages;
 3310: }
 3311: 
 3312: sub languages {
 3313:     my ($possible_langs) = @_;
 3314:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3315:     if (!ref($possible_langs)) {
 3316: 	if( wantarray ) {
 3317: 	    return @preferred_langs;
 3318: 	} else {
 3319: 	    return $preferred_langs[0];
 3320: 	}
 3321:     }
 3322:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3323:     my @preferred_possibilities;
 3324:     foreach my $preferred_lang (@preferred_langs) {
 3325: 	if (exists($possibilities{$preferred_lang})) {
 3326: 	    push(@preferred_possibilities, $preferred_lang);
 3327: 	}
 3328:     }
 3329:     if( wantarray ) {
 3330: 	return @preferred_possibilities;
 3331:     }
 3332:     return $preferred_possibilities[0];
 3333: }
 3334: 
 3335: sub user_lang {
 3336:     my ($touname,$toudom,$fromcid) = @_;
 3337:     my @userlangs;
 3338:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3339:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3340:                     $env{'course.'.$fromcid.'.languages'}));
 3341:     } else {
 3342:         my %langhash = &getlangs($touname,$toudom);
 3343:         if ($langhash{'languages'} ne '') {
 3344:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3345:         } else {
 3346:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3347:             if ($domdefs{'lang_def'} ne '') {
 3348:                 @userlangs = ($domdefs{'lang_def'});
 3349:             }
 3350:         }
 3351:     }
 3352:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3353:     my $user_lh = Apache::localize->get_handle(@languages);
 3354:     return $user_lh;
 3355: }
 3356: 
 3357: 
 3358: ###############################################################
 3359: ##               Student Answer Attempts                     ##
 3360: ###############################################################
 3361: 
 3362: =pod
 3363: 
 3364: =head1 Alternate Problem Views
 3365: 
 3366: =over 4
 3367: 
 3368: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3369:     $getattempt, $regexp, $gradesub)
 3370: 
 3371: Return string with previous attempt on problem. Arguments:
 3372: 
 3373: =over 4
 3374: 
 3375: =item * $symb: Problem, including path
 3376: 
 3377: =item * $username: username of the desired student
 3378: 
 3379: =item * $domain: domain of the desired student
 3380: 
 3381: =item * $course: Course ID
 3382: 
 3383: =item * $getattempt: Leave blank for all attempts, otherwise put
 3384:     something
 3385: 
 3386: =item * $regexp: if string matches this regexp, the string will be
 3387:     sent to $gradesub
 3388: 
 3389: =item * $gradesub: routine that processes the string if it matches $regexp
 3390: 
 3391: =back
 3392: 
 3393: The output string is a table containing all desired attempts, if any.
 3394: 
 3395: =cut
 3396: 
 3397: sub get_previous_attempt {
 3398:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3399:   my $prevattempts='';
 3400:   no strict 'refs';
 3401:   if ($symb) {
 3402:     my (%returnhash)=
 3403:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3404:     if ($returnhash{'version'}) {
 3405:       my %lasthash=();
 3406:       my $version;
 3407:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3408:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3409: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3410:         }
 3411:       }
 3412:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3413:       $prevattempts.='<th>'.&mt('History').'</th>';
 3414:       my (%typeparts,%lasthidden);
 3415:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3416:       foreach my $key (sort(keys(%lasthash))) {
 3417: 	my ($ign,@parts) = split(/\./,$key);
 3418: 	if ($#parts > 0) {
 3419: 	  my $data=$parts[-1];
 3420: 	  pop(@parts);
 3421:           if ($data eq 'type') {
 3422:               unless ($showsurv) {
 3423:                   my $id = join(',',@parts);
 3424:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3425:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3426:                       $lasthidden{$ign.'.'.$id} = 1;
 3427:                   }
 3428:               }
 3429:               delete($lasthash{$key});
 3430:           } else {
 3431: 	      $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3432:           }
 3433: 	} else {
 3434: 	  if ($#parts == 0) {
 3435: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3436: 	  } else {
 3437: 	    $prevattempts.='<th>'.$ign.'</th>';
 3438: 	  }
 3439: 	}
 3440:       }
 3441:       $prevattempts.=&end_data_table_header_row();
 3442:       if ($getattempt eq '') {
 3443: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3444:             my @hidden;
 3445:             if (%typeparts) {
 3446:                 foreach my $id (keys(%typeparts)) {
 3447:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3448:                         push(@hidden,$id);
 3449:                     }
 3450:                 }
 3451:             }
 3452:             $prevattempts.=&start_data_table_row().
 3453:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3454:             if (@hidden) {
 3455:                 foreach my $key (sort(keys(%lasthash))) {
 3456:                     my $hide;
 3457:                     foreach my $id (@hidden) {
 3458:                         if ($key =~ /^\Q$id\E/) {
 3459:                             $hide = 1;
 3460:                             last;
 3461:                         }
 3462:                     }
 3463:                     if ($hide) {
 3464:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3465:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3466:                             my $value = &format_previous_attempt_value($key,
 3467:                                              $returnhash{$version.':'.$key});
 3468:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3469:                         } else {
 3470:                             $prevattempts.='<td>&nbsp;</td>';
 3471:                         }
 3472:                     } else {
 3473:                         if ($key =~ /\./) {
 3474:                             my $value = &format_previous_attempt_value($key,
 3475:                                               $returnhash{$version.':'.$key});
 3476:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3477:                         } else {
 3478:                             $prevattempts.='<td>&nbsp;</td>';
 3479:                         }
 3480:                     }
 3481:                 }
 3482:             } else {
 3483: 	        foreach my $key (sort(keys(%lasthash))) {
 3484: 		    my $value = &format_previous_attempt_value($key,
 3485: 			            $returnhash{$version.':'.$key});
 3486: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3487: 	        }
 3488:             }
 3489: 	    $prevattempts.=&end_data_table_row();
 3490: 	 }
 3491:       }
 3492:       my @currhidden = keys(%lasthidden);
 3493:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3494:       foreach my $key (sort(keys(%lasthash))) {
 3495:           if (%typeparts) {
 3496:               my $hidden;
 3497:               foreach my $id (@currhidden) {
 3498:                   if ($key =~ /^\Q$id\E/) {
 3499:                       $hidden = 1;
 3500:                       last;
 3501:                   }
 3502:               }
 3503:               if ($hidden) {
 3504:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3505:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3506:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3507:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3508:                           $value = &$gradesub($value);
 3509:                       }
 3510:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3511:                   } else {
 3512:                       $prevattempts.='<td>&nbsp;</td>';
 3513:                   }
 3514:               } else {
 3515:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3516:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3517:                       $value = &$gradesub($value);
 3518:                   }
 3519:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3520:               }
 3521:           } else {
 3522: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3523: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3524:                   $value = &$gradesub($value);
 3525:               }
 3526: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3527:           }
 3528:       }
 3529:       $prevattempts.= &end_data_table_row().&end_data_table();
 3530:     } else {
 3531:       $prevattempts=
 3532: 	  &start_data_table().&start_data_table_row().
 3533: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3534: 	  &end_data_table_row().&end_data_table();
 3535:     }
 3536:   } else {
 3537:     $prevattempts=
 3538: 	  &start_data_table().&start_data_table_row().
 3539: 	  '<td>'.&mt('No data.').'</td>'.
 3540: 	  &end_data_table_row().&end_data_table();
 3541:   }
 3542: }
 3543: 
 3544: sub format_previous_attempt_value {
 3545:     my ($key,$value) = @_;
 3546:     if ($key =~ /timestamp/) {
 3547: 	$value = &Apache::lonlocal::locallocaltime($value);
 3548:     } elsif (ref($value) eq 'ARRAY') {
 3549: 	$value = '('.join(', ', @{ $value }).')';
 3550:     } else {
 3551: 	$value = &unescape($value);
 3552:     }
 3553:     return $value;
 3554: }
 3555: 
 3556: 
 3557: sub relative_to_absolute {
 3558:     my ($url,$output)=@_;
 3559:     my $parser=HTML::TokeParser->new(\$output);
 3560:     my $token;
 3561:     my $thisdir=$url;
 3562:     my @rlinks=();
 3563:     while ($token=$parser->get_token) {
 3564: 	if ($token->[0] eq 'S') {
 3565: 	    if ($token->[1] eq 'a') {
 3566: 		if ($token->[2]->{'href'}) {
 3567: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3568: 		}
 3569: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3570: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3571: 	    } elsif ($token->[1] eq 'base') {
 3572: 		$thisdir=$token->[2]->{'href'};
 3573: 	    }
 3574: 	}
 3575:     }
 3576:     $thisdir=~s-/[^/]*$--;
 3577:     foreach my $link (@rlinks) {
 3578: 	unless (($link=~/^https?\:\/\//i) ||
 3579: 		($link=~/^\//) ||
 3580: 		($link=~/^javascript:/i) ||
 3581: 		($link=~/^mailto:/i) ||
 3582: 		($link=~/^\#/)) {
 3583: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3584: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3585: 	}
 3586:     }
 3587: # -------------------------------------------------- Deal with Applet codebases
 3588:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3589:     return $output;
 3590: }
 3591: 
 3592: =pod
 3593: 
 3594: =item * &get_student_view()
 3595: 
 3596: show a snapshot of what student was looking at
 3597: 
 3598: =cut
 3599: 
 3600: sub get_student_view {
 3601:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3602:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3603:   my (%form);
 3604:   my @elements=('symb','courseid','domain','username');
 3605:   foreach my $element (@elements) {
 3606:       $form{'grade_'.$element}=eval '$'.$element #'
 3607:   }
 3608:   if (defined($moreenv)) {
 3609:       %form=(%form,%{$moreenv});
 3610:   }
 3611:   if (defined($target)) { $form{'grade_target'} = $target; }
 3612:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3613:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3614:   $userview=~s/\<body[^\>]*\>//gi;
 3615:   $userview=~s/\<\/body\>//gi;
 3616:   $userview=~s/\<html\>//gi;
 3617:   $userview=~s/\<\/html\>//gi;
 3618:   $userview=~s/\<head\>//gi;
 3619:   $userview=~s/\<\/head\>//gi;
 3620:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3621:   $userview=&relative_to_absolute($feedurl,$userview);
 3622:   if (wantarray) {
 3623:      return ($userview,$response);
 3624:   } else {
 3625:      return $userview;
 3626:   }
 3627: }
 3628: 
 3629: sub get_student_view_with_retries {
 3630:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3631: 
 3632:     my $ok = 0;                 # True if we got a good response.
 3633:     my $content;
 3634:     my $response;
 3635: 
 3636:     # Try to get the student_view done. within the retries count:
 3637:     
 3638:     do {
 3639:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3640:          $ok      = $response->is_success;
 3641:          if (!$ok) {
 3642:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3643:          }
 3644:          $retries--;
 3645:     } while (!$ok && ($retries > 0));
 3646:     
 3647:     if (!$ok) {
 3648:        $content = '';          # On error return an empty content.
 3649:     }
 3650:     if (wantarray) {
 3651:        return ($content, $response);
 3652:     } else {
 3653:        return $content;
 3654:     }
 3655: }
 3656: 
 3657: =pod
 3658: 
 3659: =item * &get_student_answers() 
 3660: 
 3661: show a snapshot of how student was answering problem
 3662: 
 3663: =cut
 3664: 
 3665: sub get_student_answers {
 3666:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3667:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3668:   my (%moreenv);
 3669:   my @elements=('symb','courseid','domain','username');
 3670:   foreach my $element (@elements) {
 3671:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3672:   }
 3673:   $moreenv{'grade_target'}='answer';
 3674:   %moreenv=(%form,%moreenv);
 3675:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3676:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3677:   return $userview;
 3678: }
 3679: 
 3680: =pod
 3681: 
 3682: =item * &submlink()
 3683: 
 3684: Inputs: $text $uname $udom $symb $target
 3685: 
 3686: Returns: A link to grades.pm such as to see the SUBM view of a student
 3687: 
 3688: =cut
 3689: 
 3690: ###############################################
 3691: sub submlink {
 3692:     my ($text,$uname,$udom,$symb,$target)=@_;
 3693:     if (!($uname && $udom)) {
 3694: 	(my $cursymb, my $courseid,$udom,$uname)=
 3695: 	    &Apache::lonnet::whichuser($symb);
 3696: 	if (!$symb) { $symb=$cursymb; }
 3697:     }
 3698:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3699:     $symb=&escape($symb);
 3700:     if ($target) { $target=" target=\"$target\""; }
 3701:     return
 3702:         '<a href="/adm/grades?command=submission'.
 3703:         '&amp;symb='.$symb.
 3704:         '&amp;student='.$uname.
 3705:         '&amp;userdom='.$udom.'"'.
 3706:         $target.'>'.$text.'</a>';
 3707: }
 3708: ##############################################
 3709: 
 3710: =pod
 3711: 
 3712: =item * &pgrdlink()
 3713: 
 3714: Inputs: $text $uname $udom $symb $target
 3715: 
 3716: Returns: A link to grades.pm such as to see the PGRD view of a student
 3717: 
 3718: =cut
 3719: 
 3720: ###############################################
 3721: sub pgrdlink {
 3722:     my $link=&submlink(@_);
 3723:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3724:     return $link;
 3725: }
 3726: ##############################################
 3727: 
 3728: =pod
 3729: 
 3730: =item * &pprmlink()
 3731: 
 3732: Inputs: $text $uname $udom $symb $target
 3733: 
 3734: Returns: A link to parmset.pm such as to see the PPRM view of a
 3735: student and a specific resource
 3736: 
 3737: =cut
 3738: 
 3739: ###############################################
 3740: sub pprmlink {
 3741:     my ($text,$uname,$udom,$symb,$target)=@_;
 3742:     if (!($uname && $udom)) {
 3743: 	(my $cursymb, my $courseid,$udom,$uname)=
 3744: 	    &Apache::lonnet::whichuser($symb);
 3745: 	if (!$symb) { $symb=$cursymb; }
 3746:     }
 3747:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3748:     $symb=&escape($symb);
 3749:     if ($target) { $target="target=\"$target\""; }
 3750:     return '<a href="/adm/parmset?command=set&amp;'.
 3751: 	'symb='.$symb.'&amp;uname='.$uname.
 3752: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3753: }
 3754: ##############################################
 3755: 
 3756: =pod
 3757: 
 3758: =back
 3759: 
 3760: =cut
 3761: 
 3762: ###############################################
 3763: 
 3764: 
 3765: sub timehash {
 3766:     my ($thistime) = @_;
 3767:     my $timezone = &Apache::lonlocal::gettimezone();
 3768:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3769:                      ->set_time_zone($timezone);
 3770:     my $wday = $dt->day_of_week();
 3771:     if ($wday == 7) { $wday = 0; }
 3772:     return ( 'second' => $dt->second(),
 3773:              'minute' => $dt->minute(),
 3774:              'hour'   => $dt->hour(),
 3775:              'day'     => $dt->day_of_month(),
 3776:              'month'   => $dt->month(),
 3777:              'year'    => $dt->year(),
 3778:              'weekday' => $wday,
 3779:              'dayyear' => $dt->day_of_year(),
 3780:              'dlsav'   => $dt->is_dst() );
 3781: }
 3782: 
 3783: sub utc_string {
 3784:     my ($date)=@_;
 3785:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3786: }
 3787: 
 3788: sub maketime {
 3789:     my %th=@_;
 3790:     my ($epoch_time,$timezone,$dt);
 3791:     $timezone = &Apache::lonlocal::gettimezone();
 3792:     eval {
 3793:         $dt = DateTime->new( year   => $th{'year'},
 3794:                              month  => $th{'month'},
 3795:                              day    => $th{'day'},
 3796:                              hour   => $th{'hour'},
 3797:                              minute => $th{'minute'},
 3798:                              second => $th{'second'},
 3799:                              time_zone => $timezone,
 3800:                          );
 3801:     };
 3802:     if (!$@) {
 3803:         $epoch_time = $dt->epoch;
 3804:         if ($epoch_time) {
 3805:             return $epoch_time;
 3806:         }
 3807:     }
 3808:     return POSIX::mktime(
 3809:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3810:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3811: }
 3812: 
 3813: #########################################
 3814: 
 3815: sub findallcourses {
 3816:     my ($roles,$uname,$udom) = @_;
 3817:     my %roles;
 3818:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3819:     my %courses;
 3820:     my $now=time;
 3821:     if (!defined($uname)) {
 3822:         $uname = $env{'user.name'};
 3823:     }
 3824:     if (!defined($udom)) {
 3825:         $udom = $env{'user.domain'};
 3826:     }
 3827:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3828:         my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 3829:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,
 3830:                                               $extra);
 3831:         if (!%roles) {
 3832:             %roles = (
 3833:                        cc => 1,
 3834:                        co => 1,
 3835:                        in => 1,
 3836:                        ep => 1,
 3837:                        ta => 1,
 3838:                        cr => 1,
 3839:                        st => 1,
 3840:              );
 3841:         }
 3842:         foreach my $entry (keys(%roleshash)) {
 3843:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3844:             if ($trole =~ /^cr/) { 
 3845:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3846:             } else {
 3847:                 next if (!exists($roles{$trole}));
 3848:             }
 3849:             if ($tend) {
 3850:                 next if ($tend < $now);
 3851:             }
 3852:             if ($tstart) {
 3853:                 next if ($tstart > $now);
 3854:             }
 3855:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3856:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3857:             if ($secpart eq '') {
 3858:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3859:                 $sec = 'none';
 3860:                 $realsec = '';
 3861:             } else {
 3862:                 $cnum = $cnumpart;
 3863:                 ($sec,$role) = split(/_/,$secpart);
 3864:                 $realsec = $sec;
 3865:             }
 3866:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3867:         }
 3868:     } else {
 3869:         foreach my $key (keys(%env)) {
 3870: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3871:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3872: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3873: 	        next if ($role eq 'ca' || $role eq 'aa');
 3874: 	        next if (%roles && !exists($roles{$role}));
 3875: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3876:                 my $active=1;
 3877:                 if ($starttime) {
 3878: 		    if ($now<$starttime) { $active=0; }
 3879:                 }
 3880:                 if ($endtime) {
 3881:                     if ($now>$endtime) { $active=0; }
 3882:                 }
 3883:                 if ($active) {
 3884:                     if ($sec eq '') {
 3885:                         $sec = 'none';
 3886:                     }
 3887:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3888:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3889:                 }
 3890:             }
 3891:         }
 3892:     }
 3893:     return %courses;
 3894: }
 3895: 
 3896: ###############################################
 3897: 
 3898: sub blockcheck {
 3899:     my ($setters,$activity,$uname,$udom) = @_;
 3900: 
 3901:     if (!defined($udom)) {
 3902:         $udom = $env{'user.domain'};
 3903:     }
 3904:     if (!defined($uname)) {
 3905:         $uname = $env{'user.name'};
 3906:     }
 3907: 
 3908:     # If uname and udom are for a course, check for blocks in the course.
 3909: 
 3910:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3911:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3912:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3913:         return ($startblock,$endblock);
 3914:     }
 3915: 
 3916:     my $startblock = 0;
 3917:     my $endblock = 0;
 3918:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3919: 
 3920:     # If uname is for a user, and activity is course-specific, i.e.,
 3921:     # boards, chat or groups, check for blocking in current course only.
 3922: 
 3923:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3924:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3925:         foreach my $key (keys(%live_courses)) {
 3926:             if ($key ne $env{'request.course.id'}) {
 3927:                 delete($live_courses{$key});
 3928:             }
 3929:         }
 3930:     }
 3931: 
 3932:     my $otheruser = 0;
 3933:     my %own_courses;
 3934:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3935:         # Resource belongs to user other than current user.
 3936:         $otheruser = 1;
 3937:         # Gather courses for current user
 3938:         %own_courses = 
 3939:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3940:     }
 3941: 
 3942:     # Gather active course roles - course coordinator, instructor, 
 3943:     # exam proctor, ta, student, or custom role.
 3944: 
 3945:     foreach my $course (keys(%live_courses)) {
 3946:         my ($cdom,$cnum);
 3947:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3948:             $cdom = $env{'course.'.$course.'.domain'};
 3949:             $cnum = $env{'course.'.$course.'.num'};
 3950:         } else {
 3951:             ($cdom,$cnum) = split(/_/,$course); 
 3952:         }
 3953:         my $no_ownblock = 0;
 3954:         my $no_userblock = 0;
 3955:         if ($otheruser && $activity ne 'com') {
 3956:             # Check if current user has 'evb' priv for this
 3957:             if (defined($own_courses{$course})) {
 3958:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3959:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3960:                     if ($sec ne 'none') {
 3961:                         $checkrole .= '/'.$sec;
 3962:                     }
 3963:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3964:                         $no_ownblock = 1;
 3965:                         last;
 3966:                     }
 3967:                 }
 3968:             }
 3969:             # if they have 'evb' priv and are currently not playing student
 3970:             next if (($no_ownblock) &&
 3971:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3972:         }
 3973:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3974:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3975:             if ($sec ne 'none') {
 3976:                 $checkrole .= '/'.$sec;
 3977:             }
 3978:             if ($otheruser) {
 3979:                 # Resource belongs to user other than current user.
 3980:                 # Assemble privs for that user, and check for 'evb' priv.
 3981:                 my ($trole,$tdom,$tnum,$tsec);
 3982:                 my $entry = $live_courses{$course}{$sec};
 3983:                 if ($entry =~ /^cr/) {
 3984:                     ($trole,$tdom,$tnum,$tsec) = 
 3985:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3986:                 } else {
 3987:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3988:                 }
 3989:                 my ($spec,$area,$trest,%allroles,%userroles);
 3990:                 $area = '/'.$tdom.'/'.$tnum;
 3991:                 $trest = $tnum;
 3992:                 if ($tsec ne '') {
 3993:                     $area .= '/'.$tsec;
 3994:                     $trest .= '/'.$tsec;
 3995:                 }
 3996:                 $spec = $trole.'.'.$area;
 3997:                 if ($trole =~ /^cr/) {
 3998:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3999:                                                       $tdom,$spec,$trest,$area);
 4000:                 } else {
 4001:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4002:                                                        $tdom,$spec,$trest,$area);
 4003:                 }
 4004:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4005:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4006:                     if ($1) {
 4007:                         $no_userblock = 1;
 4008:                         last;
 4009:                     }
 4010:                 }
 4011:             } else {
 4012:                 # Resource belongs to current user
 4013:                 # Check for 'evb' priv via lonnet::allowed().
 4014:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4015:                     $no_ownblock = 1;
 4016:                     last;
 4017:                 }
 4018:             }
 4019:         }
 4020:         # if they have the evb priv and are currently not playing student
 4021:         next if (($no_ownblock) &&
 4022:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4023:         next if ($no_userblock);
 4024: 
 4025:         # Retrieve blocking times and identity of locker for course
 4026:         # of specified user, unless user has 'evb' privilege.
 4027:         
 4028:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 4029:         if (($start != 0) && 
 4030:             (($startblock == 0) || ($startblock > $start))) {
 4031:             $startblock = $start;
 4032:         }
 4033:         if (($end != 0)  &&
 4034:             (($endblock == 0) || ($endblock < $end))) {
 4035:             $endblock = $end;
 4036:         }
 4037:     }
 4038:     return ($startblock,$endblock);
 4039: }
 4040: 
 4041: sub get_blocks {
 4042:     my ($setters,$activity,$cdom,$cnum) = @_;
 4043:     my $startblock = 0;
 4044:     my $endblock = 0;
 4045:     my $course = $cdom.'_'.$cnum;
 4046:     $setters->{$course} = {};
 4047:     $setters->{$course}{'staff'} = [];
 4048:     $setters->{$course}{'times'} = [];
 4049:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 4050:     foreach my $record (keys(%records)) {
 4051:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 4052:         if ($start <= time && $end >= time) {
 4053:             my ($staff_name,$staff_dom,$title,$blocks) =
 4054:                 &parse_block_record($records{$record});
 4055:             if ($blocks->{$activity} eq 'on') {
 4056:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4057:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4058:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 4059:                     $startblock = $start;
 4060:                 }
 4061:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 4062:                     $endblock = $end;
 4063:                 }
 4064:             }
 4065:         }
 4066:     }
 4067:     return ($startblock,$endblock);
 4068: }
 4069: 
 4070: sub parse_block_record {
 4071:     my ($record) = @_;
 4072:     my ($setuname,$setudom,$title,$blocks);
 4073:     if (ref($record) eq 'HASH') {
 4074:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4075:         $title = &unescape($record->{'event'});
 4076:         $blocks = $record->{'blocks'};
 4077:     } else {
 4078:         my @data = split(/:/,$record,3);
 4079:         if (scalar(@data) eq 2) {
 4080:             $title = $data[1];
 4081:             ($setuname,$setudom) = split(/@/,$data[0]);
 4082:         } else {
 4083:             ($setuname,$setudom,$title) = @data;
 4084:         }
 4085:         $blocks = { 'com' => 'on' };
 4086:     }
 4087:     return ($setuname,$setudom,$title,$blocks);
 4088: }
 4089: 
 4090: sub blocking_status {
 4091:   my ($activity,$uname,$udom) = @_;
 4092:   my %setters;
 4093: 
 4094:   # check for active blocking
 4095:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 4096: 
 4097:   my $blocked = $startblock && $endblock ? 1 : 0;
 4098: 
 4099:   # caller just wants to know whether a block is active
 4100:   if (!wantarray) { return $blocked; }
 4101: 
 4102:   # build a link to a popup window containing the details
 4103:   my $querystring  = "?activity=$activity";
 4104:   # $uname and $udom decide whose portfolio the user is trying to look at
 4105:      $querystring .= "&amp;udom=$udom"      if $udom;
 4106:      $querystring .= "&amp;uname=$uname"    if $uname;
 4107: 
 4108:   my $output .= <<'END_MYBLOCK';
 4109:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4110:         var options = "width=" + w + ",height=" + h + ",";
 4111:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4112:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4113:         var newWin = window.open(url, wdwName, options);
 4114:         newWin.focus();
 4115:     }
 4116: END_MYBLOCK
 4117: 
 4118:   $output = Apache::lonhtmlcommon::scripttag($output);
 4119:   
 4120:   my $popupUrl = "/adm/blockingstatus/$querystring";
 4121:   my $text = mt('Communication Blocked');
 4122: 
 4123:   $output .= <<"END_BLOCK";
 4124: <div class='LC_comblock'>
 4125:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4126:   title='$text'>
 4127:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4128:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4129:   title='$text'>$text</a>
 4130: </div>
 4131: 
 4132: END_BLOCK
 4133: 
 4134:   return ($blocked, $output);
 4135: }
 4136: 
 4137: ###############################################
 4138: 
 4139: sub check_ip_acc {
 4140:     my ($acc)=@_;
 4141:     &Apache::lonxml::debug("acc is $acc");
 4142:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4143:         return 1;
 4144:     }
 4145:     my $allowed=0;
 4146:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4147: 
 4148:     my $name;
 4149:     foreach my $pattern (split(',',$acc)) {
 4150:         $pattern =~ s/^\s*//;
 4151:         $pattern =~ s/\s*$//;
 4152:         if ($pattern =~ /\*$/) {
 4153:             #35.8.*
 4154:             $pattern=~s/\*//;
 4155:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4156:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4157:             #35.8.3.[34-56]
 4158:             my $low=$2;
 4159:             my $high=$3;
 4160:             $pattern=$1;
 4161:             if ($ip =~ /^\Q$pattern\E/) {
 4162:                 my $last=(split(/\./,$ip))[3];
 4163:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4164:             }
 4165:         } elsif ($pattern =~ /^\*/) {
 4166:             #*.msu.edu
 4167:             $pattern=~s/\*//;
 4168:             if (!defined($name)) {
 4169:                 use Socket;
 4170:                 my $netaddr=inet_aton($ip);
 4171:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4172:             }
 4173:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4174:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4175:             #127.0.0.1
 4176:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4177:         } else {
 4178:             #some.name.com
 4179:             if (!defined($name)) {
 4180:                 use Socket;
 4181:                 my $netaddr=inet_aton($ip);
 4182:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4183:             }
 4184:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4185:         }
 4186:         if ($allowed) { last; }
 4187:     }
 4188:     return $allowed;
 4189: }
 4190: 
 4191: ###############################################
 4192: 
 4193: =pod
 4194: 
 4195: =head1 Domain Template Functions
 4196: 
 4197: =over 4
 4198: 
 4199: =item * &determinedomain()
 4200: 
 4201: Inputs: $domain (usually will be undef)
 4202: 
 4203: Returns: Determines which domain should be used for designs
 4204: 
 4205: =cut
 4206: 
 4207: ###############################################
 4208: sub determinedomain {
 4209:     my $domain=shift;
 4210:     if (! $domain) {
 4211:         # Determine domain if we have not been given one
 4212:         $domain = &Apache::lonnet::default_login_domain();
 4213:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4214:         if ($env{'request.role.domain'}) { 
 4215:             $domain=$env{'request.role.domain'}; 
 4216:         }
 4217:     }
 4218:     return $domain;
 4219: }
 4220: ###############################################
 4221: 
 4222: sub devalidate_domconfig_cache {
 4223:     my ($udom)=@_;
 4224:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4225: }
 4226: 
 4227: # ---------------------- Get domain configuration for a domain
 4228: sub get_domainconf {
 4229:     my ($udom) = @_;
 4230:     my $cachetime=1800;
 4231:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4232:     if (defined($cached)) { return %{$result}; }
 4233: 
 4234:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4235: 					     ['login','rolecolors','autoenroll'],$udom);
 4236:     my (%designhash,%legacy);
 4237:     if (keys(%domconfig) > 0) {
 4238:         if (ref($domconfig{'login'}) eq 'HASH') {
 4239:             if (keys(%{$domconfig{'login'}})) {
 4240:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4241:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4242:                         if ($key eq 'loginvia') {
 4243:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4244:                                 my @ids = &Apache::lonnet::current_machine_ids();
 4245:                                 foreach my $hostname (@ids) {
 4246:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4247:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4248:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4249:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4250:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4251: 
 4252:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4253:                                             } else {
 4254:                                                  $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4255:                                             }
 4256:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4257:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4258:                                             }
 4259:                                         }
 4260:                                     }
 4261:                                 }
 4262:                             }
 4263:                         } else {
 4264:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4265:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4266:                                     $domconfig{'login'}{$key}{$img};
 4267:                             }
 4268:                         }
 4269:                     } else {
 4270:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4271:                     }
 4272:                 }
 4273:             } else {
 4274:                 $legacy{'login'} = 1;
 4275:             }
 4276:         } else {
 4277:             $legacy{'login'} = 1;
 4278:         }
 4279:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4280:             if (keys(%{$domconfig{'rolecolors'}})) {
 4281:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4282:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4283:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4284:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4285:                         }
 4286:                     }
 4287:                 }
 4288:             } else {
 4289:                 $legacy{'rolecolors'} = 1;
 4290:             }
 4291:         } else {
 4292:             $legacy{'rolecolors'} = 1;
 4293:         }
 4294:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4295:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4296:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4297:             }
 4298:         }
 4299:         if (keys(%legacy) > 0) {
 4300:             my %legacyhash = &get_legacy_domconf($udom);
 4301:             foreach my $item (keys(%legacyhash)) {
 4302:                 if ($item =~ /^\Q$udom\E\.login/) {
 4303:                     if ($legacy{'login'}) { 
 4304:                         $designhash{$item} = $legacyhash{$item};
 4305:                     }
 4306:                 } else {
 4307:                     if ($legacy{'rolecolors'}) {
 4308:                         $designhash{$item} = $legacyhash{$item};
 4309:                     }
 4310:                 }
 4311:             }
 4312:         }
 4313:     } else {
 4314:         %designhash = &get_legacy_domconf($udom); 
 4315:     }
 4316:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4317: 				  $cachetime);
 4318:     return %designhash;
 4319: }
 4320: 
 4321: sub get_legacy_domconf {
 4322:     my ($udom) = @_;
 4323:     my %legacyhash;
 4324:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4325:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4326:     if (-e $designfile) {
 4327:         if ( open (my $fh,"<$designfile") ) {
 4328:             while (my $line = <$fh>) {
 4329:                 next if ($line =~ /^\#/);
 4330:                 chomp($line);
 4331:                 my ($key,$val)=(split(/\=/,$line));
 4332:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4333:             }
 4334:             close($fh);
 4335:         }
 4336:     }
 4337:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4338:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4339:     }
 4340:     return %legacyhash;
 4341: }
 4342: 
 4343: =pod
 4344: 
 4345: =item * &domainlogo()
 4346: 
 4347: Inputs: $domain (usually will be undef)
 4348: 
 4349: Returns: A link to a domain logo, if the domain logo exists.
 4350: If the domain logo does not exist, a description of the domain.
 4351: 
 4352: =cut
 4353: 
 4354: ###############################################
 4355: sub domainlogo {
 4356:     my $domain = &determinedomain(shift);
 4357:     my %designhash = &get_domainconf($domain);    
 4358:     # See if there is a logo
 4359:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4360:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4361:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4362: 	    if ($imgsrc =~ m{^/res/}) {
 4363: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4364: 		&Apache::lonnet::repcopy($local_name);
 4365: 	    }
 4366: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4367:         } 
 4368:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4369:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4370:         return &Apache::lonnet::domain($domain,'description');
 4371:     } else {
 4372:         return '';
 4373:     }
 4374: }
 4375: ##############################################
 4376: 
 4377: =pod
 4378: 
 4379: =item * &designparm()
 4380: 
 4381: Inputs: $which parameter; $domain (usually will be undef)
 4382: 
 4383: Returns: value of designparamter $which
 4384: 
 4385: =cut
 4386: 
 4387: 
 4388: ##############################################
 4389: sub designparm {
 4390:     my ($which,$domain)=@_;
 4391:     if (exists($env{'environment.color.'.$which})) {
 4392:         return $env{'environment.color.'.$which};
 4393:     }
 4394:     $domain=&determinedomain($domain);
 4395:     my %domdesign = &get_domainconf($domain);
 4396:     my $output;
 4397:     if ($domdesign{$domain.'.'.$which} ne '') {
 4398:         $output = $domdesign{$domain.'.'.$which};
 4399:     } else {
 4400:         $output = $defaultdesign{$which};
 4401:     }
 4402:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4403:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4404:         if ($output =~ m{^/(adm|res)/}) {
 4405:             if ($output =~ m{^/res/}) {
 4406:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4407:                 &Apache::lonnet::repcopy($local_name);
 4408:             }
 4409:             $output = &lonhttpdurl($output);
 4410:         }
 4411:     }
 4412:     return $output;
 4413: }
 4414: 
 4415: ##############################################
 4416: =pod
 4417: 
 4418: =item * &authorspace()
 4419: 
 4420: Inputs: ./.
 4421: 
 4422: Returns: Path to the Construction Space of the current user's
 4423:          accessed author space
 4424:          The author space will be that of the current user
 4425:          when accessing the own author space
 4426:          and that of the co-author/assistent co-author
 4427:          when accessing the co-author's/assistent co-author's
 4428:          space
 4429: 
 4430: =cut
 4431: 
 4432: sub authorspace {
 4433:     my $caname = '';
 4434:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4435:         (undef,$caname) =
 4436:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4437:     } else {
 4438:         $caname = $env{'user.name'};
 4439:     }
 4440:     return '/priv/'.$caname.'/';
 4441: }
 4442: 
 4443: ##############################################
 4444: =pod
 4445: 
 4446: =item * &head_subbox()
 4447: 
 4448: Inputs: $content (contains HTML code with page functions, etc.)
 4449: 
 4450: Returns: HTML div with $content
 4451:          To be included in page header
 4452: 
 4453: =cut
 4454: 
 4455: sub head_subbox {
 4456:     my ($content)=@_;
 4457:     my $output =
 4458:         '<div id="LC_head_subbox">'
 4459:        .$content
 4460:        .'</div>'
 4461: }
 4462: 
 4463: ##############################################
 4464: =pod
 4465: 
 4466: =item * &CSTR_pageheader()
 4467: 
 4468: Inputs: ./.
 4469: 
 4470: Returns: HTML div with CSTR path and recent box
 4471:          To be included on Construction Space pages
 4472: 
 4473: =cut
 4474: 
 4475: sub CSTR_pageheader {
 4476:     # this is for resources; directories have customtitle, and crumbs
 4477:             # and select recent are created in lonpubdir.pm  
 4478:     my ($uname,$thisdisfn)=
 4479:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4480:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4481:     $formaction=~s/\/+/\//g;
 4482: 
 4483:     my $parentpath = '';
 4484:     my $lastitem = '';
 4485:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4486:         $parentpath = $1;
 4487:         $lastitem = $2;
 4488:     } else {
 4489:         $lastitem = $thisdisfn;
 4490:     }
 4491: 
 4492:     my $output =
 4493:          '<div>'
 4494:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4495:         .'<b>'.&mt('Construction Space:').'</b> '
 4496:         .'<form name="dirs" method="post" action="'.$formaction
 4497:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 4498:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv',undef,undef);
 4499: 
 4500:     if ($lastitem) {
 4501:         $output .=
 4502:              '<span class="LC_filename">'
 4503:             .$lastitem
 4504:             .'</span>';
 4505:     }
 4506:     $output .=
 4507:          '<br />'
 4508:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4509:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4510:         .'</form>'
 4511:         .&Apache::lonmenu::constspaceform()
 4512:         .'</div>';
 4513: 
 4514:     return $output;
 4515: }
 4516: 
 4517: ###############################################
 4518: ###############################################
 4519: 
 4520: =pod
 4521: 
 4522: =back
 4523: 
 4524: =head1 HTML Helpers
 4525: 
 4526: =over 4
 4527: 
 4528: =item * &bodytag()
 4529: 
 4530: Returns a uniform header for LON-CAPA web pages.
 4531: 
 4532: Inputs: 
 4533: 
 4534: =over 4
 4535: 
 4536: =item * $title, A title to be displayed on the page.
 4537: 
 4538: =item * $function, the current role (can be undef).
 4539: 
 4540: =item * $addentries, extra parameters for the <body> tag.
 4541: 
 4542: =item * $bodyonly, if defined, only return the <body> tag.
 4543: 
 4544: =item * $domain, if defined, force a given domain.
 4545: 
 4546: =item * $forcereg, if page should register as content page (relevant for 
 4547:             text interface only)
 4548: 
 4549: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4550:                      navigational links
 4551: 
 4552: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4553: 
 4554: =item * $args, optional argument valid values are
 4555:             no_auto_mt_title -> prevents &mt()ing the title arg
 4556:             inherit_jsmath -> when creating popup window in a page,
 4557:                               should it have jsmath forced on by the
 4558:                               current page
 4559: 
 4560: =back
 4561: 
 4562: Returns: A uniform header for LON-CAPA web pages.  
 4563: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4564: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4565: other decorations will be returned.
 4566: 
 4567: =cut
 4568: 
 4569: sub bodytag {
 4570:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4571:         $no_nav_bar,$bgcolor,$args)=@_;
 4572: 
 4573:     my $public;
 4574:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 4575:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 4576:         $public = 1;
 4577:     }
 4578:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4579: 
 4580:     $function = &get_users_function() if (!$function);
 4581:     my $img =    &designparm($function.'.img',$domain);
 4582:     my $font =   &designparm($function.'.font',$domain);
 4583:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4584: 
 4585:     my %design = ( 'style'   => 'margin-top: 0',
 4586: 		   'bgcolor' => $pgbg,
 4587: 		   'text'    => $font,
 4588:                    'alink'   => &designparm($function.'.alink',$domain),
 4589: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4590: 		   'link'    => &designparm($function.'.link',$domain),);
 4591:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4592: 
 4593:  # role and realm
 4594:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4595:     if ($role  eq 'ca') {
 4596:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4597:         $realm = &plainname($rname,$rdom);
 4598:     } 
 4599: # realm
 4600:     if ($env{'request.course.id'}) {
 4601:         if ($env{'request.role'} !~ /^cr/) {
 4602:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4603:         }
 4604:         if ($env{'request.course.sec'}) {
 4605:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4606:         }   
 4607: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4608:     } else {
 4609:         $role = &Apache::lonnet::plaintext($role);
 4610:     }
 4611: 
 4612:     if (!$realm) { $realm='&nbsp;'; }
 4613: 
 4614:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4615: 
 4616: # construct main body tag
 4617:     my $bodytag = "<body $extra_body_attr>".
 4618: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4619: 
 4620:     if ($bodyonly) {
 4621:         return $bodytag;
 4622:     } 
 4623: 
 4624:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4625:     if ($public) {
 4626: 	undef($role);
 4627:     } else {
 4628: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4629:     }
 4630:     
 4631:     my $titleinfo = '<h1>'.$title.'</h1>';
 4632:     #
 4633:     # Extra info if you are the DC
 4634:     my $dc_info = '';
 4635:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4636:                         $env{'course.'.$env{'request.course.id'}.
 4637:                                  '.domain'}.'/'})) {
 4638:         my $cid = $env{'request.course.id'};
 4639:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4640:         $dc_info =~ s/\s+$//;
 4641:     }
 4642: 
 4643:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4644:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4645: 
 4646:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 4647:             return $bodytag; 
 4648:         } 
 4649: 
 4650:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 4651: 
 4652:         #    if ($env{'request.state'} eq 'construct') {
 4653:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4654:         #    }
 4655: 
 4656: 
 4657: 
 4658:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4659:              if ($dc_info) {
 4660:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 4661:              }
 4662:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4663:                 <em>$realm</em> $dc_info</div>|;
 4664:             return $bodytag;
 4665:         }
 4666: 
 4667:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 4668:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 4669:         }
 4670: 
 4671:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 4672:             Apache::lonmenu::utilityfunctions(), 'start');
 4673: 
 4674:         $bodytag .= Apache::lonmenu::primary_menu();
 4675: 
 4676:         if ($dc_info) {
 4677:             $dc_info = &dc_courseid_toggle($dc_info);
 4678:         }
 4679:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 4680: 
 4681:         #don't show menus for public users
 4682:         if (!$public){
 4683:             $bodytag .= Apache::lonmenu::secondary_menu();
 4684:             $bodytag .= Apache::lonmenu::serverform();
 4685:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 4686:             if ($env{'request.state'} eq 'construct') {
 4687:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 4688:                                 $args->{'bread_crumbs'});
 4689:             } elsif ($forcereg) { 
 4690:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
 4691:             }
 4692:         }else{
 4693:             # this is to seperate menu from content when there's no secondary
 4694:             # menu. Especially needed for public accessible ressources.
 4695:             $bodytag .= '<hr style="clear:both" />';
 4696:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4697:         }
 4698: 
 4699:         return $bodytag;
 4700: }
 4701: 
 4702: sub dc_courseid_toggle {
 4703:     my ($dc_info) = @_;
 4704:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 4705:            '<a href="javascript:showCourseID();">'.
 4706:            &mt('(More ...)').'</a></span>'.
 4707:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 4708: }
 4709: 
 4710: sub make_attr_string {
 4711:     my ($register,$attr_ref) = @_;
 4712: 
 4713:     if ($attr_ref && !ref($attr_ref)) {
 4714: 	die("addentries Must be a hash ref ".
 4715: 	    join(':',caller(1))." ".
 4716: 	    join(':',caller(0))." ");
 4717:     }
 4718: 
 4719:     if ($register) {
 4720: 	my ($on_load,$on_unload);
 4721: 	foreach my $key (keys(%{$attr_ref})) {
 4722: 	    if      (lc($key) eq 'onload') {
 4723: 		$on_load.=$attr_ref->{$key}.';';
 4724: 		delete($attr_ref->{$key});
 4725: 
 4726: 	    } elsif (lc($key) eq 'onunload') {
 4727: 		$on_unload.=$attr_ref->{$key}.';';
 4728: 		delete($attr_ref->{$key});
 4729: 	    }
 4730: 	}
 4731: 	$attr_ref->{'onload'}  = $on_load;
 4732: 	$attr_ref->{'onunload'}= $on_unload;
 4733:     }
 4734: 
 4735:     my $attr_string;
 4736:     foreach my $attr (keys(%$attr_ref)) {
 4737: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4738:     }
 4739:     return $attr_string;
 4740: }
 4741: 
 4742: 
 4743: ###############################################
 4744: ###############################################
 4745: 
 4746: =pod
 4747: 
 4748: =item * &endbodytag()
 4749: 
 4750: Returns a uniform footer for LON-CAPA web pages.
 4751: 
 4752: Inputs: 1 - optional reference to an args hash
 4753: If in the hash, key for noredirectlink has a value which evaluates to true,
 4754: a 'Continue' link is not displayed if the page contains an
 4755: internal redirect in the <head></head> section,
 4756: i.e., $env{'internal.head.redirect'} exists   
 4757: 
 4758: =cut
 4759: 
 4760: sub endbodytag {
 4761:     my ($args) = @_;
 4762:     my $endbodytag='</body>';
 4763:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4764:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4765:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4766: 	    $endbodytag=
 4767: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4768: 	        &mt('Continue').'</a>'.
 4769: 	        $endbodytag;
 4770:         }
 4771:     }
 4772:     return $endbodytag;
 4773: }
 4774: 
 4775: =pod
 4776: 
 4777: =item * &standard_css()
 4778: 
 4779: Returns a style sheet
 4780: 
 4781: Inputs: (all optional)
 4782:             domain         -> force to color decorate a page for a specific
 4783:                                domain
 4784:             function       -> force usage of a specific rolish color scheme
 4785:             bgcolor        -> override the default page bgcolor
 4786: 
 4787: =cut
 4788: 
 4789: sub standard_css {
 4790:     my ($function,$domain,$bgcolor) = @_;
 4791:     $function  = &get_users_function() if (!$function);
 4792:     my $img    = &designparm($function.'.img',   $domain);
 4793:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4794:     my $font   = &designparm($function.'.font',  $domain);
 4795:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4796: #second colour for later usage
 4797:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4798:     my $pgbg_or_bgcolor =
 4799: 	         $bgcolor ||
 4800: 	         &designparm($function.'.pgbg',  $domain);
 4801:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4802:     my $alink  = &designparm($function.'.alink', $domain);
 4803:     my $vlink  = &designparm($function.'.vlink', $domain);
 4804:     my $link   = &designparm($function.'.link',  $domain);
 4805: 
 4806:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4807:     my $mono                 = 'monospace';
 4808:     my $data_table_head      = $sidebg;
 4809:     my $data_table_light     = '#FAFAFA';
 4810:     my $data_table_dark      = '#F0F0F0';
 4811:     my $data_table_darker    = '#CCCCCC';
 4812:     my $data_table_highlight = '#FFFF00';
 4813:     my $mail_new             = '#FFBB77';
 4814:     my $mail_new_hover       = '#DD9955';
 4815:     my $mail_read            = '#BBBB77';
 4816:     my $mail_read_hover      = '#999944';
 4817:     my $mail_replied         = '#AAAA88';
 4818:     my $mail_replied_hover   = '#888855';
 4819:     my $mail_other           = '#99BBBB';
 4820:     my $mail_other_hover     = '#669999';
 4821:     my $table_header         = '#DDDDDD';
 4822:     my $feedback_link_bg     = '#BBBBBB';
 4823:     my $lg_border_color      = '#C8C8C8';
 4824:     my $button_hover         = '#BF2317';
 4825: 
 4826:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4827:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4828:                                              : '0 3px 0 4px';
 4829: 
 4830: 
 4831:     return <<END;
 4832: 
 4833: /* needed for iframe to allow 100% height in FF */
 4834: body, html { 
 4835:     margin: 0;
 4836:     padding: 0 0.5%;
 4837:     height: 99%; /* to avoid scrollbars */
 4838: }
 4839: 
 4840: body {
 4841:   font-family: $sans;
 4842:   line-height:130%;
 4843:   font-size:0.83em;
 4844:   color:$font;
 4845: }
 4846: 
 4847: a:focus,
 4848: a:focus img {
 4849:   color: red;
 4850:   background: yellow;
 4851: }
 4852: 
 4853: form, .inline {
 4854:   display: inline;
 4855: }
 4856: 
 4857: .LC_right {
 4858:   text-align:right;
 4859: }
 4860: 
 4861: .LC_middle {
 4862:   vertical-align:middle;
 4863: }
 4864: 
 4865: .LC_400Box {
 4866:   width:400px;
 4867: }
 4868: 
 4869: .LC_iframecontainer {
 4870:     width: 98%;
 4871:     margin: 0;
 4872:     position: fixed;
 4873:     top: 8.5em;
 4874:     bottom: 0;
 4875: }
 4876: 
 4877: .LC_iframecontainer iframe{
 4878:     border: none;
 4879:     width: 100%;
 4880:     height: 100%;
 4881: }
 4882: 
 4883: .LC_filename {
 4884:   font-family: $mono;
 4885:   white-space:pre;
 4886:   font-size: 120%;
 4887: }
 4888: 
 4889: .LC_fileicon {
 4890:   border: none;
 4891:   height: 1.3em;
 4892:   vertical-align: text-bottom;
 4893:   margin-right: 0.3em;
 4894:   text-decoration:none;
 4895: }
 4896: 
 4897: .LC_error {
 4898:   color: red;
 4899:   font-size: larger;
 4900: }
 4901: 
 4902: .LC_warning,
 4903: .LC_diff_removed {
 4904:   color: red;
 4905: }
 4906: 
 4907: .LC_info,
 4908: .LC_success,
 4909: .LC_diff_added {
 4910:   color: green;
 4911: }
 4912: 
 4913: div.LC_confirm_box {
 4914:   background-color: #FAFAFA;
 4915:   border: 1px solid $lg_border_color;
 4916:   margin-right: 0;
 4917:   padding: 5px;
 4918: }
 4919: 
 4920: div.LC_confirm_box .LC_error img,
 4921: div.LC_confirm_box .LC_success img {
 4922:   vertical-align: middle;
 4923: }
 4924: 
 4925: .LC_icon {
 4926:   border: none;
 4927:   vertical-align: middle;
 4928: }
 4929: 
 4930: .LC_docs_spacer {
 4931:   width: 25px;
 4932:   height: 1px;
 4933:   border: none;
 4934: }
 4935: 
 4936: .LC_internal_info {
 4937:   color: #999999;
 4938: }
 4939: 
 4940: .LC_discussion {
 4941:   background: $tabbg;
 4942:   border: 1px solid black;
 4943:   margin: 2px;
 4944: }
 4945: 
 4946: .LC_disc_action_links_bar {
 4947:   background: $tabbg;
 4948:   border: none;
 4949:   margin: 4px;
 4950: }
 4951: 
 4952: .LC_disc_action_left {
 4953:   text-align: left;
 4954: }
 4955: 
 4956: .LC_disc_action_right {
 4957:   text-align: right;
 4958: }
 4959: 
 4960: .LC_disc_new_item {
 4961:   background: white;
 4962:   border: 2px solid red;
 4963:   margin: 2px;
 4964: }
 4965: 
 4966: .LC_disc_old_item {
 4967:   background: white;
 4968:   border: 1px solid black;
 4969:   margin: 2px;
 4970: }
 4971: 
 4972: table.LC_pastsubmission {
 4973:   border: 1px solid black;
 4974:   margin: 2px;
 4975: }
 4976: 
 4977: table#LC_menubuttons {
 4978:   width: 100%;
 4979:   background: $pgbg;
 4980:   border: 2px;
 4981:   border-collapse: separate;
 4982:   padding: 0;
 4983: }
 4984: 
 4985: table#LC_title_bar a {
 4986:   color: $fontmenu;
 4987: }
 4988: 
 4989: table#LC_title_bar {
 4990:   clear: both;
 4991:   display: none;
 4992: }
 4993: 
 4994: table#LC_title_bar,
 4995: table.LC_breadcrumbs, /* obsolete? */
 4996: table#LC_title_bar.LC_with_remote {
 4997:   width: 100%;
 4998:   border-color: $pgbg;
 4999:   border-style: solid;
 5000:   border-width: $border;
 5001:   background: $pgbg;
 5002:   color: $fontmenu;
 5003:   border-collapse: collapse;
 5004:   padding: 0;
 5005:   margin: 0;
 5006: }
 5007: 
 5008: ul.LC_breadcrumb_tools_outerlist {
 5009:     margin: 0;
 5010:     padding: 0;
 5011:     position: relative;
 5012:     list-style: none;
 5013: }
 5014: ul.LC_breadcrumb_tools_outerlist li {
 5015:     display: inline;
 5016: }
 5017: 
 5018: .LC_breadcrumb_tools_navigation {
 5019:     padding: 0;
 5020:     margin: 0;
 5021:     float: left;
 5022: }
 5023: .LC_breadcrumb_tools_tools {
 5024:     padding: 0;
 5025:     margin: 0;
 5026:     float: right;
 5027: }
 5028: 
 5029: table#LC_title_bar td {
 5030:   background: $tabbg;
 5031: }
 5032: 
 5033: table#LC_menubuttons img {
 5034:   border: none;
 5035: }
 5036: 
 5037: .LC_breadcrumbs_component {
 5038:   float: right;
 5039:   margin: 0 1em;
 5040: }
 5041: .LC_breadcrumbs_component img {
 5042:   vertical-align: middle;
 5043: }
 5044: 
 5045: td.LC_table_cell_checkbox {
 5046:   text-align: center;
 5047: }
 5048: 
 5049: .LC_fontsize_small {
 5050:   font-size: 70%;
 5051: }
 5052: 
 5053: #LC_breadcrumbs {
 5054:   clear:both;
 5055:   background: $sidebg;
 5056:   border-bottom: 1px solid $lg_border_color;
 5057:   line-height: 2.5em;
 5058:   overflow: hidden;
 5059:   margin: 0;
 5060:   padding: 0;
 5061: }
 5062: 
 5063: #LC_head_subbox {
 5064:   clear:both;
 5065:   background: #F8F8F8; /* $sidebg; */
 5066:   border: 1px solid $sidebg;
 5067:   margin: 0 0 10px 0;      
 5068:   padding: 3px;
 5069: }
 5070: 
 5071: .LC_fontsize_medium {
 5072:   font-size: 85%;
 5073: }
 5074: 
 5075: .LC_fontsize_large {
 5076:   font-size: 120%;
 5077: }
 5078: 
 5079: .LC_menubuttons_inline_text {
 5080:   color: $font;
 5081:   font-size: 90%;
 5082:   padding-left:3px;
 5083: }
 5084: 
 5085: .LC_menubuttons_inline_text img{
 5086:   vertical-align: middle;
 5087: }
 5088: 
 5089: li.LC_menubuttons_inline_text img,a {
 5090:   cursor:pointer;
 5091: }
 5092: 
 5093: .LC_menubuttons_link {
 5094:   text-decoration: none;
 5095: }
 5096: 
 5097: .LC_menubuttons_category {
 5098:   color: $font;
 5099:   background: $pgbg;
 5100:   font-size: larger;
 5101:   font-weight: bold;
 5102: }
 5103: 
 5104: td.LC_menubuttons_text {
 5105:   color: $font;
 5106: }
 5107: 
 5108: .LC_current_location {
 5109:   background: $tabbg;
 5110: }
 5111: 
 5112: table.LC_data_table {
 5113:   border: 1px solid #000000;
 5114:   border-collapse: separate;
 5115:   border-spacing: 1px;
 5116:   background: $pgbg;
 5117: }
 5118: 
 5119: .LC_data_table_dense {
 5120:   font-size: small;
 5121: }
 5122: 
 5123: table.LC_nested_outer {
 5124:   border: 1px solid #000000;
 5125:   border-collapse: collapse;
 5126:   border-spacing: 0;
 5127:   width: 100%;
 5128: }
 5129: 
 5130: table.LC_innerpickbox,
 5131: table.LC_nested {
 5132:   border: none;
 5133:   border-collapse: collapse;
 5134:   border-spacing: 0;
 5135:   width: 100%;
 5136: }
 5137: 
 5138: .ui-accordion,
 5139: .ui-accordion table.LC_data_table,
 5140: .ui-accordion table.LC_nested_outer{
 5141:   border: 0px;
 5142:   border-spacing: 0px;
 5143:   margin: 3px;
 5144: }
 5145: 
 5146: table.LC_data_table tr th,
 5147: table.LC_calendar tr th,
 5148: table.LC_prior_tries tr th,
 5149: table.LC_innerpickbox tr th {
 5150:   font-weight: bold;
 5151:   background-color: $data_table_head;
 5152:   color:$fontmenu;
 5153:   font-size:90%;
 5154: }
 5155: 
 5156: table.LC_innerpickbox tr th,
 5157: table.LC_innerpickbox tr td {
 5158:   vertical-align: top;
 5159: }
 5160: 
 5161: table.LC_data_table tr.LC_info_row > td {
 5162:   background-color: #CCCCCC;
 5163:   font-weight: bold;
 5164:   text-align: left;
 5165: }
 5166: 
 5167: table.LC_data_table tr.LC_odd_row > td {
 5168:   background-color: $data_table_light;
 5169:   padding: 2px;
 5170:   vertical-align: top;
 5171: }
 5172: 
 5173: table.LC_pick_box tr > td.LC_odd_row {
 5174:   background-color: $data_table_light;
 5175:   vertical-align: top;
 5176: }
 5177: 
 5178: table.LC_data_table tr.LC_even_row > td {
 5179:   background-color: $data_table_dark;
 5180:   padding: 2px;
 5181:   vertical-align: top;
 5182: }
 5183: 
 5184: table.LC_pick_box tr > td.LC_even_row {
 5185:   background-color: $data_table_dark;
 5186:   vertical-align: top;
 5187: }
 5188: 
 5189: table.LC_data_table tr.LC_data_table_highlight td {
 5190:   background-color: $data_table_darker;
 5191: }
 5192: 
 5193: table.LC_data_table tr td.LC_leftcol_header {
 5194:   background-color: $data_table_head;
 5195:   font-weight: bold;
 5196: }
 5197: 
 5198: table.LC_data_table tr.LC_empty_row td,
 5199: table.LC_nested tr.LC_empty_row td {
 5200:   font-weight: bold;
 5201:   font-style: italic;
 5202:   text-align: center;
 5203:   padding: 8px;
 5204: }
 5205: 
 5206: table.LC_data_table tr.LC_empty_row td {
 5207:   background-color: $sidebg;
 5208: }
 5209: 
 5210: table.LC_nested tr.LC_empty_row td {
 5211:   background-color: #FFFFFF;
 5212: }
 5213: 
 5214: table.LC_caption {
 5215: }
 5216: 
 5217: table.LC_nested tr.LC_empty_row td {
 5218:   padding: 4ex
 5219: }
 5220: 
 5221: table.LC_nested_outer tr th {
 5222:   font-weight: bold;
 5223:   color:$fontmenu;
 5224:   background-color: $data_table_head;
 5225:   font-size: small;
 5226:   border-bottom: 1px solid #000000;
 5227: }
 5228: 
 5229: table.LC_nested_outer tr td.LC_subheader {
 5230:   background-color: $data_table_head;
 5231:   font-weight: bold;
 5232:   font-size: small;
 5233:   border-bottom: 1px solid #000000;
 5234:   text-align: right;
 5235: }
 5236: 
 5237: table.LC_nested tr.LC_info_row td {
 5238:   background-color: #CCCCCC;
 5239:   font-weight: bold;
 5240:   font-size: small;
 5241:   text-align: center;
 5242: }
 5243: 
 5244: table.LC_nested tr.LC_info_row td.LC_left_item,
 5245: table.LC_nested_outer tr th.LC_left_item {
 5246:   text-align: left;
 5247: }
 5248: 
 5249: table.LC_nested td {
 5250:   background-color: #FFFFFF;
 5251:   font-size: small;
 5252: }
 5253: 
 5254: table.LC_nested_outer tr th.LC_right_item,
 5255: table.LC_nested tr.LC_info_row td.LC_right_item,
 5256: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5257: table.LC_nested tr td.LC_right_item {
 5258:   text-align: right;
 5259: }
 5260: 
 5261: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_left_item,
 5262: .ui-accordion table.LC_nested tr.LC_even_row td.LC_left_item {
 5263:   text-align: right;
 5264:   width: 40%;
 5265:   padding-right:10px;
 5266:   vertical-align: top;
 5267:   padding: 5px;
 5268: }
 5269: 
 5270: .ui-accordion table.LC_nested tr.LC_odd_row td.LC_right_item,
 5271: .ui-accordion table.LC_nested tr.LC_even_row td.LC_right_item {
 5272:   text-align: left;
 5273:   width: 60%;
 5274:   padding: 2px 4px;
 5275: }
 5276: 
 5277: table.LC_nested tr.LC_odd_row td {
 5278:   background-color: #EEEEEE;
 5279: }
 5280: 
 5281: table.LC_createuser {
 5282: }
 5283: 
 5284: table.LC_createuser tr.LC_section_row td {
 5285:   font-size: small;
 5286: }
 5287: 
 5288: table.LC_createuser tr.LC_info_row td  {
 5289:   background-color: #CCCCCC;
 5290:   font-weight: bold;
 5291:   text-align: center;
 5292: }
 5293: 
 5294: table.LC_calendar {
 5295:   border: 1px solid #000000;
 5296:   border-collapse: collapse;
 5297:   width: 98%;
 5298: }
 5299: 
 5300: table.LC_calendar_pickdate {
 5301:   font-size: xx-small;
 5302: }
 5303: 
 5304: table.LC_calendar tr td {
 5305:   border: 1px solid #000000;
 5306:   vertical-align: top;
 5307:   width: 14%;
 5308: }
 5309: 
 5310: table.LC_calendar tr td.LC_calendar_day_empty {
 5311:   background-color: $data_table_dark;
 5312: }
 5313: 
 5314: table.LC_calendar tr td.LC_calendar_day_current {
 5315:   background-color: $data_table_highlight;
 5316: }
 5317: 
 5318: table.LC_data_table tr td.LC_mail_new {
 5319:   background-color: $mail_new;
 5320: }
 5321: 
 5322: table.LC_data_table tr.LC_mail_new:hover {
 5323:   background-color: $mail_new_hover;
 5324: }
 5325: 
 5326: table.LC_data_table tr td.LC_mail_read {
 5327:   background-color: $mail_read;
 5328: }
 5329: 
 5330: /*
 5331: table.LC_data_table tr.LC_mail_read:hover {
 5332:   background-color: $mail_read_hover;
 5333: }
 5334: */
 5335: 
 5336: table.LC_data_table tr td.LC_mail_replied {
 5337:   background-color: $mail_replied;
 5338: }
 5339: 
 5340: /*
 5341: table.LC_data_table tr.LC_mail_replied:hover {
 5342:   background-color: $mail_replied_hover;
 5343: }
 5344: */
 5345: 
 5346: table.LC_data_table tr td.LC_mail_other {
 5347:   background-color: $mail_other;
 5348: }
 5349: 
 5350: /*
 5351: table.LC_data_table tr.LC_mail_other:hover {
 5352:   background-color: $mail_other_hover;
 5353: }
 5354: */
 5355: 
 5356: table.LC_data_table tr > td.LC_browser_file,
 5357: table.LC_data_table tr > td.LC_browser_file_published {
 5358:   background: #AAEE77;
 5359: }
 5360: 
 5361: table.LC_data_table tr > td.LC_browser_file_locked,
 5362: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5363:   background: #FFAA99;
 5364: }
 5365: 
 5366: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5367:   background: #888888;
 5368: }
 5369: 
 5370: table.LC_data_table tr > td.LC_browser_file_modified,
 5371: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5372:   background: #F8F866;
 5373: }
 5374: 
 5375: table.LC_data_table tr.LC_browser_folder > td {
 5376:   background: #E0E8FF;
 5377: }
 5378: 
 5379: table.LC_data_table tr > td.LC_roles_is {
 5380:   /* background: #77FF77; */
 5381: }
 5382: 
 5383: table.LC_data_table tr > td.LC_roles_future {
 5384:   border-right: 8px solid #FFFF77;
 5385: }
 5386: 
 5387: table.LC_data_table tr > td.LC_roles_will {
 5388:   border-right: 8px solid #FFAA77;
 5389: }
 5390: 
 5391: table.LC_data_table tr > td.LC_roles_expired {
 5392:   border-right: 8px solid #FF7777;
 5393: }
 5394: 
 5395: table.LC_data_table tr > td.LC_roles_will_not {
 5396:   border-right: 8px solid #AAFF77;
 5397: }
 5398: 
 5399: table.LC_data_table tr > td.LC_roles_selected {
 5400:   border-right: 8px solid #11CC55;
 5401: }
 5402: 
 5403: span.LC_current_location {
 5404:   font-size:larger;
 5405:   background: $pgbg;
 5406: }
 5407: 
 5408: span.LC_parm_menu_item {
 5409:   font-size: larger;
 5410: }
 5411: 
 5412: span.LC_parm_scope_all {
 5413:   color: red;
 5414: }
 5415: 
 5416: span.LC_parm_scope_folder {
 5417:   color: green;
 5418: }
 5419: 
 5420: span.LC_parm_scope_resource {
 5421:   color: orange;
 5422: }
 5423: 
 5424: span.LC_parm_part {
 5425:   color: blue;
 5426: }
 5427: 
 5428: span.LC_parm_folder,
 5429: span.LC_parm_symb {
 5430:   font-size: x-small;
 5431:   font-family: $mono;
 5432:   color: #AAAAAA;
 5433: }
 5434: 
 5435: ul.LC_parm_parmlist li {
 5436:   display: inline-block;
 5437:   padding: 0.3em 0.8em;
 5438:   vertical-align: top;
 5439:   width: 150px;
 5440:   border-top:1px solid $lg_border_color;
 5441: }
 5442: 
 5443: td.LC_parm_overview_level_menu,
 5444: td.LC_parm_overview_map_menu,
 5445: td.LC_parm_overview_parm_selectors,
 5446: td.LC_parm_overview_restrictions  {
 5447:   border: 1px solid black;
 5448:   border-collapse: collapse;
 5449: }
 5450: 
 5451: table.LC_parm_overview_restrictions td {
 5452:   border-width: 1px 4px 1px 4px;
 5453:   border-style: solid;
 5454:   border-color: $pgbg;
 5455:   text-align: center;
 5456: }
 5457: 
 5458: table.LC_parm_overview_restrictions th {
 5459:   background: $tabbg;
 5460:   border-width: 1px 4px 1px 4px;
 5461:   border-style: solid;
 5462:   border-color: $pgbg;
 5463: }
 5464: 
 5465: table#LC_helpmenu {
 5466:   border: none;
 5467:   height: 55px;
 5468:   border-spacing: 0;
 5469: }
 5470: 
 5471: table#LC_helpmenu fieldset legend {
 5472:   font-size: larger;
 5473: }
 5474: 
 5475: table#LC_helpmenu_links {
 5476:   width: 100%;
 5477:   border: 1px solid black;
 5478:   background: $pgbg;
 5479:   padding: 0;
 5480:   border-spacing: 1px;
 5481: }
 5482: 
 5483: table#LC_helpmenu_links tr td {
 5484:   padding: 1px;
 5485:   background: $tabbg;
 5486:   text-align: center;
 5487:   font-weight: bold;
 5488: }
 5489: 
 5490: table#LC_helpmenu_links a:link,
 5491: table#LC_helpmenu_links a:visited,
 5492: table#LC_helpmenu_links a:active {
 5493:   text-decoration: none;
 5494:   color: $font;
 5495: }
 5496: 
 5497: table#LC_helpmenu_links a:hover {
 5498:   text-decoration: underline;
 5499:   color: $vlink;
 5500: }
 5501: 
 5502: .LC_chrt_popup_exists {
 5503:   border: 1px solid #339933;
 5504:   margin: -1px;
 5505: }
 5506: 
 5507: .LC_chrt_popup_up {
 5508:   border: 1px solid yellow;
 5509:   margin: -1px;
 5510: }
 5511: 
 5512: .LC_chrt_popup {
 5513:   border: 1px solid #8888FF;
 5514:   background: #CCCCFF;
 5515: }
 5516: 
 5517: table.LC_pick_box {
 5518:   border-collapse: separate;
 5519:   background: white;
 5520:   border: 1px solid black;
 5521:   border-spacing: 1px;
 5522: }
 5523: 
 5524: table.LC_pick_box td.LC_pick_box_title {
 5525:   background: $sidebg;
 5526:   font-weight: bold;
 5527:   text-align: left;
 5528:   vertical-align: top;
 5529:   width: 184px;
 5530:   padding: 8px;
 5531: }
 5532: 
 5533: table.LC_pick_box td.LC_pick_box_value {
 5534:   text-align: left;
 5535:   padding: 8px;
 5536: }
 5537: 
 5538: table.LC_pick_box td.LC_pick_box_select {
 5539:   text-align: left;
 5540:   padding: 8px;
 5541: }
 5542: 
 5543: table.LC_pick_box td.LC_pick_box_separator {
 5544:   padding: 0;
 5545:   height: 1px;
 5546:   background: black;
 5547: }
 5548: 
 5549: table.LC_pick_box td.LC_pick_box_submit {
 5550:   text-align: right;
 5551: }
 5552: 
 5553: table.LC_pick_box td.LC_evenrow_value {
 5554:   text-align: left;
 5555:   padding: 8px;
 5556:   background-color: $data_table_light;
 5557: }
 5558: 
 5559: table.LC_pick_box td.LC_oddrow_value {
 5560:   text-align: left;
 5561:   padding: 8px;
 5562:   background-color: $data_table_light;
 5563: }
 5564: 
 5565: span.LC_helpform_receipt_cat {
 5566:   font-weight: bold;
 5567: }
 5568: 
 5569: table.LC_group_priv_box {
 5570:   background: white;
 5571:   border: 1px solid black;
 5572:   border-spacing: 1px;
 5573: }
 5574: 
 5575: table.LC_group_priv_box td.LC_pick_box_title {
 5576:   background: $tabbg;
 5577:   font-weight: bold;
 5578:   text-align: right;
 5579:   width: 184px;
 5580: }
 5581: 
 5582: table.LC_group_priv_box td.LC_groups_fixed {
 5583:   background: $data_table_light;
 5584:   text-align: center;
 5585: }
 5586: 
 5587: table.LC_group_priv_box td.LC_groups_optional {
 5588:   background: $data_table_dark;
 5589:   text-align: center;
 5590: }
 5591: 
 5592: table.LC_group_priv_box td.LC_groups_functionality {
 5593:   background: $data_table_darker;
 5594:   text-align: center;
 5595:   font-weight: bold;
 5596: }
 5597: 
 5598: table.LC_group_priv td {
 5599:   text-align: left;
 5600:   padding: 0;
 5601: }
 5602: 
 5603: .LC_navbuttons {
 5604:   margin: 2ex 0ex 2ex 0ex;
 5605: }
 5606: 
 5607: .LC_topic_bar {
 5608:   font-weight: bold;
 5609:   background: $tabbg;
 5610:   margin: 1em 0em 1em 2em;
 5611:   padding: 3px;
 5612:   font-size: 1.2em;
 5613: }
 5614: 
 5615: .LC_topic_bar span {
 5616:   left: 0.5em;
 5617:   position: absolute;
 5618:   vertical-align: middle;
 5619:   font-size: 1.2em;
 5620: }
 5621: 
 5622: table.LC_course_group_status {
 5623:   margin: 20px;
 5624: }
 5625: 
 5626: table.LC_status_selector td {
 5627:   vertical-align: top;
 5628:   text-align: center;
 5629:   padding: 4px;
 5630: }
 5631: 
 5632: div.LC_feedback_link {
 5633:   clear: both;
 5634:   background: $sidebg;
 5635:   width: 100%;
 5636:   padding-bottom: 10px;
 5637:   border: 1px $tabbg solid;
 5638:   height: 22px;
 5639:   line-height: 22px;
 5640:   padding-top: 5px;
 5641: }
 5642: 
 5643: div.LC_feedback_link img {
 5644:   height: 22px;
 5645:   vertical-align:middle;
 5646: }
 5647: 
 5648: div.LC_feedback_link a {
 5649:   text-decoration: none;
 5650: }
 5651: 
 5652: div.LC_comblock {
 5653:   display:inline;
 5654:   color:$font;
 5655:   font-size:90%;
 5656: }
 5657: 
 5658: div.LC_feedback_link div.LC_comblock {
 5659:   padding-left:5px;
 5660: }
 5661: 
 5662: div.LC_feedback_link div.LC_comblock a {
 5663:   color:$font;
 5664: }
 5665: 
 5666: span.LC_feedback_link {
 5667:   /* background: $feedback_link_bg; */
 5668:   font-size: larger;
 5669: }
 5670: 
 5671: span.LC_message_link {
 5672:   /* background: $feedback_link_bg; */
 5673:   font-size: larger;
 5674:   position: absolute;
 5675:   right: 1em;
 5676: }
 5677: 
 5678: table.LC_prior_tries {
 5679:   border: 1px solid #000000;
 5680:   border-collapse: separate;
 5681:   border-spacing: 1px;
 5682: }
 5683: 
 5684: table.LC_prior_tries td {
 5685:   padding: 2px;
 5686: }
 5687: 
 5688: .LC_answer_correct {
 5689:   background: lightgreen;
 5690:   color: darkgreen;
 5691:   padding: 6px;
 5692: }
 5693: 
 5694: .LC_answer_charged_try {
 5695:   background: #FFAAAA;
 5696:   color: darkred;
 5697:   padding: 6px;
 5698: }
 5699: 
 5700: .LC_answer_not_charged_try,
 5701: .LC_answer_no_grade,
 5702: .LC_answer_late {
 5703:   background: lightyellow;
 5704:   color: black;
 5705:   padding: 6px;
 5706: }
 5707: 
 5708: .LC_answer_previous {
 5709:   background: lightblue;
 5710:   color: darkblue;
 5711:   padding: 6px;
 5712: }
 5713: 
 5714: .LC_answer_no_message {
 5715:   background: #FFFFFF;
 5716:   color: black;
 5717:   padding: 6px;
 5718: }
 5719: 
 5720: .LC_answer_unknown {
 5721:   background: orange;
 5722:   color: black;
 5723:   padding: 6px;
 5724: }
 5725: 
 5726: span.LC_prior_numerical,
 5727: span.LC_prior_string,
 5728: span.LC_prior_custom,
 5729: span.LC_prior_reaction,
 5730: span.LC_prior_math {
 5731:   font-family: $mono;
 5732:   white-space: pre;
 5733: }
 5734: 
 5735: span.LC_prior_string {
 5736:   font-family: $mono;
 5737:   white-space: pre;
 5738: }
 5739: 
 5740: table.LC_prior_option {
 5741:   width: 100%;
 5742:   border-collapse: collapse;
 5743: }
 5744: 
 5745: table.LC_prior_rank,
 5746: table.LC_prior_match {
 5747:   border-collapse: collapse;
 5748: }
 5749: 
 5750: table.LC_prior_option tr td,
 5751: table.LC_prior_rank tr td,
 5752: table.LC_prior_match tr td {
 5753:   border: 1px solid #000000;
 5754: }
 5755: 
 5756: .LC_nobreak {
 5757:   white-space: nowrap;
 5758: }
 5759: 
 5760: span.LC_cusr_emph {
 5761:   font-style: italic;
 5762: }
 5763: 
 5764: span.LC_cusr_subheading {
 5765:   font-weight: normal;
 5766:   font-size: 85%;
 5767: }
 5768: 
 5769: div.LC_docs_entry_move {
 5770:   border: 1px solid #BBBBBB;
 5771:   background: #DDDDDD;
 5772:   width: 22px;
 5773:   padding: 1px;
 5774:   margin: 0;
 5775: }
 5776: 
 5777: table.LC_data_table tr > td.LC_docs_entry_commands,
 5778: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5779:   background: #DDDDDD;
 5780:   font-size: x-small;
 5781: }
 5782: 
 5783: .LC_docs_entry_parameter {
 5784:   white-space: nowrap;
 5785: }
 5786: 
 5787: .LC_docs_copy {
 5788:   color: #000099;
 5789: }
 5790: 
 5791: .LC_docs_cut {
 5792:   color: #550044;
 5793: }
 5794: 
 5795: .LC_docs_rename {
 5796:   color: #009900;
 5797: }
 5798: 
 5799: .LC_docs_remove {
 5800:   color: #990000;
 5801: }
 5802: 
 5803: .LC_docs_reinit_warn,
 5804: .LC_docs_ext_edit {
 5805:   font-size: x-small;
 5806: }
 5807: 
 5808: table.LC_docs_adddocs td,
 5809: table.LC_docs_adddocs th {
 5810:   border: 1px solid #BBBBBB;
 5811:   padding: 4px;
 5812:   background: #DDDDDD;
 5813: }
 5814: 
 5815: table.LC_sty_begin {
 5816:   background: #BBFFBB;
 5817: }
 5818: 
 5819: table.LC_sty_end {
 5820:   background: #FFBBBB;
 5821: }
 5822: 
 5823: table.LC_double_column {
 5824:   border-width: 0;
 5825:   border-collapse: collapse;
 5826:   width: 100%;
 5827:   padding: 2px;
 5828: }
 5829: 
 5830: table.LC_double_column tr td.LC_left_col {
 5831:   top: 2px;
 5832:   left: 2px;
 5833:   width: 47%;
 5834:   vertical-align: top;
 5835: }
 5836: 
 5837: table.LC_double_column tr td.LC_right_col {
 5838:   top: 2px;
 5839:   right: 2px;
 5840:   width: 47%;
 5841:   vertical-align: top;
 5842: }
 5843: 
 5844: div.LC_left_float {
 5845:   float: left;
 5846:   padding-right: 5%;
 5847:   padding-bottom: 4px;
 5848: }
 5849: 
 5850: div.LC_clear_float_header {
 5851:   padding-bottom: 2px;
 5852: }
 5853: 
 5854: div.LC_clear_float_footer {
 5855:   padding-top: 10px;
 5856:   clear: both;
 5857: }
 5858: 
 5859: div.LC_grade_show_user {
 5860: /*  border-left: 5px solid $sidebg; */
 5861:   border-top: 5px solid #000000;
 5862:   margin: 50px 0 0 0;
 5863:   padding: 15px 0 5px 10px;
 5864: }
 5865: 
 5866: div.LC_grade_show_user_odd_row {
 5867: /*  border-left: 5px solid #000000; */
 5868: }
 5869: 
 5870: div.LC_grade_show_user div.LC_Box {
 5871:   margin-right: 50px;
 5872: }
 5873: 
 5874: div.LC_grade_submissions,
 5875: div.LC_grade_message_center,
 5876: div.LC_grade_info_links {
 5877:   margin: 5px;
 5878:   width: 99%;
 5879:   background: #FFFFFF;
 5880: }
 5881: 
 5882: div.LC_grade_submissions_header,
 5883: div.LC_grade_message_center_header {
 5884:   font-weight: bold;
 5885:   font-size: large;
 5886: }
 5887: 
 5888: div.LC_grade_submissions_body,
 5889: div.LC_grade_message_center_body {
 5890:   border: 1px solid black;
 5891:   width: 99%;
 5892:   background: #FFFFFF;
 5893: }
 5894: 
 5895: table.LC_scantron_action {
 5896:   width: 100%;
 5897: }
 5898: 
 5899: table.LC_scantron_action tr th {
 5900:   font-weight:bold;
 5901:   font-style:normal;
 5902: }
 5903: 
 5904: .LC_edit_problem_header,
 5905: div.LC_edit_problem_footer {
 5906:   font-weight: normal;
 5907:   font-size:  medium;
 5908:   margin: 2px;
 5909: }
 5910: 
 5911: div.LC_edit_problem_header,
 5912: div.LC_edit_problem_header div,
 5913: div.LC_edit_problem_footer,
 5914: div.LC_edit_problem_footer div,
 5915: div.LC_edit_problem_editxml_header,
 5916: div.LC_edit_problem_editxml_header div {
 5917:   margin-top: 5px;
 5918: }
 5919: 
 5920: div.LC_edit_problem_header_title {
 5921:   font-weight: bold;
 5922:   font-size: larger;
 5923:   background: $tabbg;
 5924:   padding: 3px;
 5925: }
 5926: 
 5927: table.LC_edit_problem_header_title {
 5928:   width: 100%;
 5929:   background: $tabbg;
 5930: }
 5931: 
 5932: div.LC_edit_problem_discards {
 5933:   float: left;
 5934:   padding-bottom: 5px;
 5935: }
 5936: 
 5937: div.LC_edit_problem_saves {
 5938:   float: right;
 5939:   padding-bottom: 5px;
 5940: }
 5941: 
 5942: img.stift {
 5943:   border-width: 0;
 5944:   vertical-align: middle;
 5945: }
 5946: 
 5947: table td.LC_mainmenu_col_fieldset {
 5948:   vertical-align: top;
 5949: }
 5950: 
 5951: div.LC_createcourse {
 5952:   margin: 10px 10px 10px 10px;
 5953: }
 5954: 
 5955: .LC_dccid {
 5956:   margin: 0.2em 0 0 0;
 5957:   padding: 0;
 5958:   font-size: 90%;
 5959:   display:none;
 5960: }
 5961: 
 5962: a:hover,
 5963: ol.LC_primary_menu a:hover,
 5964: ol#LC_MenuBreadcrumbs a:hover,
 5965: ol#LC_PathBreadcrumbs a:hover,
 5966: ul#LC_secondary_menu a:hover,
 5967: .LC_FormSectionClearButton input:hover
 5968: ul.LC_TabContent   li:hover a {
 5969:   color:$button_hover;
 5970:   text-decoration:none;
 5971: }
 5972: 
 5973: h1 {
 5974:   padding: 0;
 5975:   line-height:130%;
 5976: }
 5977: 
 5978: h2,
 5979: h3,
 5980: h4,
 5981: h5,
 5982: h6 {
 5983:   margin: 5px 0 5px 0;
 5984:   padding: 0;
 5985:   line-height:130%;
 5986: }
 5987: 
 5988: .LC_hcell {
 5989:   padding:3px 15px 3px 15px;
 5990:   margin: 0;
 5991:   background-color:$tabbg;
 5992:   color:$fontmenu;
 5993:   border-bottom:solid 1px $lg_border_color;
 5994: }
 5995: 
 5996: .LC_Box > .LC_hcell {
 5997:   margin: 0 -10px 10px -10px;
 5998: }
 5999: 
 6000: .LC_noBorder {
 6001:   border: 0;
 6002: }
 6003: 
 6004: .LC_FormSectionClearButton input {
 6005:   background-color:transparent;
 6006:   border: none;
 6007:   cursor:pointer;
 6008:   text-decoration:underline;
 6009: }
 6010: 
 6011: .LC_help_open_topic {
 6012:   color: #FFFFFF;
 6013:   background-color: #EEEEFF;
 6014:   margin: 1px;
 6015:   padding: 4px;
 6016:   border: 1px solid #000033;
 6017:   white-space: nowrap;
 6018:   /* vertical-align: middle; */
 6019: }
 6020: 
 6021: dl,
 6022: ul,
 6023: div,
 6024: fieldset {
 6025:   margin: 10px 10px 10px 0;
 6026:   /* overflow: hidden; */
 6027: }
 6028: 
 6029: fieldset > legend {
 6030:   font-weight: bold;
 6031:   padding: 0 5px 0 5px;
 6032: }
 6033: 
 6034: #LC_nav_bar {
 6035:   float: left;
 6036:   margin: 0 0 2px 0;
 6037: }
 6038: 
 6039: #LC_realm {
 6040:   margin: 0.2em 0 0 0;
 6041:   padding: 0;
 6042:   font-weight: bold;
 6043:   text-align: center;
 6044: }
 6045: 
 6046: #LC_nav_bar em {
 6047:   font-weight: bold;
 6048:   font-style: normal;
 6049: }
 6050: 
 6051: ol.LC_primary_menu {
 6052:   float: right;
 6053:   margin: 0;
 6054: }
 6055: 
 6056: ol#LC_PathBreadcrumbs {
 6057:   margin: 0;
 6058: }
 6059: 
 6060: ol.LC_primary_menu li {
 6061:   display: inline;
 6062:   padding: 5px 5px 0 10px;
 6063:   vertical-align: top;
 6064: }
 6065: 
 6066: ol.LC_primary_menu li img {
 6067:   vertical-align: bottom;
 6068:   height: 1.1em;
 6069: }
 6070: 
 6071: ol.LC_primary_menu a {
 6072:   color: RGB(80, 80, 80);
 6073:   text-decoration: none;
 6074: }
 6075: 
 6076: ol.LC_primary_menu a.LC_new_message {
 6077:   font-weight:bold;
 6078:   color: darkred;
 6079: }
 6080: 
 6081: ol.LC_docs_parameters {
 6082:   margin-left: 0;
 6083:   padding: 0;
 6084:   list-style: none;
 6085: }
 6086: 
 6087: ol.LC_docs_parameters li {
 6088:   margin: 0;
 6089:   padding-right: 20px;
 6090:   display: inline;
 6091: }
 6092: 
 6093: ol.LC_docs_parameters li:before {
 6094:   content: "\\002022 \\0020";
 6095: }
 6096: 
 6097: li.LC_docs_parameters_title {
 6098:   font-weight: bold;
 6099: }
 6100: 
 6101: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6102:   content: "";
 6103: }
 6104: 
 6105: ul#LC_secondary_menu {
 6106:   clear: both;
 6107:   color: $fontmenu;
 6108:   background: $tabbg;
 6109:   list-style: none;
 6110:   padding: 0;
 6111:   margin: 0;
 6112:   width: 100%;
 6113: }
 6114: 
 6115: ul#LC_secondary_menu li {
 6116:   font-weight: bold;
 6117:   line-height: 1.8em;
 6118:   padding: 0 0.8em;
 6119:   border-right: 1px solid black;
 6120:   display: inline;
 6121:   vertical-align: middle;
 6122: }
 6123: 
 6124: ul.LC_TabContent {
 6125:   display:block;
 6126:   background: $sidebg;
 6127:   border-bottom: solid 1px $lg_border_color;
 6128:   list-style:none;
 6129:   margin: 0 -10px;
 6130:   padding: 0;
 6131: }
 6132: 
 6133: ul.LC_TabContent li,
 6134: ul.LC_TabContentBigger li {
 6135:   float:left;
 6136: }
 6137: 
 6138: ul#LC_secondary_menu li a {
 6139:   color: $fontmenu;
 6140:   text-decoration: none;
 6141: }
 6142: 
 6143: ul.LC_TabContent {
 6144:   min-height:20px;
 6145: }
 6146: 
 6147: ul.LC_TabContent li {
 6148:   vertical-align:middle;
 6149:   padding: 0 16px 0 10px;
 6150:   background-color:$tabbg;
 6151:   border-bottom:solid 1px $lg_border_color;
 6152:   border-right: solid 1px $font;
 6153: }
 6154: 
 6155: ul.LC_TabContent .right {
 6156:   float:right;
 6157: }
 6158: 
 6159: ul.LC_TabContent li a,
 6160: ul.LC_TabContent li {
 6161:   color:rgb(47,47,47);
 6162:   text-decoration:none;
 6163:   font-size:95%;
 6164:   font-weight:bold;
 6165:   min-height:20px;
 6166: }
 6167: 
 6168: ul.LC_TabContent li a:hover,
 6169: ul.LC_TabContent li a:focus {
 6170:   color: $button_hover;
 6171:   background:none;
 6172:   outline:none;
 6173: }
 6174: 
 6175: ul.LC_TabContent li:hover {
 6176:   color: $button_hover;
 6177:   cursor:pointer;
 6178: }
 6179: 
 6180: ul.LC_TabContent li.active {
 6181:   color: $font;
 6182:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6183:   border-bottom:solid 1px #FFFFFF;
 6184:   cursor: default;
 6185: }
 6186: 
 6187: ul.LC_TabContent li.active a {
 6188:   color:$font;
 6189:   background:#FFFFFF;
 6190:   outline: none;
 6191: }
 6192: #maincoursedoc {
 6193:   clear:both;
 6194: }
 6195: 
 6196: ul.LC_TabContentBigger {
 6197:   display:block;
 6198:   list-style:none;
 6199:   padding: 0;
 6200: }
 6201: 
 6202: ul.LC_TabContentBigger li {
 6203:   vertical-align:bottom;
 6204:   height: 30px;
 6205:   font-size:110%;
 6206:   font-weight:bold;
 6207:   color: #737373;
 6208: }
 6209: 
 6210: ul.LC_TabContentBigger li.active {
 6211:   position: relative;
 6212:   top: 1px;
 6213: }
 6214: 
 6215: ul.LC_TabContentBigger li a {
 6216:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6217:   height: 30px;
 6218:   line-height: 30px;
 6219:   text-align: center;
 6220:   display: block;
 6221:   text-decoration: none;
 6222:   outline: none;  
 6223: }
 6224: 
 6225: ul.LC_TabContentBigger li.active a {
 6226:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6227:   color:$font;
 6228: }
 6229: 
 6230: ul.LC_TabContentBigger li b {
 6231:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6232:   display: block;
 6233:   float: left;
 6234:   padding: 0 30px;
 6235:   border-bottom: 1px solid $lg_border_color;
 6236: }
 6237: 
 6238: ul.LC_TabContentBigger li:hover b {
 6239:   color:$button_hover;
 6240: }
 6241: 
 6242: ul.LC_TabContentBigger li.active b {
 6243:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6244:   color:$font;
 6245:   border: 0;
 6246:   cursor:default;
 6247: }
 6248: 
 6249: 
 6250: ul.LC_CourseBreadcrumbs {
 6251:   background: $sidebg;
 6252:   line-height: 32px;
 6253:   padding-left: 10px;
 6254:   margin: 0 0 10px 0;
 6255:   list-style-position: inside;
 6256: 
 6257: }
 6258: 
 6259: ol#LC_MenuBreadcrumbs,
 6260: ol#LC_PathBreadcrumbs {
 6261:   padding-left: 10px;
 6262:   margin: 0;
 6263:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6264: }
 6265: 
 6266: ol#LC_MenuBreadcrumbs li,
 6267: ol#LC_PathBreadcrumbs li,
 6268: ul.LC_CourseBreadcrumbs li {
 6269:   display: inline;
 6270:   white-space: normal;  
 6271: }
 6272: 
 6273: ol#LC_MenuBreadcrumbs li a,
 6274: ul.LC_CourseBreadcrumbs li a {
 6275:   text-decoration: none;
 6276:   font-size:90%;
 6277: }
 6278: 
 6279: ol#LC_MenuBreadcrumbs h1 {
 6280:   display: inline;
 6281:   font-size: 90%;
 6282:   line-height: 2.5em;
 6283:   margin: 0;
 6284:   padding: 0;
 6285: }
 6286: 
 6287: ol#LC_PathBreadcrumbs li a {
 6288:   text-decoration:none;
 6289:   font-size:100%;
 6290:   font-weight:bold;
 6291: }
 6292: 
 6293: .LC_Box {
 6294:   border: solid 1px $lg_border_color;
 6295:   padding: 0 10px 10px 10px;
 6296: }
 6297: 
 6298: .LC_AboutMe_Image {
 6299:   float:left;
 6300:   margin-right:10px;
 6301: }
 6302: 
 6303: .LC_Clear_AboutMe_Image {
 6304:   clear:left;
 6305: }
 6306: 
 6307: dl.LC_ListStyleClean dt {
 6308:   padding-right: 5px;
 6309:   display: table-header-group;
 6310: }
 6311: 
 6312: dl.LC_ListStyleClean dd {
 6313:   display: table-row;
 6314: }
 6315: 
 6316: .LC_ListStyleClean,
 6317: .LC_ListStyleSimple,
 6318: .LC_ListStyleNormal,
 6319: .LC_ListStyleSpecial {
 6320:   /* display:block; */
 6321:   list-style-position: inside;
 6322:   list-style-type: none;
 6323:   overflow: hidden;
 6324:   padding: 0;
 6325: }
 6326: 
 6327: .LC_ListStyleSimple li,
 6328: .LC_ListStyleSimple dd,
 6329: .LC_ListStyleNormal li,
 6330: .LC_ListStyleNormal dd,
 6331: .LC_ListStyleSpecial li,
 6332: .LC_ListStyleSpecial dd {
 6333:   margin: 0;
 6334:   padding: 5px 5px 5px 10px;
 6335:   clear: both;
 6336: }
 6337: 
 6338: .LC_ListStyleClean li,
 6339: .LC_ListStyleClean dd {
 6340:   padding-top: 0;
 6341:   padding-bottom: 0;
 6342: }
 6343: 
 6344: .LC_ListStyleSimple dd,
 6345: .LC_ListStyleSimple li {
 6346:   border-bottom: solid 1px $lg_border_color;
 6347: }
 6348: 
 6349: .LC_ListStyleSpecial li,
 6350: .LC_ListStyleSpecial dd {
 6351:   list-style-type: none;
 6352:   background-color: RGB(220, 220, 220);
 6353:   margin-bottom: 4px;
 6354: }
 6355: 
 6356: table.LC_SimpleTable {
 6357:   margin:5px;
 6358:   border:solid 1px $lg_border_color;
 6359: }
 6360: 
 6361: table.LC_SimpleTable tr {
 6362:   padding: 0;
 6363:   border:solid 1px $lg_border_color;
 6364: }
 6365: 
 6366: table.LC_SimpleTable thead {
 6367:   background:rgb(220,220,220);
 6368: }
 6369: 
 6370: div.LC_columnSection {
 6371:   display: block;
 6372:   clear: both;
 6373:   overflow: hidden;
 6374:   margin: 0;
 6375: }
 6376: 
 6377: div.LC_columnSection>* {
 6378:   float: left;
 6379:   margin: 10px 20px 10px 0;
 6380:   overflow:hidden;
 6381: }
 6382: 
 6383: table em {
 6384:   font-weight: bold;
 6385:   font-style: normal;
 6386: }
 6387: 
 6388: table.LC_tableBrowseRes,
 6389: table.LC_tableOfContent {
 6390:   border:none;
 6391:   border-spacing: 1px;
 6392:   padding: 3px;
 6393:   background-color: #FFFFFF;
 6394:   font-size: 90%;
 6395: }
 6396: 
 6397: table.LC_tableOfContent {
 6398:   border-collapse: collapse;
 6399: }
 6400: 
 6401: table.LC_tableBrowseRes a,
 6402: table.LC_tableOfContent a {
 6403:   background-color: transparent;
 6404:   text-decoration: none;
 6405: }
 6406: 
 6407: table.LC_tableOfContent img {
 6408:   border: none;
 6409:   height: 1.3em;
 6410:   vertical-align: text-bottom;
 6411:   margin-right: 0.3em;
 6412: }
 6413: 
 6414: a#LC_content_toolbar_firsthomework {
 6415:   background-image:url(/res/adm/pages/open-first-problem.gif);
 6416: }
 6417: 
 6418: a#LC_content_toolbar_everything {
 6419:   background-image:url(/res/adm/pages/show-all.gif);
 6420: }
 6421: 
 6422: a#LC_content_toolbar_uncompleted {
 6423:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6424: }
 6425: 
 6426: #LC_content_toolbar_clearbubbles {
 6427:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6428: }
 6429: 
 6430: a#LC_content_toolbar_changefolder {
 6431:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6432: }
 6433: 
 6434: a#LC_content_toolbar_changefolder_toggled {
 6435:   background-image:url(/res/adm/pages/open-all-folders.gif);
 6436: }
 6437: 
 6438: ul#LC_toolbar li a:hover {
 6439:   background-position: bottom center;
 6440: }
 6441: 
 6442: ul#LC_toolbar {
 6443:   padding: 0;
 6444:   margin: 2px;
 6445:   list-style:none;
 6446:   position:relative;
 6447:   background-color:white;
 6448: }
 6449: 
 6450: ul#LC_toolbar li {
 6451:   border:1px solid white;
 6452:   padding: 0;
 6453:   margin: 0;
 6454:   float: left;
 6455:   display:inline;
 6456:   vertical-align:middle;
 6457: }
 6458: 
 6459: 
 6460: a.LC_toolbarItem {
 6461:   display:block;
 6462:   padding: 0;
 6463:   margin: 0;
 6464:   height: 32px;
 6465:   width: 32px;
 6466:   color:white;
 6467:   border: none;
 6468:   background-repeat:no-repeat;
 6469:   background-color:transparent;
 6470: }
 6471: 
 6472: ul.LC_funclist {
 6473:     margin: 0;
 6474:     padding: 0.5em 1em 0.5em 0;
 6475: }
 6476: 
 6477: ul.LC_funclist > li:first-child {
 6478:     font-weight:bold; 
 6479:     margin-left:0.8em;
 6480: }
 6481: 
 6482: ul.LC_funclist + ul.LC_funclist {
 6483:     /* 
 6484:        left border as a seperator if we have more than
 6485:        one list 
 6486:     */
 6487:     border-left: 1px solid $sidebg;
 6488:     /* 
 6489:        this hides the left border behind the border of the 
 6490:        outer box if element is wrapped to the next 'line' 
 6491:     */
 6492:     margin-left: -1px;
 6493: }
 6494: 
 6495: ul.LC_funclist li {
 6496:   display: inline;
 6497:   white-space: nowrap;
 6498:   margin: 0 0 0 25px;
 6499:   line-height: 150%;
 6500: }
 6501: 
 6502: .ui-accordion .LC_advanced_toggle {
 6503:   float: right;
 6504:   font-size: 90%;
 6505:   padding: 0px 4px
 6506: }
 6507: 
 6508: .LC_hidden {
 6509:   display: none;
 6510: }
 6511: 
 6512: END
 6513: }
 6514: 
 6515: =pod
 6516: 
 6517: =item * &headtag()
 6518: 
 6519: Returns a uniform footer for LON-CAPA web pages.
 6520: 
 6521: Inputs: $title - optional title for the head
 6522:         $head_extra - optional extra HTML to put inside the <head>
 6523:         $args - optional arguments
 6524:             force_register - if is true call registerurl so the remote is 
 6525:                              informed
 6526:             redirect       -> array ref of
 6527:                                    1- seconds before redirect occurs
 6528:                                    2- url to redirect to
 6529:                                    3- whether the side effect should occur
 6530:                            (side effect of setting 
 6531:                                $env{'internal.head.redirect'} to the url 
 6532:                                redirected too)
 6533:             domain         -> force to color decorate a page for a specific
 6534:                                domain
 6535:             function       -> force usage of a specific rolish color scheme
 6536:             bgcolor        -> override the default page bgcolor
 6537:             no_auto_mt_title
 6538:                            -> prevent &mt()ing the title arg
 6539: 
 6540: =cut
 6541: 
 6542: sub headtag {
 6543:     my ($title,$head_extra,$args) = @_;
 6544:     
 6545:     my $function = $args->{'function'} || &get_users_function();
 6546:     my $domain   = $args->{'domain'}   || &determinedomain();
 6547:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6548:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6549: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6550: 		   #time(),
 6551: 		   $env{'environment.color.timestamp'},
 6552: 		   $function,$domain,$bgcolor);
 6553: 
 6554:     $url = '/adm/css/'.&escape($url).'.css';
 6555: 
 6556:     my $result =
 6557: 	'<head>'.
 6558: 	&font_settings();
 6559: 
 6560:     if (!$args->{'frameset'}) {
 6561: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6562:     }
 6563:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 6564:         $result .= Apache::lonxml::display_title();
 6565:     }
 6566:     if (!$args->{'no_nav_bar'} 
 6567: 	&& !$args->{'only_body'}
 6568: 	&& !$args->{'frameset'}) {
 6569: 	$result .= &help_menu_js();
 6570:     }
 6571: 
 6572:     if (ref($args->{'redirect'})) {
 6573: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6574: 	$url = &Apache::lonenc::check_encrypt($url);
 6575: 	if (!$inhibit_continue) {
 6576: 	    $env{'internal.head.redirect'} = $url;
 6577: 	}
 6578: 	$result.=<<ADDMETA
 6579: <meta http-equiv="pragma" content="no-cache" />
 6580: <meta http-equiv="Refresh" content="$time; url=$url" />
 6581: ADDMETA
 6582:     }
 6583:     if (!defined($title)) {
 6584: 	$title = 'The LearningOnline Network with CAPA';
 6585:     }
 6586:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6587:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6588: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6589: 	.$head_extra;
 6590:     return $result.'</head>';
 6591: }
 6592: 
 6593: =pod
 6594: 
 6595: =item * &font_settings()
 6596: 
 6597: Returns neccessary <meta> to set the proper encoding
 6598: 
 6599: Inputs: none
 6600: 
 6601: =cut
 6602: 
 6603: sub font_settings {
 6604:     my $headerstring='';
 6605:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6606: 	$headerstring.=
 6607: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6608:     }
 6609:     return $headerstring;
 6610: }
 6611: 
 6612: =pod
 6613: 
 6614: =item * &xml_begin()
 6615: 
 6616: Returns the needed doctype and <html>
 6617: 
 6618: Inputs: none
 6619: 
 6620: =cut
 6621: 
 6622: sub xml_begin {
 6623:     my $output='';
 6624: 
 6625:     if ($env{'browser.mathml'}) {
 6626: 	$output='<?xml version="1.0"?>'
 6627:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6628: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6629:             
 6630: #	    .'<!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">] >'
 6631: 	    .'<!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">'
 6632:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6633: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6634:     } else {
 6635: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6636:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6637:     }
 6638:     return $output;
 6639: }
 6640: 
 6641: =pod
 6642: 
 6643: =item * &start_page()
 6644: 
 6645: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6646: 
 6647: Inputs:
 6648: 
 6649: =over 4
 6650: 
 6651: $title - optional title for the page
 6652: 
 6653: $head_extra - optional extra HTML to incude inside the <head>
 6654: 
 6655: $args - additional optional args supported are:
 6656: 
 6657: =over 8
 6658: 
 6659:              only_body      -> is true will set &bodytag() onlybodytag
 6660:                                     arg on
 6661:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6662:              add_entries    -> additional attributes to add to the  <body>
 6663:              domain         -> force to color decorate a page for a 
 6664:                                     specific domain
 6665:              function       -> force usage of a specific rolish color
 6666:                                     scheme
 6667:              redirect       -> see &headtag()
 6668:              bgcolor        -> override the default page bg color
 6669:              js_ready       -> return a string ready for being used in 
 6670:                                     a javascript writeln
 6671:              html_encode    -> return a string ready for being used in 
 6672:                                     a html attribute
 6673:              force_register -> if is true will turn on the &bodytag()
 6674:                                     $forcereg arg
 6675:              frameset       -> if true will start with a <frameset>
 6676:                                     rather than <body>
 6677:              skip_phases    -> hash ref of 
 6678:                                     head -> skip the <html><head> generation
 6679:                                     body -> skip all <body> generation
 6680:              no_auto_mt_title -> prevent &mt()ing the title arg
 6681:              inherit_jsmath -> when creating popup window in a page,
 6682:                                     should it have jsmath forced on by the
 6683:                                     current page
 6684:              bread_crumbs ->             Array containing breadcrumbs
 6685:              bread_crumbs_components ->  if exists show it as headline else show only the breadcrumbs
 6686: 
 6687: =back
 6688: 
 6689: =back
 6690: 
 6691: =cut
 6692: 
 6693: sub start_page {
 6694:     my ($title,$head_extra,$args) = @_;
 6695:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6696: #SD
 6697: #I don't see why we copy certain elements of %$args to %head_args
 6698: #head args is passed to headtag() and this routine only reads those
 6699: #keys that are needed. There doesn't happen any writes or any processing
 6700: #of other keys.
 6701: #proposal: just pass $args to headtag instead of \%head_args and delete 
 6702: #marked lines
 6703: #<- MARK
 6704:     my %head_args;
 6705:     foreach my $arg ('redirect','force_register','domain','function',
 6706: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6707: 		     'no_auto_mt_title') {
 6708: 	if (defined($args->{$arg})) {
 6709: 	    $head_args{$arg} = $args->{$arg};
 6710: 	}
 6711:     }
 6712: #MARK ->
 6713: 
 6714:     $env{'internal.start_page'}++;
 6715:     my $result;
 6716: 
 6717:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6718:         $result .= 
 6719:                   &xml_begin() . &headtag($title,$head_extra,\%head_args);
 6720: #replace prev line by
 6721: #                 &xml_begin() . &headtag($title, $head_extra, $args);
 6722:     }
 6723:     
 6724:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6725: 	if ($args->{'frameset'}) {
 6726: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6727: 						$args->{'add_entries'});
 6728: 	    $result .= "\n<frameset $attr_string>\n";
 6729:         } else {
 6730:             $result .=
 6731:                 &bodytag($title, 
 6732:                          $args->{'function'},       $args->{'add_entries'},
 6733:                          $args->{'only_body'},      $args->{'domain'},
 6734:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6735:                          $args->{'bgcolor'},        $args);
 6736:         }
 6737:     }
 6738: 
 6739:     if ($args->{'js_ready'}) {
 6740: 		$result = &js_ready($result);
 6741:     }
 6742:     if ($args->{'html_encode'}) {
 6743: 		$result = &html_encode($result);
 6744:     }
 6745: 
 6746:     # Preparation for new and consistent functionlist at top of screen
 6747:     # if ($args->{'functionlist'}) {
 6748:     #            $result .= &build_functionlist();
 6749:     #}
 6750: 
 6751:     # Don't add anything more if only_body wanted or in const space
 6752:     return $result if    $args->{'only_body'} 
 6753:                       || $env{'request.state'} eq 'construct';
 6754: 
 6755:     #Breadcrumbs
 6756:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6757: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6758: 		#if any br links exists, add them to the breadcrumbs
 6759: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6760: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6761: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6762: 			}
 6763: 		}
 6764: 
 6765: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6766: 		if(exists($args->{'bread_crumbs_component'})){
 6767: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6768: 		}else{
 6769: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6770: 		}
 6771:     }
 6772:     return $result;
 6773: }
 6774: 
 6775: sub end_page {
 6776:     my ($args) = @_;
 6777:     $env{'internal.end_page'}++;
 6778:     my $result;
 6779:     if ($args->{'discussion'}) {
 6780: 	my ($target,$parser);
 6781: 	if (ref($args->{'discussion'})) {
 6782: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6783: 				$args->{'discussion'}{'parser'});
 6784: 	}
 6785: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6786:     }
 6787: 
 6788:     if ($args->{'frameset'}) {
 6789: 	$result .= '</frameset>';
 6790:     } else {
 6791: 	$result .= &endbodytag($args);
 6792:     }
 6793:     $result .= "\n</html>";
 6794: 
 6795:     if ($args->{'js_ready'}) {
 6796: 	$result = &js_ready($result);
 6797:     }
 6798: 
 6799:     if ($args->{'html_encode'}) {
 6800: 	$result = &html_encode($result);
 6801:     }
 6802: 
 6803:     return $result;
 6804: }
 6805: 
 6806: sub html_encode {
 6807:     my ($result) = @_;
 6808: 
 6809:     $result = &HTML::Entities::encode($result,'<>&"');
 6810:     
 6811:     return $result;
 6812: }
 6813: sub js_ready {
 6814:     my ($result) = @_;
 6815: 
 6816:     $result =~ s/[\n\r]/ /xmsg;
 6817:     $result =~ s/\\/\\\\/xmsg;
 6818:     $result =~ s/'/\\'/xmsg;
 6819:     $result =~ s{</}{<\\/}xmsg;
 6820:     
 6821:     return $result;
 6822: }
 6823: 
 6824: sub validate_page {
 6825:     if (  exists($env{'internal.start_page'})
 6826: 	  &&     $env{'internal.start_page'} > 1) {
 6827: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6828: 				 $env{'internal.start_page'}.' '.
 6829: 				 $ENV{'request.filename'});
 6830:     }
 6831:     if (  exists($env{'internal.end_page'})
 6832: 	  &&     $env{'internal.end_page'} > 1) {
 6833: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6834: 				 $env{'internal.end_page'}.' '.
 6835: 				 $env{'request.filename'});
 6836:     }
 6837:     if (     exists($env{'internal.start_page'})
 6838: 	&& ! exists($env{'internal.end_page'})) {
 6839: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6840: 				 $env{'request.filename'});
 6841:     }
 6842:     if (   ! exists($env{'internal.start_page'})
 6843: 	&&   exists($env{'internal.end_page'})) {
 6844: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6845: 				 $env{'request.filename'});
 6846:     }
 6847: }
 6848: 
 6849: sub simple_error_page {
 6850:     my ($r,$title,$msg) = @_;
 6851:     my $page =
 6852: 	&Apache::loncommon::start_page($title).
 6853: 	&mt($msg).
 6854: 	&Apache::loncommon::end_page();
 6855:     if (ref($r)) {
 6856: 	$r->print($page);
 6857: 	return;
 6858:     }
 6859:     return $page;
 6860: }
 6861: 
 6862: {
 6863:     my @row_count;
 6864: 
 6865:     sub start_data_table_count {
 6866:         unshift(@row_count, 0);
 6867:         return;
 6868:     }
 6869: 
 6870:     sub end_data_table_count {
 6871:         shift(@row_count);
 6872:         return;
 6873:     }
 6874: 
 6875:     sub start_data_table {
 6876: 	my ($add_class) = @_;
 6877: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6878: 	&start_data_table_count();
 6879: 	return '<table class="'.$css_class.'">'."\n";
 6880:     }
 6881: 
 6882:     sub end_data_table {
 6883: 	&end_data_table_count();
 6884: 	return '</table>'."\n";;
 6885:     }
 6886: 
 6887:     sub start_data_table_row {
 6888: 	my ($add_class, $id) = @_;
 6889: 	$row_count[0]++;
 6890: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6891: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6892:         $id = (' id="'.$id.'"') unless ($id eq '');
 6893:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6894:     }
 6895:     
 6896:     sub continue_data_table_row {
 6897: 	my ($add_class, $id) = @_;
 6898: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6899: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6900:         $id = (' id="'.$id.'"') unless ($id eq '');
 6901:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 6902:     }
 6903: 
 6904:     sub end_data_table_row {
 6905: 	return '</tr>'."\n";;
 6906:     }
 6907: 
 6908:     sub start_data_table_empty_row {
 6909: #	$row_count[0]++;
 6910: 	return  '<tr class="LC_empty_row" >'."\n";;
 6911:     }
 6912: 
 6913:     sub end_data_table_empty_row {
 6914: 	return '</tr>'."\n";;
 6915:     }
 6916: 
 6917:     sub start_data_table_header_row {
 6918: 	return  '<tr class="LC_header_row">'."\n";;
 6919:     }
 6920: 
 6921:     sub end_data_table_header_row {
 6922: 	return '</tr>'."\n";;
 6923:     }
 6924: 
 6925:     sub data_table_caption {
 6926:         my $caption = shift;
 6927:         return "<caption class=\"LC_caption\">$caption</caption>";
 6928:     }
 6929: }
 6930: 
 6931: =pod
 6932: 
 6933: =item * &inhibit_menu_check($arg)
 6934: 
 6935: Checks for a inhibitmenu state and generates output to preserve it
 6936: 
 6937: Inputs:         $arg - can be any of
 6938:                      - undef - in which case the return value is a string 
 6939:                                to add  into arguments list of a uri
 6940:                      - 'input' - in which case the return value is a HTML
 6941:                                  <form> <input> field of type hidden to
 6942:                                  preserve the value
 6943:                      - a url - in which case the return value is the url with
 6944:                                the neccesary cgi args added to preserve the
 6945:                                inhibitmenu state
 6946:                      - a ref to a url - no return value, but the string is
 6947:                                         updated to include the neccessary cgi
 6948:                                         args to preserve the inhibitmenu state
 6949: 
 6950: =cut
 6951: 
 6952: sub inhibit_menu_check {
 6953:     my ($arg) = @_;
 6954:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6955:     if ($arg eq 'input') {
 6956: 	if ($env{'form.inhibitmenu'}) {
 6957: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6958: 	} else {
 6959: 	    return
 6960: 	}
 6961:     }
 6962:     if ($env{'form.inhibitmenu'}) {
 6963: 	if (ref($arg)) {
 6964: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6965: 	} elsif ($arg eq '') {
 6966: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6967: 	} else {
 6968: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6969: 	}
 6970:     }
 6971:     if (!ref($arg)) {
 6972: 	return $arg;
 6973:     }
 6974: }
 6975: 
 6976: ###############################################
 6977: 
 6978: =pod
 6979: 
 6980: =back
 6981: 
 6982: =head1 User Information Routines
 6983: 
 6984: =over 4
 6985: 
 6986: =item * &get_users_function()
 6987: 
 6988: Used by &bodytag to determine the current users primary role.
 6989: Returns either 'student','coordinator','admin', or 'author'.
 6990: 
 6991: =cut
 6992: 
 6993: ###############################################
 6994: sub get_users_function {
 6995:     my $function = 'norole';
 6996:     if ($env{'request.role'}=~/^(st)/) {
 6997:         $function='student';
 6998:     }
 6999:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 7000:         $function='coordinator';
 7001:     }
 7002:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 7003:         $function='admin';
 7004:     }
 7005:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 7006:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 7007:         $function='author';
 7008:     }
 7009:     return $function;
 7010: }
 7011: 
 7012: ###############################################
 7013: 
 7014: =pod
 7015: 
 7016: =item * &show_course()
 7017: 
 7018: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 7019: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 7020: 
 7021: Inputs:
 7022: None
 7023: 
 7024: Outputs:
 7025: Scalar: 1 if 'Course' to be used, 0 otherwise.
 7026: 
 7027: =cut
 7028: 
 7029: ###############################################
 7030: sub show_course {
 7031:     my $course = !$env{'user.adv'};
 7032:     if (!$env{'user.adv'}) {
 7033:         foreach my $env (keys(%env)) {
 7034:             next if ($env !~ m/^user\.priv\./);
 7035:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 7036:                 $course = 0;
 7037:                 last;
 7038:             }
 7039:         }
 7040:     }
 7041:     return $course;
 7042: }
 7043: 
 7044: ###############################################
 7045: 
 7046: =pod
 7047: 
 7048: =item * &check_user_status()
 7049: 
 7050: Determines current status of supplied role for a
 7051: specific user. Roles can be active, previous or future.
 7052: 
 7053: Inputs: 
 7054: user's domain, user's username, course's domain,
 7055: course's number, optional section ID.
 7056: 
 7057: Outputs:
 7058: role status: active, previous or future. 
 7059: 
 7060: =cut
 7061: 
 7062: sub check_user_status {
 7063:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 7064:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 7065:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname,'.',undef,$extra);
 7066:     my @uroles = keys %userinfo;
 7067:     my $srchstr;
 7068:     my $active_chk = 'none';
 7069:     my $now = time;
 7070:     if (@uroles > 0) {
 7071:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 7072:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 7073:         } else {
 7074:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 7075:         }
 7076:         if (grep/^\Q$srchstr\E$/,@uroles) {
 7077:             my $role_end = 0;
 7078:             my $role_start = 0;
 7079:             $active_chk = 'active';
 7080:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 7081:                 $role_end = $1;
 7082:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 7083:                     $role_start = $1;
 7084:                 }
 7085:             }
 7086:             if ($role_start > 0) {
 7087:                 if ($now < $role_start) {
 7088:                     $active_chk = 'future';
 7089:                 }
 7090:             }
 7091:             if ($role_end > 0) {
 7092:                 if ($now > $role_end) {
 7093:                     $active_chk = 'previous';
 7094:                 }
 7095:             }
 7096:         }
 7097:     }
 7098:     return $active_chk;
 7099: }
 7100: 
 7101: ###############################################
 7102: 
 7103: =pod
 7104: 
 7105: =item * &get_sections()
 7106: 
 7107: Determines all the sections for a course including
 7108: sections with students and sections containing other roles.
 7109: Incoming parameters: 
 7110: 
 7111: 1. domain
 7112: 2. course number 
 7113: 3. reference to array containing roles for which sections should 
 7114: be gathered (optional).
 7115: 4. reference to array containing status types for which sections 
 7116: should be gathered (optional).
 7117: 
 7118: If the third argument is undefined, sections are gathered for any role. 
 7119: If the fourth argument is undefined, sections are gathered for any status.
 7120: Permissible values are 'active' or 'future' or 'previous'.
 7121:  
 7122: Returns section hash (keys are section IDs, values are
 7123: number of users in each section), subject to the
 7124: optional roles filter, optional status filter 
 7125: 
 7126: =cut
 7127: 
 7128: ###############################################
 7129: sub get_sections {
 7130:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7131:     if (!defined($cdom) || !defined($cnum)) {
 7132:         my $cid =  $env{'request.course.id'};
 7133: 
 7134: 	return if (!defined($cid));
 7135: 
 7136:         $cdom = $env{'course.'.$cid.'.domain'};
 7137:         $cnum = $env{'course.'.$cid.'.num'};
 7138:     }
 7139: 
 7140:     my %sectioncount;
 7141:     my $now = time;
 7142: 
 7143:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7144: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7145: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7146: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7147:         my $start_index = &Apache::loncoursedata::CL_START();
 7148:         my $end_index = &Apache::loncoursedata::CL_END();
 7149:         my $status;
 7150: 	while (my ($student,$data) = each(%$classlist)) {
 7151: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7152: 				                     $data->[$status_index],
 7153:                                                      $data->[$start_index],
 7154:                                                      $data->[$end_index]);
 7155:             if ($stu_status eq 'Active') {
 7156:                 $status = 'active';
 7157:             } elsif ($end < $now) {
 7158:                 $status = 'previous';
 7159:             } elsif ($start > $now) {
 7160:                 $status = 'future';
 7161:             } 
 7162: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7163:                 if ((!defined($possible_status)) || (($status ne '') && 
 7164:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7165: 		    $sectioncount{$section}++;
 7166:                 }
 7167: 	    }
 7168: 	}
 7169:     }
 7170:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7171:     foreach my $user (sort(keys(%courseroles))) {
 7172: 	if ($user !~ /^(\w{2})/) { next; }
 7173: 	my ($role) = ($user =~ /^(\w{2})/);
 7174: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7175: 	my ($section,$status);
 7176: 	if ($role eq 'cr' &&
 7177: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7178: 	    $section=$1;
 7179: 	}
 7180: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7181: 	if (!defined($section) || $section eq '-1') { next; }
 7182:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7183:         if ($end == -1 && $start == -1) {
 7184:             next; #deleted role
 7185:         }
 7186:         if (!defined($possible_status)) { 
 7187:             $sectioncount{$section}++;
 7188:         } else {
 7189:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7190:                 $status = 'active';
 7191:             } elsif ($end < $now) {
 7192:                 $status = 'future';
 7193:             } elsif ($start > $now) {
 7194:                 $status = 'previous';
 7195:             }
 7196:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7197:                 $sectioncount{$section}++;
 7198:             }
 7199:         }
 7200:     }
 7201:     return %sectioncount;
 7202: }
 7203: 
 7204: ###############################################
 7205: 
 7206: =pod
 7207: 
 7208: =item * &get_course_users()
 7209: 
 7210: Retrieves usernames:domains for users in the specified course
 7211: with specific role(s), and access status. 
 7212: 
 7213: Incoming parameters:
 7214: 1. course domain
 7215: 2. course number
 7216: 3. access status: users must have - either active, 
 7217: previous, future, or all.
 7218: 4. reference to array of permissible roles
 7219: 5. reference to array of section restrictions (optional)
 7220: 6. reference to results object (hash of hashes).
 7221: 7. reference to optional userdata hash
 7222: 8. reference to optional statushash
 7223: 9. flag if privileged users (except those set to unhide in
 7224:    course settings) should be excluded    
 7225: Keys of top level results hash are roles.
 7226: Keys of inner hashes are username:domain, with 
 7227: values set to access type.
 7228: Optional userdata hash returns an array with arguments in the 
 7229: same order as loncoursedata::get_classlist() for student data.
 7230: 
 7231: Optional statushash returns
 7232: 
 7233: Entries for end, start, section and status are blank because
 7234: of the possibility of multiple values for non-student roles.
 7235: 
 7236: =cut
 7237: 
 7238: ###############################################
 7239: 
 7240: sub get_course_users {
 7241:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7242:     my %idx = ();
 7243:     my %seclists;
 7244: 
 7245:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7246:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7247:     $idx{end} = &Apache::loncoursedata::CL_END();
 7248:     $idx{start} = &Apache::loncoursedata::CL_START();
 7249:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7250:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7251:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7252:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7253: 
 7254:     if (grep(/^st$/,@{$roles})) {
 7255:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7256:         my $now = time;
 7257:         foreach my $student (keys(%{$classlist})) {
 7258:             my $match = 0;
 7259:             my $secmatch = 0;
 7260:             my $section = $$classlist{$student}[$idx{section}];
 7261:             my $status = $$classlist{$student}[$idx{status}];
 7262:             if ($section eq '') {
 7263:                 $section = 'none';
 7264:             }
 7265:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7266:                 if (grep(/^all$/,@{$sections})) {
 7267:                     $secmatch = 1;
 7268:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7269:                     if (grep(/^none$/,@{$sections})) {
 7270:                         $secmatch = 1;
 7271:                     }
 7272:                 } else {  
 7273: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7274: 		        $secmatch = 1;
 7275:                     }
 7276: 		}
 7277:                 if (!$secmatch) {
 7278:                     next;
 7279:                 }
 7280:             }
 7281:             if (defined($$types{'active'})) {
 7282:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7283:                     push(@{$$users{st}{$student}},'active');
 7284:                     $match = 1;
 7285:                 }
 7286:             }
 7287:             if (defined($$types{'previous'})) {
 7288:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7289:                     push(@{$$users{st}{$student}},'previous');
 7290:                     $match = 1;
 7291:                 }
 7292:             }
 7293:             if (defined($$types{'future'})) {
 7294:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7295:                     push(@{$$users{st}{$student}},'future');
 7296:                     $match = 1;
 7297:                 }
 7298:             }
 7299:             if ($match) {
 7300:                 push(@{$seclists{$student}},$section);
 7301:                 if (ref($userdata) eq 'HASH') {
 7302:                     $$userdata{$student} = $$classlist{$student};
 7303:                 }
 7304:                 if (ref($statushash) eq 'HASH') {
 7305:                     $statushash->{$student}{'st'}{$section} = $status;
 7306:                 }
 7307:             }
 7308:         }
 7309:     }
 7310:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7311:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7312:         my $now = time;
 7313:         my %displaystatus = ( previous => 'Expired',
 7314:                               active   => 'Active',
 7315:                               future   => 'Future',
 7316:                             );
 7317:         my %nothide;
 7318:         if ($hidepriv) {
 7319:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7320:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7321:                 if ($user !~ /:/) {
 7322:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7323:                 } else {
 7324:                     $nothide{$user} = 1;
 7325:                 }
 7326:             }
 7327:         }
 7328:         foreach my $person (sort(keys(%coursepersonnel))) {
 7329:             my $match = 0;
 7330:             my $secmatch = 0;
 7331:             my $status;
 7332:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7333:             $user =~ s/:$//;
 7334:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7335:             if ($end == -1 || $start == -1) {
 7336:                 next;
 7337:             }
 7338:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7339:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7340:                 my ($uname,$udom) = split(/:/,$user);
 7341:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7342:                     if (grep(/^all$/,@{$sections})) {
 7343:                         $secmatch = 1;
 7344:                     } elsif ($usec eq '') {
 7345:                         if (grep(/^none$/,@{$sections})) {
 7346:                             $secmatch = 1;
 7347:                         }
 7348:                     } else {
 7349:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7350:                             $secmatch = 1;
 7351:                         }
 7352:                     }
 7353:                     if (!$secmatch) {
 7354:                         next;
 7355:                     }
 7356:                 }
 7357:                 if ($usec eq '') {
 7358:                     $usec = 'none';
 7359:                 }
 7360:                 if ($uname ne '' && $udom ne '') {
 7361:                     if ($hidepriv) {
 7362:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7363:                             (!$nothide{$uname.':'.$udom})) {
 7364:                             next;
 7365:                         }
 7366:                     }
 7367:                     if ($end > 0 && $end < $now) {
 7368:                         $status = 'previous';
 7369:                     } elsif ($start > $now) {
 7370:                         $status = 'future';
 7371:                     } else {
 7372:                         $status = 'active';
 7373:                     }
 7374:                     foreach my $type (keys(%{$types})) { 
 7375:                         if ($status eq $type) {
 7376:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7377:                                 push(@{$$users{$role}{$user}},$type);
 7378:                             }
 7379:                             $match = 1;
 7380:                         }
 7381:                     }
 7382:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7383:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7384: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7385:                         }
 7386:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7387:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7388:                         }
 7389:                         if (ref($statushash) eq 'HASH') {
 7390:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7391:                         }
 7392:                     }
 7393:                 }
 7394:             }
 7395:         }
 7396:         if (grep(/^ow$/,@{$roles})) {
 7397:             if ((defined($cdom)) && (defined($cnum))) {
 7398:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7399:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7400:                     my $owner = $csettings{'internal.courseowner'};
 7401:                     next if ($owner eq '');
 7402:                     my ($ownername,$ownerdom);
 7403:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7404:                         $ownername = $1;
 7405:                         $ownerdom = $2;
 7406:                     } else {
 7407:                         $ownername = $owner;
 7408:                         $ownerdom = $cdom;
 7409:                         $owner = $ownername.':'.$ownerdom;
 7410:                     }
 7411:                     @{$$users{'ow'}{$owner}} = 'any';
 7412:                     if (defined($userdata) && 
 7413: 			!exists($$userdata{$owner})) {
 7414: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7415:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7416:                             push(@{$seclists{$owner}},'none');
 7417:                         }
 7418:                         if (ref($statushash) eq 'HASH') {
 7419:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7420:                         }
 7421: 		    }
 7422:                 }
 7423:             }
 7424:         }
 7425:         foreach my $user (keys(%seclists)) {
 7426:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7427:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7428:         }
 7429:     }
 7430:     return;
 7431: }
 7432: 
 7433: sub get_user_info {
 7434:     my ($udom,$uname,$idx,$userdata) = @_;
 7435:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7436: 	&plainname($uname,$udom,'lastname');
 7437:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7438:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7439:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7440:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7441:     return;
 7442: }
 7443: 
 7444: ###############################################
 7445: 
 7446: =pod
 7447: 
 7448: =item * &get_user_quota()
 7449: 
 7450: Retrieves quota assigned for storage of portfolio files for a user  
 7451: 
 7452: Incoming parameters:
 7453: 1. user's username
 7454: 2. user's domain
 7455: 
 7456: Returns:
 7457: 1. Disk quota (in Mb) assigned to student.
 7458: 2. (Optional) Type of setting: custom or default
 7459:    (individually assigned or default for user's 
 7460:    institutional status).
 7461: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7462:    or student - types as defined in localenroll::inst_usertypes 
 7463:    for user's domain, which determines default quota for user.
 7464: 4. (Optional) - Default quota which would apply to the user.
 7465: 
 7466: If a value has been stored in the user's environment, 
 7467: it will return that, otherwise it returns the maximal default
 7468: defined for the user's instituional status(es) in the domain.
 7469: 
 7470: =cut
 7471: 
 7472: ###############################################
 7473: 
 7474: 
 7475: sub get_user_quota {
 7476:     my ($uname,$udom) = @_;
 7477:     my ($quota,$quotatype,$settingstatus,$defquota);
 7478:     if (!defined($udom)) {
 7479:         $udom = $env{'user.domain'};
 7480:     }
 7481:     if (!defined($uname)) {
 7482:         $uname = $env{'user.name'};
 7483:     }
 7484:     if (($udom eq '' || $uname eq '') ||
 7485:         ($udom eq 'public') && ($uname eq 'public')) {
 7486:         $quota = 0;
 7487:         $quotatype = 'default';
 7488:         $defquota = 0; 
 7489:     } else {
 7490:         my $inststatus;
 7491:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7492:             $quota = $env{'environment.portfolioquota'};
 7493:             $inststatus = $env{'environment.inststatus'};
 7494:         } else {
 7495:             my %userenv = 
 7496:                 &Apache::lonnet::get('environment',['portfolioquota',
 7497:                                      'inststatus'],$udom,$uname);
 7498:             my ($tmp) = keys(%userenv);
 7499:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7500:                 $quota = $userenv{'portfolioquota'};
 7501:                 $inststatus = $userenv{'inststatus'};
 7502:             } else {
 7503:                 undef(%userenv);
 7504:             }
 7505:         }
 7506:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7507:         if ($quota eq '') {
 7508:             $quota = $defquota;
 7509:             $quotatype = 'default';
 7510:         } else {
 7511:             $quotatype = 'custom';
 7512:         }
 7513:     }
 7514:     if (wantarray) {
 7515:         return ($quota,$quotatype,$settingstatus,$defquota);
 7516:     } else {
 7517:         return $quota;
 7518:     }
 7519: }
 7520: 
 7521: ###############################################
 7522: 
 7523: =pod
 7524: 
 7525: =item * &default_quota()
 7526: 
 7527: Retrieves default quota assigned for storage of user portfolio files,
 7528: given an (optional) user's institutional status.
 7529: 
 7530: Incoming parameters:
 7531: 1. domain
 7532: 2. (Optional) institutional status(es).  This is a : separated list of 
 7533:    status types (e.g., faculty, staff, student etc.)
 7534:    which apply to the user for whom the default is being retrieved.
 7535:    If the institutional status string in undefined, the domain
 7536:    default quota will be returned. 
 7537: 
 7538: Returns:
 7539: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7540: 2. (Optional) institutional type which determined the value of the
 7541:    default quota.
 7542: 
 7543: If a value has been stored in the domain's configuration db,
 7544: it will return that, otherwise it returns 20 (for backwards 
 7545: compatibility with domains which have not set up a configuration
 7546: db file; the original statically defined portfolio quota was 20 Mb). 
 7547: 
 7548: If the user's status includes multiple types (e.g., staff and student),
 7549: the largest default quota which applies to the user determines the
 7550: default quota returned.
 7551: 
 7552: =back
 7553: 
 7554: =cut
 7555: 
 7556: ###############################################
 7557: 
 7558: 
 7559: sub default_quota {
 7560:     my ($udom,$inststatus) = @_;
 7561:     my ($defquota,$settingstatus);
 7562:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7563:                                             ['quotas'],$udom);
 7564:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7565:         if ($inststatus ne '') {
 7566:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7567:             foreach my $item (@statuses) {
 7568:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7569:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7570:                         if ($defquota eq '') {
 7571:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7572:                             $settingstatus = $item;
 7573:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7574:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7575:                             $settingstatus = $item;
 7576:                         }
 7577:                     }
 7578:                 } else {
 7579:                     if ($quotahash{'quotas'}{$item} ne '') {
 7580:                         if ($defquota eq '') {
 7581:                             $defquota = $quotahash{'quotas'}{$item};
 7582:                             $settingstatus = $item;
 7583:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7584:                             $defquota = $quotahash{'quotas'}{$item};
 7585:                             $settingstatus = $item;
 7586:                         }
 7587:                     }
 7588:                 }
 7589:             }
 7590:         }
 7591:         if ($defquota eq '') {
 7592:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7593:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7594:             } else {
 7595:                 $defquota = $quotahash{'quotas'}{'default'};
 7596:             }
 7597:             $settingstatus = 'default';
 7598:         }
 7599:     } else {
 7600:         $settingstatus = 'default';
 7601:         $defquota = 20;
 7602:     }
 7603:     if (wantarray) {
 7604:         return ($defquota,$settingstatus);
 7605:     } else {
 7606:         return $defquota;
 7607:     }
 7608: }
 7609: 
 7610: sub get_secgrprole_info {
 7611:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7612:     my %sections_count = &get_sections($cdom,$cnum);
 7613:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7614:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7615:     my @groups = sort(keys(%curr_groups));
 7616:     my $allroles = [];
 7617:     my $rolehash;
 7618:     my $accesshash = {
 7619:                      active => 'Currently has access',
 7620:                      future => 'Will have future access',
 7621:                      previous => 'Previously had access',
 7622:                   };
 7623:     if ($needroles) {
 7624:         $rolehash = {'all' => 'all'};
 7625:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7626: 	if (&Apache::lonnet::error(%user_roles)) {
 7627: 	    undef(%user_roles);
 7628: 	}
 7629:         foreach my $item (keys(%user_roles)) {
 7630:             my ($role)=split(/\:/,$item,2);
 7631:             if ($role eq 'cr') { next; }
 7632:             if ($role =~ /^cr/) {
 7633:                 $$rolehash{$role} = (split('/',$role))[3];
 7634:             } else {
 7635:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7636:             }
 7637:         }
 7638:         foreach my $key (sort(keys(%{$rolehash}))) {
 7639:             push(@{$allroles},$key);
 7640:         }
 7641:         push (@{$allroles},'st');
 7642:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7643:     }
 7644:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7645: }
 7646: 
 7647: sub user_picker {
 7648:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7649:     my $currdom = $dom;
 7650:     my %curr_selected = (
 7651:                         srchin => 'dom',
 7652:                         srchby => 'lastname',
 7653:                       );
 7654:     my $srchterm;
 7655:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7656:         if ($srch->{'srchby'} ne '') {
 7657:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7658:         }
 7659:         if ($srch->{'srchin'} ne '') {
 7660:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7661:         }
 7662:         if ($srch->{'srchtype'} ne '') {
 7663:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7664:         }
 7665:         if ($srch->{'srchdomain'} ne '') {
 7666:             $currdom = $srch->{'srchdomain'};
 7667:         }
 7668:         $srchterm = $srch->{'srchterm'};
 7669:     }
 7670:     my %lt=&Apache::lonlocal::texthash(
 7671:                     'usr'       => 'Search criteria',
 7672:                     'doma'      => 'Domain/institution to search',
 7673:                     'uname'     => 'username',
 7674:                     'lastname'  => 'last name',
 7675:                     'lastfirst' => 'last name, first name',
 7676:                     'crs'       => 'in this course',
 7677:                     'dom'       => 'in selected LON-CAPA domain', 
 7678:                     'alc'       => 'all LON-CAPA',
 7679:                     'instd'     => 'in institutional directory for selected domain',
 7680:                     'exact'     => 'is',
 7681:                     'contains'  => 'contains',
 7682:                     'begins'    => 'begins with',
 7683:                     'youm'      => "You must include some text to search for.",
 7684:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7685:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7686:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7687:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7688:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7689:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7690:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7691:                                        );
 7692:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7693:     my $srchinsel = ' <select name="srchin">';
 7694: 
 7695:     my @srchins = ('crs','dom','alc','instd');
 7696: 
 7697:     foreach my $option (@srchins) {
 7698:         # FIXME 'alc' option unavailable until 
 7699:         #       loncreateuser::print_user_query_page()
 7700:         #       has been completed.
 7701:         next if ($option eq 'alc');
 7702:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7703:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7704:         if ($curr_selected{'srchin'} eq $option) {
 7705:             $srchinsel .= ' 
 7706:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7707:         } else {
 7708:             $srchinsel .= '
 7709:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7710:         }
 7711:     }
 7712:     $srchinsel .= "\n  </select>\n";
 7713: 
 7714:     my $srchbysel =  ' <select name="srchby">';
 7715:     foreach my $option ('lastname','lastfirst','uname') {
 7716:         if ($curr_selected{'srchby'} eq $option) {
 7717:             $srchbysel .= '
 7718:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7719:         } else {
 7720:             $srchbysel .= '
 7721:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7722:          }
 7723:     }
 7724:     $srchbysel .= "\n  </select>\n";
 7725: 
 7726:     my $srchtypesel = ' <select name="srchtype">';
 7727:     foreach my $option ('begins','contains','exact') {
 7728:         if ($curr_selected{'srchtype'} eq $option) {
 7729:             $srchtypesel .= '
 7730:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7731:         } else {
 7732:             $srchtypesel .= '
 7733:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7734:         }
 7735:     }
 7736:     $srchtypesel .= "\n  </select>\n";
 7737: 
 7738:     my ($newuserscript,$new_user_create);
 7739: 
 7740:     if ($forcenewuser) {
 7741:         if (ref($srch) eq 'HASH') {
 7742:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7743:                 if ($cancreate) {
 7744:                     $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>';
 7745:                 } else {
 7746:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7747:                     my %usertypetext = (
 7748:                         official   => 'institutional',
 7749:                         unofficial => 'non-institutional',
 7750:                     );
 7751:                     $new_user_create = '<p class="LC_warning">'
 7752:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7753:                                       .' '
 7754:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7755:                                           ,'<a href="'.$helplink.'">','</a>')
 7756:                                       .'</p><br />';
 7757:                 }
 7758:             }
 7759:         }
 7760: 
 7761:         $newuserscript = <<"ENDSCRIPT";
 7762: 
 7763: function setSearch(createnew,callingForm) {
 7764:     if (createnew == 1) {
 7765:         for (var i=0; i<callingForm.srchby.length; i++) {
 7766:             if (callingForm.srchby.options[i].value == 'uname') {
 7767:                 callingForm.srchby.selectedIndex = i;
 7768:             }
 7769:         }
 7770:         for (var i=0; i<callingForm.srchin.length; i++) {
 7771:             if ( callingForm.srchin.options[i].value == 'dom') {
 7772: 		callingForm.srchin.selectedIndex = i;
 7773:             }
 7774:         }
 7775:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7776:             if (callingForm.srchtype.options[i].value == 'exact') {
 7777:                 callingForm.srchtype.selectedIndex = i;
 7778:             }
 7779:         }
 7780:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7781:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7782:                 callingForm.srchdomain.selectedIndex = i;
 7783:             }
 7784:         }
 7785:     }
 7786: }
 7787: ENDSCRIPT
 7788: 
 7789:     }
 7790: 
 7791:     my $output = <<"END_BLOCK";
 7792: <script type="text/javascript">
 7793: // <![CDATA[
 7794: function validateEntry(callingForm) {
 7795: 
 7796:     var checkok = 1;
 7797:     var srchin;
 7798:     for (var i=0; i<callingForm.srchin.length; i++) {
 7799: 	if ( callingForm.srchin[i].checked ) {
 7800: 	    srchin = callingForm.srchin[i].value;
 7801: 	}
 7802:     }
 7803: 
 7804:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7805:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7806:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7807:     var srchterm =  callingForm.srchterm.value;
 7808:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7809:     var msg = "";
 7810: 
 7811:     if (srchterm == "") {
 7812:         checkok = 0;
 7813:         msg += "$lt{'youm'}\\n";
 7814:     }
 7815: 
 7816:     if (srchtype== 'begins') {
 7817:         if (srchterm.length < 2) {
 7818:             checkok = 0;
 7819:             msg += "$lt{'thte'}\\n";
 7820:         }
 7821:     }
 7822: 
 7823:     if (srchtype== 'contains') {
 7824:         if (srchterm.length < 3) {
 7825:             checkok = 0;
 7826:             msg += "$lt{'thet'}\\n";
 7827:         }
 7828:     }
 7829:     if (srchin == 'instd') {
 7830:         if (srchdomain == '') {
 7831:             checkok = 0;
 7832:             msg += "$lt{'yomc'}\\n";
 7833:         }
 7834:     }
 7835:     if (srchin == 'dom') {
 7836:         if (srchdomain == '') {
 7837:             checkok = 0;
 7838:             msg += "$lt{'ymcd'}\\n";
 7839:         }
 7840:     }
 7841:     if (srchby == 'lastfirst') {
 7842:         if (srchterm.indexOf(",") == -1) {
 7843:             checkok = 0;
 7844:             msg += "$lt{'whus'}\\n";
 7845:         }
 7846:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7847:             checkok = 0;
 7848:             msg += "$lt{'whse'}\\n";
 7849:         }
 7850:     }
 7851:     if (checkok == 0) {
 7852:         alert("$lt{'thfo'}\\n"+msg);
 7853:         return;
 7854:     }
 7855:     if (checkok == 1) {
 7856:         callingForm.submit();
 7857:     }
 7858: }
 7859: 
 7860: $newuserscript
 7861: 
 7862: // ]]>
 7863: </script>
 7864: 
 7865: $new_user_create
 7866: 
 7867: END_BLOCK
 7868: 
 7869:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7870:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7871:                $domform.
 7872:                &Apache::lonhtmlcommon::row_closure().
 7873:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7874:                $srchbysel.
 7875:                $srchtypesel. 
 7876:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7877:                $srchinsel.
 7878:                &Apache::lonhtmlcommon::row_closure(1). 
 7879:                &Apache::lonhtmlcommon::end_pick_box().
 7880:                '<br />';
 7881:     return $output;
 7882: }
 7883: 
 7884: sub user_rule_check {
 7885:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7886:     my $response;
 7887:     if (ref($usershash) eq 'HASH') {
 7888:         foreach my $user (keys(%{$usershash})) {
 7889:             my ($uname,$udom) = split(/:/,$user);
 7890:             next if ($udom eq '' || $uname eq '');
 7891:             my ($id,$newuser);
 7892:             if (ref($usershash->{$user}) eq 'HASH') {
 7893:                 $newuser = $usershash->{$user}->{'newuser'};
 7894:                 $id = $usershash->{$user}->{'id'};
 7895:             }
 7896:             my $inst_response;
 7897:             if (ref($checks) eq 'HASH') {
 7898:                 if (defined($checks->{'username'})) {
 7899:                     ($inst_response,%{$inst_results->{$user}}) = 
 7900:                         &Apache::lonnet::get_instuser($udom,$uname);
 7901:                 } elsif (defined($checks->{'id'})) {
 7902:                     ($inst_response,%{$inst_results->{$user}}) =
 7903:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7904:                 }
 7905:             } else {
 7906:                 ($inst_response,%{$inst_results->{$user}}) =
 7907:                     &Apache::lonnet::get_instuser($udom,$uname);
 7908:                 return;
 7909:             }
 7910:             if (!$got_rules->{$udom}) {
 7911:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7912:                                                   ['usercreation'],$udom);
 7913:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7914:                     foreach my $item ('username','id') {
 7915:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7916:                             $$curr_rules{$udom}{$item} = 
 7917:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7918:                         }
 7919:                     }
 7920:                 }
 7921:                 $got_rules->{$udom} = 1;  
 7922:             }
 7923:             foreach my $item (keys(%{$checks})) {
 7924:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7925:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7926:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7927:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7928:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7929:                                 if ($rule_check{$rule}) {
 7930:                                     $$rulematch{$user}{$item} = $rule;
 7931:                                     if ($inst_response eq 'ok') {
 7932:                                         if (ref($inst_results) eq 'HASH') {
 7933:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7934:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7935:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7936:                                                 }
 7937:                                             }
 7938:                                         }
 7939:                                     }
 7940:                                     last;
 7941:                                 }
 7942:                             }
 7943:                         }
 7944:                     }
 7945:                 }
 7946:             }
 7947:         }
 7948:     }
 7949:     return;
 7950: }
 7951: 
 7952: sub user_rule_formats {
 7953:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7954:     my %text = ( 
 7955:                  'username' => 'Usernames',
 7956:                  'id'       => 'IDs',
 7957:                );
 7958:     my $output;
 7959:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7960:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7961:         if (@{$ruleorder} > 0) {
 7962:             $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>';
 7963:             foreach my $rule (@{$ruleorder}) {
 7964:                 if (ref($curr_rules) eq 'ARRAY') {
 7965:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7966:                         if (ref($rules->{$rule}) eq 'HASH') {
 7967:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7968:                                         $rules->{$rule}{'desc'}.'</li>';
 7969:                         }
 7970:                     }
 7971:                 }
 7972:             }
 7973:             $output .= '</ul>';
 7974:         }
 7975:     }
 7976:     return $output;
 7977: }
 7978: 
 7979: sub instrule_disallow_msg {
 7980:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7981:     my $response;
 7982:     my %text = (
 7983:                   item   => 'username',
 7984:                   items  => 'usernames',
 7985:                   match  => 'matches',
 7986:                   do     => 'does',
 7987:                   action => 'a username',
 7988:                   one    => 'one',
 7989:                );
 7990:     if ($count > 1) {
 7991:         $text{'item'} = 'usernames';
 7992:         $text{'match'} ='match';
 7993:         $text{'do'} = 'do';
 7994:         $text{'action'} = 'usernames',
 7995:         $text{'one'} = 'ones';
 7996:     }
 7997:     if ($checkitem eq 'id') {
 7998:         $text{'items'} = 'IDs';
 7999:         $text{'item'} = 'ID';
 8000:         $text{'action'} = 'an ID';
 8001:         if ($count > 1) {
 8002:             $text{'item'} = 'IDs';
 8003:             $text{'action'} = 'IDs';
 8004:         }
 8005:     }
 8006:     $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 />';
 8007:     if ($mode eq 'upload') {
 8008:         if ($checkitem eq 'username') {
 8009:             $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'}.");
 8010:         } elsif ($checkitem eq 'id') {
 8011:             $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.");
 8012:         }
 8013:     } elsif ($mode eq 'selfcreate') {
 8014:         if ($checkitem eq 'id') {
 8015:             $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.");
 8016:         }
 8017:     } else {
 8018:         if ($checkitem eq 'username') {
 8019:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 8020:         } elsif ($checkitem eq 'id') {
 8021:             $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.");
 8022:         }
 8023:     }
 8024:     return $response;
 8025: }
 8026: 
 8027: sub personal_data_fieldtitles {
 8028:     my %fieldtitles = &Apache::lonlocal::texthash (
 8029:                         id => 'Student/Employee ID',
 8030:                         permanentemail => 'E-mail address',
 8031:                         lastname => 'Last Name',
 8032:                         firstname => 'First Name',
 8033:                         middlename => 'Middle Name',
 8034:                         generation => 'Generation',
 8035:                         gen => 'Generation',
 8036:                         inststatus => 'Affiliation',
 8037:                    );
 8038:     return %fieldtitles;
 8039: }
 8040: 
 8041: sub sorted_inst_types {
 8042:     my ($dom) = @_;
 8043:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 8044:     my $othertitle = &mt('All users');
 8045:     if ($env{'request.course.id'}) {
 8046:         $othertitle  = &mt('Any users');
 8047:     }
 8048:     my @types;
 8049:     if (ref($order) eq 'ARRAY') {
 8050:         @types = @{$order};
 8051:     }
 8052:     if (@types == 0) {
 8053:         if (ref($usertypes) eq 'HASH') {
 8054:             @types = sort(keys(%{$usertypes}));
 8055:         }
 8056:     }
 8057:     if (keys(%{$usertypes}) > 0) {
 8058:         $othertitle = &mt('Other users');
 8059:     }
 8060:     return ($othertitle,$usertypes,\@types);
 8061: }
 8062: 
 8063: sub get_institutional_codes {
 8064:     my ($settings,$allcourses,$LC_code) = @_;
 8065: # Get complete list of course sections to update
 8066:     my @currsections = ();
 8067:     my @currxlists = ();
 8068:     my $coursecode = $$settings{'internal.coursecode'};
 8069: 
 8070:     if ($$settings{'internal.sectionnums'} ne '') {
 8071:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 8072:     }
 8073: 
 8074:     if ($$settings{'internal.crosslistings'} ne '') {
 8075:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 8076:     }
 8077: 
 8078:     if (@currxlists > 0) {
 8079:         foreach (@currxlists) {
 8080:             if (m/^([^:]+):(\w*)$/) {
 8081:                 unless (grep/^$1$/,@{$allcourses}) {
 8082:                     push @{$allcourses},$1;
 8083:                     $$LC_code{$1} = $2;
 8084:                 }
 8085:             }
 8086:         }
 8087:     }
 8088:  
 8089:     if (@currsections > 0) {
 8090:         foreach (@currsections) {
 8091:             if (m/^(\w+):(\w*)$/) {
 8092:                 my $sec = $coursecode.$1;
 8093:                 my $lc_sec = $2;
 8094:                 unless (grep/^$sec$/,@{$allcourses}) {
 8095:                     push @{$allcourses},$sec;
 8096:                     $$LC_code{$sec} = $lc_sec;
 8097:                 }
 8098:             }
 8099:         }
 8100:     }
 8101:     return;
 8102: }
 8103: 
 8104: sub get_standard_codeitems {
 8105:     return ('Year','Semester','Department','Number','Section');
 8106: }
 8107: 
 8108: =pod
 8109: 
 8110: =head1 Slot Helpers
 8111: 
 8112: =over 4
 8113: 
 8114: =item * sorted_slots()
 8115: 
 8116: Sorts an array of slot names in order of slot start time (earliest first). 
 8117: 
 8118: Inputs:
 8119: 
 8120: =over 4
 8121: 
 8122: slotsarr  - Reference to array of unsorted slot names.
 8123: 
 8124: slots     - Reference to hash of hash, where outer hash keys are slot names.
 8125: 
 8126: =back
 8127: 
 8128: Returns:
 8129: 
 8130: =over 4
 8131: 
 8132: sorted   - An array of slot names sorted by the start time of the slot.
 8133: 
 8134: =back
 8135: 
 8136: =back
 8137: 
 8138: =cut
 8139: 
 8140: 
 8141: sub sorted_slots {
 8142:     my ($slotsarr,$slots) = @_;
 8143:     my @sorted;
 8144:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8145:         @sorted =
 8146:             sort {
 8147:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8148:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8149:                      }
 8150:                      if (ref($slots->{$a})) { return -1;}
 8151:                      if (ref($slots->{$b})) { return 1;}
 8152:                      return 0;
 8153:                  } @{$slotsarr};
 8154:     }
 8155:     return @sorted;
 8156: }
 8157: 
 8158: 
 8159: =pod
 8160: 
 8161: =head1 HTTP Helpers
 8162: 
 8163: =over 4
 8164: 
 8165: =item * &get_unprocessed_cgi($query,$possible_names)
 8166: 
 8167: Modify the %env hash to contain unprocessed CGI form parameters held in
 8168: $query.  The parameters listed in $possible_names (an array reference),
 8169: will be set in $env{'form.name'} if they do not already exist.
 8170: 
 8171: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8172: $possible_names is an ref to an array of form element names.  As an example:
 8173: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8174: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8175: 
 8176: =cut
 8177: 
 8178: sub get_unprocessed_cgi {
 8179:   my ($query,$possible_names)= @_;
 8180:   # $Apache::lonxml::debug=1;
 8181:   foreach my $pair (split(/&/,$query)) {
 8182:     my ($name, $value) = split(/=/,$pair);
 8183:     $name = &unescape($name);
 8184:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8185:       $value =~ tr/+/ /;
 8186:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8187:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8188:     }
 8189:   }
 8190: }
 8191: 
 8192: =pod
 8193: 
 8194: =item * &cacheheader() 
 8195: 
 8196: returns cache-controlling header code
 8197: 
 8198: =cut
 8199: 
 8200: sub cacheheader {
 8201:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8202:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8203:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8204:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8205:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8206:     return $output;
 8207: }
 8208: 
 8209: =pod
 8210: 
 8211: =item * &no_cache($r) 
 8212: 
 8213: specifies header code to not have cache
 8214: 
 8215: =cut
 8216: 
 8217: sub no_cache {
 8218:     my ($r) = @_;
 8219:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8220: 	$env{'request.method'} ne 'GET') { return ''; }
 8221:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8222:     $r->no_cache(1);
 8223:     $r->header_out("Expires" => $date);
 8224:     $r->header_out("Pragma" => "no-cache");
 8225: }
 8226: 
 8227: sub content_type {
 8228:     my ($r,$type,$charset) = @_;
 8229:     if ($r) {
 8230: 	#  Note that printout.pl calls this with undef for $r.
 8231: 	&no_cache($r);
 8232:     }
 8233:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8234:     unless ($charset) {
 8235: 	$charset=&Apache::lonlocal::current_encoding;
 8236:     }
 8237:     if ($charset) { $type.='; charset='.$charset; }
 8238:     if ($r) {
 8239: 	$r->content_type($type);
 8240:     } else {
 8241: 	print("Content-type: $type\n\n");
 8242:     }
 8243: }
 8244: 
 8245: =pod
 8246: 
 8247: =item * &add_to_env($name,$value) 
 8248: 
 8249: adds $name to the %env hash with value
 8250: $value, if $name already exists, the entry is converted to an array
 8251: reference and $value is added to the array.
 8252: 
 8253: =cut
 8254: 
 8255: sub add_to_env {
 8256:   my ($name,$value)=@_;
 8257:   if (defined($env{$name})) {
 8258:     if (ref($env{$name})) {
 8259:       #already have multiple values
 8260:       push(@{ $env{$name} },$value);
 8261:     } else {
 8262:       #first time seeing multiple values, convert hash entry to an arrayref
 8263:       my $first=$env{$name};
 8264:       undef($env{$name});
 8265:       push(@{ $env{$name} },$first,$value);
 8266:     }
 8267:   } else {
 8268:     $env{$name}=$value;
 8269:   }
 8270: }
 8271: 
 8272: =pod
 8273: 
 8274: =item * &get_env_multiple($name) 
 8275: 
 8276: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8277: values may be defined and end up as an array ref.
 8278: 
 8279: returns an array of values
 8280: 
 8281: =cut
 8282: 
 8283: sub get_env_multiple {
 8284:     my ($name) = @_;
 8285:     my @values;
 8286:     if (defined($env{$name})) {
 8287:         # exists is it an array
 8288:         if (ref($env{$name})) {
 8289:             @values=@{ $env{$name} };
 8290:         } else {
 8291:             $values[0]=$env{$name};
 8292:         }
 8293:     }
 8294:     return(@values);
 8295: }
 8296: 
 8297: sub ask_for_embedded_content {
 8298:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8299:     my $upload_output = '
 8300:    <form name="upload_embedded" action="'.$actionurl.'"
 8301:                   method="post" enctype="multipart/form-data">';
 8302:     $upload_output .= $state;
 8303:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8304: 
 8305:     my $num = 0;
 8306:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8307:         $upload_output .= &start_data_table_row().
 8308:             '<td>'.$embed_file.'</td><td>';
 8309:         if ($args->{'ignore_remote_references'}
 8310:             && $embed_file =~ m{^\w+://}) {
 8311:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8312:         } elsif ($args->{'error_on_invalid_names'}
 8313:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8314: 
 8315:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8316: 
 8317:         } else {
 8318:             $upload_output .='
 8319:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8320:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8321:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8322:             $upload_output .=
 8323:                 "\n\t\t".
 8324:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8325:                 $attrib.'" />';
 8326:             if (exists($$codebase{$embed_file})) {
 8327:                 $upload_output .=
 8328:                     "\n\t\t".
 8329:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8330:                     &escape($$codebase{$embed_file}).'" />';
 8331:             }
 8332:         }
 8333:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8334:         $num++;
 8335:     }
 8336:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8337:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8338:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8339:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8340:    </form>';
 8341:     return $upload_output;
 8342: }
 8343: 
 8344: sub upload_embedded {
 8345:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8346:         $current_disk_usage) = @_;
 8347:     my $output;
 8348:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8349:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8350:         my $orig_uploaded_filename =
 8351:             $env{'form.embedded_item_'.$i.'.filename'};
 8352: 
 8353:         $env{'form.embedded_orig_'.$i} =
 8354:             &unescape($env{'form.embedded_orig_'.$i});
 8355:         my ($path,$fname) =
 8356:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8357:         # no path, whole string is fname
 8358:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8359: 
 8360:         $path = $env{'form.currentpath'}.$path;
 8361:         $fname = &Apache::lonnet::clean_filename($fname);
 8362:         # See if there is anything left
 8363:         next if ($fname eq '');
 8364: 
 8365:         # Check if file already exists as a file or directory.
 8366:         my ($state,$msg);
 8367:         if ($context eq 'portfolio') {
 8368:             my $port_path = $dirpath;
 8369:             if ($group ne '') {
 8370:                 $port_path = "groups/$group/$port_path";
 8371:             }
 8372:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8373:                                               $dir_root,$port_path,$disk_quota,
 8374:                                               $current_disk_usage,$uname,$udom);
 8375:             if ($state eq 'will_exceed_quota'
 8376:                 || $state eq 'file_locked'
 8377:                 || $state eq 'file_exists' ) {
 8378:                 $output .= $msg;
 8379:                 next;
 8380:             }
 8381:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8382:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8383:             if ($state eq 'exists') {
 8384:                 $output .= $msg;
 8385:                 next;
 8386:             }
 8387:         }
 8388:         # Check if extension is valid
 8389:         if (($fname =~ /\.(\w+)$/) &&
 8390:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8391:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8392:             next;
 8393:         } elsif (($fname =~ /\.(\w+)$/) &&
 8394:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8395:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8396:             next;
 8397:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8398:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8399:             next;
 8400:         }
 8401: 
 8402:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8403:         if ($context eq 'portfolio') {
 8404:             my $result=
 8405:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8406:                                                 $dirpath.$path);
 8407:             if ($result !~ m|^/uploaded/|) {
 8408:                 $output .= '<span class="LC_error">'
 8409:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8410:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8411:                       .'</span><br />';
 8412:                 next;
 8413:             } else {
 8414:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8415:                            $path.$fname.'</span>').'</p>';     
 8416:             }
 8417:         } else {
 8418: # Save the file
 8419:             my $target = $env{'form.embedded_item_'.$i};
 8420:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8421:             my $dest = $fullpath.$fname;
 8422:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8423:             my @parts=split(/\//,$fullpath);
 8424:             my $count;
 8425:             my $filepath = $dir_root;
 8426:             for ($count=4;$count<=$#parts;$count++) {
 8427:                 $filepath .= "/$parts[$count]";
 8428:                 if ((-e $filepath)!=1) {
 8429:                     mkdir($filepath,0770);
 8430:                 }
 8431:             }
 8432:             my $fh;
 8433:             if (!open($fh,'>'.$dest)) {
 8434:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8435:                 $output .= '<span class="LC_error">'.
 8436:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8437:                            '</span><br />';
 8438:             } else {
 8439:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8440:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8441:                     $output .= '<span class="LC_error">'.
 8442:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8443:                               '</span><br />';
 8444:                 } else {
 8445:                     if ($context eq 'testbank') {
 8446:                         $output .= &mt('Embedded file uploaded successfully:').
 8447:                                    '&nbsp;<a href="'.$url.'">'.
 8448:                                    $orig_uploaded_filename.'</a><br />';
 8449:                     } else {
 8450:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8451:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8452:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8453:                     }
 8454:                 }
 8455:                 close($fh);
 8456:             }
 8457:         }
 8458:     }
 8459:     return $output;
 8460: }
 8461: 
 8462: sub check_for_existing {
 8463:     my ($path,$fname,$element) = @_;
 8464:     my ($state,$msg);
 8465:     if (-d $path.'/'.$fname) {
 8466:         $state = 'exists';
 8467:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8468:     } elsif (-e $path.'/'.$fname) {
 8469:         $state = 'exists';
 8470:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8471:     }
 8472:     if ($state eq 'exists') {
 8473:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8474:     }
 8475:     return ($state,$msg);
 8476: }
 8477: 
 8478: sub check_for_upload {
 8479:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8480:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8481:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8482:     my $getpropath = 1;
 8483:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8484:                                             $getpropath);
 8485:     my $found_file = 0;
 8486:     my $locked_file = 0;
 8487:     foreach my $line (@dir_list) {
 8488:         my ($file_name)=split(/\&/,$line,2);
 8489:         if ($file_name eq $fname){
 8490:             $file_name = $path.$file_name;
 8491:             if ($group ne '') {
 8492:                 $file_name = $group.$file_name;
 8493:             }
 8494:             $found_file = 1;
 8495:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8496:                 $locked_file = 1;
 8497:             }
 8498:         }
 8499:     }
 8500:     if (($current_disk_usage + $filesize) > $disk_quota){
 8501:         my $msg = '<span class="LC_error">'.
 8502:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8503:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8504:         return ('will_exceed_quota',$msg);
 8505:     } elsif ($found_file) {
 8506:         if ($locked_file) {
 8507:             my $msg = '<span class="LC_error">';
 8508:             $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>');
 8509:             $msg .= '</span><br />';
 8510:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8511:             return ('file_locked',$msg);
 8512:         } else {
 8513:             my $msg = '<span class="LC_error">';
 8514:             $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
 8515:             $msg .= '</span>';
 8516:             $msg .= '<br />';
 8517:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8518:             return ('file_exists',$msg);
 8519:         }
 8520:     }
 8521: }
 8522: 
 8523: 
 8524: =pod
 8525: 
 8526: =back
 8527: 
 8528: =head1 CSV Upload/Handling functions
 8529: 
 8530: =over 4
 8531: 
 8532: =item * &upfile_store($r)
 8533: 
 8534: Store uploaded file, $r should be the HTTP Request object,
 8535: needs $env{'form.upfile'}
 8536: returns $datatoken to be put into hidden field
 8537: 
 8538: =cut
 8539: 
 8540: sub upfile_store {
 8541:     my $r=shift;
 8542:     $env{'form.upfile'}=~s/\r/\n/gs;
 8543:     $env{'form.upfile'}=~s/\f/\n/gs;
 8544:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8545:     $env{'form.upfile'}=~s/\n+$//gs;
 8546: 
 8547:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8548: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8549:     {
 8550:         my $datafile = $r->dir_config('lonDaemons').
 8551:                            '/tmp/'.$datatoken.'.tmp';
 8552:         if ( open(my $fh,">$datafile") ) {
 8553:             print $fh $env{'form.upfile'};
 8554:             close($fh);
 8555:         }
 8556:     }
 8557:     return $datatoken;
 8558: }
 8559: 
 8560: =pod
 8561: 
 8562: =item * &load_tmp_file($r)
 8563: 
 8564: Load uploaded file from tmp, $r should be the HTTP Request object,
 8565: needs $env{'form.datatoken'},
 8566: sets $env{'form.upfile'} to the contents of the file
 8567: 
 8568: =cut
 8569: 
 8570: sub load_tmp_file {
 8571:     my $r=shift;
 8572:     my @studentdata=();
 8573:     {
 8574:         my $studentfile = $r->dir_config('lonDaemons').
 8575:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8576:         if ( open(my $fh,"<$studentfile") ) {
 8577:             @studentdata=<$fh>;
 8578:             close($fh);
 8579:         }
 8580:     }
 8581:     $env{'form.upfile'}=join('',@studentdata);
 8582: }
 8583: 
 8584: =pod
 8585: 
 8586: =item * &upfile_record_sep()
 8587: 
 8588: Separate uploaded file into records
 8589: returns array of records,
 8590: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8591: 
 8592: =cut
 8593: 
 8594: sub upfile_record_sep {
 8595:     if ($env{'form.upfiletype'} eq 'xml') {
 8596:     } else {
 8597: 	my @records;
 8598: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8599: 	    if ($line=~/^\s*$/) { next; }
 8600: 	    push(@records,$line);
 8601: 	}
 8602: 	return @records;
 8603:     }
 8604: }
 8605: 
 8606: =pod
 8607: 
 8608: =item * &record_sep($record)
 8609: 
 8610: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8611: 
 8612: =cut
 8613: 
 8614: sub takeleft {
 8615:     my $index=shift;
 8616:     return substr('0000'.$index,-4,4);
 8617: }
 8618: 
 8619: sub record_sep {
 8620:     my $record=shift;
 8621:     my %components=();
 8622:     if ($env{'form.upfiletype'} eq 'xml') {
 8623:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8624:         my $i=0;
 8625:         foreach my $field (split(/\s+/,$record)) {
 8626:             $field=~s/^(\"|\')//;
 8627:             $field=~s/(\"|\')$//;
 8628:             $components{&takeleft($i)}=$field;
 8629:             $i++;
 8630:         }
 8631:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8632:         my $i=0;
 8633:         foreach my $field (split(/\t/,$record)) {
 8634:             $field=~s/^(\"|\')//;
 8635:             $field=~s/(\"|\')$//;
 8636:             $components{&takeleft($i)}=$field;
 8637:             $i++;
 8638:         }
 8639:     } else {
 8640:         my $separator=',';
 8641:         if ($env{'form.upfiletype'} eq 'semisv') {
 8642:             $separator=';';
 8643:         }
 8644:         my $i=0;
 8645: # the character we are looking for to indicate the end of a quote or a record 
 8646:         my $looking_for=$separator;
 8647: # do not add the characters to the fields
 8648:         my $ignore=0;
 8649: # we just encountered a separator (or the beginning of the record)
 8650:         my $just_found_separator=1;
 8651: # store the field we are working on here
 8652:         my $field='';
 8653: # work our way through all characters in record
 8654:         foreach my $character ($record=~/(.)/g) {
 8655:             if ($character eq $looking_for) {
 8656:                if ($character ne $separator) {
 8657: # Found the end of a quote, again looking for separator
 8658:                   $looking_for=$separator;
 8659:                   $ignore=1;
 8660:                } else {
 8661: # Found a separator, store away what we got
 8662:                   $components{&takeleft($i)}=$field;
 8663: 	          $i++;
 8664:                   $just_found_separator=1;
 8665:                   $ignore=0;
 8666:                   $field='';
 8667:                }
 8668:                next;
 8669:             }
 8670: # single or double quotation marks after a separator indicate beginning of a quote
 8671: # we are now looking for the end of the quote and need to ignore separators
 8672:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8673:                $looking_for=$character;
 8674:                next;
 8675:             }
 8676: # ignore would be true after we reached the end of a quote
 8677:             if ($ignore) { next; }
 8678:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8679:             $field.=$character;
 8680:             $just_found_separator=0; 
 8681:         }
 8682: # catch the very last entry, since we never encountered the separator
 8683:         $components{&takeleft($i)}=$field;
 8684:     }
 8685:     return %components;
 8686: }
 8687: 
 8688: ######################################################
 8689: ######################################################
 8690: 
 8691: =pod
 8692: 
 8693: =item * &upfile_select_html()
 8694: 
 8695: Return HTML code to select a file from the users machine and specify 
 8696: the file type.
 8697: 
 8698: =cut
 8699: 
 8700: ######################################################
 8701: ######################################################
 8702: sub upfile_select_html {
 8703:     my %Types = (
 8704:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8705:                  semisv => &mt('Semicolon separated values'),
 8706:                  space => &mt('Space separated'),
 8707:                  tab   => &mt('Tabulator separated'),
 8708: #                 xml   => &mt('HTML/XML'),
 8709:                  );
 8710:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8711:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8712:     foreach my $type (sort(keys(%Types))) {
 8713:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8714:     }
 8715:     $Str .= "</select>\n";
 8716:     return $Str;
 8717: }
 8718: 
 8719: sub get_samples {
 8720:     my ($records,$toget) = @_;
 8721:     my @samples=({});
 8722:     my $got=0;
 8723:     foreach my $rec (@$records) {
 8724: 	my %temp = &record_sep($rec);
 8725: 	if (! grep(/\S/, values(%temp))) { next; }
 8726: 	if (%temp) {
 8727: 	    $samples[$got]=\%temp;
 8728: 	    $got++;
 8729: 	    if ($got == $toget) { last; }
 8730: 	}
 8731:     }
 8732:     return \@samples;
 8733: }
 8734: 
 8735: ######################################################
 8736: ######################################################
 8737: 
 8738: =pod
 8739: 
 8740: =item * &csv_print_samples($r,$records)
 8741: 
 8742: Prints a table of sample values from each column uploaded $r is an
 8743: Apache Request ref, $records is an arrayref from
 8744: &Apache::loncommon::upfile_record_sep
 8745: 
 8746: =cut
 8747: 
 8748: ######################################################
 8749: ######################################################
 8750: sub csv_print_samples {
 8751:     my ($r,$records) = @_;
 8752:     my $samples = &get_samples($records,5);
 8753: 
 8754:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8755:               &start_data_table_header_row());
 8756:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8757:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 8758:     $r->print(&end_data_table_header_row());
 8759:     foreach my $hash (@$samples) {
 8760: 	$r->print(&start_data_table_row());
 8761: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8762: 	    $r->print('<td>');
 8763: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8764: 	    $r->print('</td>');
 8765: 	}
 8766: 	$r->print(&end_data_table_row());
 8767:     }
 8768:     $r->print(&end_data_table().'<br />'."\n");
 8769: }
 8770: 
 8771: ######################################################
 8772: ######################################################
 8773: 
 8774: =pod
 8775: 
 8776: =item * &csv_print_select_table($r,$records,$d)
 8777: 
 8778: Prints a table to create associations between values and table columns.
 8779: 
 8780: $r is an Apache Request ref,
 8781: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8782: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8783: 
 8784: =cut
 8785: 
 8786: ######################################################
 8787: ######################################################
 8788: sub csv_print_select_table {
 8789:     my ($r,$records,$d) = @_;
 8790:     my $i=0;
 8791:     my $samples = &get_samples($records,1);
 8792:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8793: 	      &start_data_table().&start_data_table_header_row().
 8794:               '<th>'.&mt('Attribute').'</th>'.
 8795:               '<th>'.&mt('Column').'</th>'.
 8796:               &end_data_table_header_row()."\n");
 8797:     foreach my $array_ref (@$d) {
 8798: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8799: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8800: 
 8801: 	$r->print('<td><select name="f'.$i.'"'.
 8802: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8803: 	$r->print('<option value="none"></option>');
 8804: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8805: 	    $r->print('<option value="'.$sample.'"'.
 8806:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8807:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8808: 	}
 8809: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8810: 	$i++;
 8811:     }
 8812:     $r->print(&end_data_table());
 8813:     $i--;
 8814:     return $i;
 8815: }
 8816: 
 8817: ######################################################
 8818: ######################################################
 8819: 
 8820: =pod
 8821: 
 8822: =item * &csv_samples_select_table($r,$records,$d)
 8823: 
 8824: Prints a table of sample values from the upload and can make associate samples to internal names.
 8825: 
 8826: $r is an Apache Request ref,
 8827: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8828: $d is an array of 2 element arrays (internal name, displayed name)
 8829: 
 8830: =cut
 8831: 
 8832: ######################################################
 8833: ######################################################
 8834: sub csv_samples_select_table {
 8835:     my ($r,$records,$d) = @_;
 8836:     my $i=0;
 8837:     #
 8838:     my $max_samples = 5;
 8839:     my $samples = &get_samples($records,$max_samples);
 8840:     $r->print(&start_data_table().
 8841:               &start_data_table_header_row().'<th>'.
 8842:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8843:               &end_data_table_header_row());
 8844: 
 8845:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8846: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8847: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8848: 	foreach my $option (@$d) {
 8849: 	    my ($value,$display,$defaultcol)=@{ $option };
 8850: 	    $r->print('<option value="'.$value.'"'.
 8851:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8852:                       $display.'</option>');
 8853: 	}
 8854: 	$r->print('</select></td><td>');
 8855: 	foreach my $line (0..($max_samples-1)) {
 8856: 	    if (defined($samples->[$line]{$key})) { 
 8857: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8858: 	    }
 8859: 	}
 8860: 	$r->print('</td>'.&end_data_table_row());
 8861: 	$i++;
 8862:     }
 8863:     $r->print(&end_data_table());
 8864:     $i--;
 8865:     return($i);
 8866: }
 8867: 
 8868: ######################################################
 8869: ######################################################
 8870: 
 8871: =pod
 8872: 
 8873: =item * &clean_excel_name($name)
 8874: 
 8875: Returns a replacement for $name which does not contain any illegal characters.
 8876: 
 8877: =cut
 8878: 
 8879: ######################################################
 8880: ######################################################
 8881: sub clean_excel_name {
 8882:     my ($name) = @_;
 8883:     $name =~ s/[:\*\?\/\\]//g;
 8884:     if (length($name) > 31) {
 8885:         $name = substr($name,0,31);
 8886:     }
 8887:     return $name;
 8888: }
 8889: 
 8890: =pod
 8891: 
 8892: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8893: 
 8894: Returns either 1 or undef
 8895: 
 8896: 1 if the part is to be hidden, undef if it is to be shown
 8897: 
 8898: Arguments are:
 8899: 
 8900: $id the id of the part to be checked
 8901: $symb, optional the symb of the resource to check
 8902: $udom, optional the domain of the user to check for
 8903: $uname, optional the username of the user to check for
 8904: 
 8905: =cut
 8906: 
 8907: sub check_if_partid_hidden {
 8908:     my ($id,$symb,$udom,$uname) = @_;
 8909:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8910: 					 $symb,$udom,$uname);
 8911:     my $truth=1;
 8912:     #if the string starts with !, then the list is the list to show not hide
 8913:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8914:     my @hiddenlist=split(/,/,$hiddenparts);
 8915:     foreach my $checkid (@hiddenlist) {
 8916: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8917:     }
 8918:     return !$truth;
 8919: }
 8920: 
 8921: 
 8922: ############################################################
 8923: ############################################################
 8924: 
 8925: =pod
 8926: 
 8927: =back 
 8928: 
 8929: =head1 cgi-bin script and graphing routines
 8930: 
 8931: =over 4
 8932: 
 8933: =item * &get_cgi_id()
 8934: 
 8935: Inputs: none
 8936: 
 8937: Returns an id which can be used to pass environment variables
 8938: to various cgi-bin scripts.  These environment variables will
 8939: be removed from the users environment after a given time by
 8940: the routine &Apache::lonnet::transfer_profile_to_env.
 8941: 
 8942: =cut
 8943: 
 8944: ############################################################
 8945: ############################################################
 8946: my $uniq=0;
 8947: sub get_cgi_id {
 8948:     $uniq=($uniq+1)%100000;
 8949:     return (time.'_'.$$.'_'.$uniq);
 8950: }
 8951: 
 8952: ############################################################
 8953: ############################################################
 8954: 
 8955: =pod
 8956: 
 8957: =item * &DrawBarGraph()
 8958: 
 8959: Facilitates the plotting of data in a (stacked) bar graph.
 8960: Puts plot definition data into the users environment in order for 
 8961: graph.png to plot it.  Returns an <img> tag for the plot.
 8962: The bars on the plot are labeled '1','2',...,'n'.
 8963: 
 8964: Inputs:
 8965: 
 8966: =over 4
 8967: 
 8968: =item $Title: string, the title of the plot
 8969: 
 8970: =item $xlabel: string, text describing the X-axis of the plot
 8971: 
 8972: =item $ylabel: string, text describing the Y-axis of the plot
 8973: 
 8974: =item $Max: scalar, the maximum Y value to use in the plot
 8975: If $Max is < any data point, the graph will not be rendered.
 8976: 
 8977: =item $colors: array ref holding the colors to be used for the data sets when
 8978: they are plotted.  If undefined, default values will be used.
 8979: 
 8980: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8981: 
 8982: =item @Values: An array of array references.  Each array reference holds data
 8983: to be plotted in a stacked bar chart.
 8984: 
 8985: =item If the final element of @Values is a hash reference the key/value
 8986: pairs will be added to the graph definition.
 8987: 
 8988: =back
 8989: 
 8990: Returns:
 8991: 
 8992: An <img> tag which references graph.png and the appropriate identifying
 8993: information for the plot.
 8994: 
 8995: =cut
 8996: 
 8997: ############################################################
 8998: ############################################################
 8999: sub DrawBarGraph {
 9000:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 9001:     #
 9002:     if (! defined($colors)) {
 9003:         $colors = ['#33ff00', 
 9004:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 9005:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 9006:                   ]; 
 9007:     }
 9008:     my $extra_settings = {};
 9009:     if (ref($Values[-1]) eq 'HASH') {
 9010:         $extra_settings = pop(@Values);
 9011:     }
 9012:     #
 9013:     my $identifier = &get_cgi_id();
 9014:     my $id = 'cgi.'.$identifier;        
 9015:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 9016:         return '';
 9017:     }
 9018:     #
 9019:     my @Labels;
 9020:     if (defined($labels)) {
 9021:         @Labels = @$labels;
 9022:     } else {
 9023:         for (my $i=0;$i<@{$Values[0]};$i++) {
 9024:             push (@Labels,$i+1);
 9025:         }
 9026:     }
 9027:     #
 9028:     my $NumBars = scalar(@{$Values[0]});
 9029:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 9030:     my %ValuesHash;
 9031:     my $NumSets=1;
 9032:     foreach my $array (@Values) {
 9033:         next if (! ref($array));
 9034:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 9035:             join(',',@$array);
 9036:     }
 9037:     #
 9038:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 9039:     if ($NumBars < 3) {
 9040:         $width = 120+$NumBars*32;
 9041:         $xskip = 1;
 9042:         $bar_width = 30;
 9043:     } elsif ($NumBars < 5) {
 9044:         $width = 120+$NumBars*20;
 9045:         $xskip = 1;
 9046:         $bar_width = 20;
 9047:     } elsif ($NumBars < 10) {
 9048:         $width = 120+$NumBars*15;
 9049:         $xskip = 1;
 9050:         $bar_width = 15;
 9051:     } elsif ($NumBars <= 25) {
 9052:         $width = 120+$NumBars*11;
 9053:         $xskip = 5;
 9054:         $bar_width = 8;
 9055:     } elsif ($NumBars <= 50) {
 9056:         $width = 120+$NumBars*8;
 9057:         $xskip = 5;
 9058:         $bar_width = 4;
 9059:     } else {
 9060:         $width = 120+$NumBars*8;
 9061:         $xskip = 5;
 9062:         $bar_width = 4;
 9063:     }
 9064:     #
 9065:     $Max = 1 if ($Max < 1);
 9066:     if ( int($Max) < $Max ) {
 9067:         $Max++;
 9068:         $Max = int($Max);
 9069:     }
 9070:     $Title  = '' if (! defined($Title));
 9071:     $xlabel = '' if (! defined($xlabel));
 9072:     $ylabel = '' if (! defined($ylabel));
 9073:     $ValuesHash{$id.'.title'}    = &escape($Title);
 9074:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 9075:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 9076:     $ValuesHash{$id.'.y_max_value'} = $Max;
 9077:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 9078:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 9079:     $ValuesHash{$id.'.PlotType'} = 'bar';
 9080:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9081:     $ValuesHash{$id.'.height'}   = $height;
 9082:     $ValuesHash{$id.'.width'}    = $width;
 9083:     $ValuesHash{$id.'.xskip'}    = $xskip;
 9084:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 9085:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 9086:     #
 9087:     # Deal with other parameters
 9088:     while (my ($key,$value) = each(%$extra_settings)) {
 9089:         $ValuesHash{$id.'.'.$key} = $value;
 9090:     }
 9091:     #
 9092:     &Apache::lonnet::appenv(\%ValuesHash);
 9093:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9094: }
 9095: 
 9096: ############################################################
 9097: ############################################################
 9098: 
 9099: =pod
 9100: 
 9101: =item * &DrawXYGraph()
 9102: 
 9103: Facilitates the plotting of data in an XY graph.
 9104: Puts plot definition data into the users environment in order for 
 9105: graph.png to plot it.  Returns an <img> tag for the plot.
 9106: 
 9107: Inputs:
 9108: 
 9109: =over 4
 9110: 
 9111: =item $Title: string, the title of the plot
 9112: 
 9113: =item $xlabel: string, text describing the X-axis of the plot
 9114: 
 9115: =item $ylabel: string, text describing the Y-axis of the plot
 9116: 
 9117: =item $Max: scalar, the maximum Y value to use in the plot
 9118: If $Max is < any data point, the graph will not be rendered.
 9119: 
 9120: =item $colors: Array ref containing the hex color codes for the data to be 
 9121: plotted in.  If undefined, default values will be used.
 9122: 
 9123: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9124: 
 9125: =item $Ydata: Array ref containing Array refs.  
 9126: Each of the contained arrays will be plotted as a separate curve.
 9127: 
 9128: =item %Values: hash indicating or overriding any default values which are 
 9129: passed to graph.png.  
 9130: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9131: 
 9132: =back
 9133: 
 9134: Returns:
 9135: 
 9136: An <img> tag which references graph.png and the appropriate identifying
 9137: information for the plot.
 9138: 
 9139: =cut
 9140: 
 9141: ############################################################
 9142: ############################################################
 9143: sub DrawXYGraph {
 9144:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9145:     #
 9146:     # Create the identifier for the graph
 9147:     my $identifier = &get_cgi_id();
 9148:     my $id = 'cgi.'.$identifier;
 9149:     #
 9150:     $Title  = '' if (! defined($Title));
 9151:     $xlabel = '' if (! defined($xlabel));
 9152:     $ylabel = '' if (! defined($ylabel));
 9153:     my %ValuesHash = 
 9154:         (
 9155:          $id.'.title'  => &escape($Title),
 9156:          $id.'.xlabel' => &escape($xlabel),
 9157:          $id.'.ylabel' => &escape($ylabel),
 9158:          $id.'.y_max_value'=> $Max,
 9159:          $id.'.labels'     => join(',',@$Xlabels),
 9160:          $id.'.PlotType'   => 'XY',
 9161:          );
 9162:     #
 9163:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9164:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9165:     }
 9166:     #
 9167:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9168:         return '';
 9169:     }
 9170:     my $NumSets=1;
 9171:     foreach my $array (@{$Ydata}){
 9172:         next if (! ref($array));
 9173:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9174:     }
 9175:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9176:     #
 9177:     # Deal with other parameters
 9178:     while (my ($key,$value) = each(%Values)) {
 9179:         $ValuesHash{$id.'.'.$key} = $value;
 9180:     }
 9181:     #
 9182:     &Apache::lonnet::appenv(\%ValuesHash);
 9183:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9184: }
 9185: 
 9186: ############################################################
 9187: ############################################################
 9188: 
 9189: =pod
 9190: 
 9191: =item * &DrawXYYGraph()
 9192: 
 9193: Facilitates the plotting of data in an XY graph with two Y axes.
 9194: Puts plot definition data into the users environment in order for 
 9195: graph.png to plot it.  Returns an <img> tag for the plot.
 9196: 
 9197: Inputs:
 9198: 
 9199: =over 4
 9200: 
 9201: =item $Title: string, the title of the plot
 9202: 
 9203: =item $xlabel: string, text describing the X-axis of the plot
 9204: 
 9205: =item $ylabel: string, text describing the Y-axis of the plot
 9206: 
 9207: =item $colors: Array ref containing the hex color codes for the data to be 
 9208: plotted in.  If undefined, default values will be used.
 9209: 
 9210: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9211: 
 9212: =item $Ydata1: The first data set
 9213: 
 9214: =item $Min1: The minimum value of the left Y-axis
 9215: 
 9216: =item $Max1: The maximum value of the left Y-axis
 9217: 
 9218: =item $Ydata2: The second data set
 9219: 
 9220: =item $Min2: The minimum value of the right Y-axis
 9221: 
 9222: =item $Max2: The maximum value of the left Y-axis
 9223: 
 9224: =item %Values: hash indicating or overriding any default values which are 
 9225: passed to graph.png.  
 9226: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9227: 
 9228: =back
 9229: 
 9230: Returns:
 9231: 
 9232: An <img> tag which references graph.png and the appropriate identifying
 9233: information for the plot.
 9234: 
 9235: =cut
 9236: 
 9237: ############################################################
 9238: ############################################################
 9239: sub DrawXYYGraph {
 9240:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9241:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9242:     #
 9243:     # Create the identifier for the graph
 9244:     my $identifier = &get_cgi_id();
 9245:     my $id = 'cgi.'.$identifier;
 9246:     #
 9247:     $Title  = '' if (! defined($Title));
 9248:     $xlabel = '' if (! defined($xlabel));
 9249:     $ylabel = '' if (! defined($ylabel));
 9250:     my %ValuesHash = 
 9251:         (
 9252:          $id.'.title'  => &escape($Title),
 9253:          $id.'.xlabel' => &escape($xlabel),
 9254:          $id.'.ylabel' => &escape($ylabel),
 9255:          $id.'.labels' => join(',',@$Xlabels),
 9256:          $id.'.PlotType' => 'XY',
 9257:          $id.'.NumSets' => 2,
 9258:          $id.'.two_axes' => 1,
 9259:          $id.'.y1_max_value' => $Max1,
 9260:          $id.'.y1_min_value' => $Min1,
 9261:          $id.'.y2_max_value' => $Max2,
 9262:          $id.'.y2_min_value' => $Min2,
 9263:          );
 9264:     #
 9265:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9266:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9267:     }
 9268:     #
 9269:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9270:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9271:         return '';
 9272:     }
 9273:     my $NumSets=1;
 9274:     foreach my $array ($Ydata1,$Ydata2){
 9275:         next if (! ref($array));
 9276:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9277:     }
 9278:     #
 9279:     # Deal with other parameters
 9280:     while (my ($key,$value) = each(%Values)) {
 9281:         $ValuesHash{$id.'.'.$key} = $value;
 9282:     }
 9283:     #
 9284:     &Apache::lonnet::appenv(\%ValuesHash);
 9285:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9286: }
 9287: 
 9288: ############################################################
 9289: ############################################################
 9290: 
 9291: =pod
 9292: 
 9293: =back 
 9294: 
 9295: =head1 Statistics helper routines?  
 9296: 
 9297: Bad place for them but what the hell.
 9298: 
 9299: =over 4
 9300: 
 9301: =item * &chartlink()
 9302: 
 9303: Returns a link to the chart for a specific student.  
 9304: 
 9305: Inputs:
 9306: 
 9307: =over 4
 9308: 
 9309: =item $linktext: The text of the link
 9310: 
 9311: =item $sname: The students username
 9312: 
 9313: =item $sdomain: The students domain
 9314: 
 9315: =back
 9316: 
 9317: =back
 9318: 
 9319: =cut
 9320: 
 9321: ############################################################
 9322: ############################################################
 9323: sub chartlink {
 9324:     my ($linktext, $sname, $sdomain) = @_;
 9325:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9326:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9327:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9328:        '">'.$linktext.'</a>';
 9329: }
 9330: 
 9331: #######################################################
 9332: #######################################################
 9333: 
 9334: =pod
 9335: 
 9336: =head1 Course Environment Routines
 9337: 
 9338: =over 4
 9339: 
 9340: =item * &restore_course_settings()
 9341: 
 9342: =item * &store_course_settings()
 9343: 
 9344: Restores/Store indicated form parameters from the course environment.
 9345: Will not overwrite existing values of the form parameters.
 9346: 
 9347: Inputs: 
 9348: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9349: 
 9350: a hash ref describing the data to be stored.  For example:
 9351:    
 9352: %Save_Parameters = ('Status' => 'scalar',
 9353:     'chartoutputmode' => 'scalar',
 9354:     'chartoutputdata' => 'scalar',
 9355:     'Section' => 'array',
 9356:     'Group' => 'array',
 9357:     'StudentData' => 'array',
 9358:     'Maps' => 'array');
 9359: 
 9360: Returns: both routines return nothing
 9361: 
 9362: =back
 9363: 
 9364: =cut
 9365: 
 9366: #######################################################
 9367: #######################################################
 9368: sub store_course_settings {
 9369:     return &store_settings($env{'request.course.id'},@_);
 9370: }
 9371: 
 9372: sub store_settings {
 9373:     # save to the environment
 9374:     # appenv the same items, just to be safe
 9375:     my $udom  = $env{'user.domain'};
 9376:     my $uname = $env{'user.name'};
 9377:     my ($context,$prefix,$Settings) = @_;
 9378:     my %SaveHash;
 9379:     my %AppHash;
 9380:     while (my ($setting,$type) = each(%$Settings)) {
 9381:         my $basename = join('.','internal',$context,$prefix,$setting);
 9382:         my $envname = 'environment.'.$basename;
 9383:         if (exists($env{'form.'.$setting})) {
 9384:             # Save this value away
 9385:             if ($type eq 'scalar' &&
 9386:                 (! exists($env{$envname}) || 
 9387:                  $env{$envname} ne $env{'form.'.$setting})) {
 9388:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9389:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9390:             } elsif ($type eq 'array') {
 9391:                 my $stored_form;
 9392:                 if (ref($env{'form.'.$setting})) {
 9393:                     $stored_form = join(',',
 9394:                                         map {
 9395:                                             &escape($_);
 9396:                                         } sort(@{$env{'form.'.$setting}}));
 9397:                 } else {
 9398:                     $stored_form = 
 9399:                         &escape($env{'form.'.$setting});
 9400:                 }
 9401:                 # Determine if the array contents are the same.
 9402:                 if ($stored_form ne $env{$envname}) {
 9403:                     $SaveHash{$basename} = $stored_form;
 9404:                     $AppHash{$envname}   = $stored_form;
 9405:                 }
 9406:             }
 9407:         }
 9408:     }
 9409:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9410:                                           $udom,$uname);
 9411:     if ($put_result !~ /^(ok|delayed)/) {
 9412:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9413:                                  'got error:'.$put_result);
 9414:     }
 9415:     # Make sure these settings stick around in this session, too
 9416:     &Apache::lonnet::appenv(\%AppHash);
 9417:     return;
 9418: }
 9419: 
 9420: sub restore_course_settings {
 9421:     return &restore_settings($env{'request.course.id'},@_);
 9422: }
 9423: 
 9424: sub restore_settings {
 9425:     my ($context,$prefix,$Settings) = @_;
 9426:     while (my ($setting,$type) = each(%$Settings)) {
 9427:         next if (exists($env{'form.'.$setting}));
 9428:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9429:             '.'.$setting;
 9430:         if (exists($env{$envname})) {
 9431:             if ($type eq 'scalar') {
 9432:                 $env{'form.'.$setting} = $env{$envname};
 9433:             } elsif ($type eq 'array') {
 9434:                 $env{'form.'.$setting} = [ 
 9435:                                            map { 
 9436:                                                &unescape($_); 
 9437:                                            } split(',',$env{$envname})
 9438:                                            ];
 9439:             }
 9440:         }
 9441:     }
 9442: }
 9443: 
 9444: #######################################################
 9445: #######################################################
 9446: 
 9447: =pod
 9448: 
 9449: =head1 Domain E-mail Routines  
 9450: 
 9451: =over 4
 9452: 
 9453: =item * &build_recipient_list()
 9454: 
 9455: Build recipient lists for five types of e-mail:
 9456: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9457: (d) Help requests, (e) Course requests needing approval,  generated by
 9458: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
 9459: loncoursequeueadmin.pm respectively.
 9460: 
 9461: Inputs:
 9462: defmail (scalar - email address of default recipient), 
 9463: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9464: defdom (domain for which to retrieve configuration settings),
 9465: origmail (scalar - email address of recipient from loncapa.conf, 
 9466: i.e., predates configuration by DC via domainprefs.pm 
 9467: 
 9468: Returns: comma separated list of addresses to which to send e-mail.
 9469: 
 9470: =back
 9471: 
 9472: =cut
 9473: 
 9474: ############################################################
 9475: ############################################################
 9476: sub build_recipient_list {
 9477:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9478:     my @recipients;
 9479:     my $otheremails;
 9480:     my %domconfig =
 9481:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9482:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9483:         if (exists($domconfig{'contacts'}{$mailing})) {
 9484:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9485:                 my @contacts = ('adminemail','supportemail');
 9486:                 foreach my $item (@contacts) {
 9487:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9488:                         my $addr = $domconfig{'contacts'}{$item}; 
 9489:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9490:                             push(@recipients,$addr);
 9491:                         }
 9492:                     }
 9493:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9494:                 }
 9495:             }
 9496:         } elsif ($origmail ne '') {
 9497:             push(@recipients,$origmail);
 9498:         }
 9499:     } elsif ($origmail ne '') {
 9500:         push(@recipients,$origmail);
 9501:     }
 9502:     if (defined($defmail)) {
 9503:         if ($defmail ne '') {
 9504:             push(@recipients,$defmail);
 9505:         }
 9506:     }
 9507:     if ($otheremails) {
 9508:         my @others;
 9509:         if ($otheremails =~ /,/) {
 9510:             @others = split(/,/,$otheremails);
 9511:         } else {
 9512:             push(@others,$otheremails);
 9513:         }
 9514:         foreach my $addr (@others) {
 9515:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9516:                 push(@recipients,$addr);
 9517:             }
 9518:         }
 9519:     }
 9520:     my $recipientlist = join(',',@recipients); 
 9521:     return $recipientlist;
 9522: }
 9523: 
 9524: ############################################################
 9525: ############################################################
 9526: 
 9527: =pod
 9528: 
 9529: =head1 Course Catalog Routines
 9530: 
 9531: =over 4
 9532: 
 9533: =item * &gather_categories()
 9534: 
 9535: Converts category definitions - keys of categories hash stored in  
 9536: coursecategories in configuration.db on the primary library server in a 
 9537: domain - to an array.  Also generates javascript and idx hash used to 
 9538: generate Domain Coordinator interface for editing Course Categories.
 9539: 
 9540: Inputs:
 9541: 
 9542: categories (reference to hash of category definitions).
 9543: 
 9544: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9545:       categories and subcategories).
 9546: 
 9547: idx (reference to hash of counters used in Domain Coordinator interface for 
 9548:       editing Course Categories).
 9549: 
 9550: jsarray (reference to array of categories used to create Javascript arrays for
 9551:          Domain Coordinator interface for editing Course Categories).
 9552: 
 9553: Returns: nothing
 9554: 
 9555: Side effects: populates cats, idx and jsarray. 
 9556: 
 9557: =cut
 9558: 
 9559: sub gather_categories {
 9560:     my ($categories,$cats,$idx,$jsarray) = @_;
 9561:     my %counters;
 9562:     my $num = 0;
 9563:     foreach my $item (keys(%{$categories})) {
 9564:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9565:         if ($container eq '' && $depth == 0) {
 9566:             $cats->[$depth][$categories->{$item}] = $cat;
 9567:         } else {
 9568:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9569:         }
 9570:         my ($escitem,$tail) = split(/:/,$item,2);
 9571:         if ($counters{$tail} eq '') {
 9572:             $counters{$tail} = $num;
 9573:             $num ++;
 9574:         }
 9575:         if (ref($idx) eq 'HASH') {
 9576:             $idx->{$item} = $counters{$tail};
 9577:         }
 9578:         if (ref($jsarray) eq 'ARRAY') {
 9579:             push(@{$jsarray->[$counters{$tail}]},$item);
 9580:         }
 9581:     }
 9582:     return;
 9583: }
 9584: 
 9585: =pod
 9586: 
 9587: =item * &extract_categories()
 9588: 
 9589: Used to generate breadcrumb trails for course categories.
 9590: 
 9591: Inputs:
 9592: 
 9593: categories (reference to hash of category definitions).
 9594: 
 9595: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9596:       categories and subcategories).
 9597: 
 9598: trails (reference to array of breacrumb trails for each category).
 9599: 
 9600: allitems (reference to hash - key is category key 
 9601:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9602: 
 9603: idx (reference to hash of counters used in Domain Coordinator interface for
 9604:       editing Course Categories).
 9605: 
 9606: jsarray (reference to array of categories used to create Javascript arrays for
 9607:          Domain Coordinator interface for editing Course Categories).
 9608: 
 9609: subcats (reference to hash of arrays containing all subcategories within each 
 9610:          category, -recursive)
 9611: 
 9612: Returns: nothing
 9613: 
 9614: Side effects: populates trails and allitems hash references.
 9615: 
 9616: =cut
 9617: 
 9618: sub extract_categories {
 9619:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9620:     if (ref($categories) eq 'HASH') {
 9621:         &gather_categories($categories,$cats,$idx,$jsarray);
 9622:         if (ref($cats->[0]) eq 'ARRAY') {
 9623:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9624:                 my $name = $cats->[0][$i];
 9625:                 my $item = &escape($name).'::0';
 9626:                 my $trailstr;
 9627:                 if ($name eq 'instcode') {
 9628:                     $trailstr = &mt('Official courses (with institutional codes)');
 9629:                 } elsif ($name eq 'communities') {
 9630:                     $trailstr = &mt('Communities');
 9631:                 } else {
 9632:                     $trailstr = $name;
 9633:                 }
 9634:                 if ($allitems->{$item} eq '') {
 9635:                     push(@{$trails},$trailstr);
 9636:                     $allitems->{$item} = scalar(@{$trails})-1;
 9637:                 }
 9638:                 my @parents = ($name);
 9639:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9640:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9641:                         my $category = $cats->[1]{$name}[$j];
 9642:                         if (ref($subcats) eq 'HASH') {
 9643:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9644:                         }
 9645:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9646:                     }
 9647:                 } else {
 9648:                     if (ref($subcats) eq 'HASH') {
 9649:                         $subcats->{$item} = [];
 9650:                     }
 9651:                 }
 9652:             }
 9653:         }
 9654:     }
 9655:     return;
 9656: }
 9657: 
 9658: =pod
 9659: 
 9660: =item *&recurse_categories()
 9661: 
 9662: Recursively used to generate breadcrumb trails for course categories.
 9663: 
 9664: Inputs:
 9665: 
 9666: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9667:       categories and subcategories).
 9668: 
 9669: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9670: 
 9671: category (current course category, for which breadcrumb trail is being generated).
 9672: 
 9673: trails (reference to array of breadcrumb trails for each category).
 9674: 
 9675: allitems (reference to hash - key is category key
 9676:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9677: 
 9678: parents (array containing containers directories for current category, 
 9679:          back to top level). 
 9680: 
 9681: Returns: nothing
 9682: 
 9683: Side effects: populates trails and allitems hash references
 9684: 
 9685: =cut
 9686: 
 9687: sub recurse_categories {
 9688:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9689:     my $shallower = $depth - 1;
 9690:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9691:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9692:             my $name = $cats->[$depth]{$category}[$k];
 9693:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9694:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9695:             if ($allitems->{$item} eq '') {
 9696:                 push(@{$trails},$trailstr);
 9697:                 $allitems->{$item} = scalar(@{$trails})-1;
 9698:             }
 9699:             my $deeper = $depth+1;
 9700:             push(@{$parents},$category);
 9701:             if (ref($subcats) eq 'HASH') {
 9702:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9703:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9704:                     my $higher;
 9705:                     if ($j > 0) {
 9706:                         $higher = &escape($parents->[$j]).':'.
 9707:                                   &escape($parents->[$j-1]).':'.$j;
 9708:                     } else {
 9709:                         $higher = &escape($parents->[$j]).'::'.$j;
 9710:                     }
 9711:                     push(@{$subcats->{$higher}},$subcat);
 9712:                 }
 9713:             }
 9714:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9715:                                 $subcats);
 9716:             pop(@{$parents});
 9717:         }
 9718:     } else {
 9719:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9720:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9721:         if ($allitems->{$item} eq '') {
 9722:             push(@{$trails},$trailstr);
 9723:             $allitems->{$item} = scalar(@{$trails})-1;
 9724:         }
 9725:     }
 9726:     return;
 9727: }
 9728: 
 9729: =pod
 9730: 
 9731: =item *&assign_categories_table()
 9732: 
 9733: Create a datatable for display of hierarchical categories in a domain,
 9734: with checkboxes to allow a course to be categorized. 
 9735: 
 9736: Inputs:
 9737: 
 9738: cathash - reference to hash of categories defined for the domain (from
 9739:           configuration.db)
 9740: 
 9741: currcat - scalar with an & separated list of categories assigned to a course. 
 9742: 
 9743: type    - scalar contains course type (Course or Community).
 9744: 
 9745: Returns: $output (markup to be displayed) 
 9746: 
 9747: =cut
 9748: 
 9749: sub assign_categories_table {
 9750:     my ($cathash,$currcat,$type) = @_;
 9751:     my $output;
 9752:     if (ref($cathash) eq 'HASH') {
 9753:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9754:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9755:         $maxdepth = scalar(@cats);
 9756:         if (@cats > 0) {
 9757:             my $itemcount = 0;
 9758:             if (ref($cats[0]) eq 'ARRAY') {
 9759:                 my @currcategories;
 9760:                 if ($currcat ne '') {
 9761:                     @currcategories = split('&',$currcat);
 9762:                 }
 9763:                 my $table;
 9764:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9765:                     my $parent = $cats[0][$i];
 9766:                     next if ($parent eq 'instcode');
 9767:                     if ($type eq 'Community') {
 9768:                         next unless ($parent eq 'communities');
 9769:                     } else {
 9770:                         next if ($parent eq 'communities');
 9771:                     }
 9772:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9773:                     my $item = &escape($parent).'::0';
 9774:                     my $checked = '';
 9775:                     if (@currcategories > 0) {
 9776:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9777:                             $checked = ' checked="checked"';
 9778:                         }
 9779:                     }
 9780:                     my $parent_title = $parent;
 9781:                     if ($parent eq 'communities') {
 9782:                         $parent_title = &mt('Communities');
 9783:                     }
 9784:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9785:                               '<input type="checkbox" name="usecategory" value="'.
 9786:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
 9787:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9788:                     my $depth = 1;
 9789:                     push(@path,$parent);
 9790:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9791:                     pop(@path);
 9792:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9793:                     $itemcount ++;
 9794:                 }
 9795:                 if ($itemcount) {
 9796:                     $output = &Apache::loncommon::start_data_table().
 9797:                               $table.
 9798:                               &Apache::loncommon::end_data_table();
 9799:                 }
 9800:             }
 9801:         }
 9802:     }
 9803:     return $output;
 9804: }
 9805: 
 9806: =pod
 9807: 
 9808: =item *&assign_category_rows()
 9809: 
 9810: Create a datatable row for display of nested categories in a domain,
 9811: with checkboxes to allow a course to be categorized,called recursively.
 9812: 
 9813: Inputs:
 9814: 
 9815: itemcount - track row number for alternating colors
 9816: 
 9817: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9818:       categories and subcategories.
 9819: 
 9820: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9821: 
 9822: parent - parent of current category item
 9823: 
 9824: path - Array containing all categories back up through the hierarchy from the
 9825:        current category to the top level.
 9826: 
 9827: currcategories - reference to array of current categories assigned to the course
 9828: 
 9829: Returns: $output (markup to be displayed).
 9830: 
 9831: =cut
 9832: 
 9833: sub assign_category_rows {
 9834:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9835:     my ($text,$name,$item,$chgstr);
 9836:     if (ref($cats) eq 'ARRAY') {
 9837:         my $maxdepth = scalar(@{$cats});
 9838:         if (ref($cats->[$depth]) eq 'HASH') {
 9839:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9840:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9841:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9842:                 $text .= '<td><table class="LC_datatable">';
 9843:                 for (my $j=0; $j<$numchildren; $j++) {
 9844:                     $name = $cats->[$depth]{$parent}[$j];
 9845:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9846:                     my $deeper = $depth+1;
 9847:                     my $checked = '';
 9848:                     if (ref($currcategories) eq 'ARRAY') {
 9849:                         if (@{$currcategories} > 0) {
 9850:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9851:                                 $checked = ' checked="checked"';
 9852:                             }
 9853:                         }
 9854:                     }
 9855:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9856:                              '<input type="checkbox" name="usecategory" value="'.
 9857:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9858:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9859:                              '</td><td>';
 9860:                     if (ref($path) eq 'ARRAY') {
 9861:                         push(@{$path},$name);
 9862:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9863:                         pop(@{$path});
 9864:                     }
 9865:                     $text .= '</td></tr>';
 9866:                 }
 9867:                 $text .= '</table></td>';
 9868:             }
 9869:         }
 9870:     }
 9871:     return $text;
 9872: }
 9873: 
 9874: ############################################################
 9875: ############################################################
 9876: 
 9877: 
 9878: sub commit_customrole {
 9879:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9880:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9881:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9882:                          ($end?', ending '.localtime($end):'').': <b>'.
 9883:               &Apache::lonnet::assigncustomrole(
 9884:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9885:                  '</b><br />';
 9886:     return $output;
 9887: }
 9888: 
 9889: sub commit_standardrole {
 9890:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9891:     my ($output,$logmsg,$linefeed);
 9892:     if ($context eq 'auto') {
 9893:         $linefeed = "\n";
 9894:     } else {
 9895:         $linefeed = "<br />\n";
 9896:     }  
 9897:     if ($three eq 'st') {
 9898:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9899:                                          $one,$two,$sec,$context);
 9900:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9901:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9902:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9903:         } else {
 9904:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9905:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9906:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9907:             if ($context eq 'auto') {
 9908:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9909:             } else {
 9910:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9911:                &mt('Add to classlist').': <b>ok</b>';
 9912:             }
 9913:             $output .= $linefeed;
 9914:         }
 9915:     } else {
 9916:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9917:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9918:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9919:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9920:         if ($context eq 'auto') {
 9921:             $output .= $result.$linefeed;
 9922:         } else {
 9923:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9924:         }
 9925:     }
 9926:     return $output;
 9927: }
 9928: 
 9929: sub commit_studentrole {
 9930:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9931:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9932:     if ($context eq 'auto') {
 9933:         $linefeed = "\n";
 9934:     } else {
 9935:         $linefeed = '<br />'."\n";
 9936:     }
 9937:     if (defined($one) && defined($two)) {
 9938:         my $cid=$one.'_'.$two;
 9939:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9940:         my $secchange = 0;
 9941:         my $expire_role_result;
 9942:         my $modify_section_result;
 9943:         if ($oldsec ne '-1') { 
 9944:             if ($oldsec ne $sec) {
 9945:                 $secchange = 1;
 9946:                 my $now = time;
 9947:                 my $uurl='/'.$cid;
 9948:                 $uurl=~s/\_/\//g;
 9949:                 if ($oldsec) {
 9950:                     $uurl.='/'.$oldsec;
 9951:                 }
 9952:                 $oldsecurl = $uurl;
 9953:                 $expire_role_result = 
 9954:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9955:                 if ($env{'request.course.sec'} ne '') { 
 9956:                     if ($expire_role_result eq 'refused') {
 9957:                         my @roles = ('st');
 9958:                         my @statuses = ('previous');
 9959:                         my @roledoms = ($one);
 9960:                         my $withsec = 1;
 9961:                         my %roleshash = 
 9962:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9963:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9964:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9965:                             my ($oldstart,$oldend) = 
 9966:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9967:                             if ($oldend > 0 && $oldend <= $now) {
 9968:                                 $expire_role_result = 'ok';
 9969:                             }
 9970:                         }
 9971:                     }
 9972:                 }
 9973:                 $result = $expire_role_result;
 9974:             }
 9975:         }
 9976:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9977:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9978:             if ($modify_section_result =~ /^ok/) {
 9979:                 if ($secchange == 1) {
 9980:                     if ($sec eq '') {
 9981:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9982:                     } else {
 9983:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9984:                     }
 9985:                 } elsif ($oldsec eq '-1') {
 9986:                     if ($sec eq '') {
 9987:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9988:                     } else {
 9989:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9990:                     }
 9991:                 } else {
 9992:                     if ($sec eq '') {
 9993:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9994:                     } else {
 9995:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9996:                     }
 9997:                 }
 9998:             } else {
 9999:                 if ($secchange) {       
10000:                     $$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;
10001:                 } else {
10002:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
10003:                 }
10004:             }
10005:             $result = $modify_section_result;
10006:         } elsif ($secchange == 1) {
10007:             if ($oldsec eq '') {
10008:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
10009:             } else {
10010:                 $$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;
10011:             }
10012:             if ($expire_role_result eq 'refused') {
10013:                 my $newsecurl = '/'.$cid;
10014:                 $newsecurl =~ s/\_/\//g;
10015:                 if ($sec ne '') {
10016:                     $newsecurl.='/'.$sec;
10017:                 }
10018:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
10019:                     if ($sec eq '') {
10020:                         $$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;
10021:                     } else {
10022:                         $$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;
10023:                     }
10024:                 }
10025:             }
10026:         }
10027:     } else {
10028:         $$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;
10029:         $result = "error: incomplete course id\n";
10030:     }
10031:     return $result;
10032: }
10033: 
10034: ############################################################
10035: ############################################################
10036: 
10037: sub check_clone {
10038:     my ($args,$linefeed) = @_;
10039:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
10040:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
10041:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
10042:     my $clonemsg;
10043:     my $can_clone = 0;
10044:     my $lctype = lc($args->{'crstype'});
10045:     if ($lctype ne 'community') {
10046:         $lctype = 'course';
10047:     }
10048:     if ($clonehome eq 'no_host') {
10049:         if ($args->{'crstype'} eq 'Community') {
10050:             $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'});
10051:         } else {
10052:             $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'});
10053:         }     
10054:     } else {
10055: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
10056:         if ($args->{'crstype'} eq 'Community') {
10057:             if ($clonedesc{'type'} ne 'Community') {
10058:                  $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'});
10059:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
10060:             }
10061:         }
10062: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
10063:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
10064: 	    $can_clone = 1;
10065: 	} else {
10066: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
10067: 						 $args->{'clonedomain'},$args->{'clonecourse'});
10068: 	    my @cloners = split(/,/,$clonehash{'cloners'});
10069:             if (grep(/^\*$/,@cloners)) {
10070:                 $can_clone = 1;
10071:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
10072:                 $can_clone = 1;
10073:             } else {
10074:                 my $ccrole = 'cc';
10075:                 if ($args->{'crstype'} eq 'Community') {
10076:                     $ccrole = 'co';
10077:                 }
10078: 	        my %roleshash =
10079: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
10080: 					 $args->{'ccdomain'},
10081:                                          'userroles',['active'],[$ccrole],
10082: 					 [$args->{'clonedomain'}]);
10083: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
10084:                     $can_clone = 1;
10085:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
10086:                     $can_clone = 1;
10087:                 } else {
10088:                     if ($args->{'crstype'} eq 'Community') {
10089:                         $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'});
10090:                     } else {
10091:                         $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'});
10092:                     }
10093: 	        }
10094: 	    }
10095:         }
10096:     }
10097:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
10098: }
10099: 
10100: sub construct_course {
10101:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
10102:     my $outcome;
10103:     my $linefeed =  '<br />'."\n";
10104:     if ($context eq 'auto') {
10105:         $linefeed = "\n";
10106:     }
10107: 
10108: #
10109: # Are we cloning?
10110: #
10111:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
10112:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
10113: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
10114: 	if ($context ne 'auto') {
10115:             if ($clonemsg ne '') {
10116: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
10117:             }
10118: 	}
10119: 	$outcome .= $clonemsg.$linefeed;
10120: 
10121:         if (!$can_clone) {
10122: 	    return (0,$outcome);
10123: 	}
10124:     }
10125: 
10126: #
10127: # Open course
10128: #
10129:     my $crstype = lc($args->{'crstype'});
10130:     my %cenv=();
10131:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
10132:                                              $args->{'cdescr'},
10133:                                              $args->{'curl'},
10134:                                              $args->{'course_home'},
10135:                                              $args->{'nonstandard'},
10136:                                              $args->{'crscode'},
10137:                                              $args->{'ccuname'}.':'.
10138:                                              $args->{'ccdomain'},
10139:                                              $args->{'crstype'},
10140:                                              $cnum,$context,$category);
10141: 
10142:     # Note: The testing routines depend on this being output; see 
10143:     # Utils::Course. This needs to at least be output as a comment
10144:     # if anyone ever decides to not show this, and Utils::Course::new
10145:     # will need to be suitably modified.
10146:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
10147:     if ($$courseid =~ /^error:/) {
10148:         return (0,$outcome);
10149:     }
10150: 
10151: #
10152: # Check if created correctly
10153: #
10154:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
10155:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
10156:     if ($crsuhome eq 'no_host') {
10157:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
10158:         return (0,$outcome);
10159:     }
10160:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
10161: 
10162: #
10163: # Do the cloning
10164: #   
10165:     if ($can_clone && $cloneid) {
10166: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
10167: 	if ($context ne 'auto') {
10168: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
10169: 	}
10170: 	$outcome .= $clonemsg.$linefeed;
10171: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
10172: # Copy all files
10173: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
10174: # Restore URL
10175: 	$cenv{'url'}=$oldcenv{'url'};
10176: # Restore title
10177: 	$cenv{'description'}=$oldcenv{'description'};
10178: # Restore creation date, creator and creation context.
10179:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
10180:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
10181:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
10182: # Mark as cloned
10183: 	$cenv{'clonedfrom'}=$cloneid;
10184: # Need to clone grading mode
10185:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10186:         $cenv{'grading'}=$newenv{'grading'};
10187: # Do not clone these environment entries
10188:         &Apache::lonnet::del('environment',
10189:                   ['default_enrollment_start_date',
10190:                    'default_enrollment_end_date',
10191:                    'question.email',
10192:                    'policy.email',
10193:                    'comment.email',
10194:                    'pch.users.denied',
10195:                    'plc.users.denied',
10196:                    'hidefromcat',
10197:                    'categories'],
10198:                    $$crsudom,$$crsunum);
10199:     }
10200: 
10201: #
10202: # Set environment (will override cloned, if existing)
10203: #
10204:     my @sections = ();
10205:     my @xlists = ();
10206:     if ($args->{'crstype'}) {
10207:         $cenv{'type'}=$args->{'crstype'};
10208:     }
10209:     if ($args->{'crsid'}) {
10210:         $cenv{'courseid'}=$args->{'crsid'};
10211:     }
10212:     if ($args->{'crscode'}) {
10213:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10214:     }
10215:     if ($args->{'crsquota'} ne '') {
10216:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10217:     } else {
10218:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10219:     }
10220:     if ($args->{'ccuname'}) {
10221:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10222:                                         ':'.$args->{'ccdomain'};
10223:     } else {
10224:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10225:     }
10226:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10227:     if ($args->{'crssections'}) {
10228:         $cenv{'internal.sectionnums'} = '';
10229:         if ($args->{'crssections'} =~ m/,/) {
10230:             @sections = split/,/,$args->{'crssections'};
10231:         } else {
10232:             $sections[0] = $args->{'crssections'};
10233:         }
10234:         if (@sections > 0) {
10235:             foreach my $item (@sections) {
10236:                 my ($sec,$gp) = split/:/,$item;
10237:                 my $class = $args->{'crscode'}.$sec;
10238:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10239:                 $cenv{'internal.sectionnums'} .= $item.',';
10240:                 unless ($addcheck eq 'ok') {
10241:                     push @badclasses, $class;
10242:                 }
10243:             }
10244:             $cenv{'internal.sectionnums'} =~ s/,$//;
10245:         }
10246:     }
10247: # do not hide course coordinator from staff listing, 
10248: # even if privileged
10249:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10250: # add crosslistings
10251:     if ($args->{'crsxlist'}) {
10252:         $cenv{'internal.crosslistings'}='';
10253:         if ($args->{'crsxlist'} =~ m/,/) {
10254:             @xlists = split/,/,$args->{'crsxlist'};
10255:         } else {
10256:             $xlists[0] = $args->{'crsxlist'};
10257:         }
10258:         if (@xlists > 0) {
10259:             foreach my $item (@xlists) {
10260:                 my ($xl,$gp) = split/:/,$item;
10261:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10262:                 $cenv{'internal.crosslistings'} .= $item.',';
10263:                 unless ($addcheck eq 'ok') {
10264:                     push @badclasses, $xl;
10265:                 }
10266:             }
10267:             $cenv{'internal.crosslistings'} =~ s/,$//;
10268:         }
10269:     }
10270:     if ($args->{'autoadds'}) {
10271:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10272:     }
10273:     if ($args->{'autodrops'}) {
10274:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10275:     }
10276: # check for notification of enrollment changes
10277:     my @notified = ();
10278:     if ($args->{'notify_owner'}) {
10279:         if ($args->{'ccuname'} ne '') {
10280:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10281:         }
10282:     }
10283:     if ($args->{'notify_dc'}) {
10284:         if ($uname ne '') { 
10285:             push(@notified,$uname.':'.$udom);
10286:         }
10287:     }
10288:     if (@notified > 0) {
10289:         my $notifylist;
10290:         if (@notified > 1) {
10291:             $notifylist = join(',',@notified);
10292:         } else {
10293:             $notifylist = $notified[0];
10294:         }
10295:         $cenv{'internal.notifylist'} = $notifylist;
10296:     }
10297:     if (@badclasses > 0) {
10298:         my %lt=&Apache::lonlocal::texthash(
10299:                 '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',
10300:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10301:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10302:         );
10303:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10304:                            ' ('.$lt{'adby'}.')';
10305:         if ($context eq 'auto') {
10306:             $outcome .= $badclass_msg.$linefeed;
10307:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10308:             foreach my $item (@badclasses) {
10309:                 if ($context eq 'auto') {
10310:                     $outcome .= " - $item\n";
10311:                 } else {
10312:                     $outcome .= "<li>$item</li>\n";
10313:                 }
10314:             }
10315:             if ($context eq 'auto') {
10316:                 $outcome .= $linefeed;
10317:             } else {
10318:                 $outcome .= "</ul><br /><br /></div>\n";
10319:             }
10320:         } 
10321:     }
10322:     if ($args->{'no_end_date'}) {
10323:         $args->{'endaccess'} = 0;
10324:     }
10325:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10326:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10327:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10328:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10329:     if ($args->{'showphotos'}) {
10330:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10331:     }
10332:     $cenv{'internal.authtype'} = $args->{'authtype'};
10333:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10334:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10335:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10336:             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'); 
10337:             if ($context eq 'auto') {
10338:                 $outcome .= $krb_msg;
10339:             } else {
10340:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10341:             }
10342:             $outcome .= $linefeed;
10343:         }
10344:     }
10345:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10346:        if ($args->{'setpolicy'}) {
10347:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10348:        }
10349:        if ($args->{'setcontent'}) {
10350:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10351:        }
10352:     }
10353:     if ($args->{'reshome'}) {
10354: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10355: 	$cenv{'reshome'}=~s/\/+$/\//;
10356:     }
10357: #
10358: # course has keyed access
10359: #
10360:     if ($args->{'setkeys'}) {
10361:        $cenv{'keyaccess'}='yes';
10362:     }
10363: # if specified, key authority is not course, but user
10364: # only active if keyaccess is yes
10365:     if ($args->{'keyauth'}) {
10366: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10367: 	$user = &LONCAPA::clean_username($user);
10368: 	$domain = &LONCAPA::clean_username($domain);
10369: 	if ($user ne '' && $domain ne '') {
10370: 	    $cenv{'keyauth'}=$user.':'.$domain;
10371: 	}
10372:     }
10373: 
10374:     if ($args->{'disresdis'}) {
10375:         $cenv{'pch.roles.denied'}='st';
10376:     }
10377:     if ($args->{'disablechat'}) {
10378:         $cenv{'plc.roles.denied'}='st';
10379:     }
10380: 
10381:     # Record we've not yet viewed the Course Initialization Helper for this 
10382:     # course
10383:     $cenv{'course.helper.not.run'} = 1;
10384:     #
10385:     # Use new Randomseed
10386:     #
10387:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10388:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10389:     #
10390:     # The encryption code and receipt prefix for this course
10391:     #
10392:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10393:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10394:     #
10395:     # By default, use standard grading
10396:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10397: 
10398:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10399:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10400: #
10401: # Open all assignments
10402: #
10403:     if ($args->{'openall'}) {
10404:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10405:        my %storecontent = ($storeunder         => time,
10406:                            $storeunder.'.type' => 'date_start');
10407:        
10408:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10409:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10410:    }
10411: #
10412: # Set first page
10413: #
10414:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10415: 	    || ($cloneid)) {
10416: 	use LONCAPA::map;
10417: 	$outcome .= &mt('Setting first resource').': ';
10418: 
10419: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10420:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10421: 
10422:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10423:         my $title; my $url;
10424:         if ($args->{'firstres'} eq 'syl') {
10425: 	    $title=&mt('Syllabus');
10426:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10427:         } else {
10428:             $title=&mt('Table of Contents');
10429:             $url='/adm/navmaps';
10430:         }
10431: 
10432:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10433: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10434: 
10435: 	if ($errtext) { $fatal=2; }
10436:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10437:     }
10438: 
10439:     return (1,$outcome);
10440: }
10441: 
10442: ############################################################
10443: ############################################################
10444: 
10445: #SD
10446: # only Community and Course, or anything else?
10447: sub course_type {
10448:     my ($cid) = @_;
10449:     if (!defined($cid)) {
10450:         $cid = $env{'request.course.id'};
10451:     }
10452:     if (defined($env{'course.'.$cid.'.type'})) {
10453:         return $env{'course.'.$cid.'.type'};
10454:     } else {
10455:         return 'Course';
10456:     }
10457: }
10458: 
10459: sub group_term {
10460:     my $crstype = &course_type();
10461:     my %names = (
10462:                   'Course' => 'group',
10463:                   'Community' => 'group',
10464:                 );
10465:     return $names{$crstype};
10466: }
10467: 
10468: sub course_types {
10469:     my @types = ('official','unofficial','community');
10470:     my %typename = (
10471:                          official   => 'Official course',
10472:                          unofficial => 'Unofficial course',
10473:                          community  => 'Community',
10474:                    );
10475:     return (\@types,\%typename);
10476: }
10477: 
10478: sub icon {
10479:     my ($file)=@_;
10480:     my $curfext = lc((split(/\./,$file))[-1]);
10481:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10482:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10483:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10484: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10485: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10486: 	            $curfext.".gif") {
10487: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10488: 		$curfext.".gif";
10489: 	}
10490:     }
10491:     return &lonhttpdurl($iconname);
10492: } 
10493: 
10494: sub lonhttpdurl {
10495: #
10496: # Had been used for "small fry" static images on separate port 8080.
10497: # Modify here if lightweight http functionality desired again.
10498: # Currently eliminated due to increasing firewall issues.
10499: #
10500:     my ($url)=@_;
10501:     return $url;
10502: }
10503: 
10504: sub connection_aborted {
10505:     my ($r)=@_;
10506:     $r->print(" ");$r->rflush();
10507:     my $c = $r->connection;
10508:     return $c->aborted();
10509: }
10510: 
10511: #    Escapes strings that may have embedded 's that will be put into
10512: #    strings as 'strings'.
10513: sub escape_single {
10514:     my ($input) = @_;
10515:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10516:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10517:     return $input;
10518: }
10519: 
10520: #  Same as escape_single, but escape's "'s  This 
10521: #  can be used for  "strings"
10522: sub escape_double {
10523:     my ($input) = @_;
10524:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10525:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10526:     return $input;
10527: }
10528:  
10529: #   Escapes the last element of a full URL.
10530: sub escape_url {
10531:     my ($url)   = @_;
10532:     my @urlslices = split(/\//, $url,-1);
10533:     my $lastitem = &escape(pop(@urlslices));
10534:     return join('/',@urlslices).'/'.$lastitem;
10535: }
10536: 
10537: sub compare_arrays {
10538:     my ($arrayref1,$arrayref2) = @_;
10539:     my (@difference,%count);
10540:     @difference = ();
10541:     %count = ();
10542:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10543:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10544:         foreach my $element (keys(%count)) {
10545:             if ($count{$element} == 1) {
10546:                 push(@difference,$element);
10547:             }
10548:         }
10549:     }
10550:     return @difference;
10551: }
10552: 
10553: # -------------------------------------------------------- Initialize user login
10554: sub init_user_environment {
10555:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10556:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10557: 
10558:     my $public=($username eq 'public' && $domain eq 'public');
10559: 
10560: # See if old ID present, if so, remove
10561: 
10562:     my ($filename,$cookie,$userroles);
10563:     my $now=time;
10564: 
10565:     if ($public) {
10566: 	my $max_public=100;
10567: 	my $oldest;
10568: 	my $oldest_time=0;
10569: 	for(my $next=1;$next<=$max_public;$next++) {
10570: 	    if (-e $lonids."/publicuser_$next.id") {
10571: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10572: 		if ($mtime<$oldest_time || !$oldest_time) {
10573: 		    $oldest_time=$mtime;
10574: 		    $oldest=$next;
10575: 		}
10576: 	    } else {
10577: 		$cookie="publicuser_$next";
10578: 		last;
10579: 	    }
10580: 	}
10581: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10582:     } else {
10583: 	# if this isn't a robot, kill any existing non-robot sessions
10584: 	if (!$args->{'robot'}) {
10585: 	    opendir(DIR,$lonids);
10586: 	    while ($filename=readdir(DIR)) {
10587: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10588: 		    unlink($lonids.'/'.$filename);
10589: 		}
10590: 	    }
10591: 	    closedir(DIR);
10592: 	}
10593: # Give them a new cookie
10594: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10595: 		                   : $now.$$.int(rand(10000)));
10596: 	$cookie="$username\_$id\_$domain\_$authhost";
10597:     
10598: # Initialize roles
10599: 
10600: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10601:     }
10602: # ------------------------------------ Check browser type and MathML capability
10603: 
10604:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10605:         $clientunicode,$clientos) = &decode_user_agent($r);
10606: 
10607: # ------------------------------------------------------------- Get environment
10608: 
10609:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10610:     my ($tmp) = keys(%userenv);
10611:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10612:     } else {
10613: 	undef(%userenv);
10614:     }
10615:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10616: 	$form->{'interface'}=$userenv{'interface'};
10617:     }
10618:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10619: 
10620: # --------------- Do not trust query string to be put directly into environment
10621:     foreach my $option ('interface','localpath','localres') {
10622:         $form->{$option}=~s/[\n\r\=]//gs;
10623:     }
10624: # --------------------------------------------------------- Write first profile
10625: 
10626:     {
10627: 	my %initial_env = 
10628: 	    ("user.name"          => $username,
10629: 	     "user.domain"        => $domain,
10630: 	     "user.home"          => $authhost,
10631: 	     "browser.type"       => $clientbrowser,
10632: 	     "browser.version"    => $clientversion,
10633: 	     "browser.mathml"     => $clientmathml,
10634: 	     "browser.unicode"    => $clientunicode,
10635: 	     "browser.os"         => $clientos,
10636: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10637: 	     "request.course.fn"  => '',
10638: 	     "request.course.uri" => '',
10639: 	     "request.course.sec" => '',
10640: 	     "request.role"       => 'cm',
10641: 	     "request.role.adv"   => $env{'user.adv'},
10642: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10643: 
10644:         if ($form->{'localpath'}) {
10645: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10646: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10647:         }
10648: 	
10649: 	if ($form->{'interface'}) {
10650: 	    $form->{'interface'}=~s/\W//gs;
10651: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10652: 	    $env{'browser.interface'}=$form->{'interface'};
10653: 	}
10654: 
10655:         my %is_adv = ( is_adv => $env{'user.adv'} );
10656:         my %domdef = &Apache::lonnet::get_domain_defaults($domain);
10657: 
10658:         foreach my $tool ('aboutme','blog','portfolio') {
10659:             $userenv{'availabletools.'.$tool} = 
10660:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
10661:                                                   undef,\%userenv,\%domdef,\%is_adv);
10662:         }
10663: 
10664:         foreach my $crstype ('official','unofficial','community') {
10665:             $userenv{'canrequest.'.$crstype} =
10666:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10667:                                                   'reload','requestcourses',
10668:                                                   \%userenv,\%domdef,\%is_adv);
10669:         }
10670: 
10671: 	$env{'user.environment'} = "$lonids/$cookie.id";
10672: 	
10673: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10674: 		 &GDBM_WRCREAT(),0640)) {
10675: 	    &_add_to_env(\%disk_env,\%initial_env);
10676: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10677: 	    &_add_to_env(\%disk_env,$userroles);
10678: 	    if (ref($args->{'extra_env'})) {
10679: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10680: 	    }
10681: 	    untie(%disk_env);
10682: 	} else {
10683: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10684: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10685: 	    return 'error: '.$!;
10686: 	}
10687:     }
10688:     $env{'request.role'}='cm';
10689:     $env{'request.role.adv'}=$env{'user.adv'};
10690:     $env{'browser.type'}=$clientbrowser;
10691: 
10692:     return $cookie;
10693: 
10694: }
10695: 
10696: sub _add_to_env {
10697:     my ($idf,$env_data,$prefix) = @_;
10698:     if (ref($env_data) eq 'HASH') {
10699:         while (my ($key,$value) = each(%$env_data)) {
10700: 	    $idf->{$prefix.$key} = $value;
10701: 	    $env{$prefix.$key}   = $value;
10702:         }
10703:     }
10704: }
10705: 
10706: # --- Get the symbolic name of a problem and the url
10707: sub get_symb {
10708:     my ($request,$silent) = @_;
10709:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10710:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10711:     if ($symb eq '') {
10712:         if (!$silent) {
10713:             $request->print("Unable to handle ambiguous references:$url:.");
10714:             return ();
10715:         }
10716:     }
10717:     &Apache::lonenc::check_decrypt(\$symb);
10718:     return ($symb);
10719: }
10720: 
10721: # --------------------------------------------------------------Get annotation
10722: 
10723: sub get_annotation {
10724:     my ($symb,$enc) = @_;
10725: 
10726:     my $key = $symb;
10727:     if (!$enc) {
10728:         $key =
10729:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10730:     }
10731:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10732:     return $annotation{$key};
10733: }
10734: 
10735: sub clean_symb {
10736:     my ($symb,$delete_enc) = @_;
10737: 
10738:     &Apache::lonenc::check_decrypt(\$symb);
10739:     my $enc = $env{'request.enc'};
10740:     if ($delete_enc) {
10741:         delete($env{'request.enc'});
10742:     }
10743: 
10744:     return ($symb,$enc);
10745: }
10746: 
10747: =pod
10748: 
10749: =back
10750: 
10751: =cut
10752: 
10753: 1;
10754: __END__;
10755: 

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