File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.900: download - view: text, annotated - select for diffs
Thu Oct 22 13:13:12 2009 UTC (14 years, 7 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- Optimized screen ergonomics:
    - Set default vertical text align in data_tables and pick_boxes from middle to top
    - Set default horizontal text align in pick_boxes from right to left
- Optimized white spaces in HTML source code for data_table rows without additional styles

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.900 2009/10/22 13:13:12 bisitz Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:              "<span style='color:yellow;'>INFO: Read file types</span>");
  275:     $readit=1;
  276:     }  # end of unless($readit) 
  277:     
  278: }
  279: 
  280: ###############################################################
  281: ##           HTML and Javascript Helper Functions            ##
  282: ###############################################################
  283: 
  284: =pod 
  285: 
  286: =head1 HTML and Javascript Functions
  287: 
  288: =over 4
  289: 
  290: =item * &browser_and_searcher_javascript()
  291: 
  292: X<browsing, javascript>X<searching, javascript>Returns a string
  293: containing javascript with two functions, C<openbrowser> and
  294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  295: tags.
  296: 
  297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  298: 
  299: inputs: formname, elementname, only, omit
  300: 
  301: formname and elementname indicate the name of the html form and name of
  302: the element that the results of the browsing selection are to be placed in. 
  303: 
  304: Specifying 'only' will restrict the browser to displaying only files
  305: with the given extension.  Can be a comma separated list.
  306: 
  307: Specifying 'omit' will restrict the browser to NOT displaying files
  308: with the given extension.  Can be a comma separated list.
  309: 
  310: =item * &opensearcher(formname,elementname) [javascript]
  311: 
  312: Inputs: formname, elementname
  313: 
  314: formname and elementname specify the name of the html form and the name
  315: of the element the selection from the search results will be placed in.
  316: 
  317: =cut
  318: 
  319: sub browser_and_searcher_javascript {
  320:     my ($mode)=@_;
  321:     if (!defined($mode)) { $mode='edit'; }
  322:     my $resurl=&escape_single(&lastresurl());
  323:     return <<END;
  324: // <!-- BEGIN LON-CAPA Internal
  325:     var editbrowser = null;
  326:     function openbrowser(formname,elementname,only,omit,titleelement) {
  327:         var url = '$resurl/?';
  328:         if (editbrowser == null) {
  329:             url += 'launch=1&';
  330:         }
  331:         url += 'catalogmode=interactive&';
  332:         url += 'mode=$mode&';
  333:         url += 'inhibitmenu=yes&';
  334:         url += 'form=' + formname + '&';
  335:         if (only != null) {
  336:             url += 'only=' + only + '&';
  337:         } else {
  338:             url += 'only=&';
  339: 	}
  340:         if (omit != null) {
  341:             url += 'omit=' + omit + '&';
  342:         } else {
  343:             url += 'omit=&';
  344: 	}
  345:         if (titleelement != null) {
  346:             url += 'titleelement=' + titleelement + '&';
  347:         } else {
  348: 	    url += 'titleelement=&';
  349: 	}
  350:         url += 'element=' + elementname + '';
  351:         var title = 'Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  353:         options += ',width=700,height=600';
  354:         editbrowser = open(url,title,options,'1');
  355:         editbrowser.focus();
  356:     }
  357:     var editsearcher;
  358:     function opensearcher(formname,elementname,titleelement) {
  359:         var url = '/adm/searchcat?';
  360:         if (editsearcher == null) {
  361:             url += 'launch=1&';
  362:         }
  363:         url += 'catalogmode=interactive&';
  364:         url += 'mode=$mode&';
  365:         url += 'form=' + formname + '&';
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Search';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editsearcher = open(url,title,options,'1');
  376:         editsearcher.focus();
  377:     }
  378: // END LON-CAPA Internal -->
  379: END
  380: }
  381: 
  382: sub lastresurl {
  383:     if ($env{'environment.lastresurl'}) {
  384: 	return $env{'environment.lastresurl'}
  385:     } else {
  386: 	return '/res';
  387:     }
  388: }
  389: 
  390: sub storeresurl {
  391:     my $resurl=&Apache::lonnet::clutter(shift);
  392:     unless ($resurl=~/^\/res/) { return 0; }
  393:     $resurl=~s/\/$//;
  394:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  395:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  396:     return 1;
  397: }
  398: 
  399: sub studentbrowser_javascript {
  400:    unless (
  401:             (($env{'request.course.id'}) && 
  402:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  403: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  404: 					  '/'.$env{'request.course.sec'})
  405: 	      ))
  406:          || ($env{'request.role'}=~/^(au|dc|su)/)
  407:           ) { return ''; }  
  408:    return (<<'ENDSTDBRW');
  409: <script type="text/javascript" language="Javascript">
  410: // <![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)=@_;
  486:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Community - for which you wish to add/modify a user role.');
  487:     my $id_functions = &javascript_index_functions();
  488:     my $output = '
  489: <script type="text/javascript" language="JavaScript">
  490: // <![CDATA[
  491:     var stdeditbrowser;'."\n";
  492: 
  493:     $output .= <<"ENDSTDBRW";
  494:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  495:         var url = '/adm/pickcourse?';
  496:         var formid = getFormIdByName(formname);
  497:         var domainfilter = getDomainFromSelectbox(formname,udom);
  498:         if (domainfilter != null) {
  499:            if (domainfilter != '') {
  500:                url += 'domainfilter='+domainfilter+'&';
  501: 	   }
  502:         }
  503:         url += 'form=' + formname + '&cnumelement='+uname+
  504: 	                            '&cdomelement='+udom+
  505:                                     '&cnameelement='+desc;
  506:         if (extra_element !=null && extra_element != '') {
  507:             if (formname == 'rolechoice' || formname == 'studentform') {
  508:                 url += '&roleelement='+extra_element;
  509:                 if (domainfilter == null || domainfilter == '') {
  510:                     url += '&domainfilter='+extra_element;
  511:                 }
  512:             }
  513:             else {
  514:                 if (formname == 'portform') {
  515:                     url += '&setroles='+extra_element;
  516:                 } else {
  517:                     if (formname == 'rules') {
  518:                         url += '&fixeddom='+extra_element; 
  519:                     }
  520:                 }
  521:             }     
  522:         }
  523:         if (formname == 'ccrs') {
  524:             var ownername = document.forms[formid].ccuname.value;
  525:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  526:             url += '&cloner='+ownername+':'+ownerdom;
  527:         }
  528:         if (multflag !=null && multflag != '') {
  529:             url += '&multiple='+multflag;
  530:         }
  531:         if (crstype == 'Course/Community') {
  532:             if (formname == 'cu') {
  533:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  534:                 if (crstype == "") {
  535:                     alert("$crs_or_grp_alert");
  536:                     return;
  537:                 }
  538:             }
  539:         }
  540:         if (crstype !=null && crstype != '') {
  541:             url += '&type='+crstype;
  542:         }
  543:         var title = 'Course_Browser';
  544:         var options = 'scrollbars=1,resizable=1,menubar=0';
  545:         options += ',width=700,height=600';
  546:         stdeditbrowser = open(url,title,options,'1');
  547:         stdeditbrowser.focus();
  548:     }
  549: $id_functions
  550: ENDSTDBRW
  551:     if ($sec_element ne '') {
  552:         $output .= &setsec_javascript($sec_element,$formname);
  553:     }
  554:     $output .= '
  555: // ]]>
  556: </script>';
  557:     return $output;
  558: }
  559: 
  560: sub javascript_index_functions {
  561:     return <<"ENDJS";
  562: 
  563: function getFormIdByName(formname) {
  564:     for (var i=0;i<document.forms.length;i++) {
  565:         if (document.forms[i].name == formname) {
  566:             return i;
  567:         }
  568:     }
  569:     return -1;
  570: }
  571: 
  572: function getIndexByName(formid,item) {
  573:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  574:         if (document.forms[formid].elements[i].name == item) {
  575:             return i;
  576:         }
  577:     }
  578:     return -1;
  579: }
  580: 
  581: function getDomainFromSelectbox(formname,udom) {
  582:     var userdom;
  583:     var formid = getFormIdByName(formname);
  584:     if (formid > -1) {
  585:         var domid = getIndexByName(formid,udom);
  586:         if (domid > -1) {
  587:             if (document.forms[formid].elements[domid].type == 'select-one') {
  588:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  589:             }
  590:             if (document.forms[formid].elements[domid].type == 'hidden') {
  591:                 userdom=document.forms[formid].elements[domid].value;
  592:             }
  593:         }
  594:     }
  595:     return userdom;
  596: }
  597: 
  598: ENDJS
  599: 
  600: }
  601: 
  602: sub userbrowser_javascript {
  603:     my $id_functions = &javascript_index_functions();
  604:     return <<"ENDUSERBRW";
  605: 
  606: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  607:     var url = '/adm/pickuser?';
  608:     var userdom = getDomainFromSelectbox(formname,udom);
  609:     if (userdom != null) {
  610:        if (userdom != '') {
  611:            url += 'srchdom='+userdom+'&';
  612:        }
  613:     }
  614:     url += 'form=' + formname + '&unameelement='+uname+
  615:                                 '&udomelement='+udom+
  616:                                 '&ulastelement='+ulast+
  617:                                 '&ufirstelement='+ufirst+
  618:                                 '&uemailelement='+uemail+
  619:                                 '&hideudomelement='+hideudom+
  620:                                 '&coursedom='+crsdom;
  621:     if ((caller != null) && (caller != undefined)) {
  622:         url += '&caller='+caller;
  623:     }
  624:     var title = 'User_Browser';
  625:     var options = 'scrollbars=1,resizable=1,menubar=0';
  626:     options += ',width=700,height=600';
  627:     var stdeditbrowser = open(url,title,options,'1');
  628:     stdeditbrowser.focus();
  629: }
  630: 
  631: function fix_domain (formname,udom,origdom,uname) {
  632:     var formid = getFormIdByName(formname);
  633:     if (formid > -1) {
  634:         var unameid = getIndexByName(formid,uname);
  635:         var domid = getIndexByName(formid,udom);
  636:         var hidedomid = getIndexByName(formid,origdom);
  637:         if (hidedomid > -1) {
  638:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  639:             var unameval = document.forms[formid].elements[unameid].value;
  640:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  641:                 if (domid > -1) {
  642:                     var slct = document.forms[formid].elements[domid];
  643:                     if (slct.type == 'select-one') {
  644:                         var i;
  645:                         for (i=0;i<slct.length;i++) {
  646:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  647:                         }
  648:                     }
  649:                     if (slct.type == 'hidden') {
  650:                         slct.value = fixeddom;
  651:                     }
  652:                 }
  653:             }
  654:         }
  655:     }
  656:     return;
  657: }
  658: 
  659: $id_functions
  660: ENDUSERBRW
  661: }
  662: 
  663: sub setsec_javascript {
  664:     my ($sec_element,$formname) = @_;
  665:     my $setsections = qq|
  666: function setSect(sectionlist) {
  667:     var sectionsArray = new Array();
  668:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  669:         sectionsArray = sectionlist.split(",");
  670:     }
  671:     var numSections = sectionsArray.length;
  672:     document.$formname.$sec_element.length = 0;
  673:     if (numSections == 0) {
  674:         document.$formname.$sec_element.multiple=false;
  675:         document.$formname.$sec_element.size=1;
  676:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  677:     } else {
  678:         if (numSections == 1) {
  679:             document.$formname.$sec_element.multiple=false;
  680:             document.$formname.$sec_element.size=1;
  681:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  682:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  683:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  684:         } else {
  685:             for (var i=0; i<numSections; i++) {
  686:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  687:             }
  688:             document.$formname.$sec_element.multiple=true
  689:             if (numSections < 3) {
  690:                 document.$formname.$sec_element.size=numSections;
  691:             } else {
  692:                 document.$formname.$sec_element.size=3;
  693:             }
  694:             document.$formname.$sec_element.options[0].selected = false
  695:         }
  696:     }
  697: }
  698: |;
  699:     return $setsections;
  700: }
  701: 
  702: 
  703: sub selectcourse_link {
  704:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  705:    my $linktext = &mt('Select Course');
  706:    if ($selecttype eq 'Community') {
  707:        $linktext = &mt('Select Community'); 
  708:    }
  709:    return '<span class="LC_nobreak">'
  710:          ."<a href='"
  711:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  712:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  713:          .'","'.$multflag.'","'.$selecttype.'");'
  714:          ."'>".$linktext.'</a>'
  715:          .'</span>';
  716: }
  717: 
  718: sub selectauthor_link {
  719:    my ($form,$udom)=@_;
  720:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  721:           &mt('Select Author').'</a>';
  722: }
  723: 
  724: sub selectuser_link {
  725:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  726:         $coursedom,$linktext,$caller) = @_;
  727:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  728:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  729:            ');">'.$linktext.'</a>';
  730: }
  731: 
  732: sub check_uncheck_jscript {
  733:     my $jscript = <<"ENDSCRT";
  734: function checkAll(field) {
  735:     if (field.length > 0) {
  736:         for (i = 0; i < field.length; i++) {
  737:             field[i].checked = true ;
  738:         }
  739:     } else {
  740:         field.checked = true
  741:     }
  742: }
  743:  
  744: function uncheckAll(field) {
  745:     if (field.length > 0) {
  746:         for (i = 0; i < field.length; i++) {
  747:             field[i].checked = false ;
  748:         }
  749:     } else {
  750:         field.checked = false ;
  751:     }
  752: }
  753: ENDSCRT
  754:     return $jscript;
  755: }
  756: 
  757: sub select_timezone {
  758:    my ($name,$selected,$onchange,$includeempty)=@_;
  759:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  760:    if ($includeempty) {
  761:        $output .= '<option value=""';
  762:        if (($selected eq '') || ($selected eq 'local')) {
  763:            $output .= ' selected="selected" ';
  764:        }
  765:        $output .= '> </option>';
  766:    }
  767:    my @timezones = DateTime::TimeZone->all_names;
  768:    foreach my $tzone (@timezones) {
  769:        $output.= '<option value="'.$tzone.'"';
  770:        if ($tzone eq $selected) {
  771:            $output.=' selected="selected"';
  772:        }
  773:        $output.=">$tzone</option>\n";
  774:    }
  775:    $output.="</select>";
  776:    return $output;
  777: }
  778: 
  779: sub select_datelocale {
  780:     my ($name,$selected,$onchange,$includeempty)=@_;
  781:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  782:     if ($includeempty) {
  783:         $output .= '<option value=""';
  784:         if ($selected eq '') {
  785:             $output .= ' selected="selected" ';
  786:         }
  787:         $output .= '> </option>';
  788:     }
  789:     my (@possibles,%locale_names);
  790:     my @locales = DateTime::Locale::Catalog::Locales;
  791:     foreach my $locale (@locales) {
  792:         if (ref($locale) eq 'HASH') {
  793:             my $id = $locale->{'id'};
  794:             if ($id ne '') {
  795:                 my $en_terr = $locale->{'en_territory'};
  796:                 my $native_terr = $locale->{'native_territory'};
  797:                 my @languages = &Apache::lonlocal::preferred_languages();
  798:                 if (grep(/^en$/,@languages) || !@languages) {
  799:                     if ($en_terr ne '') {
  800:                         $locale_names{$id} = '('.$en_terr.')';
  801:                     } elsif ($native_terr ne '') {
  802:                         $locale_names{$id} = $native_terr;
  803:                     }
  804:                 } else {
  805:                     if ($native_terr ne '') {
  806:                         $locale_names{$id} = $native_terr.' ';
  807:                     } elsif ($en_terr ne '') {
  808:                         $locale_names{$id} = '('.$en_terr.')';
  809:                     }
  810:                 }
  811:                 push (@possibles,$id);
  812:             }
  813:         }
  814:     }
  815:     foreach my $item (sort(@possibles)) {
  816:         $output.= '<option value="'.$item.'"';
  817:         if ($item eq $selected) {
  818:             $output.=' selected="selected"';
  819:         }
  820:         $output.=">$item";
  821:         if ($locale_names{$item} ne '') {
  822:             $output.="  $locale_names{$item}</option>\n";
  823:         }
  824:         $output.="</option>\n";
  825:     }
  826:     $output.="</select>";
  827:     return $output;
  828: }
  829: 
  830: sub select_language {
  831:     my ($name,$selected,$includeempty) = @_;
  832:     my %langchoices;
  833:     if ($includeempty) {
  834:         %langchoices = ('' => 'No language preference');
  835:     }
  836:     foreach my $id (&languageids()) {
  837:         my $code = &supportedlanguagecode($id);
  838:         if ($code) {
  839:             $langchoices{$code} = &plainlanguagedescription($id);
  840:         }
  841:     }
  842:     return &select_form($selected,$name,%langchoices);
  843: }
  844: 
  845: =pod
  846: 
  847: =item * &linked_select_forms(...)
  848: 
  849: linked_select_forms returns a string containing a <script></script> block
  850: and html for two <select> menus.  The select menus will be linked in that
  851: changing the value of the first menu will result in new values being placed
  852: in the second menu.  The values in the select menu will appear in alphabetical
  853: order unless a defined order is provided.
  854: 
  855: linked_select_forms takes the following ordered inputs:
  856: 
  857: =over 4
  858: 
  859: =item * $formname, the name of the <form> tag
  860: 
  861: =item * $middletext, the text which appears between the <select> tags
  862: 
  863: =item * $firstdefault, the default value for the first menu
  864: 
  865: =item * $firstselectname, the name of the first <select> tag
  866: 
  867: =item * $secondselectname, the name of the second <select> tag
  868: 
  869: =item * $hashref, a reference to a hash containing the data for the menus.
  870: 
  871: =item * $menuorder, the order of values in the first menu
  872: 
  873: =back 
  874: 
  875: Below is an example of such a hash.  Only the 'text', 'default', and 
  876: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  877: values for the first select menu.  The text that coincides with the 
  878: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  879: and text for the second menu are given in the hash pointed to by 
  880: $menu{$choice1}->{'select2'}.  
  881: 
  882:  my %menu = ( A1 => { text =>"Choice A1" ,
  883:                        default => "B3",
  884:                        select2 => { 
  885:                            B1 => "Choice B1",
  886:                            B2 => "Choice B2",
  887:                            B3 => "Choice B3",
  888:                            B4 => "Choice B4"
  889:                            },
  890:                        order => ['B4','B3','B1','B2'],
  891:                    },
  892:                A2 => { text =>"Choice A2" ,
  893:                        default => "C2",
  894:                        select2 => { 
  895:                            C1 => "Choice C1",
  896:                            C2 => "Choice C2",
  897:                            C3 => "Choice C3"
  898:                            },
  899:                        order => ['C2','C1','C3'],
  900:                    },
  901:                A3 => { text =>"Choice A3" ,
  902:                        default => "D6",
  903:                        select2 => { 
  904:                            D1 => "Choice D1",
  905:                            D2 => "Choice D2",
  906:                            D3 => "Choice D3",
  907:                            D4 => "Choice D4",
  908:                            D5 => "Choice D5",
  909:                            D6 => "Choice D6",
  910:                            D7 => "Choice D7"
  911:                            },
  912:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  913:                    }
  914:                );
  915: 
  916: =cut
  917: 
  918: sub linked_select_forms {
  919:     my ($formname,
  920:         $middletext,
  921:         $firstdefault,
  922:         $firstselectname,
  923:         $secondselectname, 
  924:         $hashref,
  925:         $menuorder,
  926:         ) = @_;
  927:     my $second = "document.$formname.$secondselectname";
  928:     my $first = "document.$formname.$firstselectname";
  929:     # output the javascript to do the changing
  930:     my $result = '';
  931:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  932:     $result.="// <![CDATA[\n";
  933:     $result.="var select2data = new Object();\n";
  934:     $" = '","';
  935:     my $debug = '';
  936:     foreach my $s1 (sort(keys(%$hashref))) {
  937:         $result.="select2data.d_$s1 = new Object();\n";        
  938:         $result.="select2data.d_$s1.def = new String('".
  939:             $hashref->{$s1}->{'default'}."');\n";
  940:         $result.="select2data.d_$s1.values = new Array(";
  941:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  942:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  943:             @s2values = @{$hashref->{$s1}->{'order'}};
  944:         }
  945:         $result.="\"@s2values\");\n";
  946:         $result.="select2data.d_$s1.texts = new Array(";        
  947:         my @s2texts;
  948:         foreach my $value (@s2values) {
  949:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  950:         }
  951:         $result.="\"@s2texts\");\n";
  952:     }
  953:     $"=' ';
  954:     $result.= <<"END";
  955: 
  956: function select1_changed() {
  957:     // Determine new choice
  958:     var newvalue = "d_" + $first.value;
  959:     // update select2
  960:     var values     = select2data[newvalue].values;
  961:     var texts      = select2data[newvalue].texts;
  962:     var select2def = select2data[newvalue].def;
  963:     var i;
  964:     // out with the old
  965:     for (i = 0; i < $second.options.length; i++) {
  966:         $second.options[i] = null;
  967:     }
  968:     // in with the nuclear
  969:     for (i=0;i<values.length; i++) {
  970:         $second.options[i] = new Option(values[i]);
  971:         $second.options[i].value = values[i];
  972:         $second.options[i].text = texts[i];
  973:         if (values[i] == select2def) {
  974:             $second.options[i].selected = true;
  975:         }
  976:     }
  977: }
  978: // ]]>
  979: </script>
  980: END
  981:     # output the initial values for the selection lists
  982:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  983:     my @order = sort(keys(%{$hashref}));
  984:     if (ref($menuorder) eq 'ARRAY') {
  985:         @order = @{$menuorder};
  986:     }
  987:     foreach my $value (@order) {
  988:         $result.="    <option value=\"$value\" ";
  989:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  990:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  991:     }
  992:     $result .= "</select>\n";
  993:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  994:     $result .= $middletext;
  995:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  996:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  997:     
  998:     my @secondorder = sort(keys(%select2));
  999:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1000:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1001:     }
 1002:     foreach my $value (@secondorder) {
 1003:         $result.="    <option value=\"$value\" ";        
 1004:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1005:         $result.=">".&mt($select2{$value})."</option>\n";
 1006:     }
 1007:     $result .= "</select>\n";
 1008:     #    return $debug;
 1009:     return $result;
 1010: }   #  end of sub linked_select_forms {
 1011: 
 1012: =pod
 1013: 
 1014: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
 1015: 
 1016: Returns a string corresponding to an HTML link to the given help
 1017: $topic, where $topic corresponds to the name of a .tex file in
 1018: /home/httpd/html/adm/help/tex, with underscores replaced by
 1019: spaces. 
 1020: 
 1021: $text will optionally be linked to the same topic, allowing you to
 1022: link text in addition to the graphic. If you do not want to link
 1023: text, but wish to specify one of the later parameters, pass an
 1024: empty string. 
 1025: 
 1026: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1027: the link will not open a new window. If false, the link will open
 1028: a new window using Javascript. (Default is false.) 
 1029: 
 1030: $width and $height are optional numerical parameters that will
 1031: override the width and height of the popped up window, which may
 1032: be useful for certain help topics with big pictures included. 
 1033: 
 1034: =cut
 1035: 
 1036: sub help_open_topic {
 1037:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1038:     $text = "" if (not defined $text);
 1039:     $stayOnPage = 0 if (not defined $stayOnPage);
 1040:     $width = 350 if (not defined $width);
 1041:     $height = 400 if (not defined $height);
 1042:     my $filename = $topic;
 1043:     $filename =~ s/ /_/g;
 1044: 
 1045:     my $template = "";
 1046:     my $link;
 1047:     
 1048:     $topic=~s/\W/\_/g;
 1049: 
 1050:     if (!$stayOnPage) {
 1051: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1052:     } else {
 1053: 	$link = "/adm/help/${filename}.hlp";
 1054:     }
 1055: 
 1056:     # Add the text
 1057:     if ($text ne "") {	
 1058: 	$template.='<span class="LC_help_open_topic">'
 1059:                   .'<a target="_top" href="'.$link.'">'
 1060:                   .$text.'</a>';
 1061:     }
 1062: 
 1063:     # (Always) Add the graphic
 1064:     my $title = &mt('Online Help');
 1065:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1066:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1067:               .'<img src="'.$helpicon.'" border="0"'
 1068:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1069:               .' title="'.$title.'"' 
 1070:               .' /></a>';
 1071:     if ($text ne "") {	
 1072:         $template.='</span>';
 1073:     }
 1074:     return $template;
 1075: 
 1076: }
 1077: 
 1078: # This is a quicky function for Latex cheatsheet editing, since it 
 1079: # appears in at least four places
 1080: sub helpLatexCheatsheet {
 1081:     my ($topic,$text,$not_author) = @_;
 1082:     my $out;
 1083:     my $addOther = '';
 1084:     if ($topic) {
 1085: 	$addOther = '<span>'.&Apache::loncommon::help_open_topic($topic,&mt($text),
 1086: 							       undef, undef, 600).
 1087: 								   '</span> ';
 1088:     }
 1089:     $out = '<span>' # Start cheatsheet
 1090: 	  .$addOther
 1091:           .'<span>'
 1092: 	  .&Apache::loncommon::help_open_topic('Greek_Symbols',&mt('Greek Symbols'),
 1093: 					       undef,undef,600)
 1094: 	  .'</span> <span>'
 1095: 	  .&Apache::loncommon::help_open_topic('Other_Symbols',&mt('Other Symbols'),
 1096: 					       undef,undef,600)
 1097: 	  .'</span>';
 1098:     unless ($not_author) {
 1099:         $out .= ' <span>'
 1100: 	       .&Apache::loncommon::help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),
 1101: 	                                            undef,undef,600)
 1102: 	       .'</span>';
 1103:     }
 1104:     $out .= '</span>'; # End cheatsheet
 1105:     return $out;
 1106: }
 1107: 
 1108: sub general_help {
 1109:     my $helptopic='Student_Intro';
 1110:     if ($env{'request.role'}=~/^(ca|au)/) {
 1111: 	$helptopic='Authoring_Intro';
 1112:     } elsif ($env{'request.role'}=~/^cc/) {
 1113: 	$helptopic='Course_Coordination_Intro';
 1114:     } elsif ($env{'request.role'}=~/^dc/) {
 1115:         $helptopic='Domain_Coordination_Intro';
 1116:     }
 1117:     return $helptopic;
 1118: }
 1119: 
 1120: sub update_help_link {
 1121:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1122:     my $origurl = $ENV{'REQUEST_URI'};
 1123:     $origurl=~s|^/~|/priv/|;
 1124:     my $timestamp = time;
 1125:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1126:         $$datum = &escape($$datum);
 1127:     }
 1128: 
 1129:     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";
 1130:     my $output .= <<"ENDOUTPUT";
 1131: <script type="text/javascript">
 1132: // <![CDATA[
 1133: banner_link = '$banner_link';
 1134: // ]]>
 1135: </script>
 1136: ENDOUTPUT
 1137:     return $output;
 1138: }
 1139: 
 1140: # now just updates the help link and generates a blue icon
 1141: sub help_open_menu {
 1142:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1143: 	= @_;    
 1144:     $stayOnPage = 0 if (not defined $stayOnPage);
 1145:     # only use pop-up help (stayOnPage == 0)
 1146:     # if environment.remote is on (using remote control UI)
 1147:     if ($env{'environment.remote'} eq 'off' ) {
 1148:         $stayOnPage=1;
 1149:     }
 1150:     my $output;
 1151:     if ($component_help) {
 1152: 	if (!$text) {
 1153: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1154: 				       $width,$height);
 1155: 	} else {
 1156: 	    my $help_text;
 1157: 	    $help_text=&unescape($topic);
 1158: 	    $output='<table><tr><td>'.
 1159: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1160: 				 $width,$height).'</td></tr></table>';
 1161: 	}
 1162:     }
 1163:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1164:     return $output.$banner_link;
 1165: }
 1166: 
 1167: sub top_nav_help {
 1168:     my ($text) = @_;
 1169:     $text = &mt($text);
 1170:     my $stay_on_page = 
 1171: 	($env{'environment.remote'} eq 'off' );
 1172:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1173: 	                     : "javascript:helpMenu('open')";
 1174:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1175: 
 1176:     my $title = &mt('Get help');
 1177: 
 1178:     return <<"END";
 1179: $banner_link
 1180:  <a href="$link" title="$title">$text</a>
 1181: END
 1182: }
 1183: 
 1184: sub help_menu_js {
 1185:     my ($text) = @_;
 1186: 
 1187:     my $stayOnPage = 
 1188: 	($env{'environment.remote'} eq 'off' );
 1189: 
 1190:     my $width = 620;
 1191:     my $height = 600;
 1192:     my $helptopic=&general_help();
 1193:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1194:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1195:     my $start_page =
 1196:         &Apache::loncommon::start_page('Help Menu', undef,
 1197: 				       {'frameset'    => 1,
 1198: 					'js_ready'    => 1,
 1199: 					'add_entries' => {
 1200: 					    'border' => '0',
 1201: 					    'rows'   => "110,*",},});
 1202:     my $end_page =
 1203:         &Apache::loncommon::end_page({'frameset' => 1,
 1204: 				      'js_ready' => 1,});
 1205: 
 1206:     my $template .= <<"ENDTEMPLATE";
 1207: <script type="text/javascript">
 1208: // <![CDATA[
 1209: // <!-- BEGIN LON-CAPA Internal
 1210: var banner_link = '';
 1211: function helpMenu(target) {
 1212:     var caller = this;
 1213:     if (target == 'open') {
 1214:         var newWindow = null;
 1215:         try {
 1216:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1217:         }
 1218:         catch(error) {
 1219:             writeHelp(caller);
 1220:             return;
 1221:         }
 1222:         if (newWindow) {
 1223:             caller = newWindow;
 1224:         }
 1225:     }
 1226:     writeHelp(caller);
 1227:     return;
 1228: }
 1229: function writeHelp(caller) {
 1230:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1231:     caller.document.close()
 1232:     caller.focus()
 1233: }
 1234: // END LON-CAPA Internal -->
 1235: // ]]>
 1236: </script>
 1237: ENDTEMPLATE
 1238:     return $template;
 1239: }
 1240: 
 1241: sub help_open_bug {
 1242:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1243:     unless ($env{'user.adv'}) { return ''; }
 1244:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1245:     $text = "" if (not defined $text);
 1246:     $stayOnPage = 0 if (not defined $stayOnPage);
 1247:     if ($env{'environment.remote'} eq 'off' ) {
 1248: 	$stayOnPage=1;
 1249:     }
 1250:     $width = 600 if (not defined $width);
 1251:     $height = 600 if (not defined $height);
 1252: 
 1253:     $topic=~s/\W+/\+/g;
 1254:     my $link='';
 1255:     my $template='';
 1256:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1257: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1258:     if (!$stayOnPage)
 1259:     {
 1260: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1261:     }
 1262:     else
 1263:     {
 1264: 	$link = $url;
 1265:     }
 1266:     # Add the text
 1267:     if ($text ne "")
 1268:     {
 1269: 	$template .= 
 1270:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1271:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1272:     }
 1273: 
 1274:     # Add the graphic
 1275:     my $title = &mt('Report a Bug');
 1276:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1277:     $template .= <<"ENDTEMPLATE";
 1278:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1279: ENDTEMPLATE
 1280:     if ($text ne '') { $template.='</td></tr></table>' };
 1281:     return $template;
 1282: 
 1283: }
 1284: 
 1285: sub help_open_faq {
 1286:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1287:     unless ($env{'user.adv'}) { return ''; }
 1288:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1289:     $text = "" if (not defined $text);
 1290:     $stayOnPage = 0 if (not defined $stayOnPage);
 1291:     if ($env{'environment.remote'} eq 'off' ) {
 1292: 	$stayOnPage=1;
 1293:     }
 1294:     $width = 350 if (not defined $width);
 1295:     $height = 400 if (not defined $height);
 1296: 
 1297:     $topic=~s/\W+/\+/g;
 1298:     my $link='';
 1299:     my $template='';
 1300:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1301:     if (!$stayOnPage)
 1302:     {
 1303: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1304:     }
 1305:     else
 1306:     {
 1307: 	$link = $url;
 1308:     }
 1309: 
 1310:     # Add the text
 1311:     if ($text ne "")
 1312:     {
 1313: 	$template .= 
 1314:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1315:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1316:     }
 1317: 
 1318:     # Add the graphic
 1319:     my $title = &mt('View the FAQ');
 1320:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1321:     $template .= <<"ENDTEMPLATE";
 1322:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1323: ENDTEMPLATE
 1324:     if ($text ne '') { $template.='</td></tr></table>' };
 1325:     return $template;
 1326: 
 1327: }
 1328: 
 1329: ###############################################################
 1330: ###############################################################
 1331: 
 1332: =pod
 1333: 
 1334: =item * &change_content_javascript():
 1335: 
 1336: This and the next function allow you to create small sections of an
 1337: otherwise static HTML page that you can update on the fly with
 1338: Javascript, even in Netscape 4.
 1339: 
 1340: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1341: must be written to the HTML page once. It will prove the Javascript
 1342: function "change(name, content)". Calling the change function with the
 1343: name of the section 
 1344: you want to update, matching the name passed to C<changable_area>, and
 1345: the new content you want to put in there, will put the content into
 1346: that area.
 1347: 
 1348: B<Note>: Netscape 4 only reserves enough space for the changable area
 1349: to contain room for the original contents. You need to "make space"
 1350: for whatever changes you wish to make, and be B<sure> to check your
 1351: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1352: it's adequate for updating a one-line status display, but little more.
 1353: This script will set the space to 100% width, so you only need to
 1354: worry about height in Netscape 4.
 1355: 
 1356: Modern browsers are much less limiting, and if you can commit to the
 1357: user not using Netscape 4, this feature may be used freely with
 1358: pretty much any HTML.
 1359: 
 1360: =cut
 1361: 
 1362: sub change_content_javascript {
 1363:     # If we're on Netscape 4, we need to use Layer-based code
 1364:     if ($env{'browser.type'} eq 'netscape' &&
 1365: 	$env{'browser.version'} =~ /^4\./) {
 1366: 	return (<<NETSCAPE4);
 1367: 	function change(name, content) {
 1368: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1369: 	    doc.open();
 1370: 	    doc.write(content);
 1371: 	    doc.close();
 1372: 	}
 1373: NETSCAPE4
 1374:     } else {
 1375: 	# Otherwise, we need to use semi-standards-compliant code
 1376: 	# (technically, "innerHTML" isn't standard but the equivalent
 1377: 	# is really scary, and every useful browser supports it
 1378: 	return (<<DOMBASED);
 1379: 	function change(name, content) {
 1380: 	    element = document.getElementById(name);
 1381: 	    element.innerHTML = content;
 1382: 	}
 1383: DOMBASED
 1384:     }
 1385: }
 1386: 
 1387: =pod
 1388: 
 1389: =item * &changable_area($name,$origContent):
 1390: 
 1391: This provides a "changable area" that can be modified on the fly via
 1392: the Javascript code provided in C<change_content_javascript>. $name is
 1393: the name you will use to reference the area later; do not repeat the
 1394: same name on a given HTML page more then once. $origContent is what
 1395: the area will originally contain, which can be left blank.
 1396: 
 1397: =cut
 1398: 
 1399: sub changable_area {
 1400:     my ($name, $origContent) = @_;
 1401: 
 1402:     if ($env{'browser.type'} eq 'netscape' &&
 1403: 	$env{'browser.version'} =~ /^4\./) {
 1404: 	# If this is netscape 4, we need to use the Layer tag
 1405: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1406:     } else {
 1407: 	return "<span id='$name'>$origContent</span>";
 1408:     }
 1409: }
 1410: 
 1411: =pod
 1412: 
 1413: =item * &viewport_geometry_js 
 1414: 
 1415: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1416: 
 1417: =cut
 1418: 
 1419: 
 1420: sub viewport_geometry_js { 
 1421:     return <<"GEOMETRY";
 1422: var Geometry = {};
 1423: function init_geometry() {
 1424:     if (Geometry.init) { return };
 1425:     Geometry.init=1;
 1426:     if (window.innerHeight) {
 1427:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1428:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1429:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1430:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1431:     }
 1432:     else if (document.documentElement && document.documentElement.clientHeight) {
 1433:         Geometry.getViewportHeight =
 1434:             function() { return document.documentElement.clientHeight; };
 1435:         Geometry.getViewportWidth =
 1436:             function() { return document.documentElement.clientWidth; };
 1437: 
 1438:         Geometry.getHorizontalScroll =
 1439:             function() { return document.documentElement.scrollLeft; };
 1440:         Geometry.getVerticalScroll =
 1441:             function() { return document.documentElement.scrollTop; };
 1442:     }
 1443:     else if (document.body.clientHeight) {
 1444:         Geometry.getViewportHeight =
 1445:             function() { return document.body.clientHeight; };
 1446:         Geometry.getViewportWidth =
 1447:             function() { return document.body.clientWidth; };
 1448:         Geometry.getHorizontalScroll =
 1449:             function() { return document.body.scrollLeft; };
 1450:         Geometry.getVerticalScroll =
 1451:             function() { return document.body.scrollTop; };
 1452:     }
 1453: }
 1454: 
 1455: GEOMETRY
 1456: }
 1457: 
 1458: =pod
 1459: 
 1460: =item * &viewport_size_js()
 1461: 
 1462: 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. 
 1463: 
 1464: =cut
 1465: 
 1466: sub viewport_size_js {
 1467:     my $geometry = &viewport_geometry_js();
 1468:     return <<"DIMS";
 1469: 
 1470: $geometry
 1471: 
 1472: function getViewportDims(width,height) {
 1473:     init_geometry();
 1474:     width.value = Geometry.getViewportWidth();
 1475:     height.value = Geometry.getViewportHeight();
 1476:     return;
 1477: }
 1478: 
 1479: DIMS
 1480: }
 1481: 
 1482: =pod
 1483: 
 1484: =item * &resize_textarea_js()
 1485: 
 1486: emits the needed javascript to resize a textarea to be as big as possible
 1487: 
 1488: creates a function resize_textrea that takes two IDs first should be
 1489: the id of the element to resize, second should be the id of a div that
 1490: surrounds everything that comes after the textarea, this routine needs
 1491: to be attached to the <body> for the onload and onresize events.
 1492: 
 1493: =back
 1494: 
 1495: =cut
 1496: 
 1497: sub resize_textarea_js {
 1498:     my $geometry = &viewport_geometry_js();
 1499:     return <<"RESIZE";
 1500:     <script type="text/javascript">
 1501: // <![CDATA[
 1502: $geometry
 1503: 
 1504: function getX(element) {
 1505:     var x = 0;
 1506:     while (element) {
 1507: 	x += element.offsetLeft;
 1508: 	element = element.offsetParent;
 1509:     }
 1510:     return x;
 1511: }
 1512: function getY(element) {
 1513:     var y = 0;
 1514:     while (element) {
 1515: 	y += element.offsetTop;
 1516: 	element = element.offsetParent;
 1517:     }
 1518:     return y;
 1519: }
 1520: 
 1521: 
 1522: function resize_textarea(textarea_id,bottom_id) {
 1523:     init_geometry();
 1524:     var textarea        = document.getElementById(textarea_id);
 1525:     //alert(textarea);
 1526: 
 1527:     var textarea_top    = getY(textarea);
 1528:     var textarea_height = textarea.offsetHeight;
 1529:     var bottom          = document.getElementById(bottom_id);
 1530:     var bottom_top      = getY(bottom);
 1531:     var bottom_height   = bottom.offsetHeight;
 1532:     var window_height   = Geometry.getViewportHeight();
 1533:     var fudge           = 23;
 1534:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1535:     if (new_height < 300) {
 1536: 	new_height = 300;
 1537:     }
 1538:     textarea.style.height=new_height+'px';
 1539: }
 1540: // ]]>
 1541: </script>
 1542: RESIZE
 1543: 
 1544: }
 1545: 
 1546: =pod
 1547: 
 1548: =head1 Excel and CSV file utility routines
 1549: 
 1550: =over 4
 1551: 
 1552: =cut
 1553: 
 1554: ###############################################################
 1555: ###############################################################
 1556: 
 1557: =pod
 1558: 
 1559: =item * &csv_translate($text) 
 1560: 
 1561: Translate $text to allow it to be output as a 'comma separated values' 
 1562: format.
 1563: 
 1564: =cut
 1565: 
 1566: ###############################################################
 1567: ###############################################################
 1568: sub csv_translate {
 1569:     my $text = shift;
 1570:     $text =~ s/\"/\"\"/g;
 1571:     $text =~ s/\n/ /g;
 1572:     return $text;
 1573: }
 1574: 
 1575: ###############################################################
 1576: ###############################################################
 1577: 
 1578: =pod
 1579: 
 1580: =item * &define_excel_formats()
 1581: 
 1582: Define some commonly used Excel cell formats.
 1583: 
 1584: Currently supported formats:
 1585: 
 1586: =over 4
 1587: 
 1588: =item header
 1589: 
 1590: =item bold
 1591: 
 1592: =item h1
 1593: 
 1594: =item h2
 1595: 
 1596: =item h3
 1597: 
 1598: =item h4
 1599: 
 1600: =item i
 1601: 
 1602: =item date
 1603: 
 1604: =back
 1605: 
 1606: Inputs: $workbook
 1607: 
 1608: Returns: $format, a hash reference.
 1609: 
 1610: =cut
 1611: 
 1612: ###############################################################
 1613: ###############################################################
 1614: sub define_excel_formats {
 1615:     my ($workbook) = @_;
 1616:     my $format;
 1617:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1618:                                                 bottom    => 1,
 1619:                                                 align     => 'center');
 1620:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1621:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1622:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1623:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1624:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1625:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1626:     $format->{'date'} = $workbook->add_format(num_format=>
 1627:                                             'mm/dd/yyyy hh:mm:ss');
 1628:     return $format;
 1629: }
 1630: 
 1631: ###############################################################
 1632: ###############################################################
 1633: 
 1634: =pod
 1635: 
 1636: =item * &create_workbook()
 1637: 
 1638: Create an Excel worksheet.  If it fails, output message on the
 1639: request object and return undefs.
 1640: 
 1641: Inputs: Apache request object
 1642: 
 1643: Returns (undef) on failure, 
 1644:     Excel worksheet object, scalar with filename, and formats 
 1645:     from &Apache::loncommon::define_excel_formats on success
 1646: 
 1647: =cut
 1648: 
 1649: ###############################################################
 1650: ###############################################################
 1651: sub create_workbook {
 1652:     my ($r) = @_;
 1653:         #
 1654:     # Create the excel spreadsheet
 1655:     my $filename = '/prtspool/'.
 1656:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1657:         time.'_'.rand(1000000000).'.xls';
 1658:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1659:     if (! defined($workbook)) {
 1660:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1661:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1662:                             "This error has been logged.  ".
 1663:                             "Please alert your LON-CAPA administrator").
 1664:                   '</p>');
 1665:         return (undef);
 1666:     }
 1667:     #
 1668:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1669:     #
 1670:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1671:     return ($workbook,$filename,$format);
 1672: }
 1673: 
 1674: ###############################################################
 1675: ###############################################################
 1676: 
 1677: =pod
 1678: 
 1679: =item * &create_text_file()
 1680: 
 1681: Create a file to write to and eventually make available to the user.
 1682: If file creation fails, outputs an error message on the request object and 
 1683: return undefs.
 1684: 
 1685: Inputs: Apache request object, and file suffix
 1686: 
 1687: Returns (undef) on failure, 
 1688:     Filehandle and filename on success.
 1689: 
 1690: =cut
 1691: 
 1692: ###############################################################
 1693: ###############################################################
 1694: sub create_text_file {
 1695:     my ($r,$suffix) = @_;
 1696:     if (! defined($suffix)) { $suffix = 'txt'; };
 1697:     my $fh;
 1698:     my $filename = '/prtspool/'.
 1699:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1700:         time.'_'.rand(1000000000).'.'.$suffix;
 1701:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1702:     if (! defined($fh)) {
 1703:         $r->log_error("Couldn't open $filename for output $!");
 1704:         $r->print(&mt('Problems occurred in creating the output file. '
 1705:                      .'This error has been logged. '
 1706:                      .'Please alert your LON-CAPA administrator.'));
 1707:     }
 1708:     return ($fh,$filename)
 1709: }
 1710: 
 1711: 
 1712: =pod 
 1713: 
 1714: =back
 1715: 
 1716: =cut
 1717: 
 1718: ###############################################################
 1719: ##        Home server <option> list generating code          ##
 1720: ###############################################################
 1721: 
 1722: # ------------------------------------------
 1723: 
 1724: sub domain_select {
 1725:     my ($name,$value,$multiple)=@_;
 1726:     my %domains=map { 
 1727: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1728:     } &Apache::lonnet::all_domains();
 1729:     if ($multiple) {
 1730: 	$domains{''}=&mt('Any domain');
 1731: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1732: 	return &multiple_select_form($name,$value,4,\%domains);
 1733:     } else {
 1734: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1735: 	return &select_form($name,$value,%domains);
 1736:     }
 1737: }
 1738: 
 1739: #-------------------------------------------
 1740: 
 1741: =pod
 1742: 
 1743: =head1 Routines for form select boxes
 1744: 
 1745: =over 4
 1746: 
 1747: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1748: 
 1749: Returns a string containing a <select> element int multiple mode
 1750: 
 1751: 
 1752: Args:
 1753:   $name - name of the <select> element
 1754:   $value - scalar or array ref of values that should already be selected
 1755:   $size - number of rows long the select element is
 1756:   $hash - the elements should be 'option' => 'shown text'
 1757:           (shown text should already have been &mt())
 1758:   $order - (optional) array ref of the order to show the elements in
 1759: 
 1760: =cut
 1761: 
 1762: #-------------------------------------------
 1763: sub multiple_select_form {
 1764:     my ($name,$value,$size,$hash,$order)=@_;
 1765:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1766:     my $output='';
 1767:     if (! defined($size)) {
 1768:         $size = 4;
 1769:         if (scalar(keys(%$hash))<4) {
 1770:             $size = scalar(keys(%$hash));
 1771:         }
 1772:     }
 1773:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1774:     my @order;
 1775:     if (ref($order) eq 'ARRAY')  {
 1776:         @order = @{$order};
 1777:     } else {
 1778:         @order = sort(keys(%$hash));
 1779:     }
 1780:     if (exists($$hash{'select_form_order'})) {
 1781:         @order = @{$$hash{'select_form_order'}};
 1782:     }
 1783:         
 1784:     foreach my $key (@order) {
 1785:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1786:         $output.='selected="selected" ' if ($selected{$key});
 1787:         $output.='>'.$hash->{$key}."</option>\n";
 1788:     }
 1789:     $output.="</select>\n";
 1790:     return $output;
 1791: }
 1792: 
 1793: #-------------------------------------------
 1794: 
 1795: =pod
 1796: 
 1797: =item * &select_form($defdom,$name,%hash)
 1798: 
 1799: Returns a string containing a <select name='$name' size='1'> form to 
 1800: allow a user to select options from a hash option_name => displayed text.  
 1801: See lonrights.pm for an example invocation and use.
 1802: 
 1803: =cut
 1804: 
 1805: #-------------------------------------------
 1806: sub select_form {
 1807:     my ($def,$name,%hash) = @_;
 1808:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1809:     my @keys;
 1810:     if (exists($hash{'select_form_order'})) {
 1811: 	@keys=@{$hash{'select_form_order'}};
 1812:     } else {
 1813: 	@keys=sort(keys(%hash));
 1814:     }
 1815:     foreach my $key (@keys) {
 1816:         $selectform.=
 1817: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1818:             ($key eq $def ? 'selected="selected" ' : '').
 1819:                 ">".&mt($hash{$key})."</option>\n";
 1820:     }
 1821:     $selectform.="</select>";
 1822:     return $selectform;
 1823: }
 1824: 
 1825: # For display filters
 1826: 
 1827: sub display_filter {
 1828:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1829:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1830:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1831: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1832: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1833: 	   '</label></span> <span class="LC_nobreak">'.
 1834:            &mt('Filter [_1]',
 1835: 	   &select_form($env{'form.displayfilter'},
 1836: 			'displayfilter',
 1837: 			('currentfolder' => 'Current folder/page',
 1838: 			 'containing' => 'Containing phrase',
 1839: 			 'none' => 'None'))).
 1840: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1841: }
 1842: 
 1843: sub gradeleveldescription {
 1844:     my $gradelevel=shift;
 1845:     my %gradelevels=(0 => 'Not specified',
 1846: 		     1 => 'Grade 1',
 1847: 		     2 => 'Grade 2',
 1848: 		     3 => 'Grade 3',
 1849: 		     4 => 'Grade 4',
 1850: 		     5 => 'Grade 5',
 1851: 		     6 => 'Grade 6',
 1852: 		     7 => 'Grade 7',
 1853: 		     8 => 'Grade 8',
 1854: 		     9 => 'Grade 9',
 1855: 		     10 => 'Grade 10',
 1856: 		     11 => 'Grade 11',
 1857: 		     12 => 'Grade 12',
 1858: 		     13 => 'Grade 13',
 1859: 		     14 => '100 Level',
 1860: 		     15 => '200 Level',
 1861: 		     16 => '300 Level',
 1862: 		     17 => '400 Level',
 1863: 		     18 => 'Graduate Level');
 1864:     return &mt($gradelevels{$gradelevel});
 1865: }
 1866: 
 1867: sub select_level_form {
 1868:     my ($deflevel,$name)=@_;
 1869:     unless ($deflevel) { $deflevel=0; }
 1870:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1871:     for (my $i=0; $i<=18; $i++) {
 1872:         $selectform.="<option value=\"$i\" ".
 1873:             ($i==$deflevel ? 'selected="selected" ' : '').
 1874:                 ">".&gradeleveldescription($i)."</option>\n";
 1875:     }
 1876:     $selectform.="</select>";
 1877:     return $selectform;
 1878: }
 1879: 
 1880: #-------------------------------------------
 1881: 
 1882: =pod
 1883: 
 1884: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
 1885: 
 1886: Returns a string containing a <select name='$name' size='1'> form to 
 1887: allow a user to select the domain to preform an operation in.  
 1888: See loncreateuser.pm for an example invocation and use.
 1889: 
 1890: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1891: selected");
 1892: 
 1893: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1894: 
 1895: The optional $onchange argumnet specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.  
 1896: 
 1897: =cut
 1898: 
 1899: #-------------------------------------------
 1900: sub select_dom_form {
 1901:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
 1902:     if ($onchange) {
 1903:         $onchange = ' onchange="'.$onchange.'"';
 1904:     }
 1905:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1906:     if ($includeempty) { @domains=('',@domains); }
 1907:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1908:     foreach my $dom (@domains) {
 1909:         $selectdomain.="<option value=\"$dom\" ".
 1910:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1911:         if ($showdomdesc) {
 1912:             if ($dom ne '') {
 1913:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1914:                 if ($domdesc ne '') {
 1915:                     $selectdomain .= ' ('.$domdesc.')';
 1916:                 }
 1917:             } 
 1918:         }
 1919:         $selectdomain .= "</option>\n";
 1920:     }
 1921:     $selectdomain.="</select>";
 1922:     return $selectdomain;
 1923: }
 1924: 
 1925: #-------------------------------------------
 1926: 
 1927: =pod
 1928: 
 1929: =item * &home_server_form_item($domain,$name,$defaultflag)
 1930: 
 1931: input: 4 arguments (two required, two optional) - 
 1932:     $domain - domain of new user
 1933:     $name - name of form element
 1934:     $default - Value of 'default' causes a default item to be first 
 1935:                             option, and selected by default. 
 1936:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1937:                             if 1 server found, or default, if 0 found.
 1938: output: returns 2 items: 
 1939: (a) form element which contains either:
 1940:    (i) <select name="$name">
 1941:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1942:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1943:        </select>
 1944:        form item if there are multiple library servers in $domain, or
 1945:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1946:        if there is only one library server in $domain.
 1947: 
 1948: (b) number of library servers found.
 1949: 
 1950: See loncreateuser.pm for example of use.
 1951: 
 1952: =cut
 1953: 
 1954: #-------------------------------------------
 1955: sub home_server_form_item {
 1956:     my ($domain,$name,$default,$hide) = @_;
 1957:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1958:     my $result;
 1959:     my $numlib = keys(%servers);
 1960:     if ($numlib > 1) {
 1961:         $result .= '<select name="'.$name.'" />'."\n";
 1962:         if ($default) {
 1963:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1964:                        '</option>'."\n";
 1965:         }
 1966:         foreach my $hostid (sort(keys(%servers))) {
 1967:             $result.= '<option value="'.$hostid.'">'.
 1968: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1969:         }
 1970:         $result .= '</select>'."\n";
 1971:     } elsif ($numlib == 1) {
 1972:         my $hostid;
 1973:         foreach my $item (keys(%servers)) {
 1974:             $hostid = $item;
 1975:         }
 1976:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1977:                    $hostid.'" />';
 1978:                    if (!$hide) {
 1979:                        $result .= $hostid.' '.$servers{$hostid};
 1980:                    }
 1981:                    $result .= "\n";
 1982:     } elsif ($default) {
 1983:         $result .= '<input type="hidden" name="'.$name.
 1984:                    '" value="default" />';
 1985:                    if (!$hide) {
 1986:                        $result .= &mt('default');
 1987:                    }
 1988:                    $result .= "\n";
 1989:     }
 1990:     return ($result,$numlib);
 1991: }
 1992: 
 1993: =pod
 1994: 
 1995: =back 
 1996: 
 1997: =cut
 1998: 
 1999: ###############################################################
 2000: ##                  Decoding User Agent                      ##
 2001: ###############################################################
 2002: 
 2003: =pod
 2004: 
 2005: =head1 Decoding the User Agent
 2006: 
 2007: =over 4
 2008: 
 2009: =item * &decode_user_agent()
 2010: 
 2011: Inputs: $r
 2012: 
 2013: Outputs:
 2014: 
 2015: =over 4
 2016: 
 2017: =item * $httpbrowser
 2018: 
 2019: =item * $clientbrowser
 2020: 
 2021: =item * $clientversion
 2022: 
 2023: =item * $clientmathml
 2024: 
 2025: =item * $clientunicode
 2026: 
 2027: =item * $clientos
 2028: 
 2029: =back
 2030: 
 2031: =back 
 2032: 
 2033: =cut
 2034: 
 2035: ###############################################################
 2036: ###############################################################
 2037: sub decode_user_agent {
 2038:     my ($r)=@_;
 2039:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2040:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2041:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2042:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2043:     my $clientbrowser='unknown';
 2044:     my $clientversion='0';
 2045:     my $clientmathml='';
 2046:     my $clientunicode='0';
 2047:     for (my $i=0;$i<=$#browsertype;$i++) {
 2048:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2049: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2050: 	    $clientbrowser=$bname;
 2051:             $httpbrowser=~/$vreg/i;
 2052: 	    $clientversion=$1;
 2053:             $clientmathml=($clientversion>=$minv);
 2054:             $clientunicode=($clientversion>=$univ);
 2055: 	}
 2056:     }
 2057:     my $clientos='unknown';
 2058:     if (($httpbrowser=~/linux/i) ||
 2059:         ($httpbrowser=~/unix/i) ||
 2060:         ($httpbrowser=~/ux/i) ||
 2061:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2062:     if (($httpbrowser=~/vax/i) ||
 2063:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2064:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2065:     if (($httpbrowser=~/mac/i) ||
 2066:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2067:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2068:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2069:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2070:             $clientunicode,$clientos,);
 2071: }
 2072: 
 2073: ###############################################################
 2074: ##    Authentication changing form generation subroutines    ##
 2075: ###############################################################
 2076: ##
 2077: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2078: ## hash, and have reasonable default values.
 2079: ##
 2080: ##    formname = the name given in the <form> tag.
 2081: #-------------------------------------------
 2082: 
 2083: =pod
 2084: 
 2085: =head1 Authentication Routines
 2086: 
 2087: =over 4
 2088: 
 2089: =item * &authform_xxxxxx()
 2090: 
 2091: The authform_xxxxxx subroutines provide javascript and html forms which 
 2092: handle some of the conveniences required for authentication forms.  
 2093: This is not an optimal method, but it works.  
 2094: 
 2095: =over 4
 2096: 
 2097: =item * authform_header
 2098: 
 2099: =item * authform_authorwarning
 2100: 
 2101: =item * authform_nochange
 2102: 
 2103: =item * authform_kerberos
 2104: 
 2105: =item * authform_internal
 2106: 
 2107: =item * authform_filesystem
 2108: 
 2109: =back
 2110: 
 2111: See loncreateuser.pm for invocation and use examples.
 2112: 
 2113: =cut
 2114: 
 2115: #-------------------------------------------
 2116: sub authform_header{  
 2117:     my %in = (
 2118:         formname => 'cu',
 2119:         kerb_def_dom => '',
 2120:         @_,
 2121:     );
 2122:     $in{'formname'} = 'document.' . $in{'formname'};
 2123:     my $result='';
 2124: 
 2125: #---------------------------------------------- Code for upper case translation
 2126:     my $Javascript_toUpperCase;
 2127:     unless ($in{kerb_def_dom}) {
 2128:         $Javascript_toUpperCase =<<"END";
 2129:         switch (choice) {
 2130:            case 'krb': currentform.elements[choicearg].value =
 2131:                currentform.elements[choicearg].value.toUpperCase();
 2132:                break;
 2133:            default:
 2134:         }
 2135: END
 2136:     } else {
 2137:         $Javascript_toUpperCase = "";
 2138:     }
 2139: 
 2140:     my $radioval = "'nochange'";
 2141:     if (defined($in{'curr_authtype'})) {
 2142:         if ($in{'curr_authtype'} ne '') {
 2143:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2144:         }
 2145:     }
 2146:     my $argfield = 'null';
 2147:     if (defined($in{'mode'})) {
 2148:         if ($in{'mode'} eq 'modifycourse')  {
 2149:             if (defined($in{'curr_autharg'})) {
 2150:                 if ($in{'curr_autharg'} ne '') {
 2151:                     $argfield = "'$in{'curr_autharg'}'";
 2152:                 }
 2153:             }
 2154:         }
 2155:     }
 2156: 
 2157:     $result.=<<"END";
 2158: var current = new Object();
 2159: current.radiovalue = $radioval;
 2160: current.argfield = $argfield;
 2161: 
 2162: function changed_radio(choice,currentform) {
 2163:     var choicearg = choice + 'arg';
 2164:     // If a radio button in changed, we need to change the argfield
 2165:     if (current.radiovalue != choice) {
 2166:         current.radiovalue = choice;
 2167:         if (current.argfield != null) {
 2168:             currentform.elements[current.argfield].value = '';
 2169:         }
 2170:         if (choice == 'nochange') {
 2171:             current.argfield = null;
 2172:         } else {
 2173:             current.argfield = choicearg;
 2174:             switch(choice) {
 2175:                 case 'krb': 
 2176:                     currentform.elements[current.argfield].value = 
 2177:                         "$in{'kerb_def_dom'}";
 2178:                 break;
 2179:               default:
 2180:                 break;
 2181:             }
 2182:         }
 2183:     }
 2184:     return;
 2185: }
 2186: 
 2187: function changed_text(choice,currentform) {
 2188:     var choicearg = choice + 'arg';
 2189:     if (currentform.elements[choicearg].value !='') {
 2190:         $Javascript_toUpperCase
 2191:         // clear old field
 2192:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2193:             currentform.elements[current.argfield].value = '';
 2194:         }
 2195:         current.argfield = choicearg;
 2196:     }
 2197:     set_auth_radio_buttons(choice,currentform);
 2198:     return;
 2199: }
 2200: 
 2201: function set_auth_radio_buttons(newvalue,currentform) {
 2202:     var i=0;
 2203:     while (i < currentform.login.length) {
 2204:         if (currentform.login[i].value == newvalue) { break; }
 2205:         i++;
 2206:     }
 2207:     if (i == currentform.login.length) {
 2208:         return;
 2209:     }
 2210:     current.radiovalue = newvalue;
 2211:     currentform.login[i].checked = true;
 2212:     return;
 2213: }
 2214: END
 2215:     return $result;
 2216: }
 2217: 
 2218: sub authform_authorwarning{
 2219:     my $result='';
 2220:     $result='<i>'.
 2221:         &mt('As a general rule, only authors or co-authors should be '.
 2222:             'filesystem authenticated '.
 2223:             '(which allows access to the server filesystem).')."</i>\n";
 2224:     return $result;
 2225: }
 2226: 
 2227: sub authform_nochange{  
 2228:     my %in = (
 2229:               formname => 'document.cu',
 2230:               kerb_def_dom => 'MSU.EDU',
 2231:               @_,
 2232:           );
 2233:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2234:     my $result;
 2235:     if (keys(%can_assign) == 0) {
 2236:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2237:     } else {
 2238:         $result = '<label>'.&mt('[_1] Do not change login data',
 2239:                   '<input type="radio" name="login" value="nochange" '.
 2240:                   'checked="checked" onclick="'.
 2241:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2242: 	    '</label>';
 2243:     }
 2244:     return $result;
 2245: }
 2246: 
 2247: sub authform_kerberos {
 2248:     my %in = (
 2249:               formname => 'document.cu',
 2250:               kerb_def_dom => 'MSU.EDU',
 2251:               kerb_def_auth => 'krb4',
 2252:               @_,
 2253:               );
 2254:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2255:         $autharg,$jscall);
 2256:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2257:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2258:        $check5 = ' checked="checked"';
 2259:     } else {
 2260:        $check4 = ' checked="checked"';
 2261:     }
 2262:     $krbarg = $in{'kerb_def_dom'};
 2263:     if (defined($in{'curr_authtype'})) {
 2264:         if ($in{'curr_authtype'} eq 'krb') {
 2265:             $krbcheck = ' checked="checked"';
 2266:             if (defined($in{'mode'})) {
 2267:                 if ($in{'mode'} eq 'modifyuser') {
 2268:                     $krbcheck = '';
 2269:                 }
 2270:             }
 2271:             if (defined($in{'curr_kerb_ver'})) {
 2272:                 if ($in{'curr_krb_ver'} eq '5') {
 2273:                     $check5 = ' checked="checked"';
 2274:                     $check4 = '';
 2275:                 } else {
 2276:                     $check4 = ' checked="checked"';
 2277:                     $check5 = '';
 2278:                 }
 2279:             }
 2280:             if (defined($in{'curr_autharg'})) {
 2281:                 $krbarg = $in{'curr_autharg'};
 2282:             }
 2283:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2284:                 if (defined($in{'curr_autharg'})) {
 2285:                     $result = 
 2286:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2287:         $in{'curr_autharg'},$krbver);
 2288:                 } else {
 2289:                     $result =
 2290:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2291:                 }
 2292:                 return $result; 
 2293:             }
 2294:         }
 2295:     } else {
 2296:         if ($authnum == 1) {
 2297:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2298:         }
 2299:     }
 2300:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2301:         return;
 2302:     } elsif ($authtype eq '') {
 2303:         if (defined($in{'mode'})) {
 2304:             if ($in{'mode'} eq 'modifycourse') {
 2305:                 if ($authnum == 1) {
 2306:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2307:                 }
 2308:             }
 2309:         }
 2310:     }
 2311:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2312:     if ($authtype eq '') {
 2313:         $authtype = '<input type="radio" name="login" value="krb" '.
 2314:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2315:                     $krbcheck.' />';
 2316:     }
 2317:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2318:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2319:          $in{'curr_authtype'} eq 'krb5') ||
 2320:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2321:          $in{'curr_authtype'} eq 'krb4')) {
 2322:         $result .= &mt
 2323:         ('[_1] Kerberos authenticated with domain [_2] '.
 2324:          '[_3] Version 4 [_4] Version 5 [_5]',
 2325:          '<label>'.$authtype,
 2326:          '</label><input type="text" size="10" name="krbarg" '.
 2327:              'value="'.$krbarg.'" '.
 2328:              'onchange="'.$jscall.'" />',
 2329:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2330:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2331: 	 '</label>');
 2332:     } elsif ($can_assign{'krb4'}) {
 2333:         $result .= &mt
 2334:         ('[_1] Kerberos authenticated with domain [_2] '.
 2335:          '[_3] Version 4 [_4]',
 2336:          '<label>'.$authtype,
 2337:          '</label><input type="text" size="10" name="krbarg" '.
 2338:              'value="'.$krbarg.'" '.
 2339:              'onchange="'.$jscall.'" />',
 2340:          '<label><input type="hidden" name="krbver" value="4" />',
 2341:          '</label>');
 2342:     } elsif ($can_assign{'krb5'}) {
 2343:         $result .= &mt
 2344:         ('[_1] Kerberos authenticated with domain [_2] '.
 2345:          '[_3] Version 5 [_4]',
 2346:          '<label>'.$authtype,
 2347:          '</label><input type="text" size="10" name="krbarg" '.
 2348:              'value="'.$krbarg.'" '.
 2349:              'onchange="'.$jscall.'" />',
 2350:          '<label><input type="hidden" name="krbver" value="5" />',
 2351:          '</label>');
 2352:     }
 2353:     return $result;
 2354: }
 2355: 
 2356: sub authform_internal{  
 2357:     my %in = (
 2358:                 formname => 'document.cu',
 2359:                 kerb_def_dom => 'MSU.EDU',
 2360:                 @_,
 2361:                 );
 2362:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2363:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2364:     if (defined($in{'curr_authtype'})) {
 2365:         if ($in{'curr_authtype'} eq 'int') {
 2366:             if ($can_assign{'int'}) {
 2367:                 $intcheck = 'checked="checked" ';
 2368:                 if (defined($in{'mode'})) {
 2369:                     if ($in{'mode'} eq 'modifyuser') {
 2370:                         $intcheck = '';
 2371:                     }
 2372:                 }
 2373:                 if (defined($in{'curr_autharg'})) {
 2374:                     $intarg = $in{'curr_autharg'};
 2375:                 }
 2376:             } else {
 2377:                 $result = &mt('Currently internally authenticated.');
 2378:                 return $result;
 2379:             }
 2380:         }
 2381:     } else {
 2382:         if ($authnum == 1) {
 2383:             $authtype = '<input type="hidden" name="login" value="int" />';
 2384:         }
 2385:     }
 2386:     if (!$can_assign{'int'}) {
 2387:         return;
 2388:     } elsif ($authtype eq '') {
 2389:         if (defined($in{'mode'})) {
 2390:             if ($in{'mode'} eq 'modifycourse') {
 2391:                 if ($authnum == 1) {
 2392:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2393:                 }
 2394:             }
 2395:         }
 2396:     }
 2397:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2398:     if ($authtype eq '') {
 2399:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2400:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2401:     }
 2402:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2403:                $intarg.'" onchange="'.$jscall.'" />';
 2404:     $result = &mt
 2405:         ('[_1] Internally authenticated (with initial password [_2])',
 2406:          '<label>'.$authtype,'</label>'.$autharg);
 2407:     $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>';
 2408:     return $result;
 2409: }
 2410: 
 2411: sub authform_local{  
 2412:     my %in = (
 2413:               formname => 'document.cu',
 2414:               kerb_def_dom => 'MSU.EDU',
 2415:               @_,
 2416:               );
 2417:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2418:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2419:     if (defined($in{'curr_authtype'})) {
 2420:         if ($in{'curr_authtype'} eq 'loc') {
 2421:             if ($can_assign{'loc'}) {
 2422:                 $loccheck = 'checked="checked" ';
 2423:                 if (defined($in{'mode'})) {
 2424:                     if ($in{'mode'} eq 'modifyuser') {
 2425:                         $loccheck = '';
 2426:                     }
 2427:                 }
 2428:                 if (defined($in{'curr_autharg'})) {
 2429:                     $locarg = $in{'curr_autharg'};
 2430:                 }
 2431:             } else {
 2432:                 $result = &mt('Currently using local (institutional) authentication.');
 2433:                 return $result;
 2434:             }
 2435:         }
 2436:     } else {
 2437:         if ($authnum == 1) {
 2438:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2439:         }
 2440:     }
 2441:     if (!$can_assign{'loc'}) {
 2442:         return;
 2443:     } elsif ($authtype eq '') {
 2444:         if (defined($in{'mode'})) {
 2445:             if ($in{'mode'} eq 'modifycourse') {
 2446:                 if ($authnum == 1) {
 2447:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2448:                 }
 2449:             }
 2450:         }
 2451:     }
 2452:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2453:     if ($authtype eq '') {
 2454:         $authtype = '<input type="radio" name="login" value="loc" '.
 2455:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2456:                     $jscall.'" />';
 2457:     }
 2458:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2459:                $locarg.'" onchange="'.$jscall.'" />';
 2460:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2461:                   '<label>'.$authtype,'</label>'.$autharg);
 2462:     return $result;
 2463: }
 2464: 
 2465: sub authform_filesystem{  
 2466:     my %in = (
 2467:               formname => 'document.cu',
 2468:               kerb_def_dom => 'MSU.EDU',
 2469:               @_,
 2470:               );
 2471:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2472:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2473:     if (defined($in{'curr_authtype'})) {
 2474:         if ($in{'curr_authtype'} eq 'fsys') {
 2475:             if ($can_assign{'fsys'}) {
 2476:                 $fsyscheck = 'checked="checked" ';
 2477:                 if (defined($in{'mode'})) {
 2478:                     if ($in{'mode'} eq 'modifyuser') {
 2479:                         $fsyscheck = '';
 2480:                     }
 2481:                 }
 2482:             } else {
 2483:                 $result = &mt('Currently Filesystem Authenticated.');
 2484:                 return $result;
 2485:             }           
 2486:         }
 2487:     } else {
 2488:         if ($authnum == 1) {
 2489:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2490:         }
 2491:     }
 2492:     if (!$can_assign{'fsys'}) {
 2493:         return;
 2494:     } elsif ($authtype eq '') {
 2495:         if (defined($in{'mode'})) {
 2496:             if ($in{'mode'} eq 'modifycourse') {
 2497:                 if ($authnum == 1) {
 2498:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2499:                 }
 2500:             }
 2501:         }
 2502:     }
 2503:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2504:     if ($authtype eq '') {
 2505:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2506:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2507:                     $jscall.'" />';
 2508:     }
 2509:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2510:                ' onchange="'.$jscall.'" />';
 2511:     $result = &mt
 2512:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2513:          '<label><input type="radio" name="login" value="fsys" '.
 2514:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2515:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2516:                   'onchange="'.$jscall.'" />');
 2517:     return $result;
 2518: }
 2519: 
 2520: sub get_assignable_auth {
 2521:     my ($dom) = @_;
 2522:     if ($dom eq '') {
 2523:         $dom = $env{'request.role.domain'};
 2524:     }
 2525:     my %can_assign = (
 2526:                           krb4 => 1,
 2527:                           krb5 => 1,
 2528:                           int  => 1,
 2529:                           loc  => 1,
 2530:                      );
 2531:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2532:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2533:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2534:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2535:             my $context;
 2536:             if ($env{'request.role'} =~ /^au/) {
 2537:                 $context = 'author';
 2538:             } elsif ($env{'request.role'} =~ /^dc/) {
 2539:                 $context = 'domain';
 2540:             } elsif ($env{'request.course.id'}) {
 2541:                 $context = 'course';
 2542:             }
 2543:             if ($context) {
 2544:                 if (ref($authhash->{$context}) eq 'HASH') {
 2545:                    %can_assign = %{$authhash->{$context}}; 
 2546:                 }
 2547:             }
 2548:         }
 2549:     }
 2550:     my $authnum = 0;
 2551:     foreach my $key (keys(%can_assign)) {
 2552:         if ($can_assign{$key}) {
 2553:             $authnum ++;
 2554:         }
 2555:     }
 2556:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2557:         $authnum --;
 2558:     }
 2559:     return ($authnum,%can_assign);
 2560: }
 2561: 
 2562: ###############################################################
 2563: ##    Get Kerberos Defaults for Domain                 ##
 2564: ###############################################################
 2565: ##
 2566: ## Returns default kerberos version and an associated argument
 2567: ## as listed in file domain.tab. If not listed, provides
 2568: ## appropriate default domain and kerberos version.
 2569: ##
 2570: #-------------------------------------------
 2571: 
 2572: =pod
 2573: 
 2574: =item * &get_kerberos_defaults()
 2575: 
 2576: get_kerberos_defaults($target_domain) returns the default kerberos
 2577: version and domain. If not found, it defaults to version 4 and the 
 2578: domain of the server.
 2579: 
 2580: =over 4
 2581: 
 2582: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2583: 
 2584: =back
 2585: 
 2586: =back
 2587: 
 2588: =cut
 2589: 
 2590: #-------------------------------------------
 2591: sub get_kerberos_defaults {
 2592:     my $domain=shift;
 2593:     my ($krbdef,$krbdefdom);
 2594:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2595:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2596:         $krbdef = $domdefaults{'auth_def'};
 2597:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2598:     } else {
 2599:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2600:         my $krbdefdom=$1;
 2601:         $krbdefdom=~tr/a-z/A-Z/;
 2602:         $krbdef = "krb4";
 2603:     }
 2604:     return ($krbdef,$krbdefdom);
 2605: }
 2606: 
 2607: 
 2608: ###############################################################
 2609: ##                Thesaurus Functions                        ##
 2610: ###############################################################
 2611: 
 2612: =pod
 2613: 
 2614: =head1 Thesaurus Functions
 2615: 
 2616: =over 4
 2617: 
 2618: =item * &initialize_keywords()
 2619: 
 2620: Initializes the package variable %Keywords if it is empty.  Uses the
 2621: package variable $thesaurus_db_file.
 2622: 
 2623: =cut
 2624: 
 2625: ###################################################
 2626: 
 2627: sub initialize_keywords {
 2628:     return 1 if (scalar keys(%Keywords));
 2629:     # If we are here, %Keywords is empty, so fill it up
 2630:     #   Make sure the file we need exists...
 2631:     if (! -e $thesaurus_db_file) {
 2632:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2633:                                  " failed because it does not exist");
 2634:         return 0;
 2635:     }
 2636:     #   Set up the hash as a database
 2637:     my %thesaurus_db;
 2638:     if (! tie(%thesaurus_db,'GDBM_File',
 2639:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2640:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2641:                                  $thesaurus_db_file);
 2642:         return 0;
 2643:     } 
 2644:     #  Get the average number of appearances of a word.
 2645:     my $avecount = $thesaurus_db{'average.count'};
 2646:     #  Put keywords (those that appear > average) into %Keywords
 2647:     while (my ($word,$data)=each (%thesaurus_db)) {
 2648:         my ($count,undef) = split /:/,$data;
 2649:         $Keywords{$word}++ if ($count > $avecount);
 2650:     }
 2651:     untie %thesaurus_db;
 2652:     # Remove special values from %Keywords.
 2653:     foreach my $value ('total.count','average.count') {
 2654:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2655:   }
 2656:     return 1;
 2657: }
 2658: 
 2659: ###################################################
 2660: 
 2661: =pod
 2662: 
 2663: =item * &keyword($word)
 2664: 
 2665: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2666: than the average number of times in the thesaurus database.  Calls 
 2667: &initialize_keywords
 2668: 
 2669: =cut
 2670: 
 2671: ###################################################
 2672: 
 2673: sub keyword {
 2674:     return if (!&initialize_keywords());
 2675:     my $word=lc(shift());
 2676:     $word=~s/\W//g;
 2677:     return exists($Keywords{$word});
 2678: }
 2679: 
 2680: ###############################################################
 2681: 
 2682: =pod 
 2683: 
 2684: =item * &get_related_words()
 2685: 
 2686: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2687: an array of words.  If the keyword is not in the thesaurus, an empty array
 2688: will be returned.  The order of the words returned is determined by the
 2689: database which holds them.
 2690: 
 2691: Uses global $thesaurus_db_file.
 2692: 
 2693: =cut
 2694: 
 2695: ###############################################################
 2696: sub get_related_words {
 2697:     my $keyword = shift;
 2698:     my %thesaurus_db;
 2699:     if (! -e $thesaurus_db_file) {
 2700:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2701:                                  "failed because the file does not exist");
 2702:         return ();
 2703:     }
 2704:     if (! tie(%thesaurus_db,'GDBM_File',
 2705:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2706:         return ();
 2707:     } 
 2708:     my @Words=();
 2709:     my $count=0;
 2710:     if (exists($thesaurus_db{$keyword})) {
 2711: 	# The first element is the number of times
 2712: 	# the word appears.  We do not need it now.
 2713: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2714: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2715: 	my $threshold=$mostfrequentcount/10;
 2716:         foreach my $possibleword (@RelatedWords) {
 2717:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2718:             if ($wordcount>$threshold) {
 2719: 		push(@Words,$word);
 2720:                 $count++;
 2721:                 if ($count>10) { last; }
 2722: 	    }
 2723:         }
 2724:     }
 2725:     untie %thesaurus_db;
 2726:     return @Words;
 2727: }
 2728: 
 2729: =pod
 2730: 
 2731: =back
 2732: 
 2733: =cut
 2734: 
 2735: # -------------------------------------------------------------- Plaintext name
 2736: =pod
 2737: 
 2738: =head1 User Name Functions
 2739: 
 2740: =over 4
 2741: 
 2742: =item * &plainname($uname,$udom,$first)
 2743: 
 2744: Takes a users logon name and returns it as a string in
 2745: "first middle last generation" form 
 2746: if $first is set to 'lastname' then it returns it as
 2747: 'lastname generation, firstname middlename' if their is a lastname
 2748: 
 2749: =cut
 2750: 
 2751: 
 2752: ###############################################################
 2753: sub plainname {
 2754:     my ($uname,$udom,$first)=@_;
 2755:     return if (!defined($uname) || !defined($udom));
 2756:     my %names=&getnames($uname,$udom);
 2757:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2758: 					  $names{'middlename'},
 2759: 					  $names{'lastname'},
 2760: 					  $names{'generation'},$first);
 2761:     $name=~s/^\s+//;
 2762:     $name=~s/\s+$//;
 2763:     $name=~s/\s+/ /g;
 2764:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2765:     return $name;
 2766: }
 2767: 
 2768: # -------------------------------------------------------------------- Nickname
 2769: =pod
 2770: 
 2771: =item * &nickname($uname,$udom)
 2772: 
 2773: Gets a users name and returns it as a string as
 2774: 
 2775: "&quot;nickname&quot;"
 2776: 
 2777: if the user has a nickname or
 2778: 
 2779: "first middle last generation"
 2780: 
 2781: if the user does not
 2782: 
 2783: =cut
 2784: 
 2785: sub nickname {
 2786:     my ($uname,$udom)=@_;
 2787:     return if (!defined($uname) || !defined($udom));
 2788:     my %names=&getnames($uname,$udom);
 2789:     my $name=$names{'nickname'};
 2790:     if ($name) {
 2791:        $name='&quot;'.$name.'&quot;'; 
 2792:     } else {
 2793:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2794: 	     $names{'lastname'}.' '.$names{'generation'};
 2795:        $name=~s/\s+$//;
 2796:        $name=~s/\s+/ /g;
 2797:     }
 2798:     return $name;
 2799: }
 2800: 
 2801: sub getnames {
 2802:     my ($uname,$udom)=@_;
 2803:     return if (!defined($uname) || !defined($udom));
 2804:     if ($udom eq 'public' && $uname eq 'public') {
 2805: 	return ('lastname' => &mt('Public'));
 2806:     }
 2807:     my $id=$uname.':'.$udom;
 2808:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2809:     if ($cached) {
 2810: 	return %{$names};
 2811:     } else {
 2812: 	my %loadnames=&Apache::lonnet::get('environment',
 2813:                     ['firstname','middlename','lastname','generation','nickname'],
 2814: 					 $udom,$uname);
 2815: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2816: 	return %loadnames;
 2817:     }
 2818: }
 2819: 
 2820: # -------------------------------------------------------------------- getemails
 2821: 
 2822: =pod
 2823: 
 2824: =item * &getemails($uname,$udom)
 2825: 
 2826: Gets a user's email information and returns it as a hash with keys:
 2827: notification, critnotification, permanentemail
 2828: 
 2829: For notification and critnotification, values are comma-separated lists 
 2830: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2831:  
 2832: 
 2833: =cut
 2834: 
 2835: 
 2836: sub getemails {
 2837:     my ($uname,$udom)=@_;
 2838:     if ($udom eq 'public' && $uname eq 'public') {
 2839: 	return;
 2840:     }
 2841:     if (!$udom) { $udom=$env{'user.domain'}; }
 2842:     if (!$uname) { $uname=$env{'user.name'}; }
 2843:     my $id=$uname.':'.$udom;
 2844:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2845:     if ($cached) {
 2846: 	return %{$names};
 2847:     } else {
 2848: 	my %loadnames=&Apache::lonnet::get('environment',
 2849:                     			   ['notification','critnotification',
 2850: 					    'permanentemail'],
 2851: 					   $udom,$uname);
 2852: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2853: 	return %loadnames;
 2854:     }
 2855: }
 2856: 
 2857: sub flush_email_cache {
 2858:     my ($uname,$udom)=@_;
 2859:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2860:     if (!$uname) { $uname=$env{'user.name'};   }
 2861:     return if ($udom eq 'public' && $uname eq 'public');
 2862:     my $id=$uname.':'.$udom;
 2863:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2864: }
 2865: 
 2866: # -------------------------------------------------------------------- getlangs
 2867: 
 2868: =pod
 2869: 
 2870: =item * &getlangs($uname,$udom)
 2871: 
 2872: Gets a user's language preference and returns it as a hash with key:
 2873: language.
 2874: 
 2875: =cut
 2876: 
 2877: 
 2878: sub getlangs {
 2879:     my ($uname,$udom) = @_;
 2880:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2881:     if (!$uname) { $uname=$env{'user.name'};   }
 2882:     my $id=$uname.':'.$udom;
 2883:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2884:     if ($cached) {
 2885:         return %{$langs};
 2886:     } else {
 2887:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2888:                                            $udom,$uname);
 2889:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2890:         return %loadlangs;
 2891:     }
 2892: }
 2893: 
 2894: sub flush_langs_cache {
 2895:     my ($uname,$udom)=@_;
 2896:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2897:     if (!$uname) { $uname=$env{'user.name'};   }
 2898:     return if ($udom eq 'public' && $uname eq 'public');
 2899:     my $id=$uname.':'.$udom;
 2900:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2901: }
 2902: 
 2903: # ------------------------------------------------------------------ Screenname
 2904: 
 2905: =pod
 2906: 
 2907: =item * &screenname($uname,$udom)
 2908: 
 2909: Gets a users screenname and returns it as a string
 2910: 
 2911: =cut
 2912: 
 2913: sub screenname {
 2914:     my ($uname,$udom)=@_;
 2915:     if ($uname eq $env{'user.name'} &&
 2916: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2917:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2918:     return $names{'screenname'};
 2919: }
 2920: 
 2921: 
 2922: # ------------------------------------------------------------- Confirm Wrapper
 2923: =pod
 2924: 
 2925: =item confirmwrapper
 2926: 
 2927: Wrap messages about completion of operation in box
 2928: 
 2929: =cut
 2930: 
 2931: sub confirmwrapper {
 2932:     my ($message)=@_;
 2933:     if ($message) {
 2934:         return "\n".'<div class="LC_confirm_box">'."\n"
 2935:                .$message."\n"
 2936:                .'</div>'."\n";
 2937:     } else {
 2938:         return $message;
 2939:     }
 2940: }
 2941: 
 2942: # ------------------------------------------------------------- Message Wrapper
 2943: 
 2944: sub messagewrapper {
 2945:     my ($link,$username,$domain,$subject,$text)=@_;
 2946:     return 
 2947:         '<a href="/adm/email?compose=individual&amp;'.
 2948:         'recname='.$username.'&amp;recdom='.$domain.
 2949: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2950:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2951: }
 2952: 
 2953: # --------------------------------------------------------------- Notes Wrapper
 2954: 
 2955: sub noteswrapper {
 2956:     my ($link,$un,$do)=@_;
 2957:     return 
 2958: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 2959: }
 2960: 
 2961: # ------------------------------------------------------------- Aboutme Wrapper
 2962: 
 2963: sub aboutmewrapper {
 2964:     my ($link,$username,$domain,$target)=@_;
 2965:     if (!defined($username)  && !defined($domain)) {
 2966:         return;
 2967:     }
 2968:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
 2969: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2970: }
 2971: 
 2972: # ------------------------------------------------------------ Syllabus Wrapper
 2973: 
 2974: sub syllabuswrapper {
 2975:     my ($linktext,$coursedir,$domain)=@_;
 2976:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2977: }
 2978: 
 2979: # -----------------------------------------------------------------------------
 2980: 
 2981: sub track_student_link {
 2982:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 2983:     my $link ="/adm/trackstudent?";
 2984:     my $title = 'View recent activity';
 2985:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2986:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2987:         $link .= "selected_student=$sname:$sdom";
 2988:         $title .= ' of this student';
 2989:     } 
 2990:     if (defined($target) && $target !~ /^\s*$/) {
 2991:         $target = qq{target="$target"};
 2992:     } else {
 2993:         $target = '';
 2994:     }
 2995:     if ($start) { $link.='&amp;start='.$start; }
 2996:     if ($only_body) { $link .= '&amp;only_body=1'; }
 2997:     $title = &mt($title);
 2998:     $linktext = &mt($linktext);
 2999:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3000: 	&help_open_topic('View_recent_activity');
 3001: }
 3002: 
 3003: sub slot_reservations_link {
 3004:     my ($linktext,$sname,$sdom,$target) = @_;
 3005:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3006:     my $title = 'View slot reservation history';
 3007:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3008:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3009:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3010:         $title .= ' of this student';
 3011:     }
 3012:     if (defined($target) && $target !~ /^\s*$/) {
 3013:         $target = qq{target="$target"};
 3014:     } else {
 3015:         $target = '';
 3016:     }
 3017:     $title = &mt($title);
 3018:     $linktext = &mt($linktext);
 3019:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3020: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3021: 
 3022: }
 3023: 
 3024: # ===================================================== Display a student photo
 3025: 
 3026: 
 3027: sub student_image_tag {
 3028:     my ($domain,$user)=@_;
 3029:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3030:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3031: 	return '<img src="'.$imgsrc.'" align="right" />';
 3032:     } else {
 3033: 	return '';
 3034:     }
 3035: }
 3036: 
 3037: =pod
 3038: 
 3039: =back
 3040: 
 3041: =head1 Access .tab File Data
 3042: 
 3043: =over 4
 3044: 
 3045: =item * &languageids() 
 3046: 
 3047: returns list of all language ids
 3048: 
 3049: =cut
 3050: 
 3051: sub languageids {
 3052:     return sort(keys(%language));
 3053: }
 3054: 
 3055: =pod
 3056: 
 3057: =item * &languagedescription() 
 3058: 
 3059: returns description of a specified language id
 3060: 
 3061: =cut
 3062: 
 3063: sub languagedescription {
 3064:     my $code=shift;
 3065:     return  ($supported_language{$code}?'* ':'').
 3066:             $language{$code}.
 3067: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3068: }
 3069: 
 3070: sub plainlanguagedescription {
 3071:     my $code=shift;
 3072:     return $language{$code};
 3073: }
 3074: 
 3075: sub supportedlanguagecode {
 3076:     my $code=shift;
 3077:     return $supported_language{$code};
 3078: }
 3079: 
 3080: =pod
 3081: 
 3082: =item * &copyrightids() 
 3083: 
 3084: returns list of all copyrights
 3085: 
 3086: =cut
 3087: 
 3088: sub copyrightids {
 3089:     return sort(keys(%cprtag));
 3090: }
 3091: 
 3092: =pod
 3093: 
 3094: =item * &copyrightdescription() 
 3095: 
 3096: returns description of a specified copyright id
 3097: 
 3098: =cut
 3099: 
 3100: sub copyrightdescription {
 3101:     return &mt($cprtag{shift(@_)});
 3102: }
 3103: 
 3104: =pod
 3105: 
 3106: =item * &source_copyrightids() 
 3107: 
 3108: returns list of all source copyrights
 3109: 
 3110: =cut
 3111: 
 3112: sub source_copyrightids {
 3113:     return sort(keys(%scprtag));
 3114: }
 3115: 
 3116: =pod
 3117: 
 3118: =item * &source_copyrightdescription() 
 3119: 
 3120: returns description of a specified source copyright id
 3121: 
 3122: =cut
 3123: 
 3124: sub source_copyrightdescription {
 3125:     return &mt($scprtag{shift(@_)});
 3126: }
 3127: 
 3128: =pod
 3129: 
 3130: =item * &filecategories() 
 3131: 
 3132: returns list of all file categories
 3133: 
 3134: =cut
 3135: 
 3136: sub filecategories {
 3137:     return sort(keys(%category_extensions));
 3138: }
 3139: 
 3140: =pod
 3141: 
 3142: =item * &filecategorytypes() 
 3143: 
 3144: returns list of file types belonging to a given file
 3145: category
 3146: 
 3147: =cut
 3148: 
 3149: sub filecategorytypes {
 3150:     my ($cat) = @_;
 3151:     return @{$category_extensions{lc($cat)}};
 3152: }
 3153: 
 3154: =pod
 3155: 
 3156: =item * &fileembstyle() 
 3157: 
 3158: returns embedding style for a specified file type
 3159: 
 3160: =cut
 3161: 
 3162: sub fileembstyle {
 3163:     return $fe{lc(shift(@_))};
 3164: }
 3165: 
 3166: sub filemimetype {
 3167:     return $fm{lc(shift(@_))};
 3168: }
 3169: 
 3170: 
 3171: sub filecategoryselect {
 3172:     my ($name,$value)=@_;
 3173:     return &select_form($value,$name,
 3174: 			'' => &mt('Any category'),
 3175: 			map { $_,$_ } sort(keys(%category_extensions)));
 3176: }
 3177: 
 3178: =pod
 3179: 
 3180: =item * &filedescription() 
 3181: 
 3182: returns description for a specified file type
 3183: 
 3184: =cut
 3185: 
 3186: sub filedescription {
 3187:     my $file_description = $fd{lc(shift())};
 3188:     $file_description =~ s:([\[\]]):~$1:g;
 3189:     return &mt($file_description);
 3190: }
 3191: 
 3192: =pod
 3193: 
 3194: =item * &filedescriptionex() 
 3195: 
 3196: returns description for a specified file type with
 3197: extra formatting
 3198: 
 3199: =cut
 3200: 
 3201: sub filedescriptionex {
 3202:     my $ex=shift;
 3203:     my $file_description = $fd{lc($ex)};
 3204:     $file_description =~ s:([\[\]]):~$1:g;
 3205:     return '.'.$ex.' '.&mt($file_description);
 3206: }
 3207: 
 3208: # End of .tab access
 3209: =pod
 3210: 
 3211: =back
 3212: 
 3213: =cut
 3214: 
 3215: # ------------------------------------------------------------------ File Types
 3216: sub fileextensions {
 3217:     return sort(keys(%fe));
 3218: }
 3219: 
 3220: # ----------------------------------------------------------- Display Languages
 3221: # returns a hash with all desired display languages
 3222: #
 3223: 
 3224: sub display_languages {
 3225:     my %languages=();
 3226:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3227: 	$languages{$lang}=1;
 3228:     }
 3229:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3230:     if ($env{'form.displaylanguage'}) {
 3231: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3232: 	    $languages{$lang}=1;
 3233:         }
 3234:     }
 3235:     return %languages;
 3236: }
 3237: 
 3238: sub languages {
 3239:     my ($possible_langs) = @_;
 3240:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3241:     if (!ref($possible_langs)) {
 3242: 	if( wantarray ) {
 3243: 	    return @preferred_langs;
 3244: 	} else {
 3245: 	    return $preferred_langs[0];
 3246: 	}
 3247:     }
 3248:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3249:     my @preferred_possibilities;
 3250:     foreach my $preferred_lang (@preferred_langs) {
 3251: 	if (exists($possibilities{$preferred_lang})) {
 3252: 	    push(@preferred_possibilities, $preferred_lang);
 3253: 	}
 3254:     }
 3255:     if( wantarray ) {
 3256: 	return @preferred_possibilities;
 3257:     }
 3258:     return $preferred_possibilities[0];
 3259: }
 3260: 
 3261: sub user_lang {
 3262:     my ($touname,$toudom,$fromcid) = @_;
 3263:     my @userlangs;
 3264:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3265:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3266:                     $env{'course.'.$fromcid.'.languages'}));
 3267:     } else {
 3268:         my %langhash = &getlangs($touname,$toudom);
 3269:         if ($langhash{'languages'} ne '') {
 3270:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3271:         } else {
 3272:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3273:             if ($domdefs{'lang_def'} ne '') {
 3274:                 @userlangs = ($domdefs{'lang_def'});
 3275:             }
 3276:         }
 3277:     }
 3278:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3279:     my $user_lh = Apache::localize->get_handle(@languages);
 3280:     return $user_lh;
 3281: }
 3282: 
 3283: 
 3284: ###############################################################
 3285: ##               Student Answer Attempts                     ##
 3286: ###############################################################
 3287: 
 3288: =pod
 3289: 
 3290: =head1 Alternate Problem Views
 3291: 
 3292: =over 4
 3293: 
 3294: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3295:     $getattempt, $regexp, $gradesub)
 3296: 
 3297: Return string with previous attempt on problem. Arguments:
 3298: 
 3299: =over 4
 3300: 
 3301: =item * $symb: Problem, including path
 3302: 
 3303: =item * $username: username of the desired student
 3304: 
 3305: =item * $domain: domain of the desired student
 3306: 
 3307: =item * $course: Course ID
 3308: 
 3309: =item * $getattempt: Leave blank for all attempts, otherwise put
 3310:     something
 3311: 
 3312: =item * $regexp: if string matches this regexp, the string will be
 3313:     sent to $gradesub
 3314: 
 3315: =item * $gradesub: routine that processes the string if it matches $regexp
 3316: 
 3317: =back
 3318: 
 3319: The output string is a table containing all desired attempts, if any.
 3320: 
 3321: =cut
 3322: 
 3323: sub get_previous_attempt {
 3324:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3325:   my $prevattempts='';
 3326:   no strict 'refs';
 3327:   if ($symb) {
 3328:     my (%returnhash)=
 3329:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3330:     if ($returnhash{'version'}) {
 3331:       my %lasthash=();
 3332:       my $version;
 3333:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3334:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3335: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3336:         }
 3337:       }
 3338:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3339:       $prevattempts.='<th>'.&mt('History').'</th>';
 3340:       foreach my $key (sort(keys(%lasthash))) {
 3341: 	my ($ign,@parts) = split(/\./,$key);
 3342: 	if ($#parts > 0) {
 3343: 	  my $data=$parts[-1];
 3344: 	  pop(@parts);
 3345: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3346: 	} else {
 3347: 	  if ($#parts == 0) {
 3348: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3349: 	  } else {
 3350: 	    $prevattempts.='<th>'.$ign.'</th>';
 3351: 	  }
 3352: 	}
 3353:       }
 3354:       $prevattempts.=&end_data_table_header_row();
 3355:       if ($getattempt eq '') {
 3356: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3357: 	  $prevattempts.=&start_data_table_row().
 3358: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3359: 	    foreach my $key (sort(keys(%lasthash))) {
 3360: 		my $value = &format_previous_attempt_value($key,
 3361: 							   $returnhash{$version.':'.$key});
 3362: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3363: 	    }
 3364: 	  $prevattempts.=&end_data_table_row();
 3365: 	 }
 3366:       }
 3367:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3368:       foreach my $key (sort(keys(%lasthash))) {
 3369: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3370: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3371: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3372:       }
 3373:       $prevattempts.= &end_data_table_row().&end_data_table();
 3374:     } else {
 3375:       $prevattempts=
 3376: 	  &start_data_table().&start_data_table_row().
 3377: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3378: 	  &end_data_table_row().&end_data_table();
 3379:     }
 3380:   } else {
 3381:     $prevattempts=
 3382: 	  &start_data_table().&start_data_table_row().
 3383: 	  '<td>'.&mt('No data.').'</td>'.
 3384: 	  &end_data_table_row().&end_data_table();
 3385:   }
 3386: }
 3387: 
 3388: sub format_previous_attempt_value {
 3389:     my ($key,$value) = @_;
 3390:     if ($key =~ /timestamp/) {
 3391: 	$value = &Apache::lonlocal::locallocaltime($value);
 3392:     } elsif (ref($value) eq 'ARRAY') {
 3393: 	$value = '('.join(', ', @{ $value }).')';
 3394:     } else {
 3395: 	$value = &unescape($value);
 3396:     }
 3397:     return $value;
 3398: }
 3399: 
 3400: 
 3401: sub relative_to_absolute {
 3402:     my ($url,$output)=@_;
 3403:     my $parser=HTML::TokeParser->new(\$output);
 3404:     my $token;
 3405:     my $thisdir=$url;
 3406:     my @rlinks=();
 3407:     while ($token=$parser->get_token) {
 3408: 	if ($token->[0] eq 'S') {
 3409: 	    if ($token->[1] eq 'a') {
 3410: 		if ($token->[2]->{'href'}) {
 3411: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3412: 		}
 3413: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3414: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3415: 	    } elsif ($token->[1] eq 'base') {
 3416: 		$thisdir=$token->[2]->{'href'};
 3417: 	    }
 3418: 	}
 3419:     }
 3420:     $thisdir=~s-/[^/]*$--;
 3421:     foreach my $link (@rlinks) {
 3422: 	unless (($link=~/^https?\:\/\//i) ||
 3423: 		($link=~/^\//) ||
 3424: 		($link=~/^javascript:/i) ||
 3425: 		($link=~/^mailto:/i) ||
 3426: 		($link=~/^\#/)) {
 3427: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3428: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3429: 	}
 3430:     }
 3431: # -------------------------------------------------- Deal with Applet codebases
 3432:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3433:     return $output;
 3434: }
 3435: 
 3436: =pod
 3437: 
 3438: =item * &get_student_view()
 3439: 
 3440: show a snapshot of what student was looking at
 3441: 
 3442: =cut
 3443: 
 3444: sub get_student_view {
 3445:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3446:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3447:   my (%form);
 3448:   my @elements=('symb','courseid','domain','username');
 3449:   foreach my $element (@elements) {
 3450:       $form{'grade_'.$element}=eval '$'.$element #'
 3451:   }
 3452:   if (defined($moreenv)) {
 3453:       %form=(%form,%{$moreenv});
 3454:   }
 3455:   if (defined($target)) { $form{'grade_target'} = $target; }
 3456:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3457:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3458:   $userview=~s/\<body[^\>]*\>//gi;
 3459:   $userview=~s/\<\/body\>//gi;
 3460:   $userview=~s/\<html\>//gi;
 3461:   $userview=~s/\<\/html\>//gi;
 3462:   $userview=~s/\<head\>//gi;
 3463:   $userview=~s/\<\/head\>//gi;
 3464:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3465:   $userview=&relative_to_absolute($feedurl,$userview);
 3466:   if (wantarray) {
 3467:      return ($userview,$response);
 3468:   } else {
 3469:      return $userview;
 3470:   }
 3471: }
 3472: 
 3473: sub get_student_view_with_retries {
 3474:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3475: 
 3476:     my $ok = 0;                 # True if we got a good response.
 3477:     my $content;
 3478:     my $response;
 3479: 
 3480:     # Try to get the student_view done. within the retries count:
 3481:     
 3482:     do {
 3483:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3484:          $ok      = $response->is_success;
 3485:          if (!$ok) {
 3486:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3487:          }
 3488:          $retries--;
 3489:     } while (!$ok && ($retries > 0));
 3490:     
 3491:     if (!$ok) {
 3492:        $content = '';          # On error return an empty content.
 3493:     }
 3494:     if (wantarray) {
 3495:        return ($content, $response);
 3496:     } else {
 3497:        return $content;
 3498:     }
 3499: }
 3500: 
 3501: =pod
 3502: 
 3503: =item * &get_student_answers() 
 3504: 
 3505: show a snapshot of how student was answering problem
 3506: 
 3507: =cut
 3508: 
 3509: sub get_student_answers {
 3510:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3511:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3512:   my (%moreenv);
 3513:   my @elements=('symb','courseid','domain','username');
 3514:   foreach my $element (@elements) {
 3515:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3516:   }
 3517:   $moreenv{'grade_target'}='answer';
 3518:   %moreenv=(%form,%moreenv);
 3519:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3520:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3521:   return $userview;
 3522: }
 3523: 
 3524: =pod
 3525: 
 3526: =item * &submlink()
 3527: 
 3528: Inputs: $text $uname $udom $symb $target
 3529: 
 3530: Returns: A link to grades.pm such as to see the SUBM view of a student
 3531: 
 3532: =cut
 3533: 
 3534: ###############################################
 3535: sub submlink {
 3536:     my ($text,$uname,$udom,$symb,$target)=@_;
 3537:     if (!($uname && $udom)) {
 3538: 	(my $cursymb, my $courseid,$udom,$uname)=
 3539: 	    &Apache::lonnet::whichuser($symb);
 3540: 	if (!$symb) { $symb=$cursymb; }
 3541:     }
 3542:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3543:     $symb=&escape($symb);
 3544:     if ($target) { $target="target=\"$target\""; }
 3545:     return '<a href="/adm/grades?&command=submission&'.
 3546: 	'symb='.$symb.'&student='.$uname.
 3547: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3548: }
 3549: ##############################################
 3550: 
 3551: =pod
 3552: 
 3553: =item * &pgrdlink()
 3554: 
 3555: Inputs: $text $uname $udom $symb $target
 3556: 
 3557: Returns: A link to grades.pm such as to see the PGRD view of a student
 3558: 
 3559: =cut
 3560: 
 3561: ###############################################
 3562: sub pgrdlink {
 3563:     my $link=&submlink(@_);
 3564:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3565:     return $link;
 3566: }
 3567: ##############################################
 3568: 
 3569: =pod
 3570: 
 3571: =item * &pprmlink()
 3572: 
 3573: Inputs: $text $uname $udom $symb $target
 3574: 
 3575: Returns: A link to parmset.pm such as to see the PPRM view of a
 3576: student and a specific resource
 3577: 
 3578: =cut
 3579: 
 3580: ###############################################
 3581: sub pprmlink {
 3582:     my ($text,$uname,$udom,$symb,$target)=@_;
 3583:     if (!($uname && $udom)) {
 3584: 	(my $cursymb, my $courseid,$udom,$uname)=
 3585: 	    &Apache::lonnet::whichuser($symb);
 3586: 	if (!$symb) { $symb=$cursymb; }
 3587:     }
 3588:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3589:     $symb=&escape($symb);
 3590:     if ($target) { $target="target=\"$target\""; }
 3591:     return '<a href="/adm/parmset?command=set&amp;'.
 3592: 	'symb='.$symb.'&amp;uname='.$uname.
 3593: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3594: }
 3595: ##############################################
 3596: 
 3597: =pod
 3598: 
 3599: =back
 3600: 
 3601: =cut
 3602: 
 3603: ###############################################
 3604: 
 3605: 
 3606: sub timehash {
 3607:     my ($thistime) = @_;
 3608:     my $timezone = &Apache::lonlocal::gettimezone();
 3609:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3610:                      ->set_time_zone($timezone);
 3611:     my $wday = $dt->day_of_week();
 3612:     if ($wday == 7) { $wday = 0; }
 3613:     return ( 'second' => $dt->second(),
 3614:              'minute' => $dt->minute(),
 3615:              'hour'   => $dt->hour(),
 3616:              'day'     => $dt->day_of_month(),
 3617:              'month'   => $dt->month(),
 3618:              'year'    => $dt->year(),
 3619:              'weekday' => $wday,
 3620:              'dayyear' => $dt->day_of_year(),
 3621:              'dlsav'   => $dt->is_dst() );
 3622: }
 3623: 
 3624: sub utc_string {
 3625:     my ($date)=@_;
 3626:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3627: }
 3628: 
 3629: sub maketime {
 3630:     my %th=@_;
 3631:     my ($epoch_time,$timezone,$dt);
 3632:     $timezone = &Apache::lonlocal::gettimezone();
 3633:     eval {
 3634:         $dt = DateTime->new( year   => $th{'year'},
 3635:                              month  => $th{'month'},
 3636:                              day    => $th{'day'},
 3637:                              hour   => $th{'hour'},
 3638:                              minute => $th{'minute'},
 3639:                              second => $th{'second'},
 3640:                              time_zone => $timezone,
 3641:                          );
 3642:     };
 3643:     if (!$@) {
 3644:         $epoch_time = $dt->epoch;
 3645:         if ($epoch_time) {
 3646:             return $epoch_time;
 3647:         }
 3648:     }
 3649:     return POSIX::mktime(
 3650:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3651:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3652: }
 3653: 
 3654: #########################################
 3655: 
 3656: sub findallcourses {
 3657:     my ($roles,$uname,$udom) = @_;
 3658:     my %roles;
 3659:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3660:     my %courses;
 3661:     my $now=time;
 3662:     if (!defined($uname)) {
 3663:         $uname = $env{'user.name'};
 3664:     }
 3665:     if (!defined($udom)) {
 3666:         $udom = $env{'user.domain'};
 3667:     }
 3668:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3669:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3670:         if (!%roles) {
 3671:             %roles = (
 3672:                        cc => 1,
 3673:                        in => 1,
 3674:                        ep => 1,
 3675:                        ta => 1,
 3676:                        cr => 1,
 3677:                        st => 1,
 3678:              );
 3679:         }
 3680:         foreach my $entry (keys(%roleshash)) {
 3681:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3682:             if ($trole =~ /^cr/) { 
 3683:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3684:             } else {
 3685:                 next if (!exists($roles{$trole}));
 3686:             }
 3687:             if ($tend) {
 3688:                 next if ($tend < $now);
 3689:             }
 3690:             if ($tstart) {
 3691:                 next if ($tstart > $now);
 3692:             }
 3693:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3694:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3695:             if ($secpart eq '') {
 3696:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3697:                 $sec = 'none';
 3698:                 $realsec = '';
 3699:             } else {
 3700:                 $cnum = $cnumpart;
 3701:                 ($sec,$role) = split(/_/,$secpart);
 3702:                 $realsec = $sec;
 3703:             }
 3704:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3705:         }
 3706:     } else {
 3707:         foreach my $key (keys(%env)) {
 3708: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3709:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3710: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3711: 	        next if ($role eq 'ca' || $role eq 'aa');
 3712: 	        next if (%roles && !exists($roles{$role}));
 3713: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3714:                 my $active=1;
 3715:                 if ($starttime) {
 3716: 		    if ($now<$starttime) { $active=0; }
 3717:                 }
 3718:                 if ($endtime) {
 3719:                     if ($now>$endtime) { $active=0; }
 3720:                 }
 3721:                 if ($active) {
 3722:                     if ($sec eq '') {
 3723:                         $sec = 'none';
 3724:                     }
 3725:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3726:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3727:                 }
 3728:             }
 3729:         }
 3730:     }
 3731:     return %courses;
 3732: }
 3733: 
 3734: ###############################################
 3735: 
 3736: sub blockcheck {
 3737:     my ($setters,$activity,$uname,$udom) = @_;
 3738: 
 3739:     if (!defined($udom)) {
 3740:         $udom = $env{'user.domain'};
 3741:     }
 3742:     if (!defined($uname)) {
 3743:         $uname = $env{'user.name'};
 3744:     }
 3745: 
 3746:     # If uname and udom are for a course, check for blocks in the course.
 3747: 
 3748:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3749:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3750:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3751:         return ($startblock,$endblock);
 3752:     }
 3753: 
 3754:     my $startblock = 0;
 3755:     my $endblock = 0;
 3756:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3757: 
 3758:     # If uname is for a user, and activity is course-specific, i.e.,
 3759:     # boards, chat or groups, check for blocking in current course only.
 3760: 
 3761:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3762:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3763:         foreach my $key (keys(%live_courses)) {
 3764:             if ($key ne $env{'request.course.id'}) {
 3765:                 delete($live_courses{$key});
 3766:             }
 3767:         }
 3768:     }
 3769: 
 3770:     my $otheruser = 0;
 3771:     my %own_courses;
 3772:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3773:         # Resource belongs to user other than current user.
 3774:         $otheruser = 1;
 3775:         # Gather courses for current user
 3776:         %own_courses = 
 3777:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3778:     }
 3779: 
 3780:     # Gather active course roles - course coordinator, instructor, 
 3781:     # exam proctor, ta, student, or custom role.
 3782: 
 3783:     foreach my $course (keys(%live_courses)) {
 3784:         my ($cdom,$cnum);
 3785:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3786:             $cdom = $env{'course.'.$course.'.domain'};
 3787:             $cnum = $env{'course.'.$course.'.num'};
 3788:         } else {
 3789:             ($cdom,$cnum) = split(/_/,$course); 
 3790:         }
 3791:         my $no_ownblock = 0;
 3792:         my $no_userblock = 0;
 3793:         if ($otheruser && $activity ne 'com') {
 3794:             # Check if current user has 'evb' priv for this
 3795:             if (defined($own_courses{$course})) {
 3796:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3797:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3798:                     if ($sec ne 'none') {
 3799:                         $checkrole .= '/'.$sec;
 3800:                     }
 3801:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3802:                         $no_ownblock = 1;
 3803:                         last;
 3804:                     }
 3805:                 }
 3806:             }
 3807:             # if they have 'evb' priv and are currently not playing student
 3808:             next if (($no_ownblock) &&
 3809:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3810:         }
 3811:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3812:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3813:             if ($sec ne 'none') {
 3814:                 $checkrole .= '/'.$sec;
 3815:             }
 3816:             if ($otheruser) {
 3817:                 # Resource belongs to user other than current user.
 3818:                 # Assemble privs for that user, and check for 'evb' priv.
 3819:                 my ($trole,$tdom,$tnum,$tsec);
 3820:                 my $entry = $live_courses{$course}{$sec};
 3821:                 if ($entry =~ /^cr/) {
 3822:                     ($trole,$tdom,$tnum,$tsec) = 
 3823:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3824:                 } else {
 3825:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3826:                 }
 3827:                 my ($spec,$area,$trest,%allroles,%userroles);
 3828:                 $area = '/'.$tdom.'/'.$tnum;
 3829:                 $trest = $tnum;
 3830:                 if ($tsec ne '') {
 3831:                     $area .= '/'.$tsec;
 3832:                     $trest .= '/'.$tsec;
 3833:                 }
 3834:                 $spec = $trole.'.'.$area;
 3835:                 if ($trole =~ /^cr/) {
 3836:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3837:                                                       $tdom,$spec,$trest,$area);
 3838:                 } else {
 3839:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3840:                                                        $tdom,$spec,$trest,$area);
 3841:                 }
 3842:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3843:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3844:                     if ($1) {
 3845:                         $no_userblock = 1;
 3846:                         last;
 3847:                     }
 3848:                 }
 3849:             } else {
 3850:                 # Resource belongs to current user
 3851:                 # Check for 'evb' priv via lonnet::allowed().
 3852:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3853:                     $no_ownblock = 1;
 3854:                     last;
 3855:                 }
 3856:             }
 3857:         }
 3858:         # if they have the evb priv and are currently not playing student
 3859:         next if (($no_ownblock) &&
 3860:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3861:         next if ($no_userblock);
 3862: 
 3863:         # Retrieve blocking times and identity of locker for course
 3864:         # of specified user, unless user has 'evb' privilege.
 3865:         
 3866:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3867:         if (($start != 0) && 
 3868:             (($startblock == 0) || ($startblock > $start))) {
 3869:             $startblock = $start;
 3870:         }
 3871:         if (($end != 0)  &&
 3872:             (($endblock == 0) || ($endblock < $end))) {
 3873:             $endblock = $end;
 3874:         }
 3875:     }
 3876:     return ($startblock,$endblock);
 3877: }
 3878: 
 3879: sub get_blocks {
 3880:     my ($setters,$activity,$cdom,$cnum) = @_;
 3881:     my $startblock = 0;
 3882:     my $endblock = 0;
 3883:     my $course = $cdom.'_'.$cnum;
 3884:     $setters->{$course} = {};
 3885:     $setters->{$course}{'staff'} = [];
 3886:     $setters->{$course}{'times'} = [];
 3887:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3888:     foreach my $record (keys(%records)) {
 3889:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3890:         if ($start <= time && $end >= time) {
 3891:             my ($staff_name,$staff_dom,$title,$blocks) =
 3892:                 &parse_block_record($records{$record});
 3893:             if ($blocks->{$activity} eq 'on') {
 3894:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3895:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3896:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3897:                     $startblock = $start;
 3898:                 }
 3899:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3900:                     $endblock = $end;
 3901:                 }
 3902:             }
 3903:         }
 3904:     }
 3905:     return ($startblock,$endblock);
 3906: }
 3907: 
 3908: sub parse_block_record {
 3909:     my ($record) = @_;
 3910:     my ($setuname,$setudom,$title,$blocks);
 3911:     if (ref($record) eq 'HASH') {
 3912:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3913:         $title = &unescape($record->{'event'});
 3914:         $blocks = $record->{'blocks'};
 3915:     } else {
 3916:         my @data = split(/:/,$record,3);
 3917:         if (scalar(@data) eq 2) {
 3918:             $title = $data[1];
 3919:             ($setuname,$setudom) = split(/@/,$data[0]);
 3920:         } else {
 3921:             ($setuname,$setudom,$title) = @data;
 3922:         }
 3923:         $blocks = { 'com' => 'on' };
 3924:     }
 3925:     return ($setuname,$setudom,$title,$blocks);
 3926: }
 3927: 
 3928: sub blocking_status {
 3929:   my ($activity,$uname,$udom) = @_;
 3930:   my %setters;
 3931: 
 3932:   # check for active blocking
 3933:   my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3934: 
 3935:   my $blocked = $startblock && $endblock ? 1 : 0;
 3936: 
 3937:   # caller just wants to know whether a block is active
 3938:   if (!wantarray) { return $blocked; }
 3939: 
 3940:   # build a link to a popup window containing the details
 3941:   my $querystring  = "?activity=$activity";
 3942:   # $uname and $udom decide whose portfolio the user is trying to look at
 3943:      $querystring .= "&amp;udom=$udom"      if $udom;
 3944:      $querystring .= "&amp;uname=$uname"    if $uname;
 3945: 
 3946:   my $output .= <<'END_MYBLOCK';
 3947:     function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 3948:         var options = "width=" + w + ",height=" + h + ",";
 3949:         options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 3950:         options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 3951:         var newWin = window.open(url, wdwName, options);
 3952:         newWin.focus();
 3953:     }
 3954: END_MYBLOCK
 3955: 
 3956:   $output = Apache::lonhtmlcommon::scripttag($output);
 3957:   
 3958:   my $popupUrl = "/adm/blockingstatus/$querystring";
 3959:   my $text = mt('Communication Blocked');
 3960: 
 3961:   $output .= <<"END_BLOCK";
 3962: <div class='LC_comblock'>
 3963:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 3964:   title='$text'>
 3965:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 3966:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 3967:   title='$text'>$text</a>
 3968: </div>
 3969: 
 3970: END_BLOCK
 3971: 
 3972:   return ($blocked, $output);
 3973: }
 3974: 
 3975: ###############################################
 3976: 
 3977: sub check_ip_acc {
 3978:     my ($acc)=@_;
 3979:     &Apache::lonxml::debug("acc is $acc");
 3980:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3981:         return 1;
 3982:     }
 3983:     my $allowed=0;
 3984:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3985: 
 3986:     my $name;
 3987:     foreach my $pattern (split(',',$acc)) {
 3988:         $pattern =~ s/^\s*//;
 3989:         $pattern =~ s/\s*$//;
 3990:         if ($pattern =~ /\*$/) {
 3991:             #35.8.*
 3992:             $pattern=~s/\*//;
 3993:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3994:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3995:             #35.8.3.[34-56]
 3996:             my $low=$2;
 3997:             my $high=$3;
 3998:             $pattern=$1;
 3999:             if ($ip =~ /^\Q$pattern\E/) {
 4000:                 my $last=(split(/\./,$ip))[3];
 4001:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4002:             }
 4003:         } elsif ($pattern =~ /^\*/) {
 4004:             #*.msu.edu
 4005:             $pattern=~s/\*//;
 4006:             if (!defined($name)) {
 4007:                 use Socket;
 4008:                 my $netaddr=inet_aton($ip);
 4009:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4010:             }
 4011:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4012:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4013:             #127.0.0.1
 4014:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4015:         } else {
 4016:             #some.name.com
 4017:             if (!defined($name)) {
 4018:                 use Socket;
 4019:                 my $netaddr=inet_aton($ip);
 4020:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4021:             }
 4022:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4023:         }
 4024:         if ($allowed) { last; }
 4025:     }
 4026:     return $allowed;
 4027: }
 4028: 
 4029: ###############################################
 4030: 
 4031: =pod
 4032: 
 4033: =head1 Domain Template Functions
 4034: 
 4035: =over 4
 4036: 
 4037: =item * &determinedomain()
 4038: 
 4039: Inputs: $domain (usually will be undef)
 4040: 
 4041: Returns: Determines which domain should be used for designs
 4042: 
 4043: =cut
 4044: 
 4045: ###############################################
 4046: sub determinedomain {
 4047:     my $domain=shift;
 4048:     if (! $domain) {
 4049:         # Determine domain if we have not been given one
 4050:         $domain = &Apache::lonnet::default_login_domain();
 4051:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4052:         if ($env{'request.role.domain'}) { 
 4053:             $domain=$env{'request.role.domain'}; 
 4054:         }
 4055:     }
 4056:     return $domain;
 4057: }
 4058: ###############################################
 4059: 
 4060: sub devalidate_domconfig_cache {
 4061:     my ($udom)=@_;
 4062:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4063: }
 4064: 
 4065: # ---------------------- Get domain configuration for a domain
 4066: sub get_domainconf {
 4067:     my ($udom) = @_;
 4068:     my $cachetime=1800;
 4069:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4070:     if (defined($cached)) { return %{$result}; }
 4071: 
 4072:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4073: 					     ['login','rolecolors'],$udom);
 4074:     my (%designhash,%legacy);
 4075:     if (keys(%domconfig) > 0) {
 4076:         if (ref($domconfig{'login'}) eq 'HASH') {
 4077:             if (keys(%{$domconfig{'login'}})) {
 4078:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4079:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4080:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4081:                             $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4082:                                 $domconfig{'login'}{$key}{$img};
 4083:                         }
 4084:                     } else {
 4085:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4086:                     }
 4087:                 }
 4088:             } else {
 4089:                 $legacy{'login'} = 1;
 4090:             }
 4091:         } else {
 4092:             $legacy{'login'} = 1;
 4093:         }
 4094:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4095:             if (keys(%{$domconfig{'rolecolors'}})) {
 4096:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4097:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4098:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4099:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4100:                         }
 4101:                     }
 4102:                 }
 4103:             } else {
 4104:                 $legacy{'rolecolors'} = 1;
 4105:             }
 4106:         } else {
 4107:             $legacy{'rolecolors'} = 1;
 4108:         }
 4109:         if (keys(%legacy) > 0) {
 4110:             my %legacyhash = &get_legacy_domconf($udom);
 4111:             foreach my $item (keys(%legacyhash)) {
 4112:                 if ($item =~ /^\Q$udom\E\.login/) {
 4113:                     if ($legacy{'login'}) { 
 4114:                         $designhash{$item} = $legacyhash{$item};
 4115:                     }
 4116:                 } else {
 4117:                     if ($legacy{'rolecolors'}) {
 4118:                         $designhash{$item} = $legacyhash{$item};
 4119:                     }
 4120:                 }
 4121:             }
 4122:         }
 4123:     } else {
 4124:         %designhash = &get_legacy_domconf($udom); 
 4125:     }
 4126:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4127: 				  $cachetime);
 4128:     return %designhash;
 4129: }
 4130: 
 4131: sub get_legacy_domconf {
 4132:     my ($udom) = @_;
 4133:     my %legacyhash;
 4134:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4135:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4136:     if (-e $designfile) {
 4137:         if ( open (my $fh,"<$designfile") ) {
 4138:             while (my $line = <$fh>) {
 4139:                 next if ($line =~ /^\#/);
 4140:                 chomp($line);
 4141:                 my ($key,$val)=(split(/\=/,$line));
 4142:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4143:             }
 4144:             close($fh);
 4145:         }
 4146:     }
 4147:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4148:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4149:     }
 4150:     return %legacyhash;
 4151: }
 4152: 
 4153: =pod
 4154: 
 4155: =item * &domainlogo()
 4156: 
 4157: Inputs: $domain (usually will be undef)
 4158: 
 4159: Returns: A link to a domain logo, if the domain logo exists.
 4160: If the domain logo does not exist, a description of the domain.
 4161: 
 4162: =cut
 4163: 
 4164: ###############################################
 4165: sub domainlogo {
 4166:     my $domain = &determinedomain(shift);
 4167:     my %designhash = &get_domainconf($domain);    
 4168:     # See if there is a logo
 4169:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4170:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4171:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4172: 	    if ($imgsrc =~ m{^/res/}) {
 4173: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4174: 		&Apache::lonnet::repcopy($local_name);
 4175: 	    }
 4176: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4177:         } 
 4178:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4179:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4180:         return &Apache::lonnet::domain($domain,'description');
 4181:     } else {
 4182:         return '';
 4183:     }
 4184: }
 4185: ##############################################
 4186: 
 4187: =pod
 4188: 
 4189: =item * &designparm()
 4190: 
 4191: Inputs: $which parameter; $domain (usually will be undef)
 4192: 
 4193: Returns: value of designparamter $which
 4194: 
 4195: =cut
 4196: 
 4197: 
 4198: ##############################################
 4199: sub designparm {
 4200:     my ($which,$domain)=@_;
 4201:     if (exists($env{'environment.color.'.$which})) {
 4202:         return $env{'environment.color.'.$which};
 4203:     }
 4204:     $domain=&determinedomain($domain);
 4205:     my %domdesign = &get_domainconf($domain);
 4206:     my $output;
 4207:     if ($domdesign{$domain.'.'.$which} ne '') {
 4208:         $output = $domdesign{$domain.'.'.$which};
 4209:     } else {
 4210:         $output = $defaultdesign{$which};
 4211:     }
 4212:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4213:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4214:         if ($output =~ m{^/(adm|res)/}) {
 4215:             if ($output =~ m{^/res/}) {
 4216:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4217:                 &Apache::lonnet::repcopy($local_name);
 4218:             }
 4219:             $output = &lonhttpdurl($output);
 4220:         }
 4221:     }
 4222:     return $output;
 4223: }
 4224: 
 4225: ##############################################
 4226: =pod
 4227: 
 4228: =item * &authorspace()
 4229: 
 4230: Inputs: ./.
 4231: 
 4232: Returns: Path to the Construction Space of the current user's
 4233:          accessed author space
 4234:          The author space will be that of the current user
 4235:          when accessing the own author space
 4236:          and that of the co-author/assistent co-author
 4237:          when accessing the co-author's/assistent co-author's
 4238:          space
 4239: 
 4240: =cut
 4241: 
 4242: sub authorspace {
 4243:     my $caname = '';
 4244:     if ($env{'request.role'} =~ /^ca|^aa/) {
 4245:         (undef,$caname) =
 4246:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4247:     } else {
 4248:         $caname = $env{'user.name'};
 4249:     }
 4250:     return '/priv/'.$caname.'/';
 4251: }
 4252: 
 4253: ##############################################
 4254: =pod
 4255: 
 4256: =item * &head_subbox()
 4257: 
 4258: Inputs: $content (contains HTML code with page functions, etc.)
 4259: 
 4260: Returns: HTML div with $content
 4261:          To be included in page header
 4262: 
 4263: =cut
 4264: 
 4265: sub head_subbox {
 4266:     my ($content)=@_;
 4267:     my $output =
 4268:         '<div id="LC_head_subbox">'
 4269:        .$content
 4270:        .'</div>'
 4271: }
 4272: 
 4273: ##############################################
 4274: =pod
 4275: 
 4276: =item * &CSTR_pageheader()
 4277: 
 4278: Inputs: ./.
 4279: 
 4280: Returns: HTML div with CSTR path and recent box
 4281:          To be included on Construction Space pages
 4282: 
 4283: =cut
 4284: 
 4285: sub CSTR_pageheader {
 4286:     # this is for resources; directories have customtitle, and crumbs
 4287:             # and select recent are created in lonpubdir.pm  
 4288:     my ($uname,$thisdisfn)=
 4289:         ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4290:     my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4291:     $formaction=~s/\/+/\//g;
 4292: 
 4293:     my $parentpath = '';
 4294:     my $lastitem = '';
 4295:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4296:         $parentpath = $1;
 4297:         $lastitem = $2;
 4298:     } else {
 4299:         $lastitem = $thisdisfn;
 4300:     }
 4301:     return
 4302:          '<div>'
 4303:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 4304:         .'<b>'.&mt('Construction Space:').'</b> '
 4305:         .'<form name="dirs" method="post" action="'.$formaction
 4306:         .'" target="_top"><tt><b>' #FIXME lonpubdir: target="_parent"
 4307:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."$lastitem</b></tt><br />"
 4308:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 4309:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4310:         .'</form>'
 4311:         .&Apache::lonmenu::constspaceform()
 4312:         .'</div>';
 4313: }
 4314: 
 4315: ###############################################
 4316: ###############################################
 4317: 
 4318: =pod
 4319: 
 4320: =back
 4321: 
 4322: =head1 HTML Helpers
 4323: 
 4324: =over 4
 4325: 
 4326: =item * &bodytag()
 4327: 
 4328: Returns a uniform header for LON-CAPA web pages.
 4329: 
 4330: Inputs: 
 4331: 
 4332: =over 4
 4333: 
 4334: =item * $title, A title to be displayed on the page.
 4335: 
 4336: =item * $function, the current role (can be undef).
 4337: 
 4338: =item * $addentries, extra parameters for the <body> tag.
 4339: 
 4340: =item * $bodyonly, if defined, only return the <body> tag.
 4341: 
 4342: =item * $domain, if defined, force a given domain.
 4343: 
 4344: =item * $forcereg, if page should register as content page (relevant for 
 4345:             text interface only)
 4346: 
 4347: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 4348:                      navigational links
 4349: 
 4350: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4351: 
 4352: =item * $no_inline_link, if true and in remote mode, don't show the 
 4353:          'Switch To Inline Menu' link
 4354: 
 4355: =item * $args, optional argument valid values are
 4356:             no_auto_mt_title -> prevents &mt()ing the title arg
 4357:             inherit_jsmath -> when creating popup window in a page,
 4358:                               should it have jsmath forced on by the
 4359:                               current page
 4360: 
 4361: =back
 4362: 
 4363: Returns: A uniform header for LON-CAPA web pages.  
 4364: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4365: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4366: other decorations will be returned.
 4367: 
 4368: =cut
 4369: 
 4370: sub bodytag {
 4371:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 4372:         $no_nav_bar,$bgcolor,$no_inline_link,$args)=@_;
 4373: 
 4374:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4375: 
 4376:     $function = &get_users_function() if (!$function);
 4377:     my $img =    &designparm($function.'.img',$domain);
 4378:     my $font =   &designparm($function.'.font',$domain);
 4379:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4380: 
 4381:     my %design = ( 'style'   => 'margin-top: 0',
 4382: 		   'bgcolor' => $pgbg,
 4383: 		   'text'    => $font,
 4384:                    'alink'   => &designparm($function.'.alink',$domain),
 4385: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4386: 		   'link'    => &designparm($function.'.link',$domain),);
 4387:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4388: 
 4389:  # role and realm
 4390:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4391:     if ($role  eq 'ca') {
 4392:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4393:         $realm = &plainname($rname,$rdom);
 4394:     } 
 4395: # realm
 4396:     if ($env{'request.course.id'}) {
 4397:         if ($env{'request.role'} !~ /^cr/) {
 4398:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4399:         }
 4400:         if ($env{'request.course.sec'}) {
 4401:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 4402:         }   
 4403: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4404:     } else {
 4405:         $role = &Apache::lonnet::plaintext($role);
 4406:     }
 4407: 
 4408:     if (!$realm) { $realm='&nbsp;'; }
 4409: # Set messages
 4410:     my $messages=&domainlogo($domain);
 4411: 
 4412:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4413: 
 4414: # construct main body tag
 4415:     my $bodytag = "<body $extra_body_attr>".
 4416: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4417: 
 4418:     if ($bodyonly) {
 4419:         return $bodytag;
 4420:     } 
 4421: 
 4422:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4423:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4424: 	undef($role);
 4425:     } else {
 4426: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4427:     }
 4428:     
 4429:     my $titleinfo = '<h1>'.$title.'</h1>';
 4430:     #
 4431:     # Extra info if you are the DC
 4432:     my $dc_info = '';
 4433:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4434:                         $env{'course.'.$env{'request.course.id'}.
 4435:                                  '.domain'}.'/'})) {
 4436:         my $cid = $env{'request.course.id'};
 4437:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4438:         $dc_info =~ s/\s+$//;
 4439:         $dc_info = '('.$dc_info.')';
 4440:     }
 4441: 
 4442:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 4443:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 4444: 
 4445:     if ($env{'environment.remote'} eq 'off') {
 4446:         # No Remote
 4447:         if ($env{'request.state'} eq 'construct') {
 4448:             $forcereg=1;
 4449:         }
 4450: 
 4451:     #    if ($env{'request.state'} eq 'construct') {
 4452:     #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 4453:     #    }
 4454: 
 4455:         my $titletable = '<table id="LC_title_bar">'
 4456:                             ."<tr><td> $titleinfo $dc_info</td>"
 4457:                             .'</tr></table>';
 4458: 
 4459:         if ($no_nav_bar) {
 4460:             $bodytag .= $titletable;
 4461:         } else {
 4462:             $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 4463:                 <em>$realm</em> $dc_info</div>| unless $env{'form.inhibitmenu'};
 4464: 
 4465: #SD $titletable is obsolete
 4466: #SD            if ($env{'request.state'} eq 'construct') {
 4467: #SD                $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$titletable);
 4468: #SD            } else {
 4469: #SD                $bodytag .= &Apache::lonmenu::menubuttons($forcereg).$titletable;
 4470: #SD            }
 4471:                if (   $env{'form.inhibitmenu'} eq 'yes' 
 4472:                    || $ENV{'REQUEST_URI'} eq '/adm/logout'
 4473:                    || $env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 4474:                    
 4475:                    return $bodytag;
 4476:                }
 4477: 
 4478:                $bodytag .= Apache::lonhtmlcommon::scripttag(
 4479:                                 Apache::lonmenu::utilityfunctions(),
 4480:                                 'start');
 4481:                $bodytag .= Apache::lonmenu::primary_menu();
 4482:                $bodytag .= Apache::lonmenu::secondary_menu();
 4483:                #SD remove next line
 4484:                #$bodytag .= Apache::lonmenu::menubuttons($forcereg);
 4485:                $bodytag .= Apache::lonmenu::serverform();
 4486:                $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 4487:                $bodytag .= Apache::lonmenu::innerregister($forcereg) if $forcereg;
 4488:         }
 4489:         return $bodytag;
 4490:     }
 4491: 
 4492: #
 4493: # Top frame rendering, Remote is up
 4494: #
 4495: 
 4496:     my $imgsrc = $img;
 4497:     if ($img =~ /^\/adm/) {
 4498:         $imgsrc = &lonhttpdurl($img);
 4499:     }
 4500:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4501: 
 4502:     # Explicit link to get inline menu
 4503:     my $menu= ($no_inline_link?''
 4504: 	       :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 4505:     $bodytag .= qq|<div id="LC_nav_bar">$name $role
 4506:             <em>$realm</em> $dc_info </div>
 4507:             <ol class="LC_primary_menu LC_right">
 4508:                 <li>$menu</li>
 4509:             </ol>| unless $env{'form.inhibitmenu'};
 4510:     #
 4511:     return(<<ENDBODY);
 4512: $bodytag
 4513: <table id="LC_title_bar" class="LC_with_remote">
 4514: <tr><td>$upperleft</td>
 4515:     <td>$messages&nbsp;</td>
 4516: </tr>
 4517: <tr><td>$titleinfo $dc_info $menu</td>
 4518: </tr>
 4519: </table>
 4520: ENDBODY
 4521: }
 4522: 
 4523: sub make_attr_string {
 4524:     my ($register,$attr_ref) = @_;
 4525: 
 4526:     if ($attr_ref && !ref($attr_ref)) {
 4527: 	die("addentries Must be a hash ref ".
 4528: 	    join(':',caller(1))." ".
 4529: 	    join(':',caller(0))." ");
 4530:     }
 4531: 
 4532:     if ($register) {
 4533: 	my ($on_load,$on_unload);
 4534: 	foreach my $key (keys(%{$attr_ref})) {
 4535: 	    if      (lc($key) eq 'onload') {
 4536: 		$on_load.=$attr_ref->{$key}.';';
 4537: 		delete($attr_ref->{$key});
 4538: 
 4539: 	    } elsif (lc($key) eq 'onunload') {
 4540: 		$on_unload.=$attr_ref->{$key}.';';
 4541: 		delete($attr_ref->{$key});
 4542: 	    }
 4543: 	}
 4544: 	$attr_ref->{'onload'}  =
 4545: 	    &Apache::lonmenu::loadevents().  $on_load;
 4546: 	$attr_ref->{'onunload'}=
 4547: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4548:     }
 4549: 
 4550: # Accessibility font enhance
 4551:     if ($env{'browser.fontenhance'} eq 'on') {
 4552: 	my $style;
 4553: 	foreach my $key (keys(%{$attr_ref})) {
 4554: 	    if (lc($key) eq 'style') {
 4555: 		$style.=$attr_ref->{$key}.';';
 4556: 		delete($attr_ref->{$key});
 4557: 	    }
 4558: 	}
 4559: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4560:     }
 4561: 
 4562:     my $attr_string;
 4563:     foreach my $attr (keys(%$attr_ref)) {
 4564: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4565:     }
 4566:     return $attr_string;
 4567: }
 4568: 
 4569: 
 4570: ###############################################
 4571: ###############################################
 4572: 
 4573: =pod
 4574: 
 4575: =item * &endbodytag()
 4576: 
 4577: Returns a uniform footer for LON-CAPA web pages.
 4578: 
 4579: Inputs: 1 - optional reference to an args hash
 4580: If in the hash, key for noredirectlink has a value which evaluates to true,
 4581: a 'Continue' link is not displayed if the page contains an
 4582: internal redirect in the <head></head> section,
 4583: i.e., $env{'internal.head.redirect'} exists   
 4584: 
 4585: =cut
 4586: 
 4587: sub endbodytag {
 4588:     my ($args) = @_;
 4589:     my $endbodytag='</body>';
 4590:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4591:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4592:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4593: 	    $endbodytag=
 4594: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4595: 	        &mt('Continue').'</a>'.
 4596: 	        $endbodytag;
 4597:         }
 4598:     }
 4599:     return $endbodytag;
 4600: }
 4601: 
 4602: =pod
 4603: 
 4604: =item * &standard_css()
 4605: 
 4606: Returns a style sheet
 4607: 
 4608: Inputs: (all optional)
 4609:             domain         -> force to color decorate a page for a specific
 4610:                                domain
 4611:             function       -> force usage of a specific rolish color scheme
 4612:             bgcolor        -> override the default page bgcolor
 4613: 
 4614: =cut
 4615: 
 4616: sub standard_css {
 4617:     my ($function,$domain,$bgcolor) = @_;
 4618:     $function  = &get_users_function() if (!$function);
 4619:     my $img    = &designparm($function.'.img',   $domain);
 4620:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4621:     my $font   = &designparm($function.'.font',  $domain);
 4622:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 4623: #second colour for later usage
 4624:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4625:     my $pgbg_or_bgcolor =
 4626: 	         $bgcolor ||
 4627: 	         &designparm($function.'.pgbg',  $domain);
 4628:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4629:     my $alink  = &designparm($function.'.alink', $domain);
 4630:     my $vlink  = &designparm($function.'.vlink', $domain);
 4631:     my $link   = &designparm($function.'.link',  $domain);
 4632: 
 4633:     my $loginbg = &designparm('login.sidebg',$domain);
 4634:     my $bgcol = &designparm('login.bgcol',$domain);
 4635:     my $textcol = &designparm('login.textcol',$domain);
 4636: 
 4637:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4638:     my $mono                 = 'monospace';
 4639:     my $data_table_head      = $sidebg;
 4640:     my $data_table_light     = '#FAFAFA';
 4641:     my $data_table_dark      = '#F0F0F0';
 4642:     my $data_table_darker    = '#CCCCCC';
 4643:     my $data_table_highlight = '#FFFF00';
 4644:     my $mail_new             = '#FFBB77';
 4645:     my $mail_new_hover       = '#DD9955';
 4646:     my $mail_read            = '#BBBB77';
 4647:     my $mail_read_hover      = '#999944';
 4648:     my $mail_replied         = '#AAAA88';
 4649:     my $mail_replied_hover   = '#888855';
 4650:     my $mail_other           = '#99BBBB';
 4651:     my $mail_other_hover     = '#669999';
 4652:     my $table_header         = '#DDDDDD';
 4653:     my $feedback_link_bg     = '#BBBBBB';
 4654:     my $lg_border_color	     = '#C8C8C8';
 4655: 
 4656:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4657: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4658: 	                                                 : '0 3px 0 4px';
 4659: 
 4660: 
 4661:     return <<END;
 4662: body {
 4663:    font-family: $sans;
 4664:    line-height:130%;
 4665:    font-size:0.83em;
 4666:    color:$font;
 4667: }
 4668: 
 4669: a:link, a:visited { 
 4670:   font-size:100%; 
 4671: }
 4672: 
 4673: a:focus { 
 4674:   color: red;
 4675:   background: yellow 
 4676: }
 4677: 
 4678: form, .inline { 
 4679:    display: inline; 
 4680: }
 4681: 
 4682: .LC_right {
 4683:    text-align:right;
 4684: }
 4685: 
 4686: .LC_middle {
 4687:    vertical-align:middle;
 4688: }
 4689: 
 4690: /* just for tests */
 4691: .LC_400Box {width:400px; }
 4692: /* end */
 4693: 
 4694: .LC_filename {
 4695:   font-family: $mono;
 4696:   white-space:pre;
 4697: }
 4698: 
 4699: .LC_fileicon {
 4700:   border: none;
 4701:   height: 1.3em;
 4702:   vertical-align: text-bottom;
 4703:   margin-right: 0.3em;
 4704:   text-decoration:none;
 4705: }
 4706: 
 4707: .LC_error {
 4708:   color: red;
 4709:   font-size: larger;
 4710: }
 4711: 
 4712: .LC_warning,
 4713: .LC_diff_removed {
 4714:   color: red;
 4715: }
 4716: 
 4717: .LC_info,
 4718: .LC_success,
 4719: .LC_diff_added {
 4720:   color: green;
 4721: }
 4722: 
 4723: div.LC_confirm_box {
 4724:   background-color: #FAFAFA;
 4725:   border: 1px solid $lg_border_color;
 4726:   margin-right: 0;
 4727:   padding: 5px;
 4728: }
 4729: 
 4730: div.LC_confirm_box .LC_error img,
 4731: div.LC_confirm_box .LC_success img {
 4732:   vertical-align: middle;
 4733: }
 4734: 
 4735: .LC_icon {
 4736:   border: none;
 4737:   vertical-align: middle;
 4738: }
 4739: 
 4740: .LC_docs_spacer {
 4741:   width: 25px;
 4742:   height: 1px;
 4743:   border: none;
 4744: }
 4745: 
 4746: .LC_internal_info {
 4747:   color: #999999;
 4748: }
 4749: 
 4750: .LC_discussion {
 4751:    background: $tabbg;
 4752:    border: 1px solid black;
 4753:    margin: 2px;
 4754: }
 4755: 
 4756: .LC_disc_action_links_bar {
 4757:    background: $tabbg;
 4758:    border: none;
 4759:    margin: 4px;
 4760: }
 4761: 
 4762: .LC_disc_action_left {
 4763:    text-align: left;
 4764: }
 4765: 
 4766: .LC_disc_action_right {
 4767:    text-align: right;
 4768: }
 4769: 
 4770: .LC_disc_new_item {
 4771:    background: white;
 4772:    border: 2px solid red;
 4773:    margin: 2px;
 4774: }
 4775: 
 4776: .LC_disc_old_item {
 4777:    background: white;
 4778:    border: 1px solid black;
 4779:    margin: 2px;
 4780: }
 4781: 
 4782: table.LC_pastsubmission {
 4783:   border: 1px solid black;
 4784:   margin: 2px;
 4785: }
 4786: 
 4787: table#LC_top_nav,
 4788: table#LC_menubuttons,
 4789: table#LC_nav_location {
 4790:   width: 100%;
 4791:   background: $pgbg;
 4792:   border: 2px;
 4793:   border-collapse: separate;
 4794:   padding: 0;
 4795: }
 4796: 
 4797: table#LC_title_bar a {
 4798:   color: $fontmenu;
 4799: }
 4800: 
 4801: table#LC_title_bar {
 4802:   clear: both;
 4803:   display: none;
 4804: }
 4805: 
 4806: table#LC_title_bar,
 4807: table.LC_breadcrumbs,
 4808: table#LC_title_bar.LC_with_remote {
 4809:   width: 100%;
 4810:   border-color: $pgbg;
 4811:   border-style: solid;
 4812:   border-width: $border;
 4813:   background: $pgbg;
 4814:   color: $fontmenu;
 4815:   border-collapse: collapse;
 4816:   padding: 0;
 4817:   margin: 0;
 4818: }
 4819: 
 4820: table#LC_title_bar td {
 4821:   background: $tabbg;
 4822: }
 4823: 
 4824: table#LC_menubuttons img{
 4825:   border: none;
 4826: }
 4827: 
 4828: table#LC_top_nav td {
 4829:   background: $tabbg;
 4830:   border: none;
 4831:   font-size: small;
 4832:   vertical-align:top;
 4833:   padding:2px 5px 2px 5px;
 4834: }
 4835: 
 4836: table#LC_top_nav td a,
 4837: div#LC_top_nav a {
 4838:   color: $font;
 4839: }
 4840: 
 4841: table#LC_top_nav td.LC_top_nav_logo {
 4842:   background: $tabbg;
 4843:   text-align: left;
 4844:   white-space: nowrap;
 4845:   width: 31px;
 4846: }
 4847: 
 4848: table#LC_top_nav td.LC_top_nav_logo img {
 4849:   border: none;
 4850:   vertical-align: bottom;
 4851: }
 4852: 
 4853: table#LC_top_nav td.LC_top_nav_exit,
 4854: table#LC_top_nav td.LC_top_nav_help {
 4855:   width: 2.0em;
 4856: }
 4857: 
 4858: table#LC_top_nav td.LC_top_nav_login {
 4859:   width: 4.0em;
 4860:   text-align: center;
 4861: }
 4862: 
 4863: .LC_breadcrumbs_component {
 4864:     float: right;
 4865:     margin: 0 1em;
 4866: }
 4867: .LC_breadcrumbs_component img {
 4868:     vertical-align: middle;
 4869: }
 4870: 
 4871: td.LC_table_cell_checkbox {
 4872:   text-align: center;
 4873: }
 4874: 
 4875: table#LC_mainmenu td.LC_mainmenu_column {
 4876:     vertical-align: top;
 4877: }
 4878: 
 4879: .LC_fontsize_small {
 4880:  font-size: 70%;
 4881: }
 4882: 
 4883: #LC_breadcrumbs {
 4884:  clear:both;
 4885:  background: $sidebg;
 4886:  border-bottom: 1px solid $lg_border_color;
 4887:  line-height: 32px; 
 4888:  margin: 0;
 4889:  padding: 0;
 4890: }
 4891: 
 4892: /* Preliminary fix to hide breadcrumbs inside remote control window */
 4893: #LC_remote #LC_breadcrumbs {
 4894:     display:none;
 4895: }
 4896: 
 4897: #LC_head_subbox {
 4898:  clear:both;
 4899:  background: #F8F8F8; /* $sidebg; */
 4900:  border-bottom: 1px solid $lg_border_color;
 4901:  margin: 0 0 10px 0;
 4902:  padding: 5px;
 4903: }
 4904: 
 4905: .LC_fontsize_medium {
 4906:  font-size: 85%;
 4907: }
 4908: 
 4909: .LC_fontsize_large {
 4910:  font-size: 120%;
 4911: }
 4912: 
 4913: .LC_menubuttons_inline_text {
 4914:   color: $font;
 4915:   font-size: 90%;
 4916:   padding-left:3px;
 4917: }
 4918: 
 4919: .LC_menubuttons_link {
 4920:   text-decoration: none;
 4921: }
 4922: 
 4923: .LC_menubuttons_category {
 4924:   color: $font;
 4925:   background: $pgbg;
 4926:   font-size: larger;
 4927:   font-weight: bold;
 4928: }
 4929: 
 4930: td.LC_menubuttons_text {
 4931:  	color: $font;
 4932: }
 4933: 
 4934: .LC_current_location {
 4935:   background: $tabbg;
 4936: }
 4937: 
 4938: .LC_new_mail {
 4939:   background: $tabbg;
 4940:   font-weight: bold;
 4941: }
 4942: 
 4943: table.LC_data_table,
 4944: table.LC_mail_list {
 4945:   border: 1px solid #000000;
 4946:   border-collapse: separate;
 4947:   border-spacing: 1px;
 4948:   background: $pgbg;
 4949: }
 4950: 
 4951: .LC_data_table_dense {
 4952:   font-size: small;
 4953: }
 4954: 
 4955: table.LC_nested_outer {
 4956:   border: 1px solid #000000;
 4957:   border-collapse: collapse;
 4958:   border-spacing: 0;
 4959:   width: 100%;
 4960: }
 4961: 
 4962: table.LC_innerpickbox,
 4963: table.LC_nested {
 4964:   border: none;
 4965:   border-collapse: collapse;
 4966:   border-spacing: 0;
 4967:   width: 100%;
 4968: }
 4969: 
 4970: table.LC_data_table tr th, 
 4971: table.LC_calendar tr th, 
 4972: table.LC_mail_list tr th,
 4973: table.LC_prior_tries tr th,
 4974: table.LC_innerpickbox tr th {
 4975:   font-weight: bold;
 4976:   background-color: $data_table_head;
 4977:   color:$fontmenu;
 4978:   font-size:90%;
 4979: }
 4980: 
 4981: table.LC_innerpickbox tr th,
 4982: table.LC_innerpickbox tr td {
 4983:   vertical-align: top;
 4984: }
 4985: 
 4986: table.LC_data_table tr.LC_info_row > td {
 4987:   background-color: #CCCCCC;
 4988:   font-weight: bold;
 4989:   text-align: left;
 4990: }
 4991: 
 4992: table.LC_data_table tr.LC_odd_row > td,
 4993: table.LC_pick_box tr > td.LC_odd_row {
 4994:   background-color: $data_table_light;
 4995:   padding: 2px;
 4996:   vertical-align: top;
 4997: }
 4998: 
 4999: table.LC_data_table tr.LC_even_row > td,
 5000: table.LC_pick_box tr > td.LC_even_row {
 5001:   background-color: $data_table_dark;
 5002:   padding: 2px;
 5003:   vertical-align: top;
 5004: }
 5005: 
 5006: table.LC_data_table tr.LC_data_table_highlight td {
 5007:   background-color: $data_table_darker;
 5008: }
 5009: 
 5010: table.LC_data_table tr td.LC_leftcol_header {
 5011:   background-color: $data_table_head;
 5012:   font-weight: bold;
 5013: }
 5014: 
 5015: table.LC_data_table tr.LC_empty_row td,
 5016: table.LC_nested tr.LC_empty_row td {
 5017:   background-color: #FFFFFF;
 5018:   font-weight: bold;
 5019:   font-style: italic;
 5020:   text-align: center;
 5021:   padding: 8px;
 5022: }
 5023: 
 5024: table.LC_caption {
 5025: }
 5026: 
 5027: table.LC_nested tr.LC_empty_row td {
 5028:   padding: 4ex
 5029: }
 5030: 
 5031: table.LC_nested_outer tr th {
 5032:   font-weight: bold;
 5033:   color:$fontmenu;
 5034:   background-color: $data_table_head;
 5035:   font-size: small;
 5036:   border-bottom: 1px solid #000000;
 5037: }
 5038: 
 5039: table.LC_nested_outer tr td.LC_subheader {
 5040:   background-color: $data_table_head;
 5041:   font-weight: bold;
 5042:   font-size: small;
 5043:   border-bottom: 1px solid #000000;
 5044:   text-align: right;
 5045: }
 5046: 
 5047: table.LC_nested tr.LC_info_row td {
 5048:   background-color: #CCCCCC;
 5049:   font-weight: bold;
 5050:   font-size: small;
 5051:   text-align: center;
 5052: }
 5053: 
 5054: table.LC_nested tr.LC_info_row td.LC_left_item,
 5055: table.LC_nested_outer tr th.LC_left_item {
 5056:   text-align: left;
 5057: }
 5058: 
 5059: table.LC_nested td {
 5060:   background-color: #FFFFFF;
 5061:   font-size: small;
 5062: }
 5063: 
 5064: table.LC_nested_outer tr th.LC_right_item,
 5065: table.LC_nested tr.LC_info_row td.LC_right_item,
 5066: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5067: table.LC_nested tr td.LC_right_item {
 5068:   text-align: right;
 5069: }
 5070: 
 5071: table.LC_nested tr.LC_odd_row td {
 5072:   background-color: #EEEEEE;
 5073: }
 5074: 
 5075: table.LC_createuser {
 5076: }
 5077: 
 5078: table.LC_createuser tr.LC_section_row td {
 5079:   font-size: small;
 5080: }
 5081: 
 5082: table.LC_createuser tr.LC_info_row td  {
 5083:   background-color: #CCCCCC;
 5084:   font-weight: bold;
 5085:   text-align: center;
 5086: }
 5087: 
 5088: table.LC_calendar {
 5089:   border: 1px solid #000000;
 5090:   border-collapse: collapse;
 5091: }
 5092: 
 5093: table.LC_calendar_pickdate {
 5094:   font-size: xx-small;
 5095: }
 5096: 
 5097: table.LC_calendar tr td {
 5098:   border: 1px solid #000000;
 5099:   vertical-align: top;
 5100: }
 5101: 
 5102: table.LC_calendar tr td.LC_calendar_day_empty {
 5103:   background-color: $data_table_dark;
 5104: }
 5105: 
 5106: table.LC_calendar tr td.LC_calendar_day_current {
 5107:   background-color: $data_table_highlight;
 5108: }
 5109: 
 5110: table.LC_mail_list tr.LC_mail_new {
 5111:   background-color: $mail_new;
 5112: }
 5113: 
 5114: table.LC_mail_list tr.LC_mail_new:hover {
 5115:   background-color: $mail_new_hover;
 5116: }
 5117: 
 5118: table.LC_mail_list tr.LC_mail_even {
 5119: }
 5120: 
 5121: table.LC_mail_list tr.LC_mail_odd {
 5122: }
 5123: 
 5124: table.LC_mail_list tr.LC_mail_read {
 5125:   background-color: $mail_read;
 5126: }
 5127: 
 5128: table.LC_mail_list tr.LC_mail_read:hover {
 5129:   background-color: $mail_read_hover;
 5130: }
 5131: 
 5132: table.LC_mail_list tr.LC_mail_replied {
 5133:   background-color: $mail_replied;
 5134: }
 5135: 
 5136: table.LC_mail_list tr.LC_mail_replied:hover {
 5137:   background-color: $mail_replied_hover;
 5138: }
 5139: 
 5140: table.LC_mail_list tr.LC_mail_other {
 5141:   background-color: $mail_other;
 5142: }
 5143: 
 5144: table.LC_mail_list tr.LC_mail_other:hover {
 5145:   background-color: $mail_other_hover;
 5146: }
 5147: 
 5148: table.LC_data_table tr > td.LC_browser_file,
 5149: table.LC_data_table tr > td.LC_browser_file_published {
 5150:   background: #AAEE77;
 5151: }
 5152: 
 5153: table.LC_data_table tr > td.LC_browser_file_locked,
 5154: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5155:   background: #FFAA99;
 5156: }
 5157: 
 5158: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5159:   background: #888888;
 5160: }
 5161: 
 5162: table.LC_data_table tr > td.LC_browser_file_modified,
 5163: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5164:   background: #F8F866;
 5165: }
 5166: 
 5167: table.LC_data_table tr.LC_browser_folder > td {
 5168:   background: #E0E8FF;
 5169: }
 5170: 
 5171: table.LC_data_table tr > td.LC_roles_is {
 5172: /*  background: #77FF77; */
 5173: }
 5174: 
 5175: table.LC_data_table tr > td.LC_roles_future {
 5176:   background: #FFFF77;
 5177: }
 5178: 
 5179: table.LC_data_table tr > td.LC_roles_will {
 5180:   background: #FFAA77;
 5181: }
 5182: 
 5183: table.LC_data_table tr > td.LC_roles_expired {
 5184:   background: #FF7777;
 5185: }
 5186: 
 5187: table.LC_data_table tr > td.LC_roles_will_not {
 5188:   background: #AAFF77;
 5189: }
 5190: 
 5191: table.LC_data_table tr > td.LC_roles_selected {
 5192:   background: #11CC55;
 5193: }
 5194: 
 5195: span.LC_current_location {
 5196:   font-size:larger;
 5197:   background: $pgbg;
 5198: }
 5199: 
 5200: span.LC_parm_menu_item {
 5201:   font-size: larger;
 5202: }
 5203: 
 5204: span.LC_parm_scope_all {
 5205:   color: red;
 5206: }
 5207: 
 5208: span.LC_parm_scope_folder {
 5209:   color: green;
 5210: }
 5211: 
 5212: span.LC_parm_scope_resource {
 5213:   color: orange;
 5214: }
 5215: 
 5216: span.LC_parm_part {
 5217:   color: blue;
 5218: }
 5219: 
 5220: span.LC_parm_folder, span.LC_parm_symb {
 5221:   font-size: x-small;
 5222:   font-family: $mono;
 5223:   color: #AAAAAA;
 5224: }
 5225: 
 5226: td.LC_parm_overview_level_menu,
 5227: td.LC_parm_overview_map_menu,
 5228: td.LC_parm_overview_parm_selectors,
 5229: td.LC_parm_overview_restrictions  {
 5230:   border: 1px solid black;
 5231:   border-collapse: collapse;
 5232: }
 5233: 
 5234: table.LC_parm_overview_restrictions td {
 5235:   border-width: 1px 4px 1px 4px;
 5236:   border-style: solid;
 5237:   border-color: $pgbg;
 5238:   text-align: center;
 5239: }
 5240: 
 5241: table.LC_parm_overview_restrictions th {
 5242:   background: $tabbg;
 5243:   border-width: 1px 4px 1px 4px;
 5244:   border-style: solid;
 5245:   border-color: $pgbg;
 5246: }
 5247: 
 5248: table#LC_helpmenu {
 5249:   border: none;
 5250:   height: 55px;
 5251:   border-spacing: 0;
 5252: }
 5253: 
 5254: table#LC_helpmenu fieldset legend {
 5255:   font-size: larger;
 5256: }
 5257: 
 5258: table#LC_helpmenu_links {
 5259:   width: 100%;
 5260:   border: 1px solid black;
 5261:   background: $pgbg;
 5262:   padding: 0;
 5263:   border-spacing: 1px;
 5264: }
 5265: 
 5266: table#LC_helpmenu_links tr td {
 5267:   padding: 1px;
 5268:   background: $tabbg;
 5269:   text-align: center;
 5270:   font-weight: bold;
 5271: }
 5272: 
 5273: table#LC_helpmenu_links a:link,
 5274: table#LC_helpmenu_links a:visited,
 5275: table#LC_helpmenu_links a:active {
 5276:   text-decoration: none;
 5277:   color: $font;
 5278: }
 5279: 
 5280: table#LC_helpmenu_links a:hover {
 5281:   text-decoration: underline;
 5282:   color: $vlink;
 5283: }
 5284: 
 5285: .LC_chrt_popup_exists {
 5286:   border: 1px solid #339933;
 5287:   margin: -1px;
 5288: }
 5289: 
 5290: .LC_chrt_popup_up {
 5291:   border: 1px solid yellow;
 5292:   margin: -1px;
 5293: }
 5294: 
 5295: .LC_chrt_popup {
 5296:   border: 1px solid #8888FF;
 5297:   background: #CCCCFF;
 5298: }
 5299: 
 5300: table.LC_pick_box {
 5301:   border-collapse: separate;
 5302:   background: white;
 5303:   border: 1px solid black;
 5304:   border-spacing: 1px;
 5305: }
 5306: 
 5307: table.LC_pick_box td.LC_pick_box_title {
 5308:   background: $sidebg;
 5309:   font-weight: bold;
 5310:   text-align: left;
 5311:   vertical-align: top;
 5312:   width: 184px;
 5313:   padding: 8px;
 5314: }
 5315: 
 5316: table.LC_pick_box td.LC_pick_box_value {
 5317:   text-align: left;
 5318:   padding: 8px;
 5319: }
 5320: 
 5321: table.LC_pick_box td.LC_pick_box_select {
 5322:   text-align: left;
 5323:   padding: 8px;
 5324: }
 5325: 
 5326: table.LC_pick_box td.LC_pick_box_separator {
 5327:   padding: 0;
 5328:   height: 1px;
 5329:   background: black;
 5330: }
 5331: 
 5332: table.LC_pick_box td.LC_pick_box_submit {
 5333:   text-align: right;
 5334: }
 5335: 
 5336: table.LC_pick_box td.LC_evenrow_value {
 5337:   text-align: left;
 5338:   padding: 8px;
 5339:   background-color: $data_table_light;
 5340: }
 5341: 
 5342: table.LC_pick_box td.LC_oddrow_value {
 5343:   text-align: left;
 5344:   padding: 8px;
 5345:   background-color: $data_table_light;
 5346: }
 5347: 
 5348: table.LC_helpform_receipt {
 5349:   width: 620px;
 5350:   border-collapse: separate;
 5351:   background: white;
 5352:   border: 1px solid black;
 5353:   border-spacing: 1px;
 5354: }
 5355: 
 5356: table.LC_helpform_receipt td.LC_pick_box_title {
 5357:   background: $tabbg;
 5358:   font-weight: bold;
 5359:   text-align: right;
 5360:   width: 184px;
 5361:   padding: 8px;
 5362: }
 5363: 
 5364: table.LC_helpform_receipt td.LC_evenrow_value {
 5365:   text-align: left;
 5366:   padding: 8px;
 5367:   background-color: $data_table_light;
 5368: }
 5369: 
 5370: table.LC_helpform_receipt td.LC_oddrow_value {
 5371:   text-align: left;
 5372:   padding: 8px;
 5373:   background-color: $data_table_light;
 5374: }
 5375: 
 5376: table.LC_helpform_receipt td.LC_pick_box_separator {
 5377:   padding: 0;
 5378:   height: 1px;
 5379:   background: black;
 5380: }
 5381: 
 5382: span.LC_helpform_receipt_cat {
 5383:   font-weight: bold;
 5384: }
 5385: 
 5386: table.LC_group_priv_box {
 5387:   background: white;
 5388:   border: 1px solid black;
 5389:   border-spacing: 1px;
 5390: }
 5391: 
 5392: table.LC_group_priv_box td.LC_pick_box_title {
 5393:   background: $tabbg;
 5394:   font-weight: bold;
 5395:   text-align: right;
 5396:   width: 184px;
 5397: }
 5398: 
 5399: table.LC_group_priv_box td.LC_groups_fixed {
 5400:   background: $data_table_light;
 5401:   text-align: center;
 5402: }
 5403: 
 5404: table.LC_group_priv_box td.LC_groups_optional {
 5405:   background: $data_table_dark;
 5406:   text-align: center;
 5407: }
 5408: 
 5409: table.LC_group_priv_box td.LC_groups_functionality {
 5410:   background: $data_table_darker;
 5411:   text-align: center;
 5412:   font-weight: bold;
 5413: }
 5414: 
 5415: table.LC_group_priv td {
 5416:   text-align: left;
 5417:   padding: 0;
 5418: }
 5419: 
 5420: table.LC_notify_front_page {
 5421:   background: white;
 5422:   border: 1px solid black;
 5423:   padding: 8px;
 5424: }
 5425: 
 5426: table.LC_notify_front_page td {
 5427:   padding: 8px;
 5428: }
 5429: 
 5430: .LC_navbuttons {
 5431:   margin: 2ex 0ex 2ex 0ex;
 5432: }
 5433: 
 5434: .LC_topic_bar {
 5435:   font-weight: bold;
 5436:   width: 100%;
 5437:   background: $tabbg;
 5438:   vertical-align: middle;
 5439:   margin: 2ex 0ex 2ex 0ex;
 5440:   padding: 3px;
 5441: }
 5442: 
 5443: .LC_topic_bar span {
 5444:   vertical-align: middle;
 5445: }
 5446: 
 5447: .LC_topic_bar img {
 5448:   vertical-align: bottom;
 5449: }
 5450: 
 5451: table.LC_course_group_status {
 5452:   margin: 20px;
 5453: }
 5454: 
 5455: table.LC_status_selector td {
 5456:   vertical-align: top;
 5457:   text-align: center;
 5458:   padding: 4px;
 5459: }
 5460: 
 5461: div.LC_feedback_link {
 5462:   clear: both;
 5463:   background: $sidebg;
 5464:   width: 100%;
 5465:   padding-bottom: 10px;
 5466:   border: 1px $tabbg solid;
 5467:   height: 22px;
 5468:   line-height: 22px;
 5469:   padding-top: 5px;
 5470: }
 5471: 
 5472: div.LC_feedback_link img {
 5473:   height: 22px;
 5474:   vertical-align:middle;
 5475: }
 5476: 
 5477: div.LC_feedback_link a{
 5478:   text-decoration: none;
 5479: }
 5480: 
 5481: div.LC_comblock {
 5482:   display:inline; 
 5483:   color:$font;
 5484:   font-size:90%;
 5485: }
 5486: 
 5487: div.LC_feedback_link div.LC_comblock {
 5488:   padding-left:5px;
 5489: }
 5490: 
 5491: div.LC_feedback_link div.LC_comblock a {
 5492:   color:$font;
 5493: }
 5494: 
 5495: span.LC_feedback_link {
 5496:   /* background: $feedback_link_bg; */
 5497:   font-size: larger;
 5498: }
 5499: 
 5500: span.LC_message_link {
 5501:   /* background: $feedback_link_bg; */
 5502:   font-size: larger;
 5503:   position: absolute;
 5504:   right: 1em;
 5505: }
 5506: 
 5507: table.LC_prior_tries {
 5508:   border: 1px solid #000000;
 5509:   border-collapse: separate;
 5510:   border-spacing: 1px;
 5511: }
 5512: 
 5513: table.LC_prior_tries td {
 5514:   padding: 2px;
 5515: }
 5516: 
 5517: .LC_answer_correct {
 5518:   background: lightgreen;
 5519:   color: darkgreen;
 5520:   padding: 6px;
 5521: }
 5522: 
 5523: .LC_answer_charged_try {
 5524:   background: #FFAAAA;
 5525:   color: darkred;
 5526:   padding: 6px;
 5527: }
 5528: 
 5529: .LC_answer_not_charged_try,
 5530: .LC_answer_no_grade,
 5531: .LC_answer_late {
 5532:   background: lightyellow;
 5533:   color: black;
 5534:   padding: 6px;
 5535: }
 5536: 
 5537: .LC_answer_previous {
 5538:   background: lightblue;
 5539:   color: darkblue;
 5540:   padding: 6px;
 5541: }
 5542: 
 5543: .LC_answer_no_message {
 5544:   background: #FFFFFF;
 5545:   color: black;
 5546:   padding: 6px;
 5547: }
 5548: 
 5549: .LC_answer_unknown {
 5550:   background: orange;
 5551:   color: black;
 5552:   padding: 6px;
 5553: }
 5554: 
 5555: span.LC_prior_numerical,
 5556: span.LC_prior_string,
 5557: span.LC_prior_custom,
 5558: span.LC_prior_reaction,
 5559: span.LC_prior_math {
 5560:   font-family: monospace;
 5561:   white-space: pre;
 5562: }
 5563: 
 5564: span.LC_prior_string {
 5565:   font-family: monospace;
 5566:   white-space: pre;
 5567: }
 5568: 
 5569: table.LC_prior_option {
 5570:   width: 100%;
 5571:   border-collapse: collapse;
 5572: }
 5573: 
 5574: table.LC_prior_rank, 
 5575: table.LC_prior_match {
 5576:   border-collapse: collapse;
 5577: }
 5578: 
 5579: table.LC_prior_option tr td,
 5580: table.LC_prior_rank tr td,
 5581: table.LC_prior_match tr td {
 5582:   border: 1px solid #000000;
 5583: }
 5584: 
 5585: .LC_nobreak {
 5586:   white-space: nowrap;
 5587: }
 5588: 
 5589: span.LC_cusr_emph {
 5590:   font-style: italic;
 5591: }
 5592: 
 5593: span.LC_cusr_subheading {
 5594:   font-weight: normal;
 5595:   font-size: 85%;
 5596: }
 5597: 
 5598: table.LC_docs_documents {
 5599:   background: #BBBBBB;
 5600:   border-width: 0;
 5601:   border-collapse: collapse;
 5602: }
 5603: 
 5604: table.LC_docs_documents td.LC_docs_document {
 5605:   border: 2px solid black;
 5606:   padding: 4px;
 5607: }
 5608: 
 5609: div.LC_docs_entry_move {
 5610:   border: 1px solid #BBBBBB;
 5611:   background: #DDDDDD;
 5612:   width: 22px;
 5613:   padding: 1px;
 5614:   margin: 0;
 5615: }
 5616: 
 5617: table.LC_data_table tr > td.LC_docs_entry_commands,
 5618: table.LC_data_table tr > td.LC_docs_entry_parameter {
 5619:   background: #DDDDDD;
 5620:   font-size: x-small;
 5621: }
 5622: 
 5623: .LC_docs_entry_parameter {
 5624:   white-space: nowrap;
 5625: }
 5626: 
 5627: .LC_docs_copy {
 5628:   color: #000099;
 5629: }
 5630: 
 5631: .LC_docs_cut {
 5632:   color: #550044;
 5633: }
 5634: 
 5635: .LC_docs_rename {
 5636:   color: #009900;
 5637: }
 5638: 
 5639: .LC_docs_remove {
 5640:   color: #990000;
 5641: }
 5642: 
 5643: .LC_docs_reinit_warn,
 5644: .LC_docs_ext_edit {
 5645:   font-size: x-small;
 5646: }
 5647: 
 5648: table.LC_docs_adddocs td,
 5649: table.LC_docs_adddocs th {
 5650:   border: 1px solid #BBBBBB;
 5651:   padding: 4px;
 5652:   background: #DDDDDD;
 5653: }
 5654: 
 5655: table.LC_sty_begin {
 5656:   background: #BBFFBB;
 5657: }
 5658: 
 5659: table.LC_sty_end {
 5660:   background: #FFBBBB;
 5661: }
 5662: 
 5663: table.LC_double_column {
 5664:   border-width: 0;
 5665:   border-collapse: collapse;
 5666:   width: 100%;
 5667:   padding: 2px;
 5668: }
 5669: 
 5670: table.LC_double_column tr td.LC_left_col {
 5671:   top: 2px;
 5672:   left: 2px;
 5673:   width: 47%;
 5674:   vertical-align: top;
 5675: }
 5676: 
 5677: table.LC_double_column tr td.LC_right_col {
 5678:   top: 2px;
 5679:   right: 2px;
 5680:   width: 47%;
 5681:   vertical-align: top;
 5682: }
 5683: 
 5684: div.LC_left_float {
 5685:   float: left;
 5686:   padding-right: 5%;
 5687:   padding-bottom: 4px;
 5688: }
 5689: 
 5690: div.LC_clear_float_header {
 5691:   padding-bottom: 2px;
 5692: }
 5693: 
 5694: div.LC_clear_float_footer {
 5695:   padding-top: 10px;
 5696:   clear: both;
 5697: }
 5698: 
 5699: div.LC_grade_show_user {
 5700:   margin-top: 20px;
 5701:   border: 1px solid black;
 5702: }
 5703: 
 5704: div.LC_grade_user_name {
 5705:   background: #DDDDEE;
 5706:   border-bottom: 1px solid black;
 5707:   font-weight: bold;
 5708:   font-size: large;
 5709: }
 5710: 
 5711: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5712:   background: #DDEEDD;
 5713: }
 5714: 
 5715: div.LC_grade_show_problem,
 5716: div.LC_grade_submissions,
 5717: div.LC_grade_message_center,
 5718: div.LC_grade_info_links,
 5719: div.LC_grade_assign {
 5720:   margin: 5px;
 5721:   width: 99%;
 5722:   background: #FFFFFF;
 5723: }
 5724: 
 5725: div.LC_grade_show_problem_header,
 5726: div.LC_grade_submissions_header,
 5727: div.LC_grade_message_center_header,
 5728: div.LC_grade_assign_header {
 5729:   font-weight: bold;
 5730:   font-size: large;
 5731: }
 5732: 
 5733: div.LC_grade_show_problem_problem,
 5734: div.LC_grade_submissions_body,
 5735: div.LC_grade_message_center_body,
 5736: div.LC_grade_assign_body {
 5737:   border: 1px solid black;
 5738:   width: 99%;
 5739:   background: #FFFFFF;
 5740: }
 5741: 
 5742: span.LC_grade_check_note {
 5743:   font-weight: normal;
 5744:   font-size: medium;
 5745:   display: inline;
 5746:   position: absolute;
 5747:   right: 1em;
 5748: }
 5749: 
 5750: table.LC_scantron_action {
 5751:   width: 100%;
 5752: }
 5753: 
 5754: table.LC_scantron_action tr th {
 5755:   font-weight:bold;
 5756:   font-style:normal;
 5757: }
 5758: 
 5759: .LC_edit_problem_header,
 5760: div.LC_edit_problem_footer {
 5761:   font-weight: normal;
 5762:   font-size:  medium;
 5763:   margin: 2px;
 5764: }
 5765: 
 5766: div.LC_edit_problem_header,
 5767: div.LC_edit_problem_header div,
 5768: div.LC_edit_problem_footer,
 5769: div.LC_edit_problem_footer div,
 5770: div.LC_edit_problem_editxml_header,
 5771: div.LC_edit_problem_editxml_header div {
 5772:   margin-top: 5px;
 5773: }
 5774: 
 5775: div.LC_edit_problem_header_title {
 5776:   font-weight: bold;
 5777:   font-size: larger;
 5778:   background: $tabbg;
 5779:   padding: 3px;
 5780: }
 5781: 
 5782: table.LC_edit_problem_header_title {
 5783:   font-size: larger;
 5784:   font-weight:  bold;
 5785:   width: 100%;
 5786:   border-color: $pgbg;
 5787:   border-style: solid;
 5788:   border-width: $border;
 5789:   background: $tabbg;
 5790:   border-collapse: collapse;
 5791:   padding: 0;
 5792: }
 5793: 
 5794: div.LC_edit_problem_discards {
 5795:   float: left;
 5796:   padding-bottom: 5px;
 5797: }
 5798: 
 5799: div.LC_edit_problem_saves {
 5800:   float: right;
 5801:   padding-bottom: 5px;
 5802: }
 5803: 
 5804: img.stift{
 5805:   border-width: 0;
 5806:   vertical-align: middle;
 5807: }
 5808: 
 5809: table#LC_mainmenu{
 5810:  margin-top:10px;
 5811:  width:80%;
 5812: }
 5813: 
 5814: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5815:   vertical-align: top;
 5816:   width: 45%;
 5817: }
 5818: 
 5819: .LC_mainmenu_fieldset_category {
 5820:   color: $font;
 5821:   background: $pgbg;
 5822:   font-size: small;
 5823:   font-weight: bold;
 5824: }
 5825: 
 5826: div.LC_createcourse {
 5827:     margin: 10px 10px 10px 10px;
 5828: }
 5829: 
 5830: /* ---- Remove when done ----
 5831: # The following styles is part of the redesign of LON-CAPA and are
 5832: # subject to change during this project.
 5833: # Don't rely on their current functionality as they might be 
 5834: # changed or removed.
 5835: # --------------------------*/
 5836: 
 5837: a:hover,
 5838: ol.LC_primary_menu a:hover,
 5839: ol#LC_MenuBreadcrumbs a:hover,
 5840: ol#LC_PathBreadcrumbs a:hover,
 5841: ul#LC_secondary_menu a:hover,
 5842: .LC_FormSectionClearButton input:hover
 5843: ul.LC_TabContent   li:hover a {
 5844: 	color:#BF2317;
 5845:         text-decoration:none;
 5846: }
 5847: 
 5848: h1 {
 5849: 	padding: 0;
 5850: 	line-height:130%;
 5851: }
 5852: 
 5853: h2,h3,h4,h5,h6 {
 5854: 	margin: 5px 0 5px 0;
 5855: 	padding: 0;
 5856: 	line-height:130%;
 5857: }
 5858: 
 5859: .LC_hcell {
 5860:         padding:3px 15px 3px 15px;
 5861:         margin: 0;
 5862: 	background-color:$tabbg;
 5863: 	color:$fontmenu;
 5864: 	border-bottom:solid 1px $lg_border_color;
 5865: }
 5866: 
 5867: .LC_Box > .LC_hcell {
 5868:     margin: 0 -10px 10px -10px;
 5869: }
 5870: 
 5871: .LC_noBorder {
 5872:         border: 0;
 5873: }
 5874: 
 5875: .LC_Right {
 5876:         float: right;
 5877:         margin: 0;
 5878:         padding: 0;
 5879: }
 5880: 
 5881: .LC_FormSectionClearButton input {
 5882:         background-color:transparent;
 5883:         border: none;
 5884:         cursor:pointer;
 5885:         text-decoration:underline;
 5886: }
 5887: 
 5888: .LC_help_open_topic {
 5889:         color: #FFFFFF;
 5890:         background-color: #EEEEFF;
 5891:         margin: 1px;
 5892:         padding: 4px;
 5893:         border: 1px solid #000033;
 5894:         white-space: nowrap;
 5895: /*		vertical-align: middle; */
 5896: }
 5897: 
 5898: dl,ul,div,fieldset {
 5899: 	margin: 10px 10px 10px 0;
 5900: /*	overflow: hidden; */
 5901: }
 5902: 
 5903: fieldset > legend {
 5904:     font-weight: bold;
 5905:     padding: 0 5px 0 5px;
 5906: }
 5907: 
 5908: #LC_nav_bar {
 5909:     float: left;
 5910:     margin: 0.2em 0 0 0;
 5911: }
 5912: 
 5913: #LC_nav_bar em{
 5914:     font-weight: bold;
 5915:     font-style: normal;
 5916: }
 5917: 
 5918: ol.LC_primary_menu {
 5919:     float: right;
 5920:     margin: 0.2em 0 0 0;
 5921: }
 5922: 
 5923: ol#LC_PathBreadcrumbs {
 5924: 	margin: 0;
 5925: }
 5926: 
 5927: ol.LC_primary_menu li {
 5928: 	display: inline;
 5929: 	padding: 5px 5px 0 10px;
 5930: 	vertical-align: top;
 5931: }
 5932: 
 5933: ol.LC_primary_menu li img {
 5934: 	vertical-align: bottom;
 5935: }
 5936: 
 5937: ol.LC_primary_menu a {
 5938: 	font-size: 90%;
 5939: 	color: RGB(80, 80, 80);
 5940: 	text-decoration: none;
 5941: }
 5942: 
 5943: ul#LC_secondary_menu {
 5944:     clear: both;
 5945:     color: $fontmenu;
 5946:     background: $tabbg;
 5947:     list-style: none;
 5948:     padding: 0;
 5949:     margin: 0;
 5950:     width: 100%;
 5951: }
 5952: 
 5953: ul#LC_secondary_menu li {
 5954:     font-weight: bold;
 5955:     line-height: 1.8em;
 5956:     padding: 0 0.8em; 
 5957:     border-right: 1px solid black;
 5958:     display: inline;
 5959:     vertical-align: middle;
 5960: }
 5961: 
 5962: ul.LC_TabContent {
 5963: 	display:block;
 5964: 	background: $sidebg;
 5965: 	border-bottom: solid 1px $lg_border_color;
 5966: 	list-style:none;
 5967: 	margin: 0 -10px;
 5968: 	padding: 0;
 5969: }
 5970: 
 5971: ul.LC_TabContent li,
 5972: ul.LC_TabContentBigger li {
 5973: 	float:left;
 5974: }
 5975: 
 5976: ul#LC_secondary_menu li a {
 5977:     color: $fontmenu;
 5978: 	text-decoration: none;
 5979: }
 5980: 
 5981: ul.LC_TabContent {
 5982: 	min-height:1.5em;
 5983: }
 5984: 
 5985: ul.LC_TabContent li {
 5986: 	vertical-align:middle;
 5987: 	padding: 0 10px 0 10px;
 5988: 	background-color:$tabbg;
 5989: 	border-bottom:solid 1px $lg_border_color;
 5990: }
 5991: 
 5992: ul.LC_TabContent .right {
 5993: 	float:right;
 5994: }
 5995: 
 5996: ul.LC_TabContent li a, ul.LC_TabContent li {
 5997: 	color:rgb(47,47,47);
 5998: 	text-decoration:none;
 5999: 	font-size:95%;
 6000: 	font-weight:bold;
 6001: 	padding-right: 16px;
 6002: }
 6003: 
 6004: ul.LC_TabContent li:hover, ul.LC_TabContent li.active {
 6005:         background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6006: 	border-bottom:solid 2px #FFFFFF;
 6007: 	padding-right: 16px;
 6008: }
 6009: 
 6010: #maincoursedoc {
 6011: 	clear:both;
 6012: }
 6013: 
 6014: ul.LC_TabContentBigger {
 6015:         display:block;
 6016:         list-style:none;
 6017:         padding: 0;
 6018: }
 6019: 
 6020: ul.LC_TabContentBigger li {
 6021:         vertical-align:bottom;
 6022:         height: 30px;
 6023:         font-size:110%;
 6024:         font-weight:bold;
 6025:         color: #737373;
 6026: }
 6027: 
 6028: 
 6029: ul.LC_TabContentBigger li a {
 6030:         background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6031: 	height: 30px;
 6032: 	line-height: 30px;
 6033: 	text-align: center;
 6034: 	display: block;
 6035: 	text-decoration: none;
 6036: }
 6037: 
 6038: ul.LC_TabContentBigger li:hover a, 
 6039: ul.LC_TabContentBigger li.active a {
 6040: 	background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6041: 	color:$font;
 6042: 	text-decoration: underline;
 6043: }
 6044: 
 6045: 
 6046: ul.LC_TabContentBigger li b {
 6047: 	background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6048: 	display: block;
 6049: 	float: left;
 6050: 	padding: 0 30px;
 6051: }
 6052: 
 6053: ul.LC_TabContentBigger li:hover b,
 6054: ul.LC_TabContentBigger li.active b {
 6055:         background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6056:         color:$font;
 6057: 	border-bottom: 1px solid #FFFFFF;
 6058: }
 6059: 
 6060: 
 6061: ul.LC_CourseBreadcrumbs {
 6062:   background: $sidebg;
 6063:   line-height: 32px;
 6064:   padding-left: 10px;
 6065:   margin: 0 0 10px 0;
 6066:   list-style-position: inside;
 6067: 
 6068: }
 6069: 
 6070: ol#LC_MenuBreadcrumbs, 
 6071: ol#LC_PathBreadcrumbs {
 6072: 	padding-left: 10px;
 6073: 	margin: 0;
 6074: 	list-style-position: inside;
 6075: }
 6076: 
 6077: ol#LC_MenuBreadcrumbs li, 
 6078: ol#LC_PathBreadcrumbs li, 
 6079: ul.LC_CourseBreadcrumbs li {
 6080:     display: inline;
 6081:     white-space: nowrap;
 6082: }
 6083: 
 6084: ol#LC_MenuBreadcrumbs li a,
 6085: ul.LC_CourseBreadcrumbs li a {
 6086: 	text-decoration: none;
 6087: 	font-size:90%;
 6088: }
 6089: 
 6090: ol#LC_PathBreadcrumbs li a {
 6091: 	text-decoration:none;
 6092: 	font-size:100%;
 6093: 	font-weight:bold;
 6094: }
 6095: 
 6096: .LC_Box {
 6097:     border: solid 1px $lg_border_color;
 6098:     padding: 0 10px 10px 10px;
 6099: }
 6100: 
 6101: .LC_AboutMe_Image {
 6102: 	float:left;
 6103: 	margin-right:10px;
 6104: }
 6105: 
 6106: .LC_Clear_AboutMe_Image {
 6107: 	clear:left;
 6108: }
 6109: 
 6110: dl.LC_ListStyleClean dt {
 6111: 	padding-right: 5px;
 6112: 	display: table-header-group;
 6113: }
 6114: 
 6115: dl.LC_ListStyleClean dd {
 6116: 	display: table-row;
 6117: }
 6118: 
 6119: .LC_ListStyleClean,
 6120: .LC_ListStyleSimple,
 6121: .LC_ListStyleNormal,
 6122: .LC_ListStyle_Border,
 6123: .LC_ListStyleSpecial {
 6124: 	/*display:block;	*/
 6125: 	list-style-position: inside;
 6126: 	list-style-type: none;
 6127: 	overflow: hidden;
 6128: 	padding: 0;
 6129: }
 6130: 
 6131: .LC_ListStyleSimple li,
 6132: .LC_ListStyleSimple dd,
 6133: .LC_ListStyleNormal li,
 6134: .LC_ListStyleNormal dd,
 6135: .LC_ListStyleSpecial li,
 6136: .LC_ListStyleSpecial dd {
 6137: 	margin: 0;
 6138: 	padding: 5px 5px 5px 10px;
 6139: 	clear: both;
 6140: }
 6141: 
 6142: .LC_ListStyleClean li,
 6143: .LC_ListStyleClean dd {
 6144: 	padding-top: 0;
 6145: 	padding-bottom: 0;
 6146: }
 6147: 
 6148: .LC_ListStyleSimple dd,
 6149: .LC_ListStyleSimple li {
 6150: 	border-bottom: solid 1px $lg_border_color;
 6151: }
 6152: 
 6153: .LC_ListStyleSpecial li,
 6154: .LC_ListStyleSpecial dd {
 6155: 	list-style-type: none;
 6156: 	background-color: RGB(220, 220, 220);
 6157: 	margin-bottom: 4px;
 6158: }
 6159: 
 6160: table.LC_SimpleTable {
 6161: 	margin:5px;
 6162: 	border:solid 1px $lg_border_color;
 6163: }
 6164: 
 6165: table.LC_SimpleTable tr {
 6166: 	padding: 0;
 6167: 	border:solid 1px $lg_border_color;
 6168: }
 6169: 
 6170: table.LC_SimpleTable thead {
 6171: 	 background:rgb(220,220,220);
 6172: }
 6173: 
 6174: div.LC_columnSection {
 6175: 	display: block;
 6176: 	clear: both;
 6177: 	overflow: hidden;
 6178: 	margin: 0;
 6179: }
 6180: 
 6181: div.LC_columnSection>* {
 6182: 	float: left;
 6183: 	margin: 10px 20px 10px 0;
 6184: 	overflow:hidden;
 6185: }
 6186: 
 6187: .LC_loginpage_container {
 6188: 	text-align:left;
 6189: 	margin : 0 auto;
 6190: 	width:90%;
 6191: 	padding: 10px;
 6192: 	height: auto;
 6193: 	background-color:#FFFFFF;
 6194: 	border:1px solid #CCCCCC;
 6195: }
 6196: 
 6197: 
 6198: .LC_loginpage_loginContainer {
 6199: 	float:left;
 6200: 	width: 182px;
 6201: 	padding: 2px;
 6202: 	border:1px solid #CCCCCC;
 6203: 	background-color:$loginbg;
 6204: }
 6205: 
 6206: .LC_loginpage_loginContainer h2 {
 6207: 	margin-top: 0;
 6208: 	display:block;
 6209: 	background:$bgcol;
 6210: 	color:$textcol;
 6211: 	padding-left:5px;
 6212: }
 6213: 
 6214: .LC_loginpage_loginInfo {
 6215: 	float:left;
 6216: 	width:182px;
 6217: 	border:1px solid #CCCCCC;
 6218: 	padding:2px;
 6219: }
 6220: 
 6221: .LC_loginpage_space {
 6222: 	clear: both;
 6223: 	margin-bottom: 20px;
 6224: 	border-bottom: 1px solid #CCCCCC;
 6225: }
 6226: 
 6227: .LC_loginpage_floatLeft {
 6228: 	float: left;
 6229: 	width: 200px;
 6230: 	margin: 0;
 6231: }
 6232: 
 6233: table em {
 6234: 	font-weight: bold;
 6235: 	font-style: normal;
 6236: }
 6237: 
 6238: table.LC_tableBrowseRes,
 6239: table.LC_tableOfContent {
 6240:         border:none;
 6241: 	border-spacing: 1px;
 6242: 	padding: 3px;
 6243: 	background-color: #FFFFFF;
 6244: 	font-size: 90%;
 6245: }
 6246: 
 6247: table.LC_tableOfContent{
 6248:     border-collapse: collapse;
 6249: }
 6250: 
 6251: table.LC_tableBrowseRes a,
 6252: table.LC_tableOfContent a {
 6253:         background-color: transparent;
 6254: 	text-decoration: none;
 6255: }
 6256: 
 6257: table.LC_tableBrowseRes tr.LC_trOdd,
 6258: table.LC_tableOfContent tr.LC_trOdd{
 6259: 	background-color: #EEEEEE;
 6260: }
 6261: 
 6262: table.LC_tableOfContent img {
 6263: 	border: none;
 6264: 	height: 1.3em;
 6265: 	vertical-align: text-bottom;
 6266: 	margin-right: 0.3em;
 6267: }
 6268: 
 6269: a#LC_content_toolbar_firsthomework {
 6270: 	background-image:url(/res/adm/pages/open-first-problem.gif);
 6271: }
 6272: 
 6273: a#LC_content_toolbar_launchnav {
 6274: 	background-image:url(/res/adm/pages/start-navigation.gif);
 6275: }
 6276: 
 6277: a#LC_content_toolbar_closenav {
 6278: 	background-image:url(/res/adm/pages/close-navigation.gif);
 6279: }
 6280: 
 6281: a#LC_content_toolbar_everything {
 6282: 	background-image:url(/res/adm/pages/show-all.gif);
 6283: }
 6284: 
 6285: a#LC_content_toolbar_uncompleted {
 6286: 	background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 6287: }
 6288: 
 6289: #LC_content_toolbar_clearbubbles {
 6290: 	background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 6291: }
 6292: 
 6293: a#LC_content_toolbar_changefolder {
 6294: 	background : url(/res/adm/pages/close-all-folders.gif) top center ;
 6295: }
 6296: 
 6297: a#LC_content_toolbar_changefolder_toggled {
 6298: 	background-image:url(/res/adm/pages/open-all-folders.gif);
 6299: }
 6300: 
 6301: ul#LC_toolbar li a:hover {
 6302: 	background-position: bottom center;
 6303: }
 6304: 
 6305: ul#LC_toolbar {
 6306: 	padding: 0;
 6307: 	margin: 2px;
 6308: 	list-style:none;
 6309: 	position:relative;
 6310: 	background-color:white;
 6311: }
 6312: 
 6313: ul#LC_toolbar li {
 6314: 	border:1px solid white;
 6315: 	padding: 0;
 6316: 	margin: 0;
 6317:         float: left;
 6318: 	display:inline;
 6319: 	vertical-align:middle;
 6320: } 
 6321: 
 6322: 
 6323: a.LC_toolbarItem {
 6324: 	display:block;
 6325: 	padding: 0;
 6326: 	margin: 0;
 6327: 	height: 32px;
 6328: 	width: 32px;
 6329: 	color:white;
 6330: 	border: none;
 6331: 	background-repeat:no-repeat;
 6332: 	background-color:transparent;
 6333: }
 6334: 
 6335: ul.LC_funclist li {
 6336:   float: left;
 6337:   white-space: nowrap;
 6338:   height: 35px; /* at least as high as heighest list item */
 6339:   margin: 0 15px 15px 10px;
 6340: }
 6341: 
 6342: 
 6343: END
 6344: }
 6345: 
 6346: =pod
 6347: 
 6348: =item * &headtag()
 6349: 
 6350: Returns a uniform footer for LON-CAPA web pages.
 6351: 
 6352: Inputs: $title - optional title for the head
 6353:         $head_extra - optional extra HTML to put inside the <head>
 6354:         $args - optional arguments
 6355:             force_register - if is true call registerurl so the remote is 
 6356:                              informed
 6357:             redirect       -> array ref of
 6358:                                    1- seconds before redirect occurs
 6359:                                    2- url to redirect to
 6360:                                    3- whether the side effect should occur
 6361:                            (side effect of setting 
 6362:                                $env{'internal.head.redirect'} to the url 
 6363:                                redirected too)
 6364:             domain         -> force to color decorate a page for a specific
 6365:                                domain
 6366:             function       -> force usage of a specific rolish color scheme
 6367:             bgcolor        -> override the default page bgcolor
 6368:             no_auto_mt_title
 6369:                            -> prevent &mt()ing the title arg
 6370: 
 6371: =cut
 6372: 
 6373: sub headtag {
 6374:     my ($title,$head_extra,$args) = @_;
 6375:     
 6376:     my $function = $args->{'function'} || &get_users_function();
 6377:     my $domain   = $args->{'domain'}   || &determinedomain();
 6378:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 6379:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 6380: 		   $Apache::lonnet::perlvar{'lonVersion'},
 6381: 		   #time(),
 6382: 		   $env{'environment.color.timestamp'},
 6383: 		   $function,$domain,$bgcolor);
 6384: 
 6385:     $url = '/adm/css/'.&escape($url).'.css';
 6386: 
 6387:     my $result =
 6388: 	'<head>'.
 6389: 	&font_settings();
 6390: 
 6391:     if (!$args->{'frameset'}) {
 6392: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 6393:     }
 6394:     if ($args->{'force_register'}) {
 6395: 	$result .= &Apache::lonmenu::registerurl(1);
 6396:     }
 6397:     if (!$args->{'no_nav_bar'} 
 6398: 	&& !$args->{'only_body'}
 6399: 	&& !$args->{'frameset'}) {
 6400: 	$result .= &help_menu_js();
 6401:     }
 6402: 
 6403:     if (ref($args->{'redirect'})) {
 6404: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 6405: 	$url = &Apache::lonenc::check_encrypt($url);
 6406: 	if (!$inhibit_continue) {
 6407: 	    $env{'internal.head.redirect'} = $url;
 6408: 	}
 6409: 	$result.=<<ADDMETA
 6410: <meta http-equiv="pragma" content="no-cache" />
 6411: <meta http-equiv="Refresh" content="$time; url=$url" />
 6412: ADDMETA
 6413:     }
 6414:     if (!defined($title)) {
 6415: 	$title = 'The LearningOnline Network with CAPA';
 6416:     }
 6417:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 6418:     $result .= '<title> LON-CAPA '.$title.'</title>'
 6419: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 6420: 	.$head_extra;
 6421:     return $result;
 6422: }
 6423: 
 6424: =pod
 6425: 
 6426: =item * &font_settings()
 6427: 
 6428: Returns neccessary <meta> to set the proper encoding
 6429: 
 6430: Inputs: none
 6431: 
 6432: =cut
 6433: 
 6434: sub font_settings {
 6435:     my $headerstring='';
 6436:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 6437: 	$headerstring.=
 6438: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 6439:     }
 6440:     return $headerstring;
 6441: }
 6442: 
 6443: =pod
 6444: 
 6445: =item * &xml_begin()
 6446: 
 6447: Returns the needed doctype and <html>
 6448: 
 6449: Inputs: none
 6450: 
 6451: =cut
 6452: 
 6453: sub xml_begin {
 6454:     my $output='';
 6455: 
 6456:     if ($env{'internal.start_page'}==1) {
 6457: 	&Apache::lonhtmlcommon::init_htmlareafields();
 6458:     }
 6459: 
 6460:     if ($env{'browser.mathml'}) {
 6461: 	$output='<?xml version="1.0"?>'
 6462:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 6463: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 6464:             
 6465: #	    .'<!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">] >'
 6466: 	    .'<!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">'
 6467:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 6468: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 6469:     } else {
 6470: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 6471:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 6472:     }
 6473:     return $output;
 6474: }
 6475: 
 6476: =pod
 6477: 
 6478: =item * &endheadtag()
 6479: 
 6480: Returns a uniform </head> for LON-CAPA web pages.
 6481: 
 6482: Inputs: none
 6483: 
 6484: =cut
 6485: 
 6486: sub endheadtag {
 6487:     return '</head>';
 6488: }
 6489: 
 6490: =pod
 6491: 
 6492: =item * &head()
 6493: 
 6494: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 6495: 
 6496: Inputs:
 6497: 
 6498: =over 4
 6499: 
 6500: $title - optional title for the page
 6501: 
 6502: $head_extra - optional extra HTML to put inside the <head>
 6503: 
 6504: =back
 6505: 
 6506: =cut
 6507: 
 6508: sub head {
 6509:     my ($title,$head_extra,$args) = @_;
 6510:     return &headtag($title,$head_extra,$args).&endheadtag();
 6511: }
 6512: 
 6513: =pod
 6514: 
 6515: =item * &start_page()
 6516: 
 6517: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 6518: 
 6519: Inputs:
 6520: 
 6521: =over 4
 6522: 
 6523: $title - optional title for the page
 6524: 
 6525: $head_extra - optional extra HTML to incude inside the <head>
 6526: 
 6527: $args - additional optional args supported are:
 6528: 
 6529: =over 8
 6530: 
 6531:              only_body      -> is true will set &bodytag() onlybodytag
 6532:                                     arg on
 6533:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 6534:              add_entries    -> additional attributes to add to the  <body>
 6535:              domain         -> force to color decorate a page for a 
 6536:                                     specific domain
 6537:              function       -> force usage of a specific rolish color
 6538:                                     scheme
 6539:              redirect       -> see &headtag()
 6540:              bgcolor        -> override the default page bg color
 6541:              js_ready       -> return a string ready for being used in 
 6542:                                     a javascript writeln
 6543:              html_encode    -> return a string ready for being used in 
 6544:                                     a html attribute
 6545:              force_register -> if is true will turn on the &bodytag()
 6546:                                     $forcereg arg
 6547:              frameset       -> if true will start with a <frameset>
 6548:                                     rather than <body>
 6549:              skip_phases    -> hash ref of 
 6550:                                     head -> skip the <html><head> generation
 6551:                                     body -> skip all <body> generation
 6552:              no_inline_link -> if true and in remote mode, don't show the 
 6553:                                     'Switch To Inline Menu' link
 6554:              no_auto_mt_title -> prevent &mt()ing the title arg
 6555:              inherit_jsmath -> when creating popup window in a page,
 6556:                                     should it have jsmath forced on by the
 6557:                                     current page
 6558:              bread_crumbs ->             Array containing breadcrumbs
 6559:              bread_crumbs_components ->  if exists show it as headline else show only the breadcrumbs
 6560: 
 6561: =back
 6562: 
 6563: =back
 6564: 
 6565: =cut
 6566: 
 6567: sub start_page {
 6568:     my ($title,$head_extra,$args) = @_;
 6569:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 6570:     my %head_args;
 6571:     foreach my $arg ('redirect','force_register','domain','function',
 6572: 		     'bgcolor','frameset','no_nav_bar','only_body',
 6573: 		     'no_auto_mt_title') {
 6574: 	if (defined($args->{$arg})) {
 6575: 	    $head_args{$arg} = $args->{$arg};
 6576: 	}
 6577:     }
 6578: 
 6579:     $env{'internal.start_page'}++;
 6580:     my $result;
 6581:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6582: 	$result.=
 6583: 	    &xml_begin().
 6584: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6585:     }
 6586:     
 6587:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6588: 	if ($args->{'frameset'}) {
 6589: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6590: 						$args->{'add_entries'});
 6591: 	    $result .= "\n<frameset $attr_string>\n";
 6592:         } else {
 6593:             $result .=
 6594:                 &bodytag($title, 
 6595:                          $args->{'function'},       $args->{'add_entries'},
 6596:                          $args->{'only_body'},      $args->{'domain'},
 6597:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 6598:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 6599:                          $args);
 6600:         }
 6601:     }
 6602: 
 6603:     if ($args->{'js_ready'}) {
 6604: 		$result = &js_ready($result);
 6605:     }
 6606:     if ($args->{'html_encode'}) {
 6607: 		$result = &html_encode($result);
 6608:     }
 6609: 
 6610:     # Preparation for new and consistent functionlist at top of screen
 6611:     # if ($args->{'functionlist'}) {
 6612:     #            $result .= &build_functionlist();
 6613:     #}
 6614: 
 6615:     # Don't add anything more if only_body wanted
 6616:     return $result if $args->{'only_body'};
 6617: 
 6618:     #Breadcrumbs
 6619:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6620: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 6621: 		#if any br links exists, add them to the breadcrumbs
 6622: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 6623: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6624: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6625: 			}
 6626: 		}
 6627: 
 6628: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6629: 		if(exists($args->{'bread_crumbs_component'})){
 6630: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6631: 		}else{
 6632: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 6633: 		}
 6634:     }
 6635:     return $result;
 6636: }
 6637: 
 6638: 
 6639: =pod
 6640: 
 6641: =item * &head()
 6642: 
 6643: Returns a complete </body></html> section for LON-CAPA web pages.
 6644: 
 6645: Inputs:         $args - additional optional args supported are:
 6646:                  js_ready     -> return a string ready for being used in 
 6647:                                  a javascript writeln
 6648:                  html_encode  -> return a string ready for being used in 
 6649:                                  a html attribute
 6650:                  frameset     -> if true will start with a <frameset>
 6651:                                  rather than <body>
 6652:                  dicsussion   -> if true will get discussion from
 6653:                                   lonxml::xmlend
 6654:                                  (you can pass the target and parser arguments
 6655:                                   through optional 'target' and 'parser' args
 6656:                                   to this routine)
 6657: 
 6658: =cut
 6659: 
 6660: sub end_page {
 6661:     my ($args) = @_;
 6662:     $env{'internal.end_page'}++;
 6663:     my $result;
 6664:     if ($args->{'discussion'}) {
 6665: 	my ($target,$parser);
 6666: 	if (ref($args->{'discussion'})) {
 6667: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6668: 				$args->{'discussion'}{'parser'});
 6669: 	}
 6670: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6671:     }
 6672: 
 6673:     if ($args->{'frameset'}) {
 6674: 	$result .= '</frameset>';
 6675:     } else {
 6676: 	$result .= &endbodytag($args);
 6677:     }
 6678:     $result .= "\n</html>";
 6679: 
 6680:     if ($args->{'js_ready'}) {
 6681: 	$result = &js_ready($result);
 6682:     }
 6683: 
 6684:     if ($args->{'html_encode'}) {
 6685: 	$result = &html_encode($result);
 6686:     }
 6687: 
 6688:     return $result;
 6689: }
 6690: 
 6691: sub html_encode {
 6692:     my ($result) = @_;
 6693: 
 6694:     $result = &HTML::Entities::encode($result,'<>&"');
 6695:     
 6696:     return $result;
 6697: }
 6698: sub js_ready {
 6699:     my ($result) = @_;
 6700: 
 6701:     $result =~ s/[\n\r]/ /xmsg;
 6702:     $result =~ s/\\/\\\\/xmsg;
 6703:     $result =~ s/'/\\'/xmsg;
 6704:     $result =~ s{</}{<\\/}xmsg;
 6705:     
 6706:     return $result;
 6707: }
 6708: 
 6709: sub validate_page {
 6710:     if (  exists($env{'internal.start_page'})
 6711: 	  &&     $env{'internal.start_page'} > 1) {
 6712: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6713: 				 $env{'internal.start_page'}.' '.
 6714: 				 $ENV{'request.filename'});
 6715:     }
 6716:     if (  exists($env{'internal.end_page'})
 6717: 	  &&     $env{'internal.end_page'} > 1) {
 6718: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6719: 				 $env{'internal.end_page'}.' '.
 6720: 				 $env{'request.filename'});
 6721:     }
 6722:     if (     exists($env{'internal.start_page'})
 6723: 	&& ! exists($env{'internal.end_page'})) {
 6724: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6725: 				 $env{'request.filename'});
 6726:     }
 6727:     if (   ! exists($env{'internal.start_page'})
 6728: 	&&   exists($env{'internal.end_page'})) {
 6729: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6730: 				 $env{'request.filename'});
 6731:     }
 6732: }
 6733: 
 6734: sub simple_error_page {
 6735:     my ($r,$title,$msg) = @_;
 6736:     my $page =
 6737: 	&Apache::loncommon::start_page($title).
 6738: 	&mt($msg).
 6739: 	&Apache::loncommon::end_page();
 6740:     if (ref($r)) {
 6741: 	$r->print($page);
 6742: 	return;
 6743:     }
 6744:     return $page;
 6745: }
 6746: 
 6747: {
 6748:     my @row_count;
 6749:     sub start_data_table {
 6750: 	my ($add_class) = @_;
 6751: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6752: 	unshift(@row_count,0);
 6753: 	return '<table class="'.$css_class.'">'."\n";
 6754:     }
 6755: 
 6756:     sub end_data_table {
 6757: 	shift(@row_count);
 6758: 	return '</table>'."\n";;
 6759:     }
 6760: 
 6761:     sub start_data_table_row {
 6762: 	my ($add_class) = @_;
 6763: 	$row_count[0]++;
 6764: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6765: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 6766: 	return  '<tr class="'.$css_class.'">'."\n";;
 6767:     }
 6768:     
 6769:     sub continue_data_table_row {
 6770: 	my ($add_class) = @_;
 6771: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6772: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');;
 6773: 	return  '<tr class="'.$css_class.'">'."\n";;
 6774:     }
 6775: 
 6776:     sub end_data_table_row {
 6777: 	return '</tr>'."\n";;
 6778:     }
 6779: 
 6780:     sub start_data_table_empty_row {
 6781: #	$row_count[0]++;
 6782: 	return  '<tr class="LC_empty_row" >'."\n";;
 6783:     }
 6784: 
 6785:     sub end_data_table_empty_row {
 6786: 	return '</tr>'."\n";;
 6787:     }
 6788: 
 6789:     sub start_data_table_header_row {
 6790: 	return  '<tr class="LC_header_row">'."\n";;
 6791:     }
 6792: 
 6793:     sub end_data_table_header_row {
 6794: 	return '</tr>'."\n";;
 6795:     }
 6796: 
 6797:     sub data_table_caption {
 6798:         my $caption = shift;
 6799:         return "<caption class=\"LC_caption\">$caption</caption>";
 6800:     }
 6801: }
 6802: 
 6803: =pod
 6804: 
 6805: =item * &inhibit_menu_check($arg)
 6806: 
 6807: Checks for a inhibitmenu state and generates output to preserve it
 6808: 
 6809: Inputs:         $arg - can be any of
 6810:                      - undef - in which case the return value is a string 
 6811:                                to add  into arguments list of a uri
 6812:                      - 'input' - in which case the return value is a HTML
 6813:                                  <form> <input> field of type hidden to
 6814:                                  preserve the value
 6815:                      - a url - in which case the return value is the url with
 6816:                                the neccesary cgi args added to preserve the
 6817:                                inhibitmenu state
 6818:                      - a ref to a url - no return value, but the string is
 6819:                                         updated to include the neccessary cgi
 6820:                                         args to preserve the inhibitmenu state
 6821: 
 6822: =cut
 6823: 
 6824: sub inhibit_menu_check {
 6825:     my ($arg) = @_;
 6826:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6827:     if ($arg eq 'input') {
 6828: 	if ($env{'form.inhibitmenu'}) {
 6829: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6830: 	} else {
 6831: 	    return
 6832: 	}
 6833:     }
 6834:     if ($env{'form.inhibitmenu'}) {
 6835: 	if (ref($arg)) {
 6836: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6837: 	} elsif ($arg eq '') {
 6838: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6839: 	} else {
 6840: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6841: 	}
 6842:     }
 6843:     if (!ref($arg)) {
 6844: 	return $arg;
 6845:     }
 6846: }
 6847: 
 6848: ###############################################
 6849: 
 6850: =pod
 6851: 
 6852: =back
 6853: 
 6854: =head1 User Information Routines
 6855: 
 6856: =over 4
 6857: 
 6858: =item * &get_users_function()
 6859: 
 6860: Used by &bodytag to determine the current users primary role.
 6861: Returns either 'student','coordinator','admin', or 'author'.
 6862: 
 6863: =cut
 6864: 
 6865: ###############################################
 6866: sub get_users_function {
 6867:     my $function = 'norole';
 6868:     if ($env{'request.role'}=~/^(st)/) {
 6869:         $function='student';
 6870:     }
 6871:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6872:         $function='coordinator';
 6873:     }
 6874:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6875:         $function='admin';
 6876:     }
 6877:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 6878:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6879:         $function='author';
 6880:     }
 6881:     return $function;
 6882: }
 6883: 
 6884: ###############################################
 6885: 
 6886: =pod
 6887: 
 6888: =item * &show_course()
 6889: 
 6890: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 6891: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 6892: 
 6893: Inputs:
 6894: None
 6895: 
 6896: Outputs:
 6897: Scalar: 1 if 'Course' to be used, 0 otherwise.
 6898: 
 6899: =cut
 6900: 
 6901: ###############################################
 6902: sub show_course {
 6903:     my $course = !$env{'user.adv'};
 6904:     if (!$env{'user.adv'}) {
 6905:         foreach my $env (keys(%env)) {
 6906:             next if ($env !~ m/^user\.priv\./);
 6907:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 6908:                 $course = 0;
 6909:                 last;
 6910:             }
 6911:         }
 6912:     }
 6913:     return $course;
 6914: }
 6915: 
 6916: ###############################################
 6917: 
 6918: =pod
 6919: 
 6920: =item * &check_user_status()
 6921: 
 6922: Determines current status of supplied role for a
 6923: specific user. Roles can be active, previous or future.
 6924: 
 6925: Inputs: 
 6926: user's domain, user's username, course's domain,
 6927: course's number, optional section ID.
 6928: 
 6929: Outputs:
 6930: role status: active, previous or future. 
 6931: 
 6932: =cut
 6933: 
 6934: sub check_user_status {
 6935:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6936:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6937:     my @uroles = keys %userinfo;
 6938:     my $srchstr;
 6939:     my $active_chk = 'none';
 6940:     my $now = time;
 6941:     if (@uroles > 0) {
 6942:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6943:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6944:         } else {
 6945:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6946:         }
 6947:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6948:             my $role_end = 0;
 6949:             my $role_start = 0;
 6950:             $active_chk = 'active';
 6951:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6952:                 $role_end = $1;
 6953:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6954:                     $role_start = $1;
 6955:                 }
 6956:             }
 6957:             if ($role_start > 0) {
 6958:                 if ($now < $role_start) {
 6959:                     $active_chk = 'future';
 6960:                 }
 6961:             }
 6962:             if ($role_end > 0) {
 6963:                 if ($now > $role_end) {
 6964:                     $active_chk = 'previous';
 6965:                 }
 6966:             }
 6967:         }
 6968:     }
 6969:     return $active_chk;
 6970: }
 6971: 
 6972: ###############################################
 6973: 
 6974: =pod
 6975: 
 6976: =item * &get_sections()
 6977: 
 6978: Determines all the sections for a course including
 6979: sections with students and sections containing other roles.
 6980: Incoming parameters: 
 6981: 
 6982: 1. domain
 6983: 2. course number 
 6984: 3. reference to array containing roles for which sections should 
 6985: be gathered (optional).
 6986: 4. reference to array containing status types for which sections 
 6987: should be gathered (optional).
 6988: 
 6989: If the third argument is undefined, sections are gathered for any role. 
 6990: If the fourth argument is undefined, sections are gathered for any status.
 6991: Permissible values are 'active' or 'future' or 'previous'.
 6992:  
 6993: Returns section hash (keys are section IDs, values are
 6994: number of users in each section), subject to the
 6995: optional roles filter, optional status filter 
 6996: 
 6997: =cut
 6998: 
 6999: ###############################################
 7000: sub get_sections {
 7001:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 7002:     if (!defined($cdom) || !defined($cnum)) {
 7003:         my $cid =  $env{'request.course.id'};
 7004: 
 7005: 	return if (!defined($cid));
 7006: 
 7007:         $cdom = $env{'course.'.$cid.'.domain'};
 7008:         $cnum = $env{'course.'.$cid.'.num'};
 7009:     }
 7010: 
 7011:     my %sectioncount;
 7012:     my $now = time;
 7013: 
 7014:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 7015: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 7016: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 7017: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 7018:         my $start_index = &Apache::loncoursedata::CL_START();
 7019:         my $end_index = &Apache::loncoursedata::CL_END();
 7020:         my $status;
 7021: 	while (my ($student,$data) = each(%$classlist)) {
 7022: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 7023: 				                     $data->[$status_index],
 7024:                                                      $data->[$start_index],
 7025:                                                      $data->[$end_index]);
 7026:             if ($stu_status eq 'Active') {
 7027:                 $status = 'active';
 7028:             } elsif ($end < $now) {
 7029:                 $status = 'previous';
 7030:             } elsif ($start > $now) {
 7031:                 $status = 'future';
 7032:             } 
 7033: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 7034:                 if ((!defined($possible_status)) || (($status ne '') && 
 7035:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 7036: 		    $sectioncount{$section}++;
 7037:                 }
 7038: 	    }
 7039: 	}
 7040:     }
 7041:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7042:     foreach my $user (sort(keys(%courseroles))) {
 7043: 	if ($user !~ /^(\w{2})/) { next; }
 7044: 	my ($role) = ($user =~ /^(\w{2})/);
 7045: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 7046: 	my ($section,$status);
 7047: 	if ($role eq 'cr' &&
 7048: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 7049: 	    $section=$1;
 7050: 	}
 7051: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 7052: 	if (!defined($section) || $section eq '-1') { next; }
 7053:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 7054:         if ($end == -1 && $start == -1) {
 7055:             next; #deleted role
 7056:         }
 7057:         if (!defined($possible_status)) { 
 7058:             $sectioncount{$section}++;
 7059:         } else {
 7060:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 7061:                 $status = 'active';
 7062:             } elsif ($end < $now) {
 7063:                 $status = 'future';
 7064:             } elsif ($start > $now) {
 7065:                 $status = 'previous';
 7066:             }
 7067:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 7068:                 $sectioncount{$section}++;
 7069:             }
 7070:         }
 7071:     }
 7072:     return %sectioncount;
 7073: }
 7074: 
 7075: ###############################################
 7076: 
 7077: =pod
 7078: 
 7079: =item * &get_course_users()
 7080: 
 7081: Retrieves usernames:domains for users in the specified course
 7082: with specific role(s), and access status. 
 7083: 
 7084: Incoming parameters:
 7085: 1. course domain
 7086: 2. course number
 7087: 3. access status: users must have - either active, 
 7088: previous, future, or all.
 7089: 4. reference to array of permissible roles
 7090: 5. reference to array of section restrictions (optional)
 7091: 6. reference to results object (hash of hashes).
 7092: 7. reference to optional userdata hash
 7093: 8. reference to optional statushash
 7094: 9. flag if privileged users (except those set to unhide in
 7095:    course settings) should be excluded    
 7096: Keys of top level results hash are roles.
 7097: Keys of inner hashes are username:domain, with 
 7098: values set to access type.
 7099: Optional userdata hash returns an array with arguments in the 
 7100: same order as loncoursedata::get_classlist() for student data.
 7101: 
 7102: Optional statushash returns
 7103: 
 7104: Entries for end, start, section and status are blank because
 7105: of the possibility of multiple values for non-student roles.
 7106: 
 7107: =cut
 7108: 
 7109: ###############################################
 7110: 
 7111: sub get_course_users {
 7112:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 7113:     my %idx = ();
 7114:     my %seclists;
 7115: 
 7116:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 7117:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 7118:     $idx{end} = &Apache::loncoursedata::CL_END();
 7119:     $idx{start} = &Apache::loncoursedata::CL_START();
 7120:     $idx{id} = &Apache::loncoursedata::CL_ID();
 7121:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 7122:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 7123:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 7124: 
 7125:     if (grep(/^st$/,@{$roles})) {
 7126:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 7127:         my $now = time;
 7128:         foreach my $student (keys(%{$classlist})) {
 7129:             my $match = 0;
 7130:             my $secmatch = 0;
 7131:             my $section = $$classlist{$student}[$idx{section}];
 7132:             my $status = $$classlist{$student}[$idx{status}];
 7133:             if ($section eq '') {
 7134:                 $section = 'none';
 7135:             }
 7136:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7137:                 if (grep(/^all$/,@{$sections})) {
 7138:                     $secmatch = 1;
 7139:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 7140:                     if (grep(/^none$/,@{$sections})) {
 7141:                         $secmatch = 1;
 7142:                     }
 7143:                 } else {  
 7144: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 7145: 		        $secmatch = 1;
 7146:                     }
 7147: 		}
 7148:                 if (!$secmatch) {
 7149:                     next;
 7150:                 }
 7151:             }
 7152:             if (defined($$types{'active'})) {
 7153:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 7154:                     push(@{$$users{st}{$student}},'active');
 7155:                     $match = 1;
 7156:                 }
 7157:             }
 7158:             if (defined($$types{'previous'})) {
 7159:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 7160:                     push(@{$$users{st}{$student}},'previous');
 7161:                     $match = 1;
 7162:                 }
 7163:             }
 7164:             if (defined($$types{'future'})) {
 7165:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 7166:                     push(@{$$users{st}{$student}},'future');
 7167:                     $match = 1;
 7168:                 }
 7169:             }
 7170:             if ($match) {
 7171:                 push(@{$seclists{$student}},$section);
 7172:                 if (ref($userdata) eq 'HASH') {
 7173:                     $$userdata{$student} = $$classlist{$student};
 7174:                 }
 7175:                 if (ref($statushash) eq 'HASH') {
 7176:                     $statushash->{$student}{'st'}{$section} = $status;
 7177:                 }
 7178:             }
 7179:         }
 7180:     }
 7181:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 7182:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7183:         my $now = time;
 7184:         my %displaystatus = ( previous => 'Expired',
 7185:                               active   => 'Active',
 7186:                               future   => 'Future',
 7187:                             );
 7188:         my %nothide;
 7189:         if ($hidepriv) {
 7190:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 7191:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 7192:                 if ($user !~ /:/) {
 7193:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 7194:                 } else {
 7195:                     $nothide{$user} = 1;
 7196:                 }
 7197:             }
 7198:         }
 7199:         foreach my $person (sort(keys(%coursepersonnel))) {
 7200:             my $match = 0;
 7201:             my $secmatch = 0;
 7202:             my $status;
 7203:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 7204:             $user =~ s/:$//;
 7205:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 7206:             if ($end == -1 || $start == -1) {
 7207:                 next;
 7208:             }
 7209:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 7210:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 7211:                 my ($uname,$udom) = split(/:/,$user);
 7212:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 7213:                     if (grep(/^all$/,@{$sections})) {
 7214:                         $secmatch = 1;
 7215:                     } elsif ($usec eq '') {
 7216:                         if (grep(/^none$/,@{$sections})) {
 7217:                             $secmatch = 1;
 7218:                         }
 7219:                     } else {
 7220:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 7221:                             $secmatch = 1;
 7222:                         }
 7223:                     }
 7224:                     if (!$secmatch) {
 7225:                         next;
 7226:                     }
 7227:                 }
 7228:                 if ($usec eq '') {
 7229:                     $usec = 'none';
 7230:                 }
 7231:                 if ($uname ne '' && $udom ne '') {
 7232:                     if ($hidepriv) {
 7233:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 7234:                             (!$nothide{$uname.':'.$udom})) {
 7235:                             next;
 7236:                         }
 7237:                     }
 7238:                     if ($end > 0 && $end < $now) {
 7239:                         $status = 'previous';
 7240:                     } elsif ($start > $now) {
 7241:                         $status = 'future';
 7242:                     } else {
 7243:                         $status = 'active';
 7244:                     }
 7245:                     foreach my $type (keys(%{$types})) { 
 7246:                         if ($status eq $type) {
 7247:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 7248:                                 push(@{$$users{$role}{$user}},$type);
 7249:                             }
 7250:                             $match = 1;
 7251:                         }
 7252:                     }
 7253:                     if (($match) && (ref($userdata) eq 'HASH')) {
 7254:                         if (!exists($$userdata{$uname.':'.$udom})) {
 7255: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 7256:                         }
 7257:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 7258:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 7259:                         }
 7260:                         if (ref($statushash) eq 'HASH') {
 7261:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 7262:                         }
 7263:                     }
 7264:                 }
 7265:             }
 7266:         }
 7267:         if (grep(/^ow$/,@{$roles})) {
 7268:             if ((defined($cdom)) && (defined($cnum))) {
 7269:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 7270:                 if ( defined($csettings{'internal.courseowner'}) ) {
 7271:                     my $owner = $csettings{'internal.courseowner'};
 7272:                     next if ($owner eq '');
 7273:                     my ($ownername,$ownerdom);
 7274:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 7275:                         $ownername = $1;
 7276:                         $ownerdom = $2;
 7277:                     } else {
 7278:                         $ownername = $owner;
 7279:                         $ownerdom = $cdom;
 7280:                         $owner = $ownername.':'.$ownerdom;
 7281:                     }
 7282:                     @{$$users{'ow'}{$owner}} = 'any';
 7283:                     if (defined($userdata) && 
 7284: 			!exists($$userdata{$owner})) {
 7285: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 7286:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 7287:                             push(@{$seclists{$owner}},'none');
 7288:                         }
 7289:                         if (ref($statushash) eq 'HASH') {
 7290:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 7291:                         }
 7292: 		    }
 7293:                 }
 7294:             }
 7295:         }
 7296:         foreach my $user (keys(%seclists)) {
 7297:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 7298:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 7299:         }
 7300:     }
 7301:     return;
 7302: }
 7303: 
 7304: sub get_user_info {
 7305:     my ($udom,$uname,$idx,$userdata) = @_;
 7306:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 7307: 	&plainname($uname,$udom,'lastname');
 7308:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 7309:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 7310:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 7311:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 7312:     return;
 7313: }
 7314: 
 7315: ###############################################
 7316: 
 7317: =pod
 7318: 
 7319: =item * &get_user_quota()
 7320: 
 7321: Retrieves quota assigned for storage of portfolio files for a user  
 7322: 
 7323: Incoming parameters:
 7324: 1. user's username
 7325: 2. user's domain
 7326: 
 7327: Returns:
 7328: 1. Disk quota (in Mb) assigned to student.
 7329: 2. (Optional) Type of setting: custom or default
 7330:    (individually assigned or default for user's 
 7331:    institutional status).
 7332: 3. (Optional) - User's institutional status (e.g., faculty, staff
 7333:    or student - types as defined in localenroll::inst_usertypes 
 7334:    for user's domain, which determines default quota for user.
 7335: 4. (Optional) - Default quota which would apply to the user.
 7336: 
 7337: If a value has been stored in the user's environment, 
 7338: it will return that, otherwise it returns the maximal default
 7339: defined for the user's instituional status(es) in the domain.
 7340: 
 7341: =cut
 7342: 
 7343: ###############################################
 7344: 
 7345: 
 7346: sub get_user_quota {
 7347:     my ($uname,$udom) = @_;
 7348:     my ($quota,$quotatype,$settingstatus,$defquota);
 7349:     if (!defined($udom)) {
 7350:         $udom = $env{'user.domain'};
 7351:     }
 7352:     if (!defined($uname)) {
 7353:         $uname = $env{'user.name'};
 7354:     }
 7355:     if (($udom eq '' || $uname eq '') ||
 7356:         ($udom eq 'public') && ($uname eq 'public')) {
 7357:         $quota = 0;
 7358:         $quotatype = 'default';
 7359:         $defquota = 0; 
 7360:     } else {
 7361:         my $inststatus;
 7362:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 7363:             $quota = $env{'environment.portfolioquota'};
 7364:             $inststatus = $env{'environment.inststatus'};
 7365:         } else {
 7366:             my %userenv = 
 7367:                 &Apache::lonnet::get('environment',['portfolioquota',
 7368:                                      'inststatus'],$udom,$uname);
 7369:             my ($tmp) = keys(%userenv);
 7370:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7371:                 $quota = $userenv{'portfolioquota'};
 7372:                 $inststatus = $userenv{'inststatus'};
 7373:             } else {
 7374:                 undef(%userenv);
 7375:             }
 7376:         }
 7377:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 7378:         if ($quota eq '') {
 7379:             $quota = $defquota;
 7380:             $quotatype = 'default';
 7381:         } else {
 7382:             $quotatype = 'custom';
 7383:         }
 7384:     }
 7385:     if (wantarray) {
 7386:         return ($quota,$quotatype,$settingstatus,$defquota);
 7387:     } else {
 7388:         return $quota;
 7389:     }
 7390: }
 7391: 
 7392: ###############################################
 7393: 
 7394: =pod
 7395: 
 7396: =item * &default_quota()
 7397: 
 7398: Retrieves default quota assigned for storage of user portfolio files,
 7399: given an (optional) user's institutional status.
 7400: 
 7401: Incoming parameters:
 7402: 1. domain
 7403: 2. (Optional) institutional status(es).  This is a : separated list of 
 7404:    status types (e.g., faculty, staff, student etc.)
 7405:    which apply to the user for whom the default is being retrieved.
 7406:    If the institutional status string in undefined, the domain
 7407:    default quota will be returned. 
 7408: 
 7409: Returns:
 7410: 1. Default disk quota (in Mb) for user portfolios in the domain.
 7411: 2. (Optional) institutional type which determined the value of the
 7412:    default quota.
 7413: 
 7414: If a value has been stored in the domain's configuration db,
 7415: it will return that, otherwise it returns 20 (for backwards 
 7416: compatibility with domains which have not set up a configuration
 7417: db file; the original statically defined portfolio quota was 20 Mb). 
 7418: 
 7419: If the user's status includes multiple types (e.g., staff and student),
 7420: the largest default quota which applies to the user determines the
 7421: default quota returned.
 7422: 
 7423: =back
 7424: 
 7425: =cut
 7426: 
 7427: ###############################################
 7428: 
 7429: 
 7430: sub default_quota {
 7431:     my ($udom,$inststatus) = @_;
 7432:     my ($defquota,$settingstatus);
 7433:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 7434:                                             ['quotas'],$udom);
 7435:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 7436:         if ($inststatus ne '') {
 7437:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 7438:             foreach my $item (@statuses) {
 7439:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7440:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 7441:                         if ($defquota eq '') {
 7442:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7443:                             $settingstatus = $item;
 7444:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 7445:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 7446:                             $settingstatus = $item;
 7447:                         }
 7448:                     }
 7449:                 } else {
 7450:                     if ($quotahash{'quotas'}{$item} ne '') {
 7451:                         if ($defquota eq '') {
 7452:                             $defquota = $quotahash{'quotas'}{$item};
 7453:                             $settingstatus = $item;
 7454:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 7455:                             $defquota = $quotahash{'quotas'}{$item};
 7456:                             $settingstatus = $item;
 7457:                         }
 7458:                     }
 7459:                 }
 7460:             }
 7461:         }
 7462:         if ($defquota eq '') {
 7463:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 7464:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 7465:             } else {
 7466:                 $defquota = $quotahash{'quotas'}{'default'};
 7467:             }
 7468:             $settingstatus = 'default';
 7469:         }
 7470:     } else {
 7471:         $settingstatus = 'default';
 7472:         $defquota = 20;
 7473:     }
 7474:     if (wantarray) {
 7475:         return ($defquota,$settingstatus);
 7476:     } else {
 7477:         return $defquota;
 7478:     }
 7479: }
 7480: 
 7481: sub get_secgrprole_info {
 7482:     my ($cdom,$cnum,$needroles,$type)  = @_;
 7483:     my %sections_count = &get_sections($cdom,$cnum);
 7484:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 7485:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 7486:     my @groups = sort(keys(%curr_groups));
 7487:     my $allroles = [];
 7488:     my $rolehash;
 7489:     my $accesshash = {
 7490:                      active => 'Currently has access',
 7491:                      future => 'Will have future access',
 7492:                      previous => 'Previously had access',
 7493:                   };
 7494:     if ($needroles) {
 7495:         $rolehash = {'all' => 'all'};
 7496:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 7497: 	if (&Apache::lonnet::error(%user_roles)) {
 7498: 	    undef(%user_roles);
 7499: 	}
 7500:         foreach my $item (keys(%user_roles)) {
 7501:             my ($role)=split(/\:/,$item,2);
 7502:             if ($role eq 'cr') { next; }
 7503:             if ($role =~ /^cr/) {
 7504:                 $$rolehash{$role} = (split('/',$role))[3];
 7505:             } else {
 7506:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 7507:             }
 7508:         }
 7509:         foreach my $key (sort(keys(%{$rolehash}))) {
 7510:             push(@{$allroles},$key);
 7511:         }
 7512:         push (@{$allroles},'st');
 7513:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 7514:     }
 7515:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 7516: }
 7517: 
 7518: sub user_picker {
 7519:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 7520:     my $currdom = $dom;
 7521:     my %curr_selected = (
 7522:                         srchin => 'dom',
 7523:                         srchby => 'lastname',
 7524:                       );
 7525:     my $srchterm;
 7526:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 7527:         if ($srch->{'srchby'} ne '') {
 7528:             $curr_selected{'srchby'} = $srch->{'srchby'};
 7529:         }
 7530:         if ($srch->{'srchin'} ne '') {
 7531:             $curr_selected{'srchin'} = $srch->{'srchin'};
 7532:         }
 7533:         if ($srch->{'srchtype'} ne '') {
 7534:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 7535:         }
 7536:         if ($srch->{'srchdomain'} ne '') {
 7537:             $currdom = $srch->{'srchdomain'};
 7538:         }
 7539:         $srchterm = $srch->{'srchterm'};
 7540:     }
 7541:     my %lt=&Apache::lonlocal::texthash(
 7542:                     'usr'       => 'Search criteria',
 7543:                     'doma'      => 'Domain/institution to search',
 7544:                     'uname'     => 'username',
 7545:                     'lastname'  => 'last name',
 7546:                     'lastfirst' => 'last name, first name',
 7547:                     'crs'       => 'in this course',
 7548:                     'dom'       => 'in selected LON-CAPA domain', 
 7549:                     'alc'       => 'all LON-CAPA',
 7550:                     'instd'     => 'in institutional directory for selected domain',
 7551:                     'exact'     => 'is',
 7552:                     'contains'  => 'contains',
 7553:                     'begins'    => 'begins with',
 7554:                     'youm'      => "You must include some text to search for.",
 7555:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 7556:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 7557:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 7558:                     'ymcd'      => "You must choose a domain when using a domain search.",
 7559:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 7560:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 7561:                      'thfo'     => "The following need to be corrected before the search can be run:",
 7562:                                        );
 7563:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 7564:     my $srchinsel = ' <select name="srchin">';
 7565: 
 7566:     my @srchins = ('crs','dom','alc','instd');
 7567: 
 7568:     foreach my $option (@srchins) {
 7569:         # FIXME 'alc' option unavailable until 
 7570:         #       loncreateuser::print_user_query_page()
 7571:         #       has been completed.
 7572:         next if ($option eq 'alc');
 7573:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 7574:         next if ($option eq 'crs' && !$env{'request.course.id'});
 7575:         if ($curr_selected{'srchin'} eq $option) {
 7576:             $srchinsel .= ' 
 7577:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7578:         } else {
 7579:             $srchinsel .= '
 7580:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7581:         }
 7582:     }
 7583:     $srchinsel .= "\n  </select>\n";
 7584: 
 7585:     my $srchbysel =  ' <select name="srchby">';
 7586:     foreach my $option ('lastname','lastfirst','uname') {
 7587:         if ($curr_selected{'srchby'} eq $option) {
 7588:             $srchbysel .= '
 7589:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7590:         } else {
 7591:             $srchbysel .= '
 7592:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7593:          }
 7594:     }
 7595:     $srchbysel .= "\n  </select>\n";
 7596: 
 7597:     my $srchtypesel = ' <select name="srchtype">';
 7598:     foreach my $option ('begins','contains','exact') {
 7599:         if ($curr_selected{'srchtype'} eq $option) {
 7600:             $srchtypesel .= '
 7601:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7602:         } else {
 7603:             $srchtypesel .= '
 7604:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7605:         }
 7606:     }
 7607:     $srchtypesel .= "\n  </select>\n";
 7608: 
 7609:     my ($newuserscript,$new_user_create);
 7610: 
 7611:     if ($forcenewuser) {
 7612:         if (ref($srch) eq 'HASH') {
 7613:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7614:                 if ($cancreate) {
 7615:                     $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>';
 7616:                 } else {
 7617:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7618:                     my %usertypetext = (
 7619:                         official   => 'institutional',
 7620:                         unofficial => 'non-institutional',
 7621:                     );
 7622:                     $new_user_create = '<p class="LC_warning">'
 7623:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 7624:                                       .' '
 7625:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 7626:                                           ,'<a href="'.$helplink.'">','</a>')
 7627:                                       .'</p><br />';
 7628:                 }
 7629:             }
 7630:         }
 7631: 
 7632:         $newuserscript = <<"ENDSCRIPT";
 7633: 
 7634: function setSearch(createnew,callingForm) {
 7635:     if (createnew == 1) {
 7636:         for (var i=0; i<callingForm.srchby.length; i++) {
 7637:             if (callingForm.srchby.options[i].value == 'uname') {
 7638:                 callingForm.srchby.selectedIndex = i;
 7639:             }
 7640:         }
 7641:         for (var i=0; i<callingForm.srchin.length; i++) {
 7642:             if ( callingForm.srchin.options[i].value == 'dom') {
 7643: 		callingForm.srchin.selectedIndex = i;
 7644:             }
 7645:         }
 7646:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7647:             if (callingForm.srchtype.options[i].value == 'exact') {
 7648:                 callingForm.srchtype.selectedIndex = i;
 7649:             }
 7650:         }
 7651:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7652:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7653:                 callingForm.srchdomain.selectedIndex = i;
 7654:             }
 7655:         }
 7656:     }
 7657: }
 7658: ENDSCRIPT
 7659: 
 7660:     }
 7661: 
 7662:     my $output = <<"END_BLOCK";
 7663: <script type="text/javascript">
 7664: // <![CDATA[
 7665: function validateEntry(callingForm) {
 7666: 
 7667:     var checkok = 1;
 7668:     var srchin;
 7669:     for (var i=0; i<callingForm.srchin.length; i++) {
 7670: 	if ( callingForm.srchin[i].checked ) {
 7671: 	    srchin = callingForm.srchin[i].value;
 7672: 	}
 7673:     }
 7674: 
 7675:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7676:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7677:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7678:     var srchterm =  callingForm.srchterm.value;
 7679:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7680:     var msg = "";
 7681: 
 7682:     if (srchterm == "") {
 7683:         checkok = 0;
 7684:         msg += "$lt{'youm'}\\n";
 7685:     }
 7686: 
 7687:     if (srchtype== 'begins') {
 7688:         if (srchterm.length < 2) {
 7689:             checkok = 0;
 7690:             msg += "$lt{'thte'}\\n";
 7691:         }
 7692:     }
 7693: 
 7694:     if (srchtype== 'contains') {
 7695:         if (srchterm.length < 3) {
 7696:             checkok = 0;
 7697:             msg += "$lt{'thet'}\\n";
 7698:         }
 7699:     }
 7700:     if (srchin == 'instd') {
 7701:         if (srchdomain == '') {
 7702:             checkok = 0;
 7703:             msg += "$lt{'yomc'}\\n";
 7704:         }
 7705:     }
 7706:     if (srchin == 'dom') {
 7707:         if (srchdomain == '') {
 7708:             checkok = 0;
 7709:             msg += "$lt{'ymcd'}\\n";
 7710:         }
 7711:     }
 7712:     if (srchby == 'lastfirst') {
 7713:         if (srchterm.indexOf(",") == -1) {
 7714:             checkok = 0;
 7715:             msg += "$lt{'whus'}\\n";
 7716:         }
 7717:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7718:             checkok = 0;
 7719:             msg += "$lt{'whse'}\\n";
 7720:         }
 7721:     }
 7722:     if (checkok == 0) {
 7723:         alert("$lt{'thfo'}\\n"+msg);
 7724:         return;
 7725:     }
 7726:     if (checkok == 1) {
 7727:         callingForm.submit();
 7728:     }
 7729: }
 7730: 
 7731: $newuserscript
 7732: 
 7733: // ]]>
 7734: </script>
 7735: 
 7736: $new_user_create
 7737: 
 7738: END_BLOCK
 7739: 
 7740:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7741:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7742:                $domform.
 7743:                &Apache::lonhtmlcommon::row_closure().
 7744:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7745:                $srchbysel.
 7746:                $srchtypesel. 
 7747:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7748:                $srchinsel.
 7749:                &Apache::lonhtmlcommon::row_closure(1). 
 7750:                &Apache::lonhtmlcommon::end_pick_box().
 7751:                '<br />';
 7752:     return $output;
 7753: }
 7754: 
 7755: sub user_rule_check {
 7756:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7757:     my $response;
 7758:     if (ref($usershash) eq 'HASH') {
 7759:         foreach my $user (keys(%{$usershash})) {
 7760:             my ($uname,$udom) = split(/:/,$user);
 7761:             next if ($udom eq '' || $uname eq '');
 7762:             my ($id,$newuser);
 7763:             if (ref($usershash->{$user}) eq 'HASH') {
 7764:                 $newuser = $usershash->{$user}->{'newuser'};
 7765:                 $id = $usershash->{$user}->{'id'};
 7766:             }
 7767:             my $inst_response;
 7768:             if (ref($checks) eq 'HASH') {
 7769:                 if (defined($checks->{'username'})) {
 7770:                     ($inst_response,%{$inst_results->{$user}}) = 
 7771:                         &Apache::lonnet::get_instuser($udom,$uname);
 7772:                 } elsif (defined($checks->{'id'})) {
 7773:                     ($inst_response,%{$inst_results->{$user}}) =
 7774:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7775:                 }
 7776:             } else {
 7777:                 ($inst_response,%{$inst_results->{$user}}) =
 7778:                     &Apache::lonnet::get_instuser($udom,$uname);
 7779:                 return;
 7780:             }
 7781:             if (!$got_rules->{$udom}) {
 7782:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7783:                                                   ['usercreation'],$udom);
 7784:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7785:                     foreach my $item ('username','id') {
 7786:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7787:                             $$curr_rules{$udom}{$item} = 
 7788:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7789:                         }
 7790:                     }
 7791:                 }
 7792:                 $got_rules->{$udom} = 1;  
 7793:             }
 7794:             foreach my $item (keys(%{$checks})) {
 7795:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7796:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7797:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7798:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7799:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7800:                                 if ($rule_check{$rule}) {
 7801:                                     $$rulematch{$user}{$item} = $rule;
 7802:                                     if ($inst_response eq 'ok') {
 7803:                                         if (ref($inst_results) eq 'HASH') {
 7804:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7805:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7806:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7807:                                                 }
 7808:                                             }
 7809:                                         }
 7810:                                     }
 7811:                                     last;
 7812:                                 }
 7813:                             }
 7814:                         }
 7815:                     }
 7816:                 }
 7817:             }
 7818:         }
 7819:     }
 7820:     return;
 7821: }
 7822: 
 7823: sub user_rule_formats {
 7824:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7825:     my %text = ( 
 7826:                  'username' => 'Usernames',
 7827:                  'id'       => 'IDs',
 7828:                );
 7829:     my $output;
 7830:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7831:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7832:         if (@{$ruleorder} > 0) {
 7833:             $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>';
 7834:             foreach my $rule (@{$ruleorder}) {
 7835:                 if (ref($curr_rules) eq 'ARRAY') {
 7836:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7837:                         if (ref($rules->{$rule}) eq 'HASH') {
 7838:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7839:                                         $rules->{$rule}{'desc'}.'</li>';
 7840:                         }
 7841:                     }
 7842:                 }
 7843:             }
 7844:             $output .= '</ul>';
 7845:         }
 7846:     }
 7847:     return $output;
 7848: }
 7849: 
 7850: sub instrule_disallow_msg {
 7851:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7852:     my $response;
 7853:     my %text = (
 7854:                   item   => 'username',
 7855:                   items  => 'usernames',
 7856:                   match  => 'matches',
 7857:                   do     => 'does',
 7858:                   action => 'a username',
 7859:                   one    => 'one',
 7860:                );
 7861:     if ($count > 1) {
 7862:         $text{'item'} = 'usernames';
 7863:         $text{'match'} ='match';
 7864:         $text{'do'} = 'do';
 7865:         $text{'action'} = 'usernames',
 7866:         $text{'one'} = 'ones';
 7867:     }
 7868:     if ($checkitem eq 'id') {
 7869:         $text{'items'} = 'IDs';
 7870:         $text{'item'} = 'ID';
 7871:         $text{'action'} = 'an ID';
 7872:         if ($count > 1) {
 7873:             $text{'item'} = 'IDs';
 7874:             $text{'action'} = 'IDs';
 7875:         }
 7876:     }
 7877:     $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 />';
 7878:     if ($mode eq 'upload') {
 7879:         if ($checkitem eq 'username') {
 7880:             $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'}.");
 7881:         } elsif ($checkitem eq 'id') {
 7882:             $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.");
 7883:         }
 7884:     } elsif ($mode eq 'selfcreate') {
 7885:         if ($checkitem eq 'id') {
 7886:             $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.");
 7887:         }
 7888:     } else {
 7889:         if ($checkitem eq 'username') {
 7890:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7891:         } elsif ($checkitem eq 'id') {
 7892:             $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.");
 7893:         }
 7894:     }
 7895:     return $response;
 7896: }
 7897: 
 7898: sub personal_data_fieldtitles {
 7899:     my %fieldtitles = &Apache::lonlocal::texthash (
 7900:                         id => 'Student/Employee ID',
 7901:                         permanentemail => 'E-mail address',
 7902:                         lastname => 'Last Name',
 7903:                         firstname => 'First Name',
 7904:                         middlename => 'Middle Name',
 7905:                         generation => 'Generation',
 7906:                         gen => 'Generation',
 7907:                         inststatus => 'Affiliation',
 7908:                    );
 7909:     return %fieldtitles;
 7910: }
 7911: 
 7912: sub sorted_inst_types {
 7913:     my ($dom) = @_;
 7914:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7915:     my $othertitle = &mt('All users');
 7916:     if ($env{'request.course.id'}) {
 7917:         $othertitle  = &mt('Any users');
 7918:     }
 7919:     my @types;
 7920:     if (ref($order) eq 'ARRAY') {
 7921:         @types = @{$order};
 7922:     }
 7923:     if (@types == 0) {
 7924:         if (ref($usertypes) eq 'HASH') {
 7925:             @types = sort(keys(%{$usertypes}));
 7926:         }
 7927:     }
 7928:     if (keys(%{$usertypes}) > 0) {
 7929:         $othertitle = &mt('Other users');
 7930:     }
 7931:     return ($othertitle,$usertypes,\@types);
 7932: }
 7933: 
 7934: sub get_institutional_codes {
 7935:     my ($settings,$allcourses,$LC_code) = @_;
 7936: # Get complete list of course sections to update
 7937:     my @currsections = ();
 7938:     my @currxlists = ();
 7939:     my $coursecode = $$settings{'internal.coursecode'};
 7940: 
 7941:     if ($$settings{'internal.sectionnums'} ne '') {
 7942:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7943:     }
 7944: 
 7945:     if ($$settings{'internal.crosslistings'} ne '') {
 7946:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7947:     }
 7948: 
 7949:     if (@currxlists > 0) {
 7950:         foreach (@currxlists) {
 7951:             if (m/^([^:]+):(\w*)$/) {
 7952:                 unless (grep/^$1$/,@{$allcourses}) {
 7953:                     push @{$allcourses},$1;
 7954:                     $$LC_code{$1} = $2;
 7955:                 }
 7956:             }
 7957:         }
 7958:     }
 7959:  
 7960:     if (@currsections > 0) {
 7961:         foreach (@currsections) {
 7962:             if (m/^(\w+):(\w*)$/) {
 7963:                 my $sec = $coursecode.$1;
 7964:                 my $lc_sec = $2;
 7965:                 unless (grep/^$sec$/,@{$allcourses}) {
 7966:                     push @{$allcourses},$sec;
 7967:                     $$LC_code{$sec} = $lc_sec;
 7968:                 }
 7969:             }
 7970:         }
 7971:     }
 7972:     return;
 7973: }
 7974: 
 7975: =pod
 7976: 
 7977: =head1 Slot Helpers
 7978: 
 7979: =over 4
 7980: 
 7981: =item * sorted_slots()
 7982: 
 7983: Sorts an array of slot names in order of slot start time (earliest first). 
 7984: 
 7985: Inputs:
 7986: 
 7987: =over 4
 7988: 
 7989: slotsarr  - Reference to array of unsorted slot names.
 7990: 
 7991: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7992: 
 7993: =back
 7994: 
 7995: Returns:
 7996: 
 7997: =over 4
 7998: 
 7999: sorted   - An array of slot names sorted by the start time of the slot.
 8000: 
 8001: =back
 8002: 
 8003: =back
 8004: 
 8005: =cut
 8006: 
 8007: 
 8008: sub sorted_slots {
 8009:     my ($slotsarr,$slots) = @_;
 8010:     my @sorted;
 8011:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 8012:         @sorted =
 8013:             sort {
 8014:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 8015:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 8016:                      }
 8017:                      if (ref($slots->{$a})) { return -1;}
 8018:                      if (ref($slots->{$b})) { return 1;}
 8019:                      return 0;
 8020:                  } @{$slotsarr};
 8021:     }
 8022:     return @sorted;
 8023: }
 8024: 
 8025: 
 8026: =pod
 8027: 
 8028: =head1 HTTP Helpers
 8029: 
 8030: =over 4
 8031: 
 8032: =item * &get_unprocessed_cgi($query,$possible_names)
 8033: 
 8034: Modify the %env hash to contain unprocessed CGI form parameters held in
 8035: $query.  The parameters listed in $possible_names (an array reference),
 8036: will be set in $env{'form.name'} if they do not already exist.
 8037: 
 8038: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 8039: $possible_names is an ref to an array of form element names.  As an example:
 8040: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 8041: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 8042: 
 8043: =cut
 8044: 
 8045: sub get_unprocessed_cgi {
 8046:   my ($query,$possible_names)= @_;
 8047:   # $Apache::lonxml::debug=1;
 8048:   foreach my $pair (split(/&/,$query)) {
 8049:     my ($name, $value) = split(/=/,$pair);
 8050:     $name = &unescape($name);
 8051:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 8052:       $value =~ tr/+/ /;
 8053:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 8054:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 8055:     }
 8056:   }
 8057: }
 8058: 
 8059: =pod
 8060: 
 8061: =item * &cacheheader() 
 8062: 
 8063: returns cache-controlling header code
 8064: 
 8065: =cut
 8066: 
 8067: sub cacheheader {
 8068:     unless ($env{'request.method'} eq 'GET') { return ''; }
 8069:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 8070:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 8071:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 8072:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 8073:     return $output;
 8074: }
 8075: 
 8076: =pod
 8077: 
 8078: =item * &no_cache($r) 
 8079: 
 8080: specifies header code to not have cache
 8081: 
 8082: =cut
 8083: 
 8084: sub no_cache {
 8085:     my ($r) = @_;
 8086:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 8087: 	$env{'request.method'} ne 'GET') { return ''; }
 8088:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 8089:     $r->no_cache(1);
 8090:     $r->header_out("Expires" => $date);
 8091:     $r->header_out("Pragma" => "no-cache");
 8092: }
 8093: 
 8094: sub content_type {
 8095:     my ($r,$type,$charset) = @_;
 8096:     if ($r) {
 8097: 	#  Note that printout.pl calls this with undef for $r.
 8098: 	&no_cache($r);
 8099:     }
 8100:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 8101:     unless ($charset) {
 8102: 	$charset=&Apache::lonlocal::current_encoding;
 8103:     }
 8104:     if ($charset) { $type.='; charset='.$charset; }
 8105:     if ($r) {
 8106: 	$r->content_type($type);
 8107:     } else {
 8108: 	print("Content-type: $type\n\n");
 8109:     }
 8110: }
 8111: 
 8112: =pod
 8113: 
 8114: =item * &add_to_env($name,$value) 
 8115: 
 8116: adds $name to the %env hash with value
 8117: $value, if $name already exists, the entry is converted to an array
 8118: reference and $value is added to the array.
 8119: 
 8120: =cut
 8121: 
 8122: sub add_to_env {
 8123:   my ($name,$value)=@_;
 8124:   if (defined($env{$name})) {
 8125:     if (ref($env{$name})) {
 8126:       #already have multiple values
 8127:       push(@{ $env{$name} },$value);
 8128:     } else {
 8129:       #first time seeing multiple values, convert hash entry to an arrayref
 8130:       my $first=$env{$name};
 8131:       undef($env{$name});
 8132:       push(@{ $env{$name} },$first,$value);
 8133:     }
 8134:   } else {
 8135:     $env{$name}=$value;
 8136:   }
 8137: }
 8138: 
 8139: =pod
 8140: 
 8141: =item * &get_env_multiple($name) 
 8142: 
 8143: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8144: values may be defined and end up as an array ref.
 8145: 
 8146: returns an array of values
 8147: 
 8148: =cut
 8149: 
 8150: sub get_env_multiple {
 8151:     my ($name) = @_;
 8152:     my @values;
 8153:     if (defined($env{$name})) {
 8154:         # exists is it an array
 8155:         if (ref($env{$name})) {
 8156:             @values=@{ $env{$name} };
 8157:         } else {
 8158:             $values[0]=$env{$name};
 8159:         }
 8160:     }
 8161:     return(@values);
 8162: }
 8163: 
 8164: sub ask_for_embedded_content {
 8165:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 8166:     my $upload_output = '
 8167:    <form name="upload_embedded" action="'.$actionurl.'"
 8168:                   method="post" enctype="multipart/form-data">';
 8169:     $upload_output .= $state;
 8170:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 8171: 
 8172:     my $num = 0;
 8173:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 8174:         $upload_output .= &start_data_table_row().
 8175:             '<td>'.$embed_file.'</td><td>';
 8176:         if ($args->{'ignore_remote_references'}
 8177:             && $embed_file =~ m{^\w+://}) {
 8178:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 8179:         } elsif ($args->{'error_on_invalid_names'}
 8180:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 8181: 
 8182:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 8183: 
 8184:         } else {
 8185:             $upload_output .='
 8186:            <input name="embedded_item_'.$num.'" type="file" value="" />
 8187:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 8188:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 8189:             $upload_output .=
 8190:                 "\n\t\t".
 8191:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 8192:                 $attrib.'" />';
 8193:             if (exists($$codebase{$embed_file})) {
 8194:                 $upload_output .=
 8195:                     "\n\t\t".
 8196:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 8197:                     &escape($$codebase{$embed_file}).'" />';
 8198:             }
 8199:         }
 8200:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 8201:         $num++;
 8202:     }
 8203:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 8204:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 8205:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 8206:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 8207:    </form>';
 8208:     return $upload_output;
 8209: }
 8210: 
 8211: sub upload_embedded {
 8212:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 8213:         $current_disk_usage) = @_;
 8214:     my $output;
 8215:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 8216:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 8217:         my $orig_uploaded_filename =
 8218:             $env{'form.embedded_item_'.$i.'.filename'};
 8219: 
 8220:         $env{'form.embedded_orig_'.$i} =
 8221:             &unescape($env{'form.embedded_orig_'.$i});
 8222:         my ($path,$fname) =
 8223:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 8224:         # no path, whole string is fname
 8225:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 8226: 
 8227:         $path = $env{'form.currentpath'}.$path;
 8228:         $fname = &Apache::lonnet::clean_filename($fname);
 8229:         # See if there is anything left
 8230:         next if ($fname eq '');
 8231: 
 8232:         # Check if file already exists as a file or directory.
 8233:         my ($state,$msg);
 8234:         if ($context eq 'portfolio') {
 8235:             my $port_path = $dirpath;
 8236:             if ($group ne '') {
 8237:                 $port_path = "groups/$group/$port_path";
 8238:             }
 8239:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 8240:                                               $dir_root,$port_path,$disk_quota,
 8241:                                               $current_disk_usage,$uname,$udom);
 8242:             if ($state eq 'will_exceed_quota'
 8243:                 || $state eq 'file_locked'
 8244:                 || $state eq 'file_exists' ) {
 8245:                 $output .= $msg;
 8246:                 next;
 8247:             }
 8248:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 8249:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 8250:             if ($state eq 'exists') {
 8251:                 $output .= $msg;
 8252:                 next;
 8253:             }
 8254:         }
 8255:         # Check if extension is valid
 8256:         if (($fname =~ /\.(\w+)$/) &&
 8257:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8258:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 8259:             next;
 8260:         } elsif (($fname =~ /\.(\w+)$/) &&
 8261:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 8262:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8263:             next;
 8264:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 8265:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8266:             next;
 8267:         }
 8268: 
 8269:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 8270:         if ($context eq 'portfolio') {
 8271:             my $result=
 8272:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 8273:                                                 $dirpath.$path);
 8274:             if ($result !~ m|^/uploaded/|) {
 8275:                 $output .= '<span class="LC_error">'
 8276:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 8277:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 8278:                       .'</span><br />';
 8279:                 next;
 8280:             } else {
 8281:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 8282:                            $path.$fname.'</span>').'</p>';     
 8283:             }
 8284:         } else {
 8285: # Save the file
 8286:             my $target = $env{'form.embedded_item_'.$i};
 8287:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 8288:             my $dest = $fullpath.$fname;
 8289:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 8290:             my @parts=split(/\//,$fullpath);
 8291:             my $count;
 8292:             my $filepath = $dir_root;
 8293:             for ($count=4;$count<=$#parts;$count++) {
 8294:                 $filepath .= "/$parts[$count]";
 8295:                 if ((-e $filepath)!=1) {
 8296:                     mkdir($filepath,0770);
 8297:                 }
 8298:             }
 8299:             my $fh;
 8300:             if (!open($fh,'>'.$dest)) {
 8301:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 8302:                 $output .= '<span class="LC_error">'.
 8303:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8304:                            '</span><br />';
 8305:             } else {
 8306:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 8307:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 8308:                     $output .= '<span class="LC_error">'.
 8309:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 8310:                               '</span><br />';
 8311:                 } else {
 8312:                     if ($context eq 'testbank') {
 8313:                         $output .= &mt('Embedded file uploaded successfully:').
 8314:                                    '&nbsp;<a href="'.$url.'">'.
 8315:                                    $orig_uploaded_filename.'</a><br />';
 8316:                     } else {
 8317:                         $output .= '<span class=\"LC_fontsize_large\">'.
 8318:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 8319:                                    $orig_uploaded_filename.'</a>').'</span><br />';
 8320:                     }
 8321:                 }
 8322:                 close($fh);
 8323:             }
 8324:         }
 8325:     }
 8326:     return $output;
 8327: }
 8328: 
 8329: sub check_for_existing {
 8330:     my ($path,$fname,$element) = @_;
 8331:     my ($state,$msg);
 8332:     if (-d $path.'/'.$fname) {
 8333:         $state = 'exists';
 8334:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8335:     } elsif (-e $path.'/'.$fname) {
 8336:         $state = 'exists';
 8337:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 8338:     }
 8339:     if ($state eq 'exists') {
 8340:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 8341:     }
 8342:     return ($state,$msg);
 8343: }
 8344: 
 8345: sub check_for_upload {
 8346:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 8347:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 8348:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 8349:     my $getpropath = 1;
 8350:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 8351:                                             $getpropath);
 8352:     my $found_file = 0;
 8353:     my $locked_file = 0;
 8354:     foreach my $line (@dir_list) {
 8355:         my ($file_name)=split(/\&/,$line,2);
 8356:         if ($file_name eq $fname){
 8357:             $file_name = $path.$file_name;
 8358:             if ($group ne '') {
 8359:                 $file_name = $group.$file_name;
 8360:             }
 8361:             $found_file = 1;
 8362:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 8363:                 $locked_file = 1;
 8364:             }
 8365:         }
 8366:     }
 8367:     if (($current_disk_usage + $filesize) > $disk_quota){
 8368:         my $msg = '<span class="LC_error">'.
 8369:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 8370:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 8371:         return ('will_exceed_quota',$msg);
 8372:     } elsif ($found_file) {
 8373:         if ($locked_file) {
 8374:             my $msg = '<span class="LC_error">';
 8375:             $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>');
 8376:             $msg .= '</span><br />';
 8377:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 8378:             return ('file_locked',$msg);
 8379:         } else {
 8380:             my $msg = '<span class="LC_error">';
 8381:             $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'});
 8382:             $msg .= '</span>';
 8383:             $msg .= '<br />';
 8384:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 8385:             return ('file_exists',$msg);
 8386:         }
 8387:     }
 8388: }
 8389: 
 8390: 
 8391: =pod
 8392: 
 8393: =back
 8394: 
 8395: =head1 CSV Upload/Handling functions
 8396: 
 8397: =over 4
 8398: 
 8399: =item * &upfile_store($r)
 8400: 
 8401: Store uploaded file, $r should be the HTTP Request object,
 8402: needs $env{'form.upfile'}
 8403: returns $datatoken to be put into hidden field
 8404: 
 8405: =cut
 8406: 
 8407: sub upfile_store {
 8408:     my $r=shift;
 8409:     $env{'form.upfile'}=~s/\r/\n/gs;
 8410:     $env{'form.upfile'}=~s/\f/\n/gs;
 8411:     $env{'form.upfile'}=~s/\n+/\n/gs;
 8412:     $env{'form.upfile'}=~s/\n+$//gs;
 8413: 
 8414:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 8415: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 8416:     {
 8417:         my $datafile = $r->dir_config('lonDaemons').
 8418:                            '/tmp/'.$datatoken.'.tmp';
 8419:         if ( open(my $fh,">$datafile") ) {
 8420:             print $fh $env{'form.upfile'};
 8421:             close($fh);
 8422:         }
 8423:     }
 8424:     return $datatoken;
 8425: }
 8426: 
 8427: =pod
 8428: 
 8429: =item * &load_tmp_file($r)
 8430: 
 8431: Load uploaded file from tmp, $r should be the HTTP Request object,
 8432: needs $env{'form.datatoken'},
 8433: sets $env{'form.upfile'} to the contents of the file
 8434: 
 8435: =cut
 8436: 
 8437: sub load_tmp_file {
 8438:     my $r=shift;
 8439:     my @studentdata=();
 8440:     {
 8441:         my $studentfile = $r->dir_config('lonDaemons').
 8442:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 8443:         if ( open(my $fh,"<$studentfile") ) {
 8444:             @studentdata=<$fh>;
 8445:             close($fh);
 8446:         }
 8447:     }
 8448:     $env{'form.upfile'}=join('',@studentdata);
 8449: }
 8450: 
 8451: =pod
 8452: 
 8453: =item * &upfile_record_sep()
 8454: 
 8455: Separate uploaded file into records
 8456: returns array of records,
 8457: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 8458: 
 8459: =cut
 8460: 
 8461: sub upfile_record_sep {
 8462:     if ($env{'form.upfiletype'} eq 'xml') {
 8463:     } else {
 8464: 	my @records;
 8465: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 8466: 	    if ($line=~/^\s*$/) { next; }
 8467: 	    push(@records,$line);
 8468: 	}
 8469: 	return @records;
 8470:     }
 8471: }
 8472: 
 8473: =pod
 8474: 
 8475: =item * &record_sep($record)
 8476: 
 8477: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 8478: 
 8479: =cut
 8480: 
 8481: sub takeleft {
 8482:     my $index=shift;
 8483:     return substr('0000'.$index,-4,4);
 8484: }
 8485: 
 8486: sub record_sep {
 8487:     my $record=shift;
 8488:     my %components=();
 8489:     if ($env{'form.upfiletype'} eq 'xml') {
 8490:     } elsif ($env{'form.upfiletype'} eq 'space') {
 8491:         my $i=0;
 8492:         foreach my $field (split(/\s+/,$record)) {
 8493:             $field=~s/^(\"|\')//;
 8494:             $field=~s/(\"|\')$//;
 8495:             $components{&takeleft($i)}=$field;
 8496:             $i++;
 8497:         }
 8498:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 8499:         my $i=0;
 8500:         foreach my $field (split(/\t/,$record)) {
 8501:             $field=~s/^(\"|\')//;
 8502:             $field=~s/(\"|\')$//;
 8503:             $components{&takeleft($i)}=$field;
 8504:             $i++;
 8505:         }
 8506:     } else {
 8507:         my $separator=',';
 8508:         if ($env{'form.upfiletype'} eq 'semisv') {
 8509:             $separator=';';
 8510:         }
 8511:         my $i=0;
 8512: # the character we are looking for to indicate the end of a quote or a record 
 8513:         my $looking_for=$separator;
 8514: # do not add the characters to the fields
 8515:         my $ignore=0;
 8516: # we just encountered a separator (or the beginning of the record)
 8517:         my $just_found_separator=1;
 8518: # store the field we are working on here
 8519:         my $field='';
 8520: # work our way through all characters in record
 8521:         foreach my $character ($record=~/(.)/g) {
 8522:             if ($character eq $looking_for) {
 8523:                if ($character ne $separator) {
 8524: # Found the end of a quote, again looking for separator
 8525:                   $looking_for=$separator;
 8526:                   $ignore=1;
 8527:                } else {
 8528: # Found a separator, store away what we got
 8529:                   $components{&takeleft($i)}=$field;
 8530: 	          $i++;
 8531:                   $just_found_separator=1;
 8532:                   $ignore=0;
 8533:                   $field='';
 8534:                }
 8535:                next;
 8536:             }
 8537: # single or double quotation marks after a separator indicate beginning of a quote
 8538: # we are now looking for the end of the quote and need to ignore separators
 8539:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 8540:                $looking_for=$character;
 8541:                next;
 8542:             }
 8543: # ignore would be true after we reached the end of a quote
 8544:             if ($ignore) { next; }
 8545:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 8546:             $field.=$character;
 8547:             $just_found_separator=0; 
 8548:         }
 8549: # catch the very last entry, since we never encountered the separator
 8550:         $components{&takeleft($i)}=$field;
 8551:     }
 8552:     return %components;
 8553: }
 8554: 
 8555: ######################################################
 8556: ######################################################
 8557: 
 8558: =pod
 8559: 
 8560: =item * &upfile_select_html()
 8561: 
 8562: Return HTML code to select a file from the users machine and specify 
 8563: the file type.
 8564: 
 8565: =cut
 8566: 
 8567: ######################################################
 8568: ######################################################
 8569: sub upfile_select_html {
 8570:     my %Types = (
 8571:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 8572:                  semisv => &mt('Semicolon separated values'),
 8573:                  space => &mt('Space separated'),
 8574:                  tab   => &mt('Tabulator separated'),
 8575: #                 xml   => &mt('HTML/XML'),
 8576:                  );
 8577:     my $Str = '<input type="file" name="upfile" size="50" />'.
 8578:         '<br />'.&mt('Type').': <select name="upfiletype">';
 8579:     foreach my $type (sort(keys(%Types))) {
 8580:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 8581:     }
 8582:     $Str .= "</select>\n";
 8583:     return $Str;
 8584: }
 8585: 
 8586: sub get_samples {
 8587:     my ($records,$toget) = @_;
 8588:     my @samples=({});
 8589:     my $got=0;
 8590:     foreach my $rec (@$records) {
 8591: 	my %temp = &record_sep($rec);
 8592: 	if (! grep(/\S/, values(%temp))) { next; }
 8593: 	if (%temp) {
 8594: 	    $samples[$got]=\%temp;
 8595: 	    $got++;
 8596: 	    if ($got == $toget) { last; }
 8597: 	}
 8598:     }
 8599:     return \@samples;
 8600: }
 8601: 
 8602: ######################################################
 8603: ######################################################
 8604: 
 8605: =pod
 8606: 
 8607: =item * &csv_print_samples($r,$records)
 8608: 
 8609: Prints a table of sample values from each column uploaded $r is an
 8610: Apache Request ref, $records is an arrayref from
 8611: &Apache::loncommon::upfile_record_sep
 8612: 
 8613: =cut
 8614: 
 8615: ######################################################
 8616: ######################################################
 8617: sub csv_print_samples {
 8618:     my ($r,$records) = @_;
 8619:     my $samples = &get_samples($records,5);
 8620: 
 8621:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8622:               &start_data_table_header_row());
 8623:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8624:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
 8625:     $r->print(&end_data_table_header_row());
 8626:     foreach my $hash (@$samples) {
 8627: 	$r->print(&start_data_table_row());
 8628: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8629: 	    $r->print('<td>');
 8630: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8631: 	    $r->print('</td>');
 8632: 	}
 8633: 	$r->print(&end_data_table_row());
 8634:     }
 8635:     $r->print(&end_data_table().'<br />'."\n");
 8636: }
 8637: 
 8638: ######################################################
 8639: ######################################################
 8640: 
 8641: =pod
 8642: 
 8643: =item * &csv_print_select_table($r,$records,$d)
 8644: 
 8645: Prints a table to create associations between values and table columns.
 8646: 
 8647: $r is an Apache Request ref,
 8648: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8649: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8650: 
 8651: =cut
 8652: 
 8653: ######################################################
 8654: ######################################################
 8655: sub csv_print_select_table {
 8656:     my ($r,$records,$d) = @_;
 8657:     my $i=0;
 8658:     my $samples = &get_samples($records,1);
 8659:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8660: 	      &start_data_table().&start_data_table_header_row().
 8661:               '<th>'.&mt('Attribute').'</th>'.
 8662:               '<th>'.&mt('Column').'</th>'.
 8663:               &end_data_table_header_row()."\n");
 8664:     foreach my $array_ref (@$d) {
 8665: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8666: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8667: 
 8668: 	$r->print('<td><select name="f'.$i.'"'.
 8669: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8670: 	$r->print('<option value="none"></option>');
 8671: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8672: 	    $r->print('<option value="'.$sample.'"'.
 8673:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8674:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8675: 	}
 8676: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8677: 	$i++;
 8678:     }
 8679:     $r->print(&end_data_table());
 8680:     $i--;
 8681:     return $i;
 8682: }
 8683: 
 8684: ######################################################
 8685: ######################################################
 8686: 
 8687: =pod
 8688: 
 8689: =item * &csv_samples_select_table($r,$records,$d)
 8690: 
 8691: Prints a table of sample values from the upload and can make associate samples to internal names.
 8692: 
 8693: $r is an Apache Request ref,
 8694: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8695: $d is an array of 2 element arrays (internal name, displayed name)
 8696: 
 8697: =cut
 8698: 
 8699: ######################################################
 8700: ######################################################
 8701: sub csv_samples_select_table {
 8702:     my ($r,$records,$d) = @_;
 8703:     my $i=0;
 8704:     #
 8705:     my $max_samples = 5;
 8706:     my $samples = &get_samples($records,$max_samples);
 8707:     $r->print(&start_data_table().
 8708:               &start_data_table_header_row().'<th>'.
 8709:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8710:               &end_data_table_header_row());
 8711: 
 8712:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8713: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8714: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8715: 	foreach my $option (@$d) {
 8716: 	    my ($value,$display,$defaultcol)=@{ $option };
 8717: 	    $r->print('<option value="'.$value.'"'.
 8718:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8719:                       $display.'</option>');
 8720: 	}
 8721: 	$r->print('</select></td><td>');
 8722: 	foreach my $line (0..($max_samples-1)) {
 8723: 	    if (defined($samples->[$line]{$key})) { 
 8724: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8725: 	    }
 8726: 	}
 8727: 	$r->print('</td>'.&end_data_table_row());
 8728: 	$i++;
 8729:     }
 8730:     $r->print(&end_data_table());
 8731:     $i--;
 8732:     return($i);
 8733: }
 8734: 
 8735: ######################################################
 8736: ######################################################
 8737: 
 8738: =pod
 8739: 
 8740: =item * &clean_excel_name($name)
 8741: 
 8742: Returns a replacement for $name which does not contain any illegal characters.
 8743: 
 8744: =cut
 8745: 
 8746: ######################################################
 8747: ######################################################
 8748: sub clean_excel_name {
 8749:     my ($name) = @_;
 8750:     $name =~ s/[:\*\?\/\\]//g;
 8751:     if (length($name) > 31) {
 8752:         $name = substr($name,0,31);
 8753:     }
 8754:     return $name;
 8755: }
 8756: 
 8757: =pod
 8758: 
 8759: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8760: 
 8761: Returns either 1 or undef
 8762: 
 8763: 1 if the part is to be hidden, undef if it is to be shown
 8764: 
 8765: Arguments are:
 8766: 
 8767: $id the id of the part to be checked
 8768: $symb, optional the symb of the resource to check
 8769: $udom, optional the domain of the user to check for
 8770: $uname, optional the username of the user to check for
 8771: 
 8772: =cut
 8773: 
 8774: sub check_if_partid_hidden {
 8775:     my ($id,$symb,$udom,$uname) = @_;
 8776:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8777: 					 $symb,$udom,$uname);
 8778:     my $truth=1;
 8779:     #if the string starts with !, then the list is the list to show not hide
 8780:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8781:     my @hiddenlist=split(/,/,$hiddenparts);
 8782:     foreach my $checkid (@hiddenlist) {
 8783: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8784:     }
 8785:     return !$truth;
 8786: }
 8787: 
 8788: 
 8789: ############################################################
 8790: ############################################################
 8791: 
 8792: =pod
 8793: 
 8794: =back 
 8795: 
 8796: =head1 cgi-bin script and graphing routines
 8797: 
 8798: =over 4
 8799: 
 8800: =item * &get_cgi_id()
 8801: 
 8802: Inputs: none
 8803: 
 8804: Returns an id which can be used to pass environment variables
 8805: to various cgi-bin scripts.  These environment variables will
 8806: be removed from the users environment after a given time by
 8807: the routine &Apache::lonnet::transfer_profile_to_env.
 8808: 
 8809: =cut
 8810: 
 8811: ############################################################
 8812: ############################################################
 8813: my $uniq=0;
 8814: sub get_cgi_id {
 8815:     $uniq=($uniq+1)%100000;
 8816:     return (time.'_'.$$.'_'.$uniq);
 8817: }
 8818: 
 8819: ############################################################
 8820: ############################################################
 8821: 
 8822: =pod
 8823: 
 8824: =item * &DrawBarGraph()
 8825: 
 8826: Facilitates the plotting of data in a (stacked) bar graph.
 8827: Puts plot definition data into the users environment in order for 
 8828: graph.png to plot it.  Returns an <img> tag for the plot.
 8829: The bars on the plot are labeled '1','2',...,'n'.
 8830: 
 8831: Inputs:
 8832: 
 8833: =over 4
 8834: 
 8835: =item $Title: string, the title of the plot
 8836: 
 8837: =item $xlabel: string, text describing the X-axis of the plot
 8838: 
 8839: =item $ylabel: string, text describing the Y-axis of the plot
 8840: 
 8841: =item $Max: scalar, the maximum Y value to use in the plot
 8842: If $Max is < any data point, the graph will not be rendered.
 8843: 
 8844: =item $colors: array ref holding the colors to be used for the data sets when
 8845: they are plotted.  If undefined, default values will be used.
 8846: 
 8847: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8848: 
 8849: =item @Values: An array of array references.  Each array reference holds data
 8850: to be plotted in a stacked bar chart.
 8851: 
 8852: =item If the final element of @Values is a hash reference the key/value
 8853: pairs will be added to the graph definition.
 8854: 
 8855: =back
 8856: 
 8857: Returns:
 8858: 
 8859: An <img> tag which references graph.png and the appropriate identifying
 8860: information for the plot.
 8861: 
 8862: =cut
 8863: 
 8864: ############################################################
 8865: ############################################################
 8866: sub DrawBarGraph {
 8867:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8868:     #
 8869:     if (! defined($colors)) {
 8870:         $colors = ['#33ff00', 
 8871:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8872:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8873:                   ]; 
 8874:     }
 8875:     my $extra_settings = {};
 8876:     if (ref($Values[-1]) eq 'HASH') {
 8877:         $extra_settings = pop(@Values);
 8878:     }
 8879:     #
 8880:     my $identifier = &get_cgi_id();
 8881:     my $id = 'cgi.'.$identifier;        
 8882:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8883:         return '';
 8884:     }
 8885:     #
 8886:     my @Labels;
 8887:     if (defined($labels)) {
 8888:         @Labels = @$labels;
 8889:     } else {
 8890:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8891:             push (@Labels,$i+1);
 8892:         }
 8893:     }
 8894:     #
 8895:     my $NumBars = scalar(@{$Values[0]});
 8896:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8897:     my %ValuesHash;
 8898:     my $NumSets=1;
 8899:     foreach my $array (@Values) {
 8900:         next if (! ref($array));
 8901:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8902:             join(',',@$array);
 8903:     }
 8904:     #
 8905:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8906:     if ($NumBars < 3) {
 8907:         $width = 120+$NumBars*32;
 8908:         $xskip = 1;
 8909:         $bar_width = 30;
 8910:     } elsif ($NumBars < 5) {
 8911:         $width = 120+$NumBars*20;
 8912:         $xskip = 1;
 8913:         $bar_width = 20;
 8914:     } elsif ($NumBars < 10) {
 8915:         $width = 120+$NumBars*15;
 8916:         $xskip = 1;
 8917:         $bar_width = 15;
 8918:     } elsif ($NumBars <= 25) {
 8919:         $width = 120+$NumBars*11;
 8920:         $xskip = 5;
 8921:         $bar_width = 8;
 8922:     } elsif ($NumBars <= 50) {
 8923:         $width = 120+$NumBars*8;
 8924:         $xskip = 5;
 8925:         $bar_width = 4;
 8926:     } else {
 8927:         $width = 120+$NumBars*8;
 8928:         $xskip = 5;
 8929:         $bar_width = 4;
 8930:     }
 8931:     #
 8932:     $Max = 1 if ($Max < 1);
 8933:     if ( int($Max) < $Max ) {
 8934:         $Max++;
 8935:         $Max = int($Max);
 8936:     }
 8937:     $Title  = '' if (! defined($Title));
 8938:     $xlabel = '' if (! defined($xlabel));
 8939:     $ylabel = '' if (! defined($ylabel));
 8940:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8941:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8942:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8943:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8944:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8945:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8946:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8947:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8948:     $ValuesHash{$id.'.height'}   = $height;
 8949:     $ValuesHash{$id.'.width'}    = $width;
 8950:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8951:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8952:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8953:     #
 8954:     # Deal with other parameters
 8955:     while (my ($key,$value) = each(%$extra_settings)) {
 8956:         $ValuesHash{$id.'.'.$key} = $value;
 8957:     }
 8958:     #
 8959:     &Apache::lonnet::appenv(\%ValuesHash);
 8960:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8961: }
 8962: 
 8963: ############################################################
 8964: ############################################################
 8965: 
 8966: =pod
 8967: 
 8968: =item * &DrawXYGraph()
 8969: 
 8970: Facilitates the plotting of data in an XY graph.
 8971: Puts plot definition data into the users environment in order for 
 8972: graph.png to plot it.  Returns an <img> tag for the plot.
 8973: 
 8974: Inputs:
 8975: 
 8976: =over 4
 8977: 
 8978: =item $Title: string, the title of the plot
 8979: 
 8980: =item $xlabel: string, text describing the X-axis of the plot
 8981: 
 8982: =item $ylabel: string, text describing the Y-axis of the plot
 8983: 
 8984: =item $Max: scalar, the maximum Y value to use in the plot
 8985: If $Max is < any data point, the graph will not be rendered.
 8986: 
 8987: =item $colors: Array ref containing the hex color codes for the data to be 
 8988: plotted in.  If undefined, default values will be used.
 8989: 
 8990: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8991: 
 8992: =item $Ydata: Array ref containing Array refs.  
 8993: Each of the contained arrays will be plotted as a separate curve.
 8994: 
 8995: =item %Values: hash indicating or overriding any default values which are 
 8996: passed to graph.png.  
 8997: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8998: 
 8999: =back
 9000: 
 9001: Returns:
 9002: 
 9003: An <img> tag which references graph.png and the appropriate identifying
 9004: information for the plot.
 9005: 
 9006: =cut
 9007: 
 9008: ############################################################
 9009: ############################################################
 9010: sub DrawXYGraph {
 9011:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 9012:     #
 9013:     # Create the identifier for the graph
 9014:     my $identifier = &get_cgi_id();
 9015:     my $id = 'cgi.'.$identifier;
 9016:     #
 9017:     $Title  = '' if (! defined($Title));
 9018:     $xlabel = '' if (! defined($xlabel));
 9019:     $ylabel = '' if (! defined($ylabel));
 9020:     my %ValuesHash = 
 9021:         (
 9022:          $id.'.title'  => &escape($Title),
 9023:          $id.'.xlabel' => &escape($xlabel),
 9024:          $id.'.ylabel' => &escape($ylabel),
 9025:          $id.'.y_max_value'=> $Max,
 9026:          $id.'.labels'     => join(',',@$Xlabels),
 9027:          $id.'.PlotType'   => 'XY',
 9028:          );
 9029:     #
 9030:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9031:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9032:     }
 9033:     #
 9034:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 9035:         return '';
 9036:     }
 9037:     my $NumSets=1;
 9038:     foreach my $array (@{$Ydata}){
 9039:         next if (! ref($array));
 9040:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9041:     }
 9042:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 9043:     #
 9044:     # Deal with other parameters
 9045:     while (my ($key,$value) = each(%Values)) {
 9046:         $ValuesHash{$id.'.'.$key} = $value;
 9047:     }
 9048:     #
 9049:     &Apache::lonnet::appenv(\%ValuesHash);
 9050:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9051: }
 9052: 
 9053: ############################################################
 9054: ############################################################
 9055: 
 9056: =pod
 9057: 
 9058: =item * &DrawXYYGraph()
 9059: 
 9060: Facilitates the plotting of data in an XY graph with two Y axes.
 9061: Puts plot definition data into the users environment in order for 
 9062: graph.png to plot it.  Returns an <img> tag for the plot.
 9063: 
 9064: Inputs:
 9065: 
 9066: =over 4
 9067: 
 9068: =item $Title: string, the title of the plot
 9069: 
 9070: =item $xlabel: string, text describing the X-axis of the plot
 9071: 
 9072: =item $ylabel: string, text describing the Y-axis of the plot
 9073: 
 9074: =item $colors: Array ref containing the hex color codes for the data to be 
 9075: plotted in.  If undefined, default values will be used.
 9076: 
 9077: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 9078: 
 9079: =item $Ydata1: The first data set
 9080: 
 9081: =item $Min1: The minimum value of the left Y-axis
 9082: 
 9083: =item $Max1: The maximum value of the left Y-axis
 9084: 
 9085: =item $Ydata2: The second data set
 9086: 
 9087: =item $Min2: The minimum value of the right Y-axis
 9088: 
 9089: =item $Max2: The maximum value of the left Y-axis
 9090: 
 9091: =item %Values: hash indicating or overriding any default values which are 
 9092: passed to graph.png.  
 9093: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 9094: 
 9095: =back
 9096: 
 9097: Returns:
 9098: 
 9099: An <img> tag which references graph.png and the appropriate identifying
 9100: information for the plot.
 9101: 
 9102: =cut
 9103: 
 9104: ############################################################
 9105: ############################################################
 9106: sub DrawXYYGraph {
 9107:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 9108:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 9109:     #
 9110:     # Create the identifier for the graph
 9111:     my $identifier = &get_cgi_id();
 9112:     my $id = 'cgi.'.$identifier;
 9113:     #
 9114:     $Title  = '' if (! defined($Title));
 9115:     $xlabel = '' if (! defined($xlabel));
 9116:     $ylabel = '' if (! defined($ylabel));
 9117:     my %ValuesHash = 
 9118:         (
 9119:          $id.'.title'  => &escape($Title),
 9120:          $id.'.xlabel' => &escape($xlabel),
 9121:          $id.'.ylabel' => &escape($ylabel),
 9122:          $id.'.labels' => join(',',@$Xlabels),
 9123:          $id.'.PlotType' => 'XY',
 9124:          $id.'.NumSets' => 2,
 9125:          $id.'.two_axes' => 1,
 9126:          $id.'.y1_max_value' => $Max1,
 9127:          $id.'.y1_min_value' => $Min1,
 9128:          $id.'.y2_max_value' => $Max2,
 9129:          $id.'.y2_min_value' => $Min2,
 9130:          );
 9131:     #
 9132:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 9133:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 9134:     }
 9135:     #
 9136:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 9137:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 9138:         return '';
 9139:     }
 9140:     my $NumSets=1;
 9141:     foreach my $array ($Ydata1,$Ydata2){
 9142:         next if (! ref($array));
 9143:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 9144:     }
 9145:     #
 9146:     # Deal with other parameters
 9147:     while (my ($key,$value) = each(%Values)) {
 9148:         $ValuesHash{$id.'.'.$key} = $value;
 9149:     }
 9150:     #
 9151:     &Apache::lonnet::appenv(\%ValuesHash);
 9152:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 9153: }
 9154: 
 9155: ############################################################
 9156: ############################################################
 9157: 
 9158: =pod
 9159: 
 9160: =back 
 9161: 
 9162: =head1 Statistics helper routines?  
 9163: 
 9164: Bad place for them but what the hell.
 9165: 
 9166: =over 4
 9167: 
 9168: =item * &chartlink()
 9169: 
 9170: Returns a link to the chart for a specific student.  
 9171: 
 9172: Inputs:
 9173: 
 9174: =over 4
 9175: 
 9176: =item $linktext: The text of the link
 9177: 
 9178: =item $sname: The students username
 9179: 
 9180: =item $sdomain: The students domain
 9181: 
 9182: =back
 9183: 
 9184: =back
 9185: 
 9186: =cut
 9187: 
 9188: ############################################################
 9189: ############################################################
 9190: sub chartlink {
 9191:     my ($linktext, $sname, $sdomain) = @_;
 9192:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 9193:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 9194:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 9195:        '">'.$linktext.'</a>';
 9196: }
 9197: 
 9198: #######################################################
 9199: #######################################################
 9200: 
 9201: =pod
 9202: 
 9203: =head1 Course Environment Routines
 9204: 
 9205: =over 4
 9206: 
 9207: =item * &restore_course_settings()
 9208: 
 9209: =item * &store_course_settings()
 9210: 
 9211: Restores/Store indicated form parameters from the course environment.
 9212: Will not overwrite existing values of the form parameters.
 9213: 
 9214: Inputs: 
 9215: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 9216: 
 9217: a hash ref describing the data to be stored.  For example:
 9218:    
 9219: %Save_Parameters = ('Status' => 'scalar',
 9220:     'chartoutputmode' => 'scalar',
 9221:     'chartoutputdata' => 'scalar',
 9222:     'Section' => 'array',
 9223:     'Group' => 'array',
 9224:     'StudentData' => 'array',
 9225:     'Maps' => 'array');
 9226: 
 9227: Returns: both routines return nothing
 9228: 
 9229: =back
 9230: 
 9231: =cut
 9232: 
 9233: #######################################################
 9234: #######################################################
 9235: sub store_course_settings {
 9236:     return &store_settings($env{'request.course.id'},@_);
 9237: }
 9238: 
 9239: sub store_settings {
 9240:     # save to the environment
 9241:     # appenv the same items, just to be safe
 9242:     my $udom  = $env{'user.domain'};
 9243:     my $uname = $env{'user.name'};
 9244:     my ($context,$prefix,$Settings) = @_;
 9245:     my %SaveHash;
 9246:     my %AppHash;
 9247:     while (my ($setting,$type) = each(%$Settings)) {
 9248:         my $basename = join('.','internal',$context,$prefix,$setting);
 9249:         my $envname = 'environment.'.$basename;
 9250:         if (exists($env{'form.'.$setting})) {
 9251:             # Save this value away
 9252:             if ($type eq 'scalar' &&
 9253:                 (! exists($env{$envname}) || 
 9254:                  $env{$envname} ne $env{'form.'.$setting})) {
 9255:                 $SaveHash{$basename} = $env{'form.'.$setting};
 9256:                 $AppHash{$envname}   = $env{'form.'.$setting};
 9257:             } elsif ($type eq 'array') {
 9258:                 my $stored_form;
 9259:                 if (ref($env{'form.'.$setting})) {
 9260:                     $stored_form = join(',',
 9261:                                         map {
 9262:                                             &escape($_);
 9263:                                         } sort(@{$env{'form.'.$setting}}));
 9264:                 } else {
 9265:                     $stored_form = 
 9266:                         &escape($env{'form.'.$setting});
 9267:                 }
 9268:                 # Determine if the array contents are the same.
 9269:                 if ($stored_form ne $env{$envname}) {
 9270:                     $SaveHash{$basename} = $stored_form;
 9271:                     $AppHash{$envname}   = $stored_form;
 9272:                 }
 9273:             }
 9274:         }
 9275:     }
 9276:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 9277:                                           $udom,$uname);
 9278:     if ($put_result !~ /^(ok|delayed)/) {
 9279:         &Apache::lonnet::logthis('unable to save form parameters, '.
 9280:                                  'got error:'.$put_result);
 9281:     }
 9282:     # Make sure these settings stick around in this session, too
 9283:     &Apache::lonnet::appenv(\%AppHash);
 9284:     return;
 9285: }
 9286: 
 9287: sub restore_course_settings {
 9288:     return &restore_settings($env{'request.course.id'},@_);
 9289: }
 9290: 
 9291: sub restore_settings {
 9292:     my ($context,$prefix,$Settings) = @_;
 9293:     while (my ($setting,$type) = each(%$Settings)) {
 9294:         next if (exists($env{'form.'.$setting}));
 9295:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 9296:             '.'.$setting;
 9297:         if (exists($env{$envname})) {
 9298:             if ($type eq 'scalar') {
 9299:                 $env{'form.'.$setting} = $env{$envname};
 9300:             } elsif ($type eq 'array') {
 9301:                 $env{'form.'.$setting} = [ 
 9302:                                            map { 
 9303:                                                &unescape($_); 
 9304:                                            } split(',',$env{$envname})
 9305:                                            ];
 9306:             }
 9307:         }
 9308:     }
 9309: }
 9310: 
 9311: #######################################################
 9312: #######################################################
 9313: 
 9314: =pod
 9315: 
 9316: =head1 Domain E-mail Routines  
 9317: 
 9318: =over 4
 9319: 
 9320: =item * &build_recipient_list()
 9321: 
 9322: Build recipient lists for five types of e-mail:
 9323: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 9324: (d) Help requests, (e) Course requests needing approval,  generated by
 9325: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
 9326: loncoursequeueadmin.pm respectively.
 9327: 
 9328: Inputs:
 9329: defmail (scalar - email address of default recipient), 
 9330: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 9331: defdom (domain for which to retrieve configuration settings),
 9332: origmail (scalar - email address of recipient from loncapa.conf, 
 9333: i.e., predates configuration by DC via domainprefs.pm 
 9334: 
 9335: Returns: comma separated list of addresses to which to send e-mail.
 9336: 
 9337: =back
 9338: 
 9339: =cut
 9340: 
 9341: ############################################################
 9342: ############################################################
 9343: sub build_recipient_list {
 9344:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 9345:     my @recipients;
 9346:     my $otheremails;
 9347:     my %domconfig =
 9348:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 9349:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9350:         if (exists($domconfig{'contacts'}{$mailing})) {
 9351:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 9352:                 my @contacts = ('adminemail','supportemail');
 9353:                 foreach my $item (@contacts) {
 9354:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 9355:                         my $addr = $domconfig{'contacts'}{$item}; 
 9356:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 9357:                             push(@recipients,$addr);
 9358:                         }
 9359:                     }
 9360:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 9361:                 }
 9362:             }
 9363:         } elsif ($origmail ne '') {
 9364:             push(@recipients,$origmail);
 9365:         }
 9366:     } elsif ($origmail ne '') {
 9367:         push(@recipients,$origmail);
 9368:     }
 9369:     if (defined($defmail)) {
 9370:         if ($defmail ne '') {
 9371:             push(@recipients,$defmail);
 9372:         }
 9373:     }
 9374:     if ($otheremails) {
 9375:         my @others;
 9376:         if ($otheremails =~ /,/) {
 9377:             @others = split(/,/,$otheremails);
 9378:         } else {
 9379:             push(@others,$otheremails);
 9380:         }
 9381:         foreach my $addr (@others) {
 9382:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 9383:                 push(@recipients,$addr);
 9384:             }
 9385:         }
 9386:     }
 9387:     my $recipientlist = join(',',@recipients); 
 9388:     return $recipientlist;
 9389: }
 9390: 
 9391: ############################################################
 9392: ############################################################
 9393: 
 9394: =pod
 9395: 
 9396: =head1 Course Catalog Routines
 9397: 
 9398: =over 4
 9399: 
 9400: =item * &gather_categories()
 9401: 
 9402: Converts category definitions - keys of categories hash stored in  
 9403: coursecategories in configuration.db on the primary library server in a 
 9404: domain - to an array.  Also generates javascript and idx hash used to 
 9405: generate Domain Coordinator interface for editing Course Categories.
 9406: 
 9407: Inputs:
 9408: 
 9409: categories (reference to hash of category definitions).
 9410: 
 9411: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9412:       categories and subcategories).
 9413: 
 9414: idx (reference to hash of counters used in Domain Coordinator interface for 
 9415:       editing Course Categories).
 9416: 
 9417: jsarray (reference to array of categories used to create Javascript arrays for
 9418:          Domain Coordinator interface for editing Course Categories).
 9419: 
 9420: Returns: nothing
 9421: 
 9422: Side effects: populates cats, idx and jsarray. 
 9423: 
 9424: =cut
 9425: 
 9426: sub gather_categories {
 9427:     my ($categories,$cats,$idx,$jsarray) = @_;
 9428:     my %counters;
 9429:     my $num = 0;
 9430:     foreach my $item (keys(%{$categories})) {
 9431:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 9432:         if ($container eq '' && $depth == 0) {
 9433:             $cats->[$depth][$categories->{$item}] = $cat;
 9434:         } else {
 9435:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 9436:         }
 9437:         my ($escitem,$tail) = split(/:/,$item,2);
 9438:         if ($counters{$tail} eq '') {
 9439:             $counters{$tail} = $num;
 9440:             $num ++;
 9441:         }
 9442:         if (ref($idx) eq 'HASH') {
 9443:             $idx->{$item} = $counters{$tail};
 9444:         }
 9445:         if (ref($jsarray) eq 'ARRAY') {
 9446:             push(@{$jsarray->[$counters{$tail}]},$item);
 9447:         }
 9448:     }
 9449:     return;
 9450: }
 9451: 
 9452: =pod
 9453: 
 9454: =item * &extract_categories()
 9455: 
 9456: Used to generate breadcrumb trails for course categories.
 9457: 
 9458: Inputs:
 9459: 
 9460: categories (reference to hash of category definitions).
 9461: 
 9462: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9463:       categories and subcategories).
 9464: 
 9465: trails (reference to array of breacrumb trails for each category).
 9466: 
 9467: allitems (reference to hash - key is category key 
 9468:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9469: 
 9470: idx (reference to hash of counters used in Domain Coordinator interface for
 9471:       editing Course Categories).
 9472: 
 9473: jsarray (reference to array of categories used to create Javascript arrays for
 9474:          Domain Coordinator interface for editing Course Categories).
 9475: 
 9476: subcats (reference to hash of arrays containing all subcategories within each 
 9477:          category, -recursive)
 9478: 
 9479: Returns: nothing
 9480: 
 9481: Side effects: populates trails and allitems hash references.
 9482: 
 9483: =cut
 9484: 
 9485: sub extract_categories {
 9486:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 9487:     if (ref($categories) eq 'HASH') {
 9488:         &gather_categories($categories,$cats,$idx,$jsarray);
 9489:         if (ref($cats->[0]) eq 'ARRAY') {
 9490:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 9491:                 my $name = $cats->[0][$i];
 9492:                 my $item = &escape($name).'::0';
 9493:                 my $trailstr;
 9494:                 if ($name eq 'instcode') {
 9495:                     $trailstr = &mt('Official courses (with institutional codes)');
 9496:                 } else {
 9497:                     $trailstr = $name;
 9498:                 }
 9499:                 if ($allitems->{$item} eq '') {
 9500:                     push(@{$trails},$trailstr);
 9501:                     $allitems->{$item} = scalar(@{$trails})-1;
 9502:                 }
 9503:                 my @parents = ($name);
 9504:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 9505:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 9506:                         my $category = $cats->[1]{$name}[$j];
 9507:                         if (ref($subcats) eq 'HASH') {
 9508:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 9509:                         }
 9510:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 9511:                     }
 9512:                 } else {
 9513:                     if (ref($subcats) eq 'HASH') {
 9514:                         $subcats->{$item} = [];
 9515:                     }
 9516:                 }
 9517:             }
 9518:         }
 9519:     }
 9520:     return;
 9521: }
 9522: 
 9523: =pod
 9524: 
 9525: =item *&recurse_categories()
 9526: 
 9527: Recursively used to generate breadcrumb trails for course categories.
 9528: 
 9529: Inputs:
 9530: 
 9531: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 9532:       categories and subcategories).
 9533: 
 9534: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 9535: 
 9536: category (current course category, for which breadcrumb trail is being generated).
 9537: 
 9538: trails (reference to array of breadcrumb trails for each category).
 9539: 
 9540: allitems (reference to hash - key is category key
 9541:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 9542: 
 9543: parents (array containing containers directories for current category, 
 9544:          back to top level). 
 9545: 
 9546: Returns: nothing
 9547: 
 9548: Side effects: populates trails and allitems hash references
 9549: 
 9550: =cut
 9551: 
 9552: sub recurse_categories {
 9553:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 9554:     my $shallower = $depth - 1;
 9555:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 9556:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 9557:             my $name = $cats->[$depth]{$category}[$k];
 9558:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9559:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9560:             if ($allitems->{$item} eq '') {
 9561:                 push(@{$trails},$trailstr);
 9562:                 $allitems->{$item} = scalar(@{$trails})-1;
 9563:             }
 9564:             my $deeper = $depth+1;
 9565:             push(@{$parents},$category);
 9566:             if (ref($subcats) eq 'HASH') {
 9567:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 9568:                 for (my $j=@{$parents}; $j>=0; $j--) {
 9569:                     my $higher;
 9570:                     if ($j > 0) {
 9571:                         $higher = &escape($parents->[$j]).':'.
 9572:                                   &escape($parents->[$j-1]).':'.$j;
 9573:                     } else {
 9574:                         $higher = &escape($parents->[$j]).'::'.$j;
 9575:                     }
 9576:                     push(@{$subcats->{$higher}},$subcat);
 9577:                 }
 9578:             }
 9579:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 9580:                                 $subcats);
 9581:             pop(@{$parents});
 9582:         }
 9583:     } else {
 9584:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 9585:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 9586:         if ($allitems->{$item} eq '') {
 9587:             push(@{$trails},$trailstr);
 9588:             $allitems->{$item} = scalar(@{$trails})-1;
 9589:         }
 9590:     }
 9591:     return;
 9592: }
 9593: 
 9594: =pod
 9595: 
 9596: =item *&assign_categories_table()
 9597: 
 9598: Create a datatable for display of hierarchical categories in a domain,
 9599: with checkboxes to allow a course to be categorized. 
 9600: 
 9601: Inputs:
 9602: 
 9603: cathash - reference to hash of categories defined for the domain (from
 9604:           configuration.db)
 9605: 
 9606: currcat - scalar with an & separated list of categories assigned to a course. 
 9607: 
 9608: Returns: $output (markup to be displayed) 
 9609: 
 9610: =cut
 9611: 
 9612: sub assign_categories_table {
 9613:     my ($cathash,$currcat) = @_;
 9614:     my $output;
 9615:     if (ref($cathash) eq 'HASH') {
 9616:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9617:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9618:         $maxdepth = scalar(@cats);
 9619:         if (@cats > 0) {
 9620:             my $itemcount = 0;
 9621:             if (ref($cats[0]) eq 'ARRAY') {
 9622:                 $output = &Apache::loncommon::start_data_table();
 9623:                 my @currcategories;
 9624:                 if ($currcat ne '') {
 9625:                     @currcategories = split('&',$currcat);
 9626:                 }
 9627:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9628:                     my $parent = $cats[0][$i];
 9629:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9630:                     next if ($parent eq 'instcode');
 9631:                     my $item = &escape($parent).'::0';
 9632:                     my $checked = '';
 9633:                     if (@currcategories > 0) {
 9634:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9635:                             $checked = ' checked="checked"';
 9636:                         }
 9637:                     }
 9638:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9639:                                '<input type="checkbox" name="usecategory" value="'.
 9640:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9641:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9642:                     my $depth = 1;
 9643:                     push(@path,$parent);
 9644:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9645:                     pop(@path);
 9646:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9647:                     $itemcount ++;
 9648:                 }
 9649:                 $output .= &Apache::loncommon::end_data_table();
 9650:             }
 9651:         }
 9652:     }
 9653:     return $output;
 9654: }
 9655: 
 9656: =pod
 9657: 
 9658: =item *&assign_category_rows()
 9659: 
 9660: Create a datatable row for display of nested categories in a domain,
 9661: with checkboxes to allow a course to be categorized,called recursively.
 9662: 
 9663: Inputs:
 9664: 
 9665: itemcount - track row number for alternating colors
 9666: 
 9667: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9668:       categories and subcategories.
 9669: 
 9670: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9671: 
 9672: parent - parent of current category item
 9673: 
 9674: path - Array containing all categories back up through the hierarchy from the
 9675:        current category to the top level.
 9676: 
 9677: currcategories - reference to array of current categories assigned to the course
 9678: 
 9679: Returns: $output (markup to be displayed).
 9680: 
 9681: =cut
 9682: 
 9683: sub assign_category_rows {
 9684:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9685:     my ($text,$name,$item,$chgstr);
 9686:     if (ref($cats) eq 'ARRAY') {
 9687:         my $maxdepth = scalar(@{$cats});
 9688:         if (ref($cats->[$depth]) eq 'HASH') {
 9689:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9690:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9691:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9692:                 $text .= '<td><table class="LC_datatable">';
 9693:                 for (my $j=0; $j<$numchildren; $j++) {
 9694:                     $name = $cats->[$depth]{$parent}[$j];
 9695:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9696:                     my $deeper = $depth+1;
 9697:                     my $checked = '';
 9698:                     if (ref($currcategories) eq 'ARRAY') {
 9699:                         if (@{$currcategories} > 0) {
 9700:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9701:                                 $checked = ' checked="checked"';
 9702:                             }
 9703:                         }
 9704:                     }
 9705:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9706:                              '<input type="checkbox" name="usecategory" value="'.
 9707:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9708:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9709:                              '</td><td>';
 9710:                     if (ref($path) eq 'ARRAY') {
 9711:                         push(@{$path},$name);
 9712:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9713:                         pop(@{$path});
 9714:                     }
 9715:                     $text .= '</td></tr>';
 9716:                 }
 9717:                 $text .= '</table></td>';
 9718:             }
 9719:         }
 9720:     }
 9721:     return $text;
 9722: }
 9723: 
 9724: ############################################################
 9725: ############################################################
 9726: 
 9727: 
 9728: sub commit_customrole {
 9729:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9730:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9731:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9732:                          ($end?', ending '.localtime($end):'').': <b>'.
 9733:               &Apache::lonnet::assigncustomrole(
 9734:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9735:                  '</b><br />';
 9736:     return $output;
 9737: }
 9738: 
 9739: sub commit_standardrole {
 9740:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9741:     my ($output,$logmsg,$linefeed);
 9742:     if ($context eq 'auto') {
 9743:         $linefeed = "\n";
 9744:     } else {
 9745:         $linefeed = "<br />\n";
 9746:     }  
 9747:     if ($three eq 'st') {
 9748:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9749:                                          $one,$two,$sec,$context);
 9750:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9751:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9752:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9753:         } else {
 9754:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9755:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9756:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9757:             if ($context eq 'auto') {
 9758:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9759:             } else {
 9760:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9761:                &mt('Add to classlist').': <b>ok</b>';
 9762:             }
 9763:             $output .= $linefeed;
 9764:         }
 9765:     } else {
 9766:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9767:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9768:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9769:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9770:         if ($context eq 'auto') {
 9771:             $output .= $result.$linefeed;
 9772:         } else {
 9773:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9774:         }
 9775:     }
 9776:     return $output;
 9777: }
 9778: 
 9779: sub commit_studentrole {
 9780:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9781:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9782:     if ($context eq 'auto') {
 9783:         $linefeed = "\n";
 9784:     } else {
 9785:         $linefeed = '<br />'."\n";
 9786:     }
 9787:     if (defined($one) && defined($two)) {
 9788:         my $cid=$one.'_'.$two;
 9789:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9790:         my $secchange = 0;
 9791:         my $expire_role_result;
 9792:         my $modify_section_result;
 9793:         if ($oldsec ne '-1') { 
 9794:             if ($oldsec ne $sec) {
 9795:                 $secchange = 1;
 9796:                 my $now = time;
 9797:                 my $uurl='/'.$cid;
 9798:                 $uurl=~s/\_/\//g;
 9799:                 if ($oldsec) {
 9800:                     $uurl.='/'.$oldsec;
 9801:                 }
 9802:                 $oldsecurl = $uurl;
 9803:                 $expire_role_result = 
 9804:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9805:                 if ($env{'request.course.sec'} ne '') { 
 9806:                     if ($expire_role_result eq 'refused') {
 9807:                         my @roles = ('st');
 9808:                         my @statuses = ('previous');
 9809:                         my @roledoms = ($one);
 9810:                         my $withsec = 1;
 9811:                         my %roleshash = 
 9812:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9813:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9814:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9815:                             my ($oldstart,$oldend) = 
 9816:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9817:                             if ($oldend > 0 && $oldend <= $now) {
 9818:                                 $expire_role_result = 'ok';
 9819:                             }
 9820:                         }
 9821:                     }
 9822:                 }
 9823:                 $result = $expire_role_result;
 9824:             }
 9825:         }
 9826:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9827:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9828:             if ($modify_section_result =~ /^ok/) {
 9829:                 if ($secchange == 1) {
 9830:                     if ($sec eq '') {
 9831:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9832:                     } else {
 9833:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9834:                     }
 9835:                 } elsif ($oldsec eq '-1') {
 9836:                     if ($sec eq '') {
 9837:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9838:                     } else {
 9839:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9840:                     }
 9841:                 } else {
 9842:                     if ($sec eq '') {
 9843:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9844:                     } else {
 9845:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9846:                     }
 9847:                 }
 9848:             } else {
 9849:                 if ($secchange) {       
 9850:                     $$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;
 9851:                 } else {
 9852:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9853:                 }
 9854:             }
 9855:             $result = $modify_section_result;
 9856:         } elsif ($secchange == 1) {
 9857:             if ($oldsec eq '') {
 9858:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9859:             } else {
 9860:                 $$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;
 9861:             }
 9862:             if ($expire_role_result eq 'refused') {
 9863:                 my $newsecurl = '/'.$cid;
 9864:                 $newsecurl =~ s/\_/\//g;
 9865:                 if ($sec ne '') {
 9866:                     $newsecurl.='/'.$sec;
 9867:                 }
 9868:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9869:                     if ($sec eq '') {
 9870:                         $$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;
 9871:                     } else {
 9872:                         $$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;
 9873:                     }
 9874:                 }
 9875:             }
 9876:         }
 9877:     } else {
 9878:         $$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;
 9879:         $result = "error: incomplete course id\n";
 9880:     }
 9881:     return $result;
 9882: }
 9883: 
 9884: ############################################################
 9885: ############################################################
 9886: 
 9887: sub check_clone {
 9888:     my ($args,$linefeed) = @_;
 9889:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9890:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9891:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9892:     my $clonemsg;
 9893:     my $can_clone = 0;
 9894: 
 9895:     if ($clonehome eq 'no_host') {
 9896:         $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'});     
 9897:     } else {
 9898: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9899: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
 9900:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
 9901: 	    $can_clone = 1;
 9902: 	} else {
 9903: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9904: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9905: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9906:             if (grep(/^\*$/,@cloners)) {
 9907:                 $can_clone = 1;
 9908:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9909:                 $can_clone = 1;
 9910:             } else {
 9911: 	        my %roleshash =
 9912: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9913: 					 $args->{'ccdomain'},
 9914:                                          'userroles',['active'],['cc'],
 9915: 					 [$args->{'clonedomain'}]);
 9916: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9917: 		    $can_clone = 1;
 9918: 	        } else {
 9919:                     $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'});
 9920: 	        }
 9921: 	    }
 9922:         }
 9923:     }
 9924:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9925: }
 9926: 
 9927: sub construct_course {
 9928:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
 9929:     my $outcome;
 9930:     my $linefeed =  '<br />'."\n";
 9931:     if ($context eq 'auto') {
 9932:         $linefeed = "\n";
 9933:     }
 9934: 
 9935: #
 9936: # Are we cloning?
 9937: #
 9938:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9939:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9940: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9941: 	if ($context ne 'auto') {
 9942:             if ($clonemsg ne '') {
 9943: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9944:             }
 9945: 	}
 9946: 	$outcome .= $clonemsg.$linefeed;
 9947: 
 9948:         if (!$can_clone) {
 9949: 	    return (0,$outcome);
 9950: 	}
 9951:     }
 9952: 
 9953: #
 9954: # Open course
 9955: #
 9956:     my $crstype = lc($args->{'crstype'});
 9957:     my %cenv=();
 9958:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9959:                                              $args->{'cdescr'},
 9960:                                              $args->{'curl'},
 9961:                                              $args->{'course_home'},
 9962:                                              $args->{'nonstandard'},
 9963:                                              $args->{'crscode'},
 9964:                                              $args->{'ccuname'}.':'.
 9965:                                              $args->{'ccdomain'},
 9966:                                              $args->{'crstype'},
 9967:                                              $cnum,$context,$category);
 9968: 
 9969:     # Note: The testing routines depend on this being output; see 
 9970:     # Utils::Course. This needs to at least be output as a comment
 9971:     # if anyone ever decides to not show this, and Utils::Course::new
 9972:     # will need to be suitably modified.
 9973:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9974: #
 9975: # Check if created correctly
 9976: #
 9977:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9978:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9979:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9980: 
 9981: #
 9982: # Do the cloning
 9983: #   
 9984:     if ($can_clone && $cloneid) {
 9985: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9986: 	if ($context ne 'auto') {
 9987: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9988: 	}
 9989: 	$outcome .= $clonemsg.$linefeed;
 9990: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9991: # Copy all files
 9992: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9993: # Restore URL
 9994: 	$cenv{'url'}=$oldcenv{'url'};
 9995: # Restore title
 9996: 	$cenv{'description'}=$oldcenv{'description'};
 9997: # Mark as cloned
 9998: 	$cenv{'clonedfrom'}=$cloneid;
 9999: # Need to clone grading mode
10000:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
10001:         $cenv{'grading'}=$newenv{'grading'};
10002: # Do not clone these environment entries
10003:         &Apache::lonnet::del('environment',
10004:                   ['default_enrollment_start_date',
10005:                    'default_enrollment_end_date',
10006:                    'question.email',
10007:                    'policy.email',
10008:                    'comment.email',
10009:                    'pch.users.denied',
10010:                    'plc.users.denied',
10011:                    'hidefromcat',
10012:                    'categories'],
10013:                    $$crsudom,$$crsunum);
10014:     }
10015: 
10016: #
10017: # Set environment (will override cloned, if existing)
10018: #
10019:     my @sections = ();
10020:     my @xlists = ();
10021:     if ($args->{'crstype'}) {
10022:         $cenv{'type'}=$args->{'crstype'};
10023:     }
10024:     if ($args->{'crsid'}) {
10025:         $cenv{'courseid'}=$args->{'crsid'};
10026:     }
10027:     if ($args->{'crscode'}) {
10028:         $cenv{'internal.coursecode'}=$args->{'crscode'};
10029:     }
10030:     if ($args->{'crsquota'} ne '') {
10031:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
10032:     } else {
10033:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
10034:     }
10035:     if ($args->{'ccuname'}) {
10036:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
10037:                                         ':'.$args->{'ccdomain'};
10038:     } else {
10039:         $cenv{'internal.courseowner'} = $args->{'curruser'};
10040:     }
10041:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
10042:     if ($args->{'crssections'}) {
10043:         $cenv{'internal.sectionnums'} = '';
10044:         if ($args->{'crssections'} =~ m/,/) {
10045:             @sections = split/,/,$args->{'crssections'};
10046:         } else {
10047:             $sections[0] = $args->{'crssections'};
10048:         }
10049:         if (@sections > 0) {
10050:             foreach my $item (@sections) {
10051:                 my ($sec,$gp) = split/:/,$item;
10052:                 my $class = $args->{'crscode'}.$sec;
10053:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
10054:                 $cenv{'internal.sectionnums'} .= $item.',';
10055:                 unless ($addcheck eq 'ok') {
10056:                     push @badclasses, $class;
10057:                 }
10058:             }
10059:             $cenv{'internal.sectionnums'} =~ s/,$//;
10060:         }
10061:     }
10062: # do not hide course coordinator from staff listing, 
10063: # even if privileged
10064:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10065: # add crosslistings
10066:     if ($args->{'crsxlist'}) {
10067:         $cenv{'internal.crosslistings'}='';
10068:         if ($args->{'crsxlist'} =~ m/,/) {
10069:             @xlists = split/,/,$args->{'crsxlist'};
10070:         } else {
10071:             $xlists[0] = $args->{'crsxlist'};
10072:         }
10073:         if (@xlists > 0) {
10074:             foreach my $item (@xlists) {
10075:                 my ($xl,$gp) = split/:/,$item;
10076:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
10077:                 $cenv{'internal.crosslistings'} .= $item.',';
10078:                 unless ($addcheck eq 'ok') {
10079:                     push @badclasses, $xl;
10080:                 }
10081:             }
10082:             $cenv{'internal.crosslistings'} =~ s/,$//;
10083:         }
10084:     }
10085:     if ($args->{'autoadds'}) {
10086:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
10087:     }
10088:     if ($args->{'autodrops'}) {
10089:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
10090:     }
10091: # check for notification of enrollment changes
10092:     my @notified = ();
10093:     if ($args->{'notify_owner'}) {
10094:         if ($args->{'ccuname'} ne '') {
10095:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
10096:         }
10097:     }
10098:     if ($args->{'notify_dc'}) {
10099:         if ($uname ne '') { 
10100:             push(@notified,$uname.':'.$udom);
10101:         }
10102:     }
10103:     if (@notified > 0) {
10104:         my $notifylist;
10105:         if (@notified > 1) {
10106:             $notifylist = join(',',@notified);
10107:         } else {
10108:             $notifylist = $notified[0];
10109:         }
10110:         $cenv{'internal.notifylist'} = $notifylist;
10111:     }
10112:     if (@badclasses > 0) {
10113:         my %lt=&Apache::lonlocal::texthash(
10114:                 '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',
10115:                 'dnhr' => 'does not have rights to access enrollment in these classes',
10116:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
10117:         );
10118:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
10119:                            ' ('.$lt{'adby'}.')';
10120:         if ($context eq 'auto') {
10121:             $outcome .= $badclass_msg.$linefeed;
10122:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
10123:             foreach my $item (@badclasses) {
10124:                 if ($context eq 'auto') {
10125:                     $outcome .= " - $item\n";
10126:                 } else {
10127:                     $outcome .= "<li>$item</li>\n";
10128:                 }
10129:             }
10130:             if ($context eq 'auto') {
10131:                 $outcome .= $linefeed;
10132:             } else {
10133:                 $outcome .= "</ul><br /><br /></div>\n";
10134:             }
10135:         } 
10136:     }
10137:     if ($args->{'no_end_date'}) {
10138:         $args->{'endaccess'} = 0;
10139:     }
10140:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
10141:     $cenv{'internal.autoend'}=$args->{'enrollend'};
10142:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
10143:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
10144:     if ($args->{'showphotos'}) {
10145:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
10146:     }
10147:     $cenv{'internal.authtype'} = $args->{'authtype'};
10148:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
10149:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
10150:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
10151:             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'); 
10152:             if ($context eq 'auto') {
10153:                 $outcome .= $krb_msg;
10154:             } else {
10155:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
10156:             }
10157:             $outcome .= $linefeed;
10158:         }
10159:     }
10160:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
10161:        if ($args->{'setpolicy'}) {
10162:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10163:        }
10164:        if ($args->{'setcontent'}) {
10165:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
10166:        }
10167:     }
10168:     if ($args->{'reshome'}) {
10169: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
10170: 	$cenv{'reshome'}=~s/\/+$/\//;
10171:     }
10172: #
10173: # course has keyed access
10174: #
10175:     if ($args->{'setkeys'}) {
10176:        $cenv{'keyaccess'}='yes';
10177:     }
10178: # if specified, key authority is not course, but user
10179: # only active if keyaccess is yes
10180:     if ($args->{'keyauth'}) {
10181: 	my ($user,$domain) = split(':',$args->{'keyauth'});
10182: 	$user = &LONCAPA::clean_username($user);
10183: 	$domain = &LONCAPA::clean_username($domain);
10184: 	if ($user ne '' && $domain ne '') {
10185: 	    $cenv{'keyauth'}=$user.':'.$domain;
10186: 	}
10187:     }
10188: 
10189:     if ($args->{'disresdis'}) {
10190:         $cenv{'pch.roles.denied'}='st';
10191:     }
10192:     if ($args->{'disablechat'}) {
10193:         $cenv{'plc.roles.denied'}='st';
10194:     }
10195: 
10196:     # Record we've not yet viewed the Course Initialization Helper for this 
10197:     # course
10198:     $cenv{'course.helper.not.run'} = 1;
10199:     #
10200:     # Use new Randomseed
10201:     #
10202:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
10203:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
10204:     #
10205:     # The encryption code and receipt prefix for this course
10206:     #
10207:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
10208:     $cenv{'internal.encpref'}=100+int(9*rand(99));
10209:     #
10210:     # By default, use standard grading
10211:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
10212: 
10213:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
10214:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
10215: #
10216: # Open all assignments
10217: #
10218:     if ($args->{'openall'}) {
10219:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
10220:        my %storecontent = ($storeunder         => time,
10221:                            $storeunder.'.type' => 'date_start');
10222:        
10223:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
10224:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
10225:    }
10226: #
10227: # Set first page
10228: #
10229:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
10230: 	    || ($cloneid)) {
10231: 	use LONCAPA::map;
10232: 	$outcome .= &mt('Setting first resource').': ';
10233: 
10234: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
10235:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
10236: 
10237:         $outcome .= ($fatal?$errtext:'read ok').' - ';
10238:         my $title; my $url;
10239:         if ($args->{'firstres'} eq 'syl') {
10240: 	    $title=&mt('Syllabus');
10241:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
10242:         } else {
10243:             $title=&mt('Navigate Contents');
10244:             $url='/adm/navmaps';
10245:         }
10246: 
10247:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
10248: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
10249: 
10250: 	if ($errtext) { $fatal=2; }
10251:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
10252:     }
10253: 
10254:     return (1,$outcome);
10255: }
10256: 
10257: ############################################################
10258: ############################################################
10259: 
10260: sub course_type {
10261:     my ($cid) = @_;
10262:     if (!defined($cid)) {
10263:         $cid = $env{'request.course.id'};
10264:     }
10265:     if (defined($env{'course.'.$cid.'.type'})) {
10266:         return $env{'course.'.$cid.'.type'};
10267:     } else {
10268:         return 'Course';
10269:     }
10270: }
10271: 
10272: sub group_term {
10273:     my $crstype = &course_type();
10274:     my %names = (
10275:                   'Course' => 'group',
10276:                   'Community' => 'group',
10277:                 );
10278:     return $names{$crstype};
10279: }
10280: 
10281: sub icon {
10282:     my ($file)=@_;
10283:     my $curfext = lc((split(/\./,$file))[-1]);
10284:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
10285:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
10286:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
10287: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
10288: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10289: 	            $curfext.".gif") {
10290: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
10291: 		$curfext.".gif";
10292: 	}
10293:     }
10294:     return &lonhttpdurl($iconname);
10295: } 
10296: 
10297: sub lonhttpdurl {
10298: #
10299: # Had been used for "small fry" static images on separate port 8080.
10300: # Modify here if lightweight http functionality desired again.
10301: # Currently eliminated due to increasing firewall issues.
10302: #
10303:     my ($url)=@_;
10304:     return $url;
10305: }
10306: 
10307: sub connection_aborted {
10308:     my ($r)=@_;
10309:     $r->print(" ");$r->rflush();
10310:     my $c = $r->connection;
10311:     return $c->aborted();
10312: }
10313: 
10314: #    Escapes strings that may have embedded 's that will be put into
10315: #    strings as 'strings'.
10316: sub escape_single {
10317:     my ($input) = @_;
10318:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
10319:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
10320:     return $input;
10321: }
10322: 
10323: #  Same as escape_single, but escape's "'s  This 
10324: #  can be used for  "strings"
10325: sub escape_double {
10326:     my ($input) = @_;
10327:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
10328:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
10329:     return $input;
10330: }
10331:  
10332: #   Escapes the last element of a full URL.
10333: sub escape_url {
10334:     my ($url)   = @_;
10335:     my @urlslices = split(/\//, $url,-1);
10336:     my $lastitem = &escape(pop(@urlslices));
10337:     return join('/',@urlslices).'/'.$lastitem;
10338: }
10339: 
10340: sub compare_arrays {
10341:     my ($arrayref1,$arrayref2) = @_;
10342:     my (@difference,%count);
10343:     @difference = ();
10344:     %count = ();
10345:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
10346:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
10347:         foreach my $element (keys(%count)) {
10348:             if ($count{$element} == 1) {
10349:                 push(@difference,$element);
10350:             }
10351:         }
10352:     }
10353:     return @difference;
10354: }
10355: 
10356: # -------------------------------------------------------- Initialize user login
10357: sub init_user_environment {
10358:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
10359:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
10360: 
10361:     my $public=($username eq 'public' && $domain eq 'public');
10362: 
10363: # See if old ID present, if so, remove
10364: 
10365:     my ($filename,$cookie,$userroles);
10366:     my $now=time;
10367: 
10368:     if ($public) {
10369: 	my $max_public=100;
10370: 	my $oldest;
10371: 	my $oldest_time=0;
10372: 	for(my $next=1;$next<=$max_public;$next++) {
10373: 	    if (-e $lonids."/publicuser_$next.id") {
10374: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
10375: 		if ($mtime<$oldest_time || !$oldest_time) {
10376: 		    $oldest_time=$mtime;
10377: 		    $oldest=$next;
10378: 		}
10379: 	    } else {
10380: 		$cookie="publicuser_$next";
10381: 		last;
10382: 	    }
10383: 	}
10384: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
10385:     } else {
10386: 	# if this isn't a robot, kill any existing non-robot sessions
10387: 	if (!$args->{'robot'}) {
10388: 	    opendir(DIR,$lonids);
10389: 	    while ($filename=readdir(DIR)) {
10390: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
10391: 		    unlink($lonids.'/'.$filename);
10392: 		}
10393: 	    }
10394: 	    closedir(DIR);
10395: 	}
10396: # Give them a new cookie
10397: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
10398: 		                   : $now.$$.int(rand(10000)));
10399: 	$cookie="$username\_$id\_$domain\_$authhost";
10400:     
10401: # Initialize roles
10402: 
10403: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
10404:     }
10405: # ------------------------------------ Check browser type and MathML capability
10406: 
10407:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
10408:         $clientunicode,$clientos) = &decode_user_agent($r);
10409: 
10410: # ------------------------------------------------------------- Get environment
10411: 
10412:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
10413:     my ($tmp) = keys(%userenv);
10414:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10415: 	# default remote control to off
10416: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
10417:     } else {
10418: 	undef(%userenv);
10419:     }
10420:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
10421: 	$form->{'interface'}=$userenv{'interface'};
10422:     }
10423:     $env{'environment.remote'}=$userenv{'remote'};
10424:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
10425: 
10426: # --------------- Do not trust query string to be put directly into environment
10427:     foreach my $option ('interface','localpath','localres') {
10428:         $form->{$option}=~s/[\n\r\=]//gs;
10429:     }
10430: # --------------------------------------------------------- Write first profile
10431: 
10432:     {
10433: 	my %initial_env = 
10434: 	    ("user.name"          => $username,
10435: 	     "user.domain"        => $domain,
10436: 	     "user.home"          => $authhost,
10437: 	     "browser.type"       => $clientbrowser,
10438: 	     "browser.version"    => $clientversion,
10439: 	     "browser.mathml"     => $clientmathml,
10440: 	     "browser.unicode"    => $clientunicode,
10441: 	     "browser.os"         => $clientos,
10442: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
10443: 	     "request.course.fn"  => '',
10444: 	     "request.course.uri" => '',
10445: 	     "request.course.sec" => '',
10446: 	     "request.role"       => 'cm',
10447: 	     "request.role.adv"   => $env{'user.adv'},
10448: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
10449: 
10450:         if ($form->{'localpath'}) {
10451: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
10452: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
10453:         }
10454: 	
10455: 	if ($public) {
10456: 	    $initial_env{"environment.remote"} = "off";
10457: 	}
10458: 	if ($form->{'interface'}) {
10459: 	    $form->{'interface'}=~s/\W//gs;
10460: 	    $initial_env{"browser.interface"} = $form->{'interface'};
10461: 	    $env{'browser.interface'}=$form->{'interface'};
10462: 	}
10463: 
10464:         foreach my $tool ('aboutme','blog','portfolio') {
10465:             $userenv{'availabletools.'.$tool} = 
10466:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10467:         }
10468: 
10469:         foreach my $crstype ('official','unofficial','community') {
10470:             $userenv{'canrequest.'.$crstype} =
10471:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
10472:                                                   'reload','requestcourses');
10473:         }
10474: 
10475: 	$env{'user.environment'} = "$lonids/$cookie.id";
10476: 	
10477: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10478: 		 &GDBM_WRCREAT(),0640)) {
10479: 	    &_add_to_env(\%disk_env,\%initial_env);
10480: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
10481: 	    &_add_to_env(\%disk_env,$userroles);
10482: 	    if (ref($args->{'extra_env'})) {
10483: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
10484: 	    }
10485: 	    untie(%disk_env);
10486: 	} else {
10487: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
10488: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
10489: 	    return 'error: '.$!;
10490: 	}
10491:     }
10492:     $env{'request.role'}='cm';
10493:     $env{'request.role.adv'}=$env{'user.adv'};
10494:     $env{'browser.type'}=$clientbrowser;
10495: 
10496:     return $cookie;
10497: 
10498: }
10499: 
10500: sub _add_to_env {
10501:     my ($idf,$env_data,$prefix) = @_;
10502:     if (ref($env_data) eq 'HASH') {
10503:         while (my ($key,$value) = each(%$env_data)) {
10504: 	    $idf->{$prefix.$key} = $value;
10505: 	    $env{$prefix.$key}   = $value;
10506:         }
10507:     }
10508: }
10509: 
10510: # --- Get the symbolic name of a problem and the url
10511: sub get_symb {
10512:     my ($request,$silent) = @_;
10513:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10514:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10515:     if ($symb eq '') {
10516:         if (!$silent) {
10517:             $request->print("Unable to handle ambiguous references:$url:.");
10518:             return ();
10519:         }
10520:     }
10521:     &Apache::lonenc::check_decrypt(\$symb);
10522:     return ($symb);
10523: }
10524: 
10525: # --------------------------------------------------------------Get annotation
10526: 
10527: sub get_annotation {
10528:     my ($symb,$enc) = @_;
10529: 
10530:     my $key = $symb;
10531:     if (!$enc) {
10532:         $key =
10533:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10534:     }
10535:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10536:     return $annotation{$key};
10537: }
10538: 
10539: sub clean_symb {
10540:     my ($symb,$delete_enc) = @_;
10541: 
10542:     &Apache::lonenc::check_decrypt(\$symb);
10543:     my $enc = $env{'request.enc'};
10544:     if ($delete_enc) {
10545:         delete($env{'request.enc'});
10546:     }
10547: 
10548:     return ($symb,$enc);
10549: }
10550: 
10551: =pod
10552: 
10553: =back
10554: 
10555: =cut
10556: 
10557: 1;
10558: __END__;
10559: 

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