File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.692.4.18: download - view: text, annotated - select for diffs
Sat Oct 10 03:40:24 2009 UTC (14 years, 7 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.692: preferred, unified
- Backport 1.893, 1.895.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.692.4.18 2009/10/10 03:40:24 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use LONCAPA qw(:DEFAULT :match);
   71: use DateTime::TimeZone;
   72: use DateTime::Locale::Catalog;
   73: 
   74: # ---------------------------------------------- Designs
   75: use vars qw(%defaultdesign);
   76: 
   77: my $readit;
   78: 
   79: 
   80: ##
   81: ## Global Variables
   82: ##
   83: 
   84: 
   85: # ----------------------------------------------- SSI with retries:
   86: #
   87: 
   88: =pod
   89: 
   90: =head1 Server Side include with retries:
   91: 
   92: =over 4
   93: 
   94: =item * &ssi_with_retries(resource,retries form)
   95: 
   96: Performs an ssi with some number of retries.  Retries continue either
   97: until the result is ok or until the retry count supplied by the
   98: caller is exhausted.  
   99: 
  100: Inputs:
  101: 
  102: =over 4
  103: 
  104: resource   - Identifies the resource to insert.
  105: 
  106: retries    - Count of the number of retries allowed.
  107: 
  108: form       - Hash that identifies the rendering options.
  109: 
  110: =back
  111: 
  112: Returns:
  113: 
  114: =over 4
  115: 
  116: content    - The content of the response.  If retries were exhausted this is empty.
  117: 
  118: response   - The response from the last attempt (which may or may not have been successful.
  119: 
  120: =back
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: sub ssi_with_retries {
  127:     my ($resource, $retries, %form) = @_;
  128: 
  129: 
  130:     my $ok = 0;			# True if we got a good response.
  131:     my $content;
  132:     my $response;
  133: 
  134:     # Try to get the ssi done. within the retries count:
  135: 
  136:     do {
  137: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  138: 	$ok      = $response->is_success;
  139:         if (!$ok) {
  140:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  141:         }
  142: 	$retries--;
  143:     } while (!$ok && ($retries > 0));
  144: 
  145:     if (!$ok) {
  146: 	$content = '';		# On error return an empty content.
  147:     }
  148:     return ($content, $response);
  149: 
  150: }
  151: 
  152: 
  153: 
  154: # ----------------------------------------------- Filetypes/Languages/Copyright
  155: my %language;
  156: my %supported_language;
  157: my %cprtag;
  158: my %scprtag;
  159: my %fe; my %fd; my %fm;
  160: my %category_extensions;
  161: 
  162: # ---------------------------------------------- Thesaurus variables
  163: #
  164: # %Keywords:
  165: #      A hash used by &keyword to determine if a word is considered a keyword.
  166: # $thesaurus_db_file 
  167: #      Scalar containing the full path to the thesaurus database.
  168: 
  169: my %Keywords;
  170: my $thesaurus_db_file;
  171: 
  172: #
  173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  174: # thesaurus.tab, and filecategories.tab.
  175: #
  176: BEGIN {
  177:     # Variable initialization
  178:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  179:     #
  180:     unless ($readit) {
  181: # ------------------------------------------------------------------- languages
  182:     {
  183:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  184:                                    '/language.tab';
  185:         if ( open(my $fh,"<$langtabfile") ) {
  186:             while (my $line = <$fh>) {
  187:                 next if ($line=~/^\#/);
  188:                 chomp($line);
  189:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  190:                 $language{$key}=$val.' - '.$enc;
  191:                 if ($sup) {
  192:                     $supported_language{$key}=$sup;
  193:                 }
  194:             }
  195:             close($fh);
  196:         }
  197:     }
  198: # ------------------------------------------------------------------ copyrights
  199:     {
  200:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  201:                                   '/copyright.tab';
  202:         if ( open (my $fh,"<$copyrightfile") ) {
  203:             while (my $line = <$fh>) {
  204:                 next if ($line=~/^\#/);
  205:                 chomp($line);
  206:                 my ($key,$val)=(split(/\s+/,$line,2));
  207:                 $cprtag{$key}=$val;
  208:             }
  209:             close($fh);
  210:         }
  211:     }
  212: # ----------------------------------------------------------- source copyrights
  213:     {
  214:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  215:                                   '/source_copyright.tab';
  216:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  217:             while (my $line = <$fh>) {
  218:                 next if ($line =~ /^\#/);
  219:                 chomp($line);
  220:                 my ($key,$val)=(split(/\s+/,$line,2));
  221:                 $scprtag{$key}=$val;
  222:             }
  223:             close($fh);
  224:         }
  225:     }
  226: 
  227: # -------------------------------------------------------------- default domain designs
  228:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  229:     my $designfile = $designdir.'/default.tab';
  230:     if ( open (my $fh,"<$designfile") ) {
  231:         while (my $line = <$fh>) {
  232:             next if ($line =~ /^\#/);
  233:             chomp($line);
  234:             my ($key,$val)=(split(/\=/,$line));
  235:             if ($val) { $defaultdesign{$key}=$val; }
  236:         }
  237:         close($fh);
  238:     }
  239: 
  240: # ------------------------------------------------------------- file categories
  241:     {
  242:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  243:                                   '/filecategories.tab';
  244:         if ( open (my $fh,"<$categoryfile") ) {
  245: 	    while (my $line = <$fh>) {
  246: 		next if ($line =~ /^\#/);
  247: 		chomp($line);
  248:                 my ($extension,$category)=(split(/\s+/,$line,2));
  249:                 push @{$category_extensions{lc($category)}},$extension;
  250:             }
  251:             close($fh);
  252:         }
  253: 
  254:     }
  255: # ------------------------------------------------------------------ file types
  256:     {
  257:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  258:                '/filetypes.tab';
  259:         if ( open (my $fh,"<$typesfile") ) {
  260:             while (my $line = <$fh>) {
  261: 		next if ($line =~ /^\#/);
  262: 		chomp($line);
  263:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  264:                 if ($descr ne '') {
  265:                     $fe{$ending}=lc($emb);
  266:                     $fd{$ending}=$descr;
  267:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  268:                 }
  269:             }
  270:             close($fh);
  271:         }
  272:     }
  273:     &Apache::lonnet::logthis(
  274:               "<font color=yellow>INFO: Read file types</font>");
  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">
  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: </script>
  480: ENDAUTHORBRW
  481: }
  482: 
  483: sub coursebrowser_javascript {
  484:     my ($domainfilter,$sec_element,$formname)=@_;
  485:     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.');
  486:     my $id_functions = &javascript_index_functions();
  487:     my $output = '
  488: <script type="text/javascript" language="JavaScript">
  489: // <![CDATA[
  490:     var stdeditbrowser;'."\n";
  491: 
  492:     $output .= <<"ENDSTDBRW";
  493:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  494:         var url = '/adm/pickcourse?';
  495:         var formid = getFormIdByName(formname);
  496:         var domainfilter = getDomainFromSelectbox(formname,udom);
  497:         if (domainfilter != null) {
  498:            if (domainfilter != '') {
  499:                url += 'domainfilter='+domainfilter+'&';
  500: 	   }
  501:         }
  502:         url += 'form=' + formname + '&cnumelement='+uname+
  503: 	                            '&cdomelement='+udom+
  504:                                     '&cnameelement='+desc;
  505:         if (extra_element !=null && extra_element != '') {
  506:             if (formname == 'rolechoice' || formname == 'studentform') {
  507:                 url += '&roleelement='+extra_element;
  508:                 if (domainfilter == null || domainfilter == '') {
  509:                     url += '&domainfilter='+extra_element;
  510:                 }
  511:             }
  512:             else {
  513:                 if (formname == 'portform') {
  514:                     url += '&setroles='+extra_element;
  515:                 }
  516:             }     
  517:         }
  518:         if (formname == 'ccrs') {
  519:             var ownername = document.forms[formid].ccuname.value;
  520:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  521:             url += '&cloner='+ownername+':'+ownerdom;
  522:         }
  523:         if (multflag !=null && multflag != '') {
  524:             url += '&multiple='+multflag;
  525:         }
  526:         if (crstype == 'Course/Community') {
  527:             if (formname == 'cu') {
  528:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  529:                 if (crstype == "") {
  530:                     alert("$crs_or_grp_alert");
  531:                     return;
  532:                 }
  533:             }
  534:         }
  535:         if (crstype !=null && crstype != '') {
  536:             url += '&type='+crstype;
  537:         }
  538:         var title = 'Course_Browser';
  539:         var options = 'scrollbars=1,resizable=1,menubar=0';
  540:         options += ',width=700,height=600';
  541:         stdeditbrowser = open(url,title,options,'1');
  542:         stdeditbrowser.focus();
  543:     }
  544: $id_functions
  545: ENDSTDBRW
  546:     if ($sec_element ne '') {
  547:         $output .= &setsec_javascript($sec_element,$formname);
  548:     }
  549:     $output .= '
  550: // ]]>
  551: </script>';
  552:     return $output;
  553: }
  554: 
  555: sub javascript_index_functions {
  556:     return <<"ENDJS";
  557: 
  558: function getFormIdByName(formname) {
  559:     for (var i=0;i<document.forms.length;i++) {
  560:         if (document.forms[i].name == formname) {
  561:             return i;
  562:         }
  563:     }
  564:     return -1;
  565: }
  566: 
  567: function getIndexByName(formid,item) {
  568:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  569:         if (document.forms[formid].elements[i].name == item) {
  570:             return i;
  571:         }
  572:     }
  573:     return -1;
  574: }
  575: 
  576: function getDomainFromSelectbox(formname,udom) {
  577:     var userdom;
  578:     var formid = getFormIdByName(formname);
  579:     if (formid > -1) {
  580:         var domid = getIndexByName(formid,udom);
  581:         if (domid > -1) {
  582:             if (document.forms[formid].elements[domid].type == 'select-one') {
  583:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  584:             }
  585:             if (document.forms[formid].elements[domid].type == 'hidden') {
  586:                 userdom=document.forms[formid].elements[domid].value;
  587:             }
  588:         }
  589:     }
  590:     return userdom;
  591: }
  592: 
  593: ENDJS
  594: 
  595: }
  596: 
  597: sub userbrowser_javascript {
  598:     my $id_functions = &javascript_index_functions();
  599:     return <<"ENDUSERBRW";
  600: 
  601: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  602:     var url = '/adm/pickuser?';
  603:     var userdom = getDomainFromSelectbox(formname,udom);
  604:     if (userdom != null) {
  605:        if (userdom != '') {
  606:            url += 'srchdom='+userdom+'&';
  607:        }
  608:     }
  609:     url += 'form=' + formname + '&unameelement='+uname+
  610:                                 '&udomelement='+udom+
  611:                                 '&ulastelement='+ulast+
  612:                                 '&ufirstelement='+ufirst+
  613:                                 '&uemailelement='+uemail+
  614:                                 '&hideudomelement='+hideudom+
  615:                                 '&coursedom='+crsdom;
  616:     if ((caller != null) && (caller != undefined)) {
  617:         url += '&caller='+caller;
  618:     }
  619:     var title = 'User_Browser';
  620:     var options = 'scrollbars=1,resizable=1,menubar=0';
  621:     options += ',width=700,height=600';
  622:     var stdeditbrowser = open(url,title,options,'1');
  623:     stdeditbrowser.focus();
  624: }
  625: 
  626: function fix_domain (formname,udom,origdom,uname) {
  627:     var formid = getFormIdByName(formname);
  628:     if (formid > -1) {
  629:         var unameid = getIndexByName(formid,uname);
  630:         var domid = getIndexByName(formid,udom);
  631:         var hidedomid = getIndexByName(formid,origdom);
  632:         if (hidedomid > -1) {
  633:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  634:             var unameval = document.forms[formid].elements[unameid].value;
  635:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  636:                 if (domid > -1) {
  637:                     var slct = document.forms[formid].elements[domid];
  638:                     if (slct.type == 'select-one') {
  639:                         var i;
  640:                         for (i=0;i<slct.length;i++) {
  641:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  642:                         }
  643:                     }
  644:                     if (slct.type == 'hidden') {
  645:                         slct.value = fixeddom;
  646:                     }
  647:                 }
  648:             }
  649:         }
  650:     }
  651:     return;
  652: }
  653: 
  654: $id_functions
  655: ENDUSERBRW
  656: }
  657: 
  658: 
  659: sub setsec_javascript {
  660:     my ($sec_element,$formname) = @_;
  661:     my $setsections = qq|
  662: function setSect(sectionlist) {
  663:     var sectionsArray = new Array();
  664:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  665:         sectionsArray = sectionlist.split(",");
  666:     }
  667:     var numSections = sectionsArray.length;
  668:     document.$formname.$sec_element.length = 0;
  669:     if (numSections == 0) {
  670:         document.$formname.$sec_element.multiple=false;
  671:         document.$formname.$sec_element.size=1;
  672:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  673:     } else {
  674:         if (numSections == 1) {
  675:             document.$formname.$sec_element.multiple=false;
  676:             document.$formname.$sec_element.size=1;
  677:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  678:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  679:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  680:         } else {
  681:             for (var i=0; i<numSections; i++) {
  682:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  683:             }
  684:             document.$formname.$sec_element.multiple=true
  685:             if (numSections < 3) {
  686:                 document.$formname.$sec_element.size=numSections;
  687:             } else {
  688:                 document.$formname.$sec_element.size=3;
  689:             }
  690:             document.$formname.$sec_element.options[0].selected = false
  691:         }
  692:     }
  693: }
  694: |;
  695:     return $setsections;
  696: }
  697: 
  698: 
  699: sub selectcourse_link {
  700:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  701:    my $linktext = &mt('Select Course');
  702:    if ($selecttype eq 'Community') {
  703:        $linktext = &mt('Select Community');
  704:    }
  705:    return '<span class="LC_nobreak">'
  706:          ."<a href='"
  707:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  708:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  709:          .'","'.$multflag.'","'.$selecttype.'");'
  710:          ."'>".$linktext.'</a>'
  711:          .'</span>';
  712: }
  713: 
  714: sub selectauthor_link {
  715:    my ($form,$udom)=@_;
  716:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  717:           &mt('Select Author').'</a>';
  718: }
  719: 
  720: sub selectuser_link {
  721:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  722:         $coursedom,$linktext,$caller) = @_;
  723:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  724:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  725:            ');">'.$linktext.'</a>';
  726: }
  727: 
  728: sub check_uncheck_jscript {
  729:     my $jscript = <<"ENDSCRT";
  730: function checkAll(field) {
  731:     if (field.length > 0) {
  732:         for (i = 0; i < field.length; i++) {
  733:             field[i].checked = true ;
  734:         }
  735:     } else {
  736:         field.checked = true
  737:     }
  738: }
  739:  
  740: function uncheckAll(field) {
  741:     if (field.length > 0) {
  742:         for (i = 0; i < field.length; i++) {
  743:             field[i].checked = false ;
  744:         }
  745:     } else {
  746:         field.checked = false ;
  747:     }
  748: }
  749: ENDSCRT
  750:     return $jscript;
  751: }
  752: 
  753: sub select_timezone {
  754:    my ($name,$selected,$onchange,$includeempty)=@_;
  755:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  756:    if ($includeempty) {
  757:        $output .= '<option value=""';
  758:        if (($selected eq '') || ($selected eq 'local')) {
  759:            $output .= ' selected="selected" ';
  760:        }
  761:        $output .= '> </option>';
  762:    }
  763:    my @timezones = DateTime::TimeZone->all_names;
  764:    foreach my $tzone (@timezones) {
  765:        $output.= '<option value="'.$tzone.'"';
  766:        if ($tzone eq $selected) {
  767:            $output.=' selected="selected"';
  768:        }
  769:        $output.=">$tzone</option>\n";
  770:    }
  771:    $output.="</select>";
  772:    return $output;
  773: }
  774: 
  775: sub select_datelocale {
  776:     my ($name,$selected,$onchange,$includeempty)=@_;
  777:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  778:     if ($includeempty) {
  779:         $output .= '<option value=""';
  780:         if ($selected eq '') {
  781:             $output .= ' selected="selected" ';
  782:         }
  783:         $output .= '> </option>';
  784:     }
  785:     my (@possibles,%locale_names);
  786:     my @locales = DateTime::Locale::Catalog::Locales;
  787:     foreach my $locale (@locales) {
  788:         if (ref($locale) eq 'HASH') {
  789:             my $id = $locale->{'id'};
  790:             if ($id ne '') {
  791:                 my $en_terr = $locale->{'en_territory'};
  792:                 my $native_terr = $locale->{'native_territory'};
  793:                 my @languages = &Apache::lonlocal::preferred_languages();
  794:                 if (grep(/^en$/,@languages) || !@languages) {
  795:                     if ($en_terr ne '') {
  796:                         $locale_names{$id} = '('.$en_terr.')';
  797:                     } elsif ($native_terr ne '') {
  798:                         $locale_names{$id} = $native_terr;
  799:                     }
  800:                 } else {
  801:                     if ($native_terr ne '') {
  802:                         $locale_names{$id} = $native_terr.' ';
  803:                     } elsif ($en_terr ne '') {
  804:                         $locale_names{$id} = '('.$en_terr.')';
  805:                     }
  806:                 }
  807:                 push (@possibles,$id);
  808:             }
  809:         }
  810:     }
  811:     foreach my $item (sort(@possibles)) {
  812:         $output.= '<option value="'.$item.'"';
  813:         if ($item eq $selected) {
  814:             $output.=' selected="selected"';
  815:         }
  816:         $output.=">$item";
  817:         if ($locale_names{$item} ne '') {
  818:             $output.="  $locale_names{$item}</option>\n";
  819:         }
  820:         $output.="</option>\n";
  821:     }
  822:     $output.="</select>";
  823:     return $output;
  824: }
  825: 
  826: sub select_language {
  827:     my ($name,$selected,$includeempty) = @_;
  828:     my %langchoices;
  829:     if ($includeempty) {
  830:         %langchoices = ('' => 'No language preference');
  831:     }
  832:     foreach my $id (&languageids()) {
  833:         my $code = &supportedlanguagecode($id);
  834:         if ($code) {
  835:             $langchoices{$code} = &plainlanguagedescription($id);
  836:         }
  837:     }
  838:     return &select_form($selected,$name,%langchoices);
  839: }
  840: 
  841: =pod
  842: 
  843: =item * &linked_select_forms(...)
  844: 
  845: linked_select_forms returns a string containing a <script></script> block
  846: and html for two <select> menus.  The select menus will be linked in that
  847: changing the value of the first menu will result in new values being placed
  848: in the second menu.  The values in the select menu will appear in alphabetical
  849: order unless a defined order is provided.
  850: 
  851: linked_select_forms takes the following ordered inputs:
  852: 
  853: =over 4
  854: 
  855: =item * $formname, the name of the <form> tag
  856: 
  857: =item * $middletext, the text which appears between the <select> tags
  858: 
  859: =item * $firstdefault, the default value for the first menu
  860: 
  861: =item * $firstselectname, the name of the first <select> tag
  862: 
  863: =item * $secondselectname, the name of the second <select> tag
  864: 
  865: =item * $hashref, a reference to a hash containing the data for the menus.
  866: 
  867: =item * $menuorder, the order of values in the first menu
  868: 
  869: =back 
  870: 
  871: Below is an example of such a hash.  Only the 'text', 'default', and 
  872: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  873: values for the first select menu.  The text that coincides with the 
  874: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  875: and text for the second menu are given in the hash pointed to by 
  876: $menu{$choice1}->{'select2'}.  
  877: 
  878:  my %menu = ( A1 => { text =>"Choice A1" ,
  879:                        default => "B3",
  880:                        select2 => { 
  881:                            B1 => "Choice B1",
  882:                            B2 => "Choice B2",
  883:                            B3 => "Choice B3",
  884:                            B4 => "Choice B4"
  885:                            },
  886:                        order => ['B4','B3','B1','B2'],
  887:                    },
  888:                A2 => { text =>"Choice A2" ,
  889:                        default => "C2",
  890:                        select2 => { 
  891:                            C1 => "Choice C1",
  892:                            C2 => "Choice C2",
  893:                            C3 => "Choice C3"
  894:                            },
  895:                        order => ['C2','C1','C3'],
  896:                    },
  897:                A3 => { text =>"Choice A3" ,
  898:                        default => "D6",
  899:                        select2 => { 
  900:                            D1 => "Choice D1",
  901:                            D2 => "Choice D2",
  902:                            D3 => "Choice D3",
  903:                            D4 => "Choice D4",
  904:                            D5 => "Choice D5",
  905:                            D6 => "Choice D6",
  906:                            D7 => "Choice D7"
  907:                            },
  908:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  909:                    }
  910:                );
  911: 
  912: =cut
  913: 
  914: sub linked_select_forms {
  915:     my ($formname,
  916:         $middletext,
  917:         $firstdefault,
  918:         $firstselectname,
  919:         $secondselectname, 
  920:         $hashref,
  921:         $menuorder,
  922:         ) = @_;
  923:     my $second = "document.$formname.$secondselectname";
  924:     my $first = "document.$formname.$firstselectname";
  925:     # output the javascript to do the changing
  926:     my $result = '';
  927:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  928:     $result.="// <![CDATA[\n";
  929:     $result.="var select2data = new Object();\n";
  930:     $" = '","';
  931:     my $debug = '';
  932:     foreach my $s1 (sort(keys(%$hashref))) {
  933:         $result.="select2data.d_$s1 = new Object();\n";        
  934:         $result.="select2data.d_$s1.def = new String('".
  935:             $hashref->{$s1}->{'default'}."');\n";
  936:         $result.="select2data.d_$s1.values = new Array(";
  937:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  938:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  939:             @s2values = @{$hashref->{$s1}->{'order'}};
  940:         }
  941:         $result.="\"@s2values\");\n";
  942:         $result.="select2data.d_$s1.texts = new Array(";        
  943:         my @s2texts;
  944:         foreach my $value (@s2values) {
  945:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  946:         }
  947:         $result.="\"@s2texts\");\n";
  948:     }
  949:     $"=' ';
  950:     $result.= <<"END";
  951: 
  952: function select1_changed() {
  953:     // Determine new choice
  954:     var newvalue = "d_" + $first.value;
  955:     // update select2
  956:     var values     = select2data[newvalue].values;
  957:     var texts      = select2data[newvalue].texts;
  958:     var select2def = select2data[newvalue].def;
  959:     var i;
  960:     // out with the old
  961:     for (i = 0; i < $second.options.length; i++) {
  962:         $second.options[i] = null;
  963:     }
  964:     // in with the nuclear
  965:     for (i=0;i<values.length; i++) {
  966:         $second.options[i] = new Option(values[i]);
  967:         $second.options[i].value = values[i];
  968:         $second.options[i].text = texts[i];
  969:         if (values[i] == select2def) {
  970:             $second.options[i].selected = true;
  971:         }
  972:     }
  973: }
  974: // ]]>
  975: </script>
  976: END
  977:     # output the initial values for the selection lists
  978:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  979:     my @order = sort(keys(%{$hashref}));
  980:     if (ref($menuorder) eq 'ARRAY') {
  981:         @order = @{$menuorder};
  982:     }
  983:     foreach my $value (@order) {
  984:         $result.="    <option value=\"$value\" ";
  985:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  986:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  987:     }
  988:     $result .= "</select>\n";
  989:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  990:     $result .= $middletext;
  991:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  992:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  993:     
  994:     my @secondorder = sort(keys(%select2));
  995:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  996:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  997:     }
  998:     foreach my $value (@secondorder) {
  999:         $result.="    <option value=\"$value\" ";        
 1000:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1001:         $result.=">".&mt($select2{$value})."</option>\n";
 1002:     }
 1003:     $result .= "</select>\n";
 1004:     #    return $debug;
 1005:     return $result;
 1006: }   #  end of sub linked_select_forms {
 1007: 
 1008: =pod
 1009: 
 1010: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
 1011: 
 1012: Returns a string corresponding to an HTML link to the given help
 1013: $topic, where $topic corresponds to the name of a .tex file in
 1014: /home/httpd/html/adm/help/tex, with underscores replaced by
 1015: spaces. 
 1016: 
 1017: $text will optionally be linked to the same topic, allowing you to
 1018: link text in addition to the graphic. If you do not want to link
 1019: text, but wish to specify one of the later parameters, pass an
 1020: empty string. 
 1021: 
 1022: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1023: the link will not open a new window. If false, the link will open
 1024: a new window using Javascript. (Default is false.) 
 1025: 
 1026: $width and $height are optional numerical parameters that will
 1027: override the width and height of the popped up window, which may
 1028: be useful for certain help topics with big pictures included. 
 1029: 
 1030: =cut
 1031: 
 1032: sub help_open_topic {
 1033:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1034:     $text = "" if (not defined $text);
 1035:     $stayOnPage = 0 if (not defined $stayOnPage);
 1036:     if ($env{'browser.interface'} eq 'textual') {
 1037: 	$stayOnPage=1;
 1038:     }
 1039:     $width = 350 if (not defined $width);
 1040:     $height = 400 if (not defined $height);
 1041:     my $filename = $topic;
 1042:     $filename =~ s/ /_/g;
 1043: 
 1044:     my $template = "";
 1045:     my $link;
 1046:     
 1047:     $topic=~s/\W/\_/g;
 1048: 
 1049:     if (!$stayOnPage) {
 1050: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1051:     } else {
 1052: 	$link = "/adm/help/${filename}.hlp";
 1053:     }
 1054: 
 1055:     # Add the text
 1056:     if ($text ne "") {
 1057: 	$template .= 
 1058:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
 1059:             "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1060:     }
 1061: 
 1062:     # Add the graphic
 1063:     my $title = &mt('Online Help');
 1064:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1065:     $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
 1066:                  '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
 1067:                  '" title="'.$title.'" /></a>';
 1068:     if ($text ne '') {
 1069:         $template.='</span></td></tr></table>';
 1070:     }
 1071:     return $template;
 1072: 
 1073: }
 1074: 
 1075: # This is a quicky function for Latex cheatsheet editing, since it 
 1076: # appears in at least four places
 1077: sub helpLatexCheatsheet {
 1078:     my ($topic,$text,$not_author) = @_;
 1079:     my $out;
 1080:     my $addOther = '';
 1081:     if ($topic) {
 1082: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
 1083: 						       undef, undef, 600) .
 1084: 							   '</td><td>';
 1085:     }
 1086:     $out = '<table><tr><td>'.
 1087:            $addOther .
 1088:            &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
 1089:                                                undef,undef,600).
 1090:            '</td><td>'.
 1091:            &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
 1092:                                                undef,undef,600).
 1093:            '</td>';
 1094:     unless ($not_author) {
 1095:         $out .= '<td>'.
 1096:                 &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
 1097:                                                     undef,undef,600).
 1098:                 '</td>';
 1099:     }
 1100:     $out .= '</tr></table>';
 1101:     return $out;
 1102: }
 1103: 
 1104: sub general_help {
 1105:     my $helptopic='Student_Intro';
 1106:     if ($env{'request.role'}=~/^(ca|au)/) {
 1107: 	$helptopic='Authoring_Intro';
 1108:     } elsif ($env{'request.role'}=~/^cc/) {
 1109: 	$helptopic='Course_Coordination_Intro';
 1110:     } elsif ($env{'request.role'}=~/^dc/) {
 1111:         $helptopic='Domain_Coordination_Intro';
 1112:     }
 1113:     return $helptopic;
 1114: }
 1115: 
 1116: sub update_help_link {
 1117:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1118:     my $origurl = $ENV{'REQUEST_URI'};
 1119:     $origurl=~s|^/~|/priv/|;
 1120:     my $timestamp = time;
 1121:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1122:         $$datum = &escape($$datum);
 1123:     }
 1124: 
 1125:     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";
 1126:     my $output .= <<"ENDOUTPUT";
 1127: <script type="text/javascript">
 1128: // <![CDATA[
 1129: banner_link = '$banner_link';
 1130: // ]]>
 1131: </script>
 1132: ENDOUTPUT
 1133:     return $output;
 1134: }
 1135: 
 1136: # now just updates the help link and generates a blue icon
 1137: sub help_open_menu {
 1138:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1139: 	= @_;    
 1140:     $stayOnPage = 0 if (not defined $stayOnPage);
 1141:     # only use pop-up help (stayOnPage == 0)
 1142:     # if environment.remote is on (using remote control UI)
 1143:     if ($env{'browser.interface'} eq 'textual' ||
 1144:     	$env{'environment.remote'} eq 'off' ) {
 1145:         $stayOnPage=1;
 1146:     }
 1147:     my $output;
 1148:     if ($component_help) {
 1149: 	if (!$text) {
 1150: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1151: 				       $width,$height);
 1152: 	} else {
 1153: 	    my $help_text;
 1154: 	    $help_text=&unescape($topic);
 1155: 	    $output='<table><tr><td>'.
 1156: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1157: 				 $width,$height).'</td></tr></table>';
 1158: 	}
 1159:     }
 1160:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1161:     return $output.$banner_link;
 1162: }
 1163: 
 1164: sub top_nav_help {
 1165:     my ($text) = @_;
 1166:     $text = &mt($text);
 1167:     my $stay_on_page = 
 1168: 	($env{'browser.interface'}  eq 'textual' ||
 1169: 	 $env{'environment.remote'} eq 'off' );
 1170:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1171: 	                     : "javascript:helpMenu('open')";
 1172:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1173: 
 1174:     my $title = &mt('Get help');
 1175: 
 1176:     return <<"END";
 1177: $banner_link
 1178:  <a href="$link" title="$title">$text</a>
 1179: END
 1180: }
 1181: 
 1182: sub help_menu_js {
 1183:     my ($text) = @_;
 1184: 
 1185:     my $stayOnPage = 
 1186: 	($env{'browser.interface'}  eq 'textual' ||
 1187: 	 $env{'environment.remote'} eq 'off' );
 1188: 
 1189:     my $width = 620;
 1190:     my $height = 600;
 1191:     my $helptopic=&general_help();
 1192:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1193:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1194:     my $start_page =
 1195:         &Apache::loncommon::start_page('Help Menu', undef,
 1196: 				       {'frameset'    => 1,
 1197: 					'js_ready'    => 1,
 1198: 					'add_entries' => {
 1199: 					    'border' => '0',
 1200: 					    'rows'   => "110,*",},});
 1201:     my $end_page =
 1202:         &Apache::loncommon::end_page({'frameset' => 1,
 1203: 				      'js_ready' => 1,});
 1204: 
 1205:     my $template .= <<"ENDTEMPLATE";
 1206: <script type="text/javascript">
 1207: // <![CDATA[
 1208: // <!-- BEGIN LON-CAPA Internal
 1209: var banner_link = '';
 1210: function helpMenu(target) {
 1211:     var caller = this;
 1212:     if (target == 'open') {
 1213:         var newWindow = null;
 1214:         try {
 1215:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1216:         }
 1217:         catch(error) {
 1218:             writeHelp(caller);
 1219:             return;
 1220:         }
 1221:         if (newWindow) {
 1222:             caller = newWindow;
 1223:         }
 1224:     }
 1225:     writeHelp(caller);
 1226:     return;
 1227: }
 1228: function writeHelp(caller) {
 1229:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1230:     caller.document.close()
 1231:     caller.focus()
 1232: }
 1233: // END LON-CAPA Internal -->
 1234: // ]]>
 1235: </script>
 1236: ENDTEMPLATE
 1237:     return $template;
 1238: }
 1239: 
 1240: sub help_open_bug {
 1241:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1242:     unless ($env{'user.adv'}) { return ''; }
 1243:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1244:     $text = "" if (not defined $text);
 1245:     $stayOnPage = 0 if (not defined $stayOnPage);
 1246:     if ($env{'browser.interface'} eq 'textual' ||
 1247: 	$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\"><font color='#FFFFFF' size='2'>$text</font></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{'browser.interface'} eq 'textual' ||
 1292: 	$env{'environment.remote'} eq 'off' ) {
 1293: 	$stayOnPage=1;
 1294:     }
 1295:     $width = 350 if (not defined $width);
 1296:     $height = 400 if (not defined $height);
 1297: 
 1298:     $topic=~s/\W+/\+/g;
 1299:     my $link='';
 1300:     my $template='';
 1301:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1302:     if (!$stayOnPage)
 1303:     {
 1304: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1305:     }
 1306:     else
 1307:     {
 1308: 	$link = $url;
 1309:     }
 1310: 
 1311:     # Add the text
 1312:     if ($text ne "")
 1313:     {
 1314: 	$template .= 
 1315:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1316:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1317:     }
 1318: 
 1319:     # Add the graphic
 1320:     my $title = &mt('View the FAQ');
 1321:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1322:     $template .= <<"ENDTEMPLATE";
 1323:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1324: ENDTEMPLATE
 1325:     if ($text ne '') { $template.='</td></tr></table>' };
 1326:     return $template;
 1327: 
 1328: }
 1329: 
 1330: ###############################################################
 1331: ###############################################################
 1332: 
 1333: =pod
 1334: 
 1335: =item * &change_content_javascript():
 1336: 
 1337: This and the next function allow you to create small sections of an
 1338: otherwise static HTML page that you can update on the fly with
 1339: Javascript, even in Netscape 4.
 1340: 
 1341: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1342: must be written to the HTML page once. It will prove the Javascript
 1343: function "change(name, content)". Calling the change function with the
 1344: name of the section 
 1345: you want to update, matching the name passed to C<changable_area>, and
 1346: the new content you want to put in there, will put the content into
 1347: that area.
 1348: 
 1349: B<Note>: Netscape 4 only reserves enough space for the changable area
 1350: to contain room for the original contents. You need to "make space"
 1351: for whatever changes you wish to make, and be B<sure> to check your
 1352: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1353: it's adequate for updating a one-line status display, but little more.
 1354: This script will set the space to 100% width, so you only need to
 1355: worry about height in Netscape 4.
 1356: 
 1357: Modern browsers are much less limiting, and if you can commit to the
 1358: user not using Netscape 4, this feature may be used freely with
 1359: pretty much any HTML.
 1360: 
 1361: =cut
 1362: 
 1363: sub change_content_javascript {
 1364:     # If we're on Netscape 4, we need to use Layer-based code
 1365:     if ($env{'browser.type'} eq 'netscape' &&
 1366: 	$env{'browser.version'} =~ /^4\./) {
 1367: 	return (<<NETSCAPE4);
 1368: 	function change(name, content) {
 1369: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1370: 	    doc.open();
 1371: 	    doc.write(content);
 1372: 	    doc.close();
 1373: 	}
 1374: NETSCAPE4
 1375:     } else {
 1376: 	# Otherwise, we need to use semi-standards-compliant code
 1377: 	# (technically, "innerHTML" isn't standard but the equivalent
 1378: 	# is really scary, and every useful browser supports it
 1379: 	return (<<DOMBASED);
 1380: 	function change(name, content) {
 1381: 	    element = document.getElementById(name);
 1382: 	    element.innerHTML = content;
 1383: 	}
 1384: DOMBASED
 1385:     }
 1386: }
 1387: 
 1388: =pod
 1389: 
 1390: =item * &changable_area($name,$origContent):
 1391: 
 1392: This provides a "changable area" that can be modified on the fly via
 1393: the Javascript code provided in C<change_content_javascript>. $name is
 1394: the name you will use to reference the area later; do not repeat the
 1395: same name on a given HTML page more then once. $origContent is what
 1396: the area will originally contain, which can be left blank.
 1397: 
 1398: =cut
 1399: 
 1400: sub changable_area {
 1401:     my ($name, $origContent) = @_;
 1402: 
 1403:     if ($env{'browser.type'} eq 'netscape' &&
 1404: 	$env{'browser.version'} =~ /^4\./) {
 1405: 	# If this is netscape 4, we need to use the Layer tag
 1406: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1407:     } else {
 1408: 	return "<span id='$name'>$origContent</span>";
 1409:     }
 1410: }
 1411: 
 1412: =pod
 1413: 
 1414: =item * &viewport_geometry_js 
 1415: 
 1416: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1417: 
 1418: =cut
 1419: 
 1420: 
 1421: sub viewport_geometry_js { 
 1422:     return <<"GEOMETRY";
 1423: var Geometry = {};
 1424: function init_geometry() {
 1425:     if (Geometry.init) { return };
 1426:     Geometry.init=1;
 1427:     if (window.innerHeight) {
 1428:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1429:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1430:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1431:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1432:     }
 1433:     else if (document.documentElement && document.documentElement.clientHeight) {
 1434:         Geometry.getViewportHeight =
 1435:             function() { return document.documentElement.clientHeight; };
 1436:         Geometry.getViewportWidth =
 1437:             function() { return document.documentElement.clientWidth; };
 1438: 
 1439:         Geometry.getHorizontalScroll =
 1440:             function() { return document.documentElement.scrollLeft; };
 1441:         Geometry.getVerticalScroll =
 1442:             function() { return document.documentElement.scrollTop; };
 1443:     }
 1444:     else if (document.body.clientHeight) {
 1445:         Geometry.getViewportHeight =
 1446:             function() { return document.body.clientHeight; };
 1447:         Geometry.getViewportWidth =
 1448:             function() { return document.body.clientWidth; };
 1449:         Geometry.getHorizontalScroll =
 1450:             function() { return document.body.scrollLeft; };
 1451:         Geometry.getVerticalScroll =
 1452:             function() { return document.body.scrollTop; };
 1453:     }
 1454: }
 1455: 
 1456: GEOMETRY
 1457: }
 1458: 
 1459: =pod
 1460: 
 1461: =item * &viewport_size_js()
 1462: 
 1463: 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. 
 1464: 
 1465: =cut
 1466: 
 1467: sub viewport_size_js {
 1468:     my $geometry = &viewport_geometry_js();
 1469:     return <<"DIMS";
 1470: 
 1471: $geometry
 1472: 
 1473: function getViewportDims(width,height) {
 1474:     init_geometry();
 1475:     width.value = Geometry.getViewportWidth();
 1476:     height.value = Geometry.getViewportHeight();
 1477:     return;
 1478: }
 1479: 
 1480: DIMS
 1481: }
 1482: 
 1483: =pod
 1484: 
 1485: =item * &resize_textarea_js()
 1486: 
 1487: emits the needed javascript to resize a textarea to be as big as possible
 1488: 
 1489: creates a function resize_textrea that takes two IDs first should be
 1490: the id of the element to resize, second should be the id of a div that
 1491: surrounds everything that comes after the textarea, this routine needs
 1492: to be attached to the <body> for the onload and onresize events.
 1493: 
 1494: =back
 1495: 
 1496: =cut
 1497: 
 1498: sub resize_textarea_js {
 1499:     my $geometry = &viewport_geometry_js();
 1500:     return <<"RESIZE";
 1501:     <script type="text/javascript">
 1502: // <![CDATA[
 1503: $geometry
 1504: 
 1505: function getX(element) {
 1506:     var x = 0;
 1507:     while (element) {
 1508: 	x += element.offsetLeft;
 1509: 	element = element.offsetParent;
 1510:     }
 1511:     return x;
 1512: }
 1513: function getY(element) {
 1514:     var y = 0;
 1515:     while (element) {
 1516: 	y += element.offsetTop;
 1517: 	element = element.offsetParent;
 1518:     }
 1519:     return y;
 1520: }
 1521: 
 1522: 
 1523: function resize_textarea(textarea_id,bottom_id) {
 1524:     init_geometry();
 1525:     var textarea        = document.getElementById(textarea_id);
 1526:     //alert(textarea);
 1527: 
 1528:     var textarea_top    = getY(textarea);
 1529:     var textarea_height = textarea.offsetHeight;
 1530:     var bottom          = document.getElementById(bottom_id);
 1531:     var bottom_top      = getY(bottom);
 1532:     var bottom_height   = bottom.offsetHeight;
 1533:     var window_height   = Geometry.getViewportHeight();
 1534:     var fudge           = 23;
 1535:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1536:     if (new_height < 300) {
 1537: 	new_height = 300;
 1538:     }
 1539:     textarea.style.height=new_height+'px';
 1540: }
 1541: // ]]>
 1542: </script>
 1543: RESIZE
 1544: 
 1545: }
 1546: 
 1547: =pod
 1548: 
 1549: =head1 Excel and CSV file utility routines
 1550: 
 1551: =over 4
 1552: 
 1553: =cut
 1554: 
 1555: ###############################################################
 1556: ###############################################################
 1557: 
 1558: =pod
 1559: 
 1560: =item * &csv_translate($text) 
 1561: 
 1562: Translate $text to allow it to be output as a 'comma separated values' 
 1563: format.
 1564: 
 1565: =cut
 1566: 
 1567: ###############################################################
 1568: ###############################################################
 1569: sub csv_translate {
 1570:     my $text = shift;
 1571:     $text =~ s/\"/\"\"/g;
 1572:     $text =~ s/\n/ /g;
 1573:     return $text;
 1574: }
 1575: 
 1576: ###############################################################
 1577: ###############################################################
 1578: 
 1579: =pod
 1580: 
 1581: =item * &define_excel_formats()
 1582: 
 1583: Define some commonly used Excel cell formats.
 1584: 
 1585: Currently supported formats:
 1586: 
 1587: =over 4
 1588: 
 1589: =item header
 1590: 
 1591: =item bold
 1592: 
 1593: =item h1
 1594: 
 1595: =item h2
 1596: 
 1597: =item h3
 1598: 
 1599: =item h4
 1600: 
 1601: =item i
 1602: 
 1603: =item date
 1604: 
 1605: =back
 1606: 
 1607: Inputs: $workbook
 1608: 
 1609: Returns: $format, a hash reference.
 1610: 
 1611: =cut
 1612: 
 1613: ###############################################################
 1614: ###############################################################
 1615: sub define_excel_formats {
 1616:     my ($workbook) = @_;
 1617:     my $format;
 1618:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1619:                                                 bottom    => 1,
 1620:                                                 align     => 'center');
 1621:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1622:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1623:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1624:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1625:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1626:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1627:     $format->{'date'} = $workbook->add_format(num_format=>
 1628:                                             'mm/dd/yyyy hh:mm:ss');
 1629:     return $format;
 1630: }
 1631: 
 1632: ###############################################################
 1633: ###############################################################
 1634: 
 1635: =pod
 1636: 
 1637: =item * &create_workbook()
 1638: 
 1639: Create an Excel worksheet.  If it fails, output message on the
 1640: request object and return undefs.
 1641: 
 1642: Inputs: Apache request object
 1643: 
 1644: Returns (undef) on failure, 
 1645:     Excel worksheet object, scalar with filename, and formats 
 1646:     from &Apache::loncommon::define_excel_formats on success
 1647: 
 1648: =cut
 1649: 
 1650: ###############################################################
 1651: ###############################################################
 1652: sub create_workbook {
 1653:     my ($r) = @_;
 1654:         #
 1655:     # Create the excel spreadsheet
 1656:     my $filename = '/prtspool/'.
 1657:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1658:         time.'_'.rand(1000000000).'.xls';
 1659:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1660:     if (! defined($workbook)) {
 1661:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1662:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1663:                             "This error has been logged.  ".
 1664:                             "Please alert your LON-CAPA administrator").
 1665:                   '</p>');
 1666:         return (undef);
 1667:     }
 1668:     #
 1669:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1670:     #
 1671:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1672:     return ($workbook,$filename,$format);
 1673: }
 1674: 
 1675: ###############################################################
 1676: ###############################################################
 1677: 
 1678: =pod
 1679: 
 1680: =item * &create_text_file()
 1681: 
 1682: Create a file to write to and eventually make available to the user.
 1683: If file creation fails, outputs an error message on the request object and 
 1684: return undefs.
 1685: 
 1686: Inputs: Apache request object, and file suffix
 1687: 
 1688: Returns (undef) on failure, 
 1689:     Filehandle and filename on success.
 1690: 
 1691: =cut
 1692: 
 1693: ###############################################################
 1694: ###############################################################
 1695: sub create_text_file {
 1696:     my ($r,$suffix) = @_;
 1697:     if (! defined($suffix)) { $suffix = 'txt'; };
 1698:     my $fh;
 1699:     my $filename = '/prtspool/'.
 1700:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1701:         time.'_'.rand(1000000000).'.'.$suffix;
 1702:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1703:     if (! defined($fh)) {
 1704:         $r->log_error("Couldn't open $filename for output $!");
 1705:         $r->print(&mt('Problems occurred in creating the output file. '
 1706:                      .'This error has been logged. '
 1707:                      .'Please alert your LON-CAPA administrator.'));
 1708:     }
 1709:     return ($fh,$filename)
 1710: }
 1711: 
 1712: 
 1713: =pod 
 1714: 
 1715: =back
 1716: 
 1717: =cut
 1718: 
 1719: ###############################################################
 1720: ##        Home server <option> list generating code          ##
 1721: ###############################################################
 1722: 
 1723: # ------------------------------------------
 1724: 
 1725: sub domain_select {
 1726:     my ($name,$value,$multiple)=@_;
 1727:     my %domains=map { 
 1728: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1729:     } &Apache::lonnet::all_domains();
 1730:     if ($multiple) {
 1731: 	$domains{''}=&mt('Any domain');
 1732: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1733: 	return &multiple_select_form($name,$value,4,\%domains);
 1734:     } else {
 1735: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1736: 	return &select_form($name,$value,%domains);
 1737:     }
 1738: }
 1739: 
 1740: #-------------------------------------------
 1741: 
 1742: =pod
 1743: 
 1744: =head1 Routines for form select boxes
 1745: 
 1746: =over 4
 1747: 
 1748: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1749: 
 1750: Returns a string containing a <select> element int multiple mode
 1751: 
 1752: 
 1753: Args:
 1754:   $name - name of the <select> element
 1755:   $value - scalar or array ref of values that should already be selected
 1756:   $size - number of rows long the select element is
 1757:   $hash - the elements should be 'option' => 'shown text'
 1758:           (shown text should already have been &mt())
 1759:   $order - (optional) array ref of the order to show the elements in
 1760: 
 1761: =cut
 1762: 
 1763: #-------------------------------------------
 1764: sub multiple_select_form {
 1765:     my ($name,$value,$size,$hash,$order)=@_;
 1766:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1767:     my $output='';
 1768:     if (! defined($size)) {
 1769:         $size = 4;
 1770:         if (scalar(keys(%$hash))<4) {
 1771:             $size = scalar(keys(%$hash));
 1772:         }
 1773:     }
 1774:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1775:     my @order;
 1776:     if (ref($order) eq 'ARRAY')  {
 1777:         @order = @{$order};
 1778:     } else {
 1779:         @order = sort(keys(%$hash));
 1780:     }
 1781:     if (exists($$hash{'select_form_order'})) {
 1782:         @order = @{$$hash{'select_form_order'}};
 1783:     }
 1784:         
 1785:     foreach my $key (@order) {
 1786:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1787:         $output.='selected="selected" ' if ($selected{$key});
 1788:         $output.='>'.$hash->{$key}."</option>\n";
 1789:     }
 1790:     $output.="</select>\n";
 1791:     return $output;
 1792: }
 1793: 
 1794: #-------------------------------------------
 1795: 
 1796: =pod
 1797: 
 1798: =item * &select_form($defdom,$name,%hash)
 1799: 
 1800: Returns a string containing a <select name='$name' size='1'> form to 
 1801: allow a user to select options from a hash option_name => displayed text.  
 1802: See lonrights.pm for an example invocation and use.
 1803: 
 1804: =cut
 1805: 
 1806: #-------------------------------------------
 1807: sub select_form {
 1808:     my ($def,$name,%hash) = @_;
 1809:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1810:     my @keys;
 1811:     if (exists($hash{'select_form_order'})) {
 1812: 	@keys=@{$hash{'select_form_order'}};
 1813:     } else {
 1814: 	@keys=sort(keys(%hash));
 1815:     }
 1816:     foreach my $key (@keys) {
 1817:         $selectform.=
 1818: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1819:             ($key eq $def ? 'selected="selected" ' : '').
 1820:                 ">".&mt($hash{$key})."</option>\n";
 1821:     }
 1822:     $selectform.="</select>";
 1823:     return $selectform;
 1824: }
 1825: 
 1826: # For display filters
 1827: 
 1828: sub display_filter {
 1829:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1830:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1831:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1832: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1833: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1834: 	   '</label></span> <span class="LC_nobreak">'.
 1835:            &mt('Filter [_1]',
 1836: 	   &select_form($env{'form.displayfilter'},
 1837: 			'displayfilter',
 1838: 			('currentfolder' => 'Current folder/page',
 1839: 			 'containing' => 'Containing phrase',
 1840: 			 'none' => 'None'))).
 1841: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1842: }
 1843: 
 1844: sub gradeleveldescription {
 1845:     my $gradelevel=shift;
 1846:     my %gradelevels=(0 => 'Not specified',
 1847: 		     1 => 'Grade 1',
 1848: 		     2 => 'Grade 2',
 1849: 		     3 => 'Grade 3',
 1850: 		     4 => 'Grade 4',
 1851: 		     5 => 'Grade 5',
 1852: 		     6 => 'Grade 6',
 1853: 		     7 => 'Grade 7',
 1854: 		     8 => 'Grade 8',
 1855: 		     9 => 'Grade 9',
 1856: 		     10 => 'Grade 10',
 1857: 		     11 => 'Grade 11',
 1858: 		     12 => 'Grade 12',
 1859: 		     13 => 'Grade 13',
 1860: 		     14 => '100 Level',
 1861: 		     15 => '200 Level',
 1862: 		     16 => '300 Level',
 1863: 		     17 => '400 Level',
 1864: 		     18 => 'Graduate Level');
 1865:     return &mt($gradelevels{$gradelevel});
 1866: }
 1867: 
 1868: sub select_level_form {
 1869:     my ($deflevel,$name)=@_;
 1870:     unless ($deflevel) { $deflevel=0; }
 1871:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1872:     for (my $i=0; $i<=18; $i++) {
 1873:         $selectform.="<option value=\"$i\" ".
 1874:             ($i==$deflevel ? 'selected="selected" ' : '').
 1875:                 ">".&gradeleveldescription($i)."</option>\n";
 1876:     }
 1877:     $selectform.="</select>";
 1878:     return $selectform;
 1879: }
 1880: 
 1881: #-------------------------------------------
 1882: 
 1883: =pod
 1884: 
 1885: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
 1886: 
 1887: Returns a string containing a <select name='$name' size='1'> form to 
 1888: allow a user to select the domain to preform an operation in.  
 1889: See loncreateuser.pm for an example invocation and use.
 1890: 
 1891: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1892: selected");
 1893: 
 1894: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1895: 
 1896: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 1897: 
 1898: =cut
 1899: 
 1900: #-------------------------------------------
 1901: sub select_dom_form {
 1902:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
 1903:     if ($onchange) {
 1904:         $onchange = ' onchange="'.$onchange.'"';
 1905:     }
 1906:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1907:     if ($includeempty) { @domains=('',@domains); }
 1908:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1909:     foreach my $dom (@domains) {
 1910:         $selectdomain.="<option value=\"$dom\" ".
 1911:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1912:         if ($showdomdesc) {
 1913:             if ($dom ne '') {
 1914:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1915:                 if ($domdesc ne '') {
 1916:                     $selectdomain .= ' ('.$domdesc.')';
 1917:                 }
 1918:             } 
 1919:         }
 1920:         $selectdomain .= "</option>\n";
 1921:     }
 1922:     $selectdomain.="</select>";
 1923:     return $selectdomain;
 1924: }
 1925: 
 1926: #-------------------------------------------
 1927: 
 1928: =pod
 1929: 
 1930: =item * &home_server_form_item($domain,$name,$defaultflag)
 1931: 
 1932: input: 4 arguments (two required, two optional) - 
 1933:     $domain - domain of new user
 1934:     $name - name of form element
 1935:     $default - Value of 'default' causes a default item to be first 
 1936:                             option, and selected by default. 
 1937:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1938:                             if 1 server found, or default, if 0 found.
 1939: output: returns 2 items: 
 1940: (a) form element which contains either:
 1941:    (i) <select name="$name">
 1942:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1943:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1944:        </select>
 1945:        form item if there are multiple library servers in $domain, or
 1946:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1947:        if there is only one library server in $domain.
 1948: 
 1949: (b) number of library servers found.
 1950: 
 1951: See loncreateuser.pm for example of use.
 1952: 
 1953: =cut
 1954: 
 1955: #-------------------------------------------
 1956: sub home_server_form_item {
 1957:     my ($domain,$name,$default,$hide) = @_;
 1958:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1959:     my $result;
 1960:     my $numlib = keys(%servers);
 1961:     if ($numlib > 1) {
 1962:         $result .= '<select name="'.$name.'" />'."\n";
 1963:         if ($default) {
 1964:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1965:                        '</option>'."\n";
 1966:         }
 1967:         foreach my $hostid (sort(keys(%servers))) {
 1968:             $result.= '<option value="'.$hostid.'">'.
 1969: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1970:         }
 1971:         $result .= '</select>'."\n";
 1972:     } elsif ($numlib == 1) {
 1973:         my $hostid;
 1974:         foreach my $item (keys(%servers)) {
 1975:             $hostid = $item;
 1976:         }
 1977:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1978:                    $hostid.'" />';
 1979:                    if (!$hide) {
 1980:                        $result .= $hostid.' '.$servers{$hostid};
 1981:                    }
 1982:                    $result .= "\n";
 1983:     } elsif ($default) {
 1984:         $result .= '<input type="hidden" name="'.$name.
 1985:                    '" value="default" />';
 1986:                    if (!$hide) {
 1987:                        $result .= &mt('default');
 1988:                    }
 1989:                    $result .= "\n";
 1990:     }
 1991:     return ($result,$numlib);
 1992: }
 1993: 
 1994: =pod
 1995: 
 1996: =back 
 1997: 
 1998: =cut
 1999: 
 2000: ###############################################################
 2001: ##                  Decoding User Agent                      ##
 2002: ###############################################################
 2003: 
 2004: =pod
 2005: 
 2006: =head1 Decoding the User Agent
 2007: 
 2008: =over 4
 2009: 
 2010: =item * &decode_user_agent()
 2011: 
 2012: Inputs: $r
 2013: 
 2014: Outputs:
 2015: 
 2016: =over 4
 2017: 
 2018: =item * $httpbrowser
 2019: 
 2020: =item * $clientbrowser
 2021: 
 2022: =item * $clientversion
 2023: 
 2024: =item * $clientmathml
 2025: 
 2026: =item * $clientunicode
 2027: 
 2028: =item * $clientos
 2029: 
 2030: =back
 2031: 
 2032: =back 
 2033: 
 2034: =cut
 2035: 
 2036: ###############################################################
 2037: ###############################################################
 2038: sub decode_user_agent {
 2039:     my ($r)=@_;
 2040:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2041:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2042:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2043:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2044:     my $clientbrowser='unknown';
 2045:     my $clientversion='0';
 2046:     my $clientmathml='';
 2047:     my $clientunicode='0';
 2048:     for (my $i=0;$i<=$#browsertype;$i++) {
 2049:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2050: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2051: 	    $clientbrowser=$bname;
 2052:             $httpbrowser=~/$vreg/i;
 2053: 	    $clientversion=$1;
 2054:             $clientmathml=($clientversion>=$minv);
 2055:             $clientunicode=($clientversion>=$univ);
 2056: 	}
 2057:     }
 2058:     my $clientos='unknown';
 2059:     if (($httpbrowser=~/linux/i) ||
 2060:         ($httpbrowser=~/unix/i) ||
 2061:         ($httpbrowser=~/ux/i) ||
 2062:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2063:     if (($httpbrowser=~/vax/i) ||
 2064:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2065:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2066:     if (($httpbrowser=~/mac/i) ||
 2067:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2068:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2069:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2070:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2071:             $clientunicode,$clientos,);
 2072: }
 2073: 
 2074: ###############################################################
 2075: ##    Authentication changing form generation subroutines    ##
 2076: ###############################################################
 2077: ##
 2078: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2079: ## hash, and have reasonable default values.
 2080: ##
 2081: ##    formname = the name given in the <form> tag.
 2082: #-------------------------------------------
 2083: 
 2084: =pod
 2085: 
 2086: =head1 Authentication Routines
 2087: 
 2088: =over 4
 2089: 
 2090: =item * &authform_xxxxxx()
 2091: 
 2092: The authform_xxxxxx subroutines provide javascript and html forms which 
 2093: handle some of the conveniences required for authentication forms.  
 2094: This is not an optimal method, but it works.  
 2095: 
 2096: =over 4
 2097: 
 2098: =item * authform_header
 2099: 
 2100: =item * authform_authorwarning
 2101: 
 2102: =item * authform_nochange
 2103: 
 2104: =item * authform_kerberos
 2105: 
 2106: =item * authform_internal
 2107: 
 2108: =item * authform_filesystem
 2109: 
 2110: =back
 2111: 
 2112: See loncreateuser.pm for invocation and use examples.
 2113: 
 2114: =cut
 2115: 
 2116: #-------------------------------------------
 2117: sub authform_header{  
 2118:     my %in = (
 2119:         formname => 'cu',
 2120:         kerb_def_dom => '',
 2121:         @_,
 2122:     );
 2123:     $in{'formname'} = 'document.' . $in{'formname'};
 2124:     my $result='';
 2125: 
 2126: #---------------------------------------------- Code for upper case translation
 2127:     my $Javascript_toUpperCase;
 2128:     unless ($in{kerb_def_dom}) {
 2129:         $Javascript_toUpperCase =<<"END";
 2130:         switch (choice) {
 2131:            case 'krb': currentform.elements[choicearg].value =
 2132:                currentform.elements[choicearg].value.toUpperCase();
 2133:                break;
 2134:            default:
 2135:         }
 2136: END
 2137:     } else {
 2138:         $Javascript_toUpperCase = "";
 2139:     }
 2140: 
 2141:     my $radioval = "'nochange'";
 2142:     if (defined($in{'curr_authtype'})) {
 2143:         if ($in{'curr_authtype'} ne '') {
 2144:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2145:         }
 2146:     }
 2147:     my $argfield = 'null';
 2148:     if (defined($in{'mode'})) {
 2149:         if ($in{'mode'} eq 'modifycourse')  {
 2150:             if (defined($in{'curr_autharg'})) {
 2151:                 if ($in{'curr_autharg'} ne '') {
 2152:                     $argfield = "'$in{'curr_autharg'}'";
 2153:                 }
 2154:             }
 2155:         }
 2156:     }
 2157: 
 2158:     $result.=<<"END";
 2159: var current = new Object();
 2160: current.radiovalue = $radioval;
 2161: current.argfield = $argfield;
 2162: 
 2163: function changed_radio(choice,currentform) {
 2164:     var choicearg = choice + 'arg';
 2165:     // If a radio button in changed, we need to change the argfield
 2166:     if (current.radiovalue != choice) {
 2167:         current.radiovalue = choice;
 2168:         if (current.argfield != null) {
 2169:             currentform.elements[current.argfield].value = '';
 2170:         }
 2171:         if (choice == 'nochange') {
 2172:             current.argfield = null;
 2173:         } else {
 2174:             current.argfield = choicearg;
 2175:             switch(choice) {
 2176:                 case 'krb': 
 2177:                     currentform.elements[current.argfield].value = 
 2178:                         "$in{'kerb_def_dom'}";
 2179:                 break;
 2180:               default:
 2181:                 break;
 2182:             }
 2183:         }
 2184:     }
 2185:     return;
 2186: }
 2187: 
 2188: function changed_text(choice,currentform) {
 2189:     var choicearg = choice + 'arg';
 2190:     if (currentform.elements[choicearg].value !='') {
 2191:         $Javascript_toUpperCase
 2192:         // clear old field
 2193:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2194:             currentform.elements[current.argfield].value = '';
 2195:         }
 2196:         current.argfield = choicearg;
 2197:     }
 2198:     set_auth_radio_buttons(choice,currentform);
 2199:     return;
 2200: }
 2201: 
 2202: function set_auth_radio_buttons(newvalue,currentform) {
 2203:     var i=0;
 2204:     while (i < currentform.login.length) {
 2205:         if (currentform.login[i].value == newvalue) { break; }
 2206:         i++;
 2207:     }
 2208:     if (i == currentform.login.length) {
 2209:         return;
 2210:     }
 2211:     current.radiovalue = newvalue;
 2212:     currentform.login[i].checked = true;
 2213:     return;
 2214: }
 2215: END
 2216:     return $result;
 2217: }
 2218: 
 2219: sub authform_authorwarning{
 2220:     my $result='';
 2221:     $result='<i>'.
 2222:         &mt('As a general rule, only authors or co-authors should be '.
 2223:             'filesystem authenticated '.
 2224:             '(which allows access to the server filesystem).')."</i>\n";
 2225:     return $result;
 2226: }
 2227: 
 2228: sub authform_nochange{  
 2229:     my %in = (
 2230:               formname => 'document.cu',
 2231:               kerb_def_dom => 'MSU.EDU',
 2232:               @_,
 2233:           );
 2234:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2235:     my $result;
 2236:     if (keys(%can_assign) == 0) {
 2237:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2238:     } else {
 2239:         $result = '<label>'.&mt('[_1] Do not change login data',
 2240:                   '<input type="radio" name="login" value="nochange" '.
 2241:                   'checked="checked" onclick="'.
 2242:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2243: 	    '</label>';
 2244:     }
 2245:     return $result;
 2246: }
 2247: 
 2248: sub authform_kerberos {
 2249:     my %in = (
 2250:               formname => 'document.cu',
 2251:               kerb_def_dom => 'MSU.EDU',
 2252:               kerb_def_auth => 'krb4',
 2253:               @_,
 2254:               );
 2255:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2256:         $autharg,$jscall);
 2257:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2258:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2259:        $check5 = ' checked="checked"';
 2260:     } else {
 2261:        $check4 = ' checked="checked"';
 2262:     }
 2263:     $krbarg = $in{'kerb_def_dom'};
 2264:     if (defined($in{'curr_authtype'})) {
 2265:         if ($in{'curr_authtype'} eq 'krb') {
 2266:             $krbcheck = ' checked="checked"';
 2267:             if (defined($in{'mode'})) {
 2268:                 if ($in{'mode'} eq 'modifyuser') {
 2269:                     $krbcheck = '';
 2270:                 }
 2271:             }
 2272:             if (defined($in{'curr_kerb_ver'})) {
 2273:                 if ($in{'curr_krb_ver'} eq '5') {
 2274:                     $check5 = ' checked="checked"';
 2275:                     $check4 = '';
 2276:                 } else {
 2277:                     $check4 = ' checked="checked"';
 2278:                     $check5 = '';
 2279:                 }
 2280:             }
 2281:             if (defined($in{'curr_autharg'})) {
 2282:                 $krbarg = $in{'curr_autharg'};
 2283:             }
 2284:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2285:                 if (defined($in{'curr_autharg'})) {
 2286:                     $result = 
 2287:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2288:         $in{'curr_autharg'},$krbver);
 2289:                 } else {
 2290:                     $result =
 2291:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2292:                 }
 2293:                 return $result; 
 2294:             }
 2295:         }
 2296:     } else {
 2297:         if ($authnum == 1) {
 2298:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2299:         }
 2300:     }
 2301:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2302:         return;
 2303:     } elsif ($authtype eq '') {
 2304:         if (defined($in{'mode'})) {
 2305:             if ($in{'mode'} eq 'modifycourse') {
 2306:                 if ($authnum == 1) {
 2307:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2308:                 }
 2309:             }
 2310:         }
 2311:     }
 2312:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2313:     if ($authtype eq '') {
 2314:         $authtype = '<input type="radio" name="login" value="krb" '.
 2315:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2316:                     $krbcheck.' />';
 2317:     }
 2318:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2319:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2320:          $in{'curr_authtype'} eq 'krb5') ||
 2321:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2322:          $in{'curr_authtype'} eq 'krb4')) {
 2323:         $result .= &mt
 2324:         ('[_1] Kerberos authenticated with domain [_2] '.
 2325:          '[_3] Version 4 [_4] Version 5 [_5]',
 2326:          '<label>'.$authtype,
 2327:          '</label><input type="text" size="10" name="krbarg" '.
 2328:              'value="'.$krbarg.'" '.
 2329:              'onchange="'.$jscall.'" />',
 2330:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2331:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2332: 	 '</label>');
 2333:     } elsif ($can_assign{'krb4'}) {
 2334:         $result .= &mt
 2335:         ('[_1] Kerberos authenticated with domain [_2] '.
 2336:          '[_3] Version 4 [_4]',
 2337:          '<label>'.$authtype,
 2338:          '</label><input type="text" size="10" name="krbarg" '.
 2339:              'value="'.$krbarg.'" '.
 2340:              'onchange="'.$jscall.'" />',
 2341:          '<label><input type="hidden" name="krbver" value="4" />',
 2342:          '</label>');
 2343:     } elsif ($can_assign{'krb5'}) {
 2344:         $result .= &mt
 2345:         ('[_1] Kerberos authenticated with domain [_2] '.
 2346:          '[_3] Version 5 [_4]',
 2347:          '<label>'.$authtype,
 2348:          '</label><input type="text" size="10" name="krbarg" '.
 2349:              'value="'.$krbarg.'" '.
 2350:              'onchange="'.$jscall.'" />',
 2351:          '<label><input type="hidden" name="krbver" value="5" />',
 2352:          '</label>');
 2353:     }
 2354:     return $result;
 2355: }
 2356: 
 2357: sub authform_internal{  
 2358:     my %in = (
 2359:                 formname => 'document.cu',
 2360:                 kerb_def_dom => 'MSU.EDU',
 2361:                 @_,
 2362:                 );
 2363:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2364:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2365:     if (defined($in{'curr_authtype'})) {
 2366:         if ($in{'curr_authtype'} eq 'int') {
 2367:             if ($can_assign{'int'}) {
 2368:                 $intcheck = 'checked="checked" ';
 2369:                 if (defined($in{'mode'})) {
 2370:                     if ($in{'mode'} eq 'modifyuser') {
 2371:                         $intcheck = '';
 2372:                     }
 2373:                 }
 2374:                 if (defined($in{'curr_autharg'})) {
 2375:                     $intarg = $in{'curr_autharg'};
 2376:                 }
 2377:             } else {
 2378:                 $result = &mt('Currently internally authenticated.');
 2379:                 return $result;
 2380:             }
 2381:         }
 2382:     } else {
 2383:         if ($authnum == 1) {
 2384:             $authtype = '<input type="hidden" name="login" value="int" />';
 2385:         }
 2386:     }
 2387:     if (!$can_assign{'int'}) {
 2388:         return;
 2389:     } elsif ($authtype eq '') {
 2390:         if (defined($in{'mode'})) {
 2391:             if ($in{'mode'} eq 'modifycourse') {
 2392:                 if ($authnum == 1) {
 2393:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2394:                 }
 2395:             }
 2396:         }
 2397:     }
 2398:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2399:     if ($authtype eq '') {
 2400:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2401:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2402:     }
 2403:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2404:                $intarg.'" onchange="'.$jscall.'" />';
 2405:     $result = &mt
 2406:         ('[_1] Internally authenticated (with initial password [_2])',
 2407:          '<label>'.$authtype,'</label>'.$autharg);
 2408:     $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>';
 2409:     return $result;
 2410: }
 2411: 
 2412: sub authform_local{  
 2413:     my %in = (
 2414:               formname => 'document.cu',
 2415:               kerb_def_dom => 'MSU.EDU',
 2416:               @_,
 2417:               );
 2418:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2419:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2420:     if (defined($in{'curr_authtype'})) {
 2421:         if ($in{'curr_authtype'} eq 'loc') {
 2422:             if ($can_assign{'loc'}) {
 2423:                 $loccheck = 'checked="checked" ';
 2424:                 if (defined($in{'mode'})) {
 2425:                     if ($in{'mode'} eq 'modifyuser') {
 2426:                         $loccheck = '';
 2427:                     }
 2428:                 }
 2429:                 if (defined($in{'curr_autharg'})) {
 2430:                     $locarg = $in{'curr_autharg'};
 2431:                 }
 2432:             } else {
 2433:                 $result = &mt('Currently using local (institutional) authentication.');
 2434:                 return $result;
 2435:             }
 2436:         }
 2437:     } else {
 2438:         if ($authnum == 1) {
 2439:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2440:         }
 2441:     }
 2442:     if (!$can_assign{'loc'}) {
 2443:         return;
 2444:     } elsif ($authtype eq '') {
 2445:         if (defined($in{'mode'})) {
 2446:             if ($in{'mode'} eq 'modifycourse') {
 2447:                 if ($authnum == 1) {
 2448:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2449:                 }
 2450:             }
 2451:         }
 2452:     }
 2453:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2454:     if ($authtype eq '') {
 2455:         $authtype = '<input type="radio" name="login" value="loc" '.
 2456:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2457:                     $jscall.'" />';
 2458:     }
 2459:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2460:                $locarg.'" onchange="'.$jscall.'" />';
 2461:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2462:                   '<label>'.$authtype,'</label>'.$autharg);
 2463:     return $result;
 2464: }
 2465: 
 2466: sub authform_filesystem{  
 2467:     my %in = (
 2468:               formname => 'document.cu',
 2469:               kerb_def_dom => 'MSU.EDU',
 2470:               @_,
 2471:               );
 2472:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2473:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2474:     if (defined($in{'curr_authtype'})) {
 2475:         if ($in{'curr_authtype'} eq 'fsys') {
 2476:             if ($can_assign{'fsys'}) {
 2477:                 $fsyscheck = 'checked="checked" ';
 2478:                 if (defined($in{'mode'})) {
 2479:                     if ($in{'mode'} eq 'modifyuser') {
 2480:                         $fsyscheck = '';
 2481:                     }
 2482:                 }
 2483:             } else {
 2484:                 $result = &mt('Currently Filesystem Authenticated.');
 2485:                 return $result;
 2486:             }           
 2487:         }
 2488:     } else {
 2489:         if ($authnum == 1) {
 2490:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2491:         }
 2492:     }
 2493:     if (!$can_assign{'fsys'}) {
 2494:         return;
 2495:     } elsif ($authtype eq '') {
 2496:         if (defined($in{'mode'})) {
 2497:             if ($in{'mode'} eq 'modifycourse') {
 2498:                 if ($authnum == 1) {
 2499:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2500:                 }
 2501:             }
 2502:         }
 2503:     }
 2504:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2505:     if ($authtype eq '') {
 2506:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2507:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2508:                     $jscall.'" />';
 2509:     }
 2510:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2511:                ' onchange="'.$jscall.'" />';
 2512:     $result = &mt
 2513:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2514:          '<label><input type="radio" name="login" value="fsys" '.
 2515:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2516:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2517:                   'onchange="'.$jscall.'" />');
 2518:     return $result;
 2519: }
 2520: 
 2521: sub get_assignable_auth {
 2522:     my ($dom) = @_;
 2523:     if ($dom eq '') {
 2524:         $dom = $env{'request.role.domain'};
 2525:     }
 2526:     my %can_assign = (
 2527:                           krb4 => 1,
 2528:                           krb5 => 1,
 2529:                           int  => 1,
 2530:                           loc  => 1,
 2531:                      );
 2532:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2533:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2534:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2535:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2536:             my $context;
 2537:             if ($env{'request.role'} =~ /^au/) {
 2538:                 $context = 'author';
 2539:             } elsif ($env{'request.role'} =~ /^dc/) {
 2540:                 $context = 'domain';
 2541:             } elsif ($env{'request.course.id'}) {
 2542:                 $context = 'course';
 2543:             }
 2544:             if ($context) {
 2545:                 if (ref($authhash->{$context}) eq 'HASH') {
 2546:                    %can_assign = %{$authhash->{$context}}; 
 2547:                 }
 2548:             }
 2549:         }
 2550:     }
 2551:     my $authnum = 0;
 2552:     foreach my $key (keys(%can_assign)) {
 2553:         if ($can_assign{$key}) {
 2554:             $authnum ++;
 2555:         }
 2556:     }
 2557:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2558:         $authnum --;
 2559:     }
 2560:     return ($authnum,%can_assign);
 2561: }
 2562: 
 2563: ###############################################################
 2564: ##    Get Kerberos Defaults for Domain                 ##
 2565: ###############################################################
 2566: ##
 2567: ## Returns default kerberos version and an associated argument
 2568: ## as listed in file domain.tab. If not listed, provides
 2569: ## appropriate default domain and kerberos version.
 2570: ##
 2571: #-------------------------------------------
 2572: 
 2573: =pod
 2574: 
 2575: =item * &get_kerberos_defaults()
 2576: 
 2577: get_kerberos_defaults($target_domain) returns the default kerberos
 2578: version and domain. If not found, it defaults to version 4 and the 
 2579: domain of the server.
 2580: 
 2581: =over 4
 2582: 
 2583: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2584: 
 2585: =back
 2586: 
 2587: =back
 2588: 
 2589: =cut
 2590: 
 2591: #-------------------------------------------
 2592: sub get_kerberos_defaults {
 2593:     my $domain=shift;
 2594:     my ($krbdef,$krbdefdom);
 2595:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2596:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2597:         $krbdef = $domdefaults{'auth_def'};
 2598:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2599:     } else {
 2600:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2601:         my $krbdefdom=$1;
 2602:         $krbdefdom=~tr/a-z/A-Z/;
 2603:         $krbdef = "krb4";
 2604:     }
 2605:     return ($krbdef,$krbdefdom);
 2606: }
 2607: 
 2608: 
 2609: ###############################################################
 2610: ##                Thesaurus Functions                        ##
 2611: ###############################################################
 2612: 
 2613: =pod
 2614: 
 2615: =head1 Thesaurus Functions
 2616: 
 2617: =over 4
 2618: 
 2619: =item * &initialize_keywords()
 2620: 
 2621: Initializes the package variable %Keywords if it is empty.  Uses the
 2622: package variable $thesaurus_db_file.
 2623: 
 2624: =cut
 2625: 
 2626: ###################################################
 2627: 
 2628: sub initialize_keywords {
 2629:     return 1 if (scalar keys(%Keywords));
 2630:     # If we are here, %Keywords is empty, so fill it up
 2631:     #   Make sure the file we need exists...
 2632:     if (! -e $thesaurus_db_file) {
 2633:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2634:                                  " failed because it does not exist");
 2635:         return 0;
 2636:     }
 2637:     #   Set up the hash as a database
 2638:     my %thesaurus_db;
 2639:     if (! tie(%thesaurus_db,'GDBM_File',
 2640:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2641:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2642:                                  $thesaurus_db_file);
 2643:         return 0;
 2644:     } 
 2645:     #  Get the average number of appearances of a word.
 2646:     my $avecount = $thesaurus_db{'average.count'};
 2647:     #  Put keywords (those that appear > average) into %Keywords
 2648:     while (my ($word,$data)=each (%thesaurus_db)) {
 2649:         my ($count,undef) = split /:/,$data;
 2650:         $Keywords{$word}++ if ($count > $avecount);
 2651:     }
 2652:     untie %thesaurus_db;
 2653:     # Remove special values from %Keywords.
 2654:     foreach my $value ('total.count','average.count') {
 2655:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2656:   }
 2657:     return 1;
 2658: }
 2659: 
 2660: ###################################################
 2661: 
 2662: =pod
 2663: 
 2664: =item * &keyword($word)
 2665: 
 2666: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2667: than the average number of times in the thesaurus database.  Calls 
 2668: &initialize_keywords
 2669: 
 2670: =cut
 2671: 
 2672: ###################################################
 2673: 
 2674: sub keyword {
 2675:     return if (!&initialize_keywords());
 2676:     my $word=lc(shift());
 2677:     $word=~s/\W//g;
 2678:     return exists($Keywords{$word});
 2679: }
 2680: 
 2681: ###############################################################
 2682: 
 2683: =pod 
 2684: 
 2685: =item * &get_related_words()
 2686: 
 2687: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2688: an array of words.  If the keyword is not in the thesaurus, an empty array
 2689: will be returned.  The order of the words returned is determined by the
 2690: database which holds them.
 2691: 
 2692: Uses global $thesaurus_db_file.
 2693: 
 2694: =cut
 2695: 
 2696: ###############################################################
 2697: sub get_related_words {
 2698:     my $keyword = shift;
 2699:     my %thesaurus_db;
 2700:     if (! -e $thesaurus_db_file) {
 2701:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2702:                                  "failed because the file does not exist");
 2703:         return ();
 2704:     }
 2705:     if (! tie(%thesaurus_db,'GDBM_File',
 2706:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2707:         return ();
 2708:     } 
 2709:     my @Words=();
 2710:     my $count=0;
 2711:     if (exists($thesaurus_db{$keyword})) {
 2712: 	# The first element is the number of times
 2713: 	# the word appears.  We do not need it now.
 2714: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2715: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2716: 	my $threshold=$mostfrequentcount/10;
 2717:         foreach my $possibleword (@RelatedWords) {
 2718:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2719:             if ($wordcount>$threshold) {
 2720: 		push(@Words,$word);
 2721:                 $count++;
 2722:                 if ($count>10) { last; }
 2723: 	    }
 2724:         }
 2725:     }
 2726:     untie %thesaurus_db;
 2727:     return @Words;
 2728: }
 2729: 
 2730: =pod
 2731: 
 2732: =back
 2733: 
 2734: =cut
 2735: 
 2736: # -------------------------------------------------------------- Plaintext name
 2737: =pod
 2738: 
 2739: =head1 User Name Functions
 2740: 
 2741: =over 4
 2742: 
 2743: =item * &plainname($uname,$udom,$first)
 2744: 
 2745: Takes a users logon name and returns it as a string in
 2746: "first middle last generation" form 
 2747: if $first is set to 'lastname' then it returns it as
 2748: 'lastname generation, firstname middlename' if their is a lastname
 2749: 
 2750: =cut
 2751: 
 2752: 
 2753: ###############################################################
 2754: sub plainname {
 2755:     my ($uname,$udom,$first)=@_;
 2756:     return if (!defined($uname) || !defined($udom));
 2757:     my %names=&getnames($uname,$udom);
 2758:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2759: 					  $names{'middlename'},
 2760: 					  $names{'lastname'},
 2761: 					  $names{'generation'},$first);
 2762:     $name=~s/^\s+//;
 2763:     $name=~s/\s+$//;
 2764:     $name=~s/\s+/ /g;
 2765:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2766:     return $name;
 2767: }
 2768: 
 2769: # -------------------------------------------------------------------- Nickname
 2770: =pod
 2771: 
 2772: =item * &nickname($uname,$udom)
 2773: 
 2774: Gets a users name and returns it as a string as
 2775: 
 2776: "&quot;nickname&quot;"
 2777: 
 2778: if the user has a nickname or
 2779: 
 2780: "first middle last generation"
 2781: 
 2782: if the user does not
 2783: 
 2784: =cut
 2785: 
 2786: sub nickname {
 2787:     my ($uname,$udom)=@_;
 2788:     return if (!defined($uname) || !defined($udom));
 2789:     my %names=&getnames($uname,$udom);
 2790:     my $name=$names{'nickname'};
 2791:     if ($name) {
 2792:        $name='&quot;'.$name.'&quot;'; 
 2793:     } else {
 2794:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2795: 	     $names{'lastname'}.' '.$names{'generation'};
 2796:        $name=~s/\s+$//;
 2797:        $name=~s/\s+/ /g;
 2798:     }
 2799:     return $name;
 2800: }
 2801: 
 2802: sub getnames {
 2803:     my ($uname,$udom)=@_;
 2804:     return if (!defined($uname) || !defined($udom));
 2805:     if ($udom eq 'public' && $uname eq 'public') {
 2806: 	return ('lastname' => &mt('Public'));
 2807:     }
 2808:     my $id=$uname.':'.$udom;
 2809:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2810:     if ($cached) {
 2811: 	return %{$names};
 2812:     } else {
 2813: 	my %loadnames=&Apache::lonnet::get('environment',
 2814:                     ['firstname','middlename','lastname','generation','nickname'],
 2815: 					 $udom,$uname);
 2816: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2817: 	return %loadnames;
 2818:     }
 2819: }
 2820: 
 2821: # -------------------------------------------------------------------- getemails
 2822: 
 2823: =pod
 2824: 
 2825: =item * &getemails($uname,$udom)
 2826: 
 2827: Gets a user's email information and returns it as a hash with keys:
 2828: notification, critnotification, permanentemail
 2829: 
 2830: For notification and critnotification, values are comma-separated lists 
 2831: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2832:  
 2833: 
 2834: =cut
 2835: 
 2836: 
 2837: sub getemails {
 2838:     my ($uname,$udom)=@_;
 2839:     if ($udom eq 'public' && $uname eq 'public') {
 2840: 	return;
 2841:     }
 2842:     if (!$udom) { $udom=$env{'user.domain'}; }
 2843:     if (!$uname) { $uname=$env{'user.name'}; }
 2844:     my $id=$uname.':'.$udom;
 2845:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2846:     if ($cached) {
 2847: 	return %{$names};
 2848:     } else {
 2849: 	my %loadnames=&Apache::lonnet::get('environment',
 2850:                     			   ['notification','critnotification',
 2851: 					    'permanentemail'],
 2852: 					   $udom,$uname);
 2853: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2854: 	return %loadnames;
 2855:     }
 2856: }
 2857: 
 2858: sub flush_email_cache {
 2859:     my ($uname,$udom)=@_;
 2860:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2861:     if (!$uname) { $uname=$env{'user.name'};   }
 2862:     return if ($udom eq 'public' && $uname eq 'public');
 2863:     my $id=$uname.':'.$udom;
 2864:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2865: }
 2866: 
 2867: # -------------------------------------------------------------------- getlangs
 2868: 
 2869: =pod
 2870: 
 2871: =item * &getlangs($uname,$udom)
 2872: 
 2873: Gets a user's language preference and returns it as a hash with key:
 2874: language.
 2875: 
 2876: =cut
 2877: 
 2878: 
 2879: sub getlangs {
 2880:     my ($uname,$udom) = @_;
 2881:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2882:     if (!$uname) { $uname=$env{'user.name'};   }
 2883:     my $id=$uname.':'.$udom;
 2884:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2885:     if ($cached) {
 2886:         return %{$langs};
 2887:     } else {
 2888:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2889:                                            $udom,$uname);
 2890:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2891:         return %loadlangs;
 2892:     }
 2893: }
 2894: 
 2895: sub flush_langs_cache {
 2896:     my ($uname,$udom)=@_;
 2897:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2898:     if (!$uname) { $uname=$env{'user.name'};   }
 2899:     return if ($udom eq 'public' && $uname eq 'public');
 2900:     my $id=$uname.':'.$udom;
 2901:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2902: }
 2903: 
 2904: # ------------------------------------------------------------------ Screenname
 2905: 
 2906: =pod
 2907: 
 2908: =item * &screenname($uname,$udom)
 2909: 
 2910: Gets a users screenname and returns it as a string
 2911: 
 2912: =cut
 2913: 
 2914: sub screenname {
 2915:     my ($uname,$udom)=@_;
 2916:     if ($uname eq $env{'user.name'} &&
 2917: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2918:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2919:     return $names{'screenname'};
 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: # --------------------------------------------------------------- Notes Wrapper
 2953: 
 2954: sub noteswrapper {
 2955:     my ($link,$un,$do)=@_;
 2956:     return 
 2957: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2958: }
 2959: # ------------------------------------------------------------- Aboutme Wrapper
 2960: 
 2961: sub aboutmewrapper {
 2962:     my ($link,$username,$domain,$target)=@_;
 2963:     if (!defined($username)  && !defined($domain)) {
 2964:         return;
 2965:     }
 2966:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2967: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2968: }
 2969: 
 2970: # ------------------------------------------------------------ Syllabus Wrapper
 2971: 
 2972: 
 2973: sub syllabuswrapper {
 2974:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2975:     if ($fontcolor) { 
 2976:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2977:     }
 2978:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 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: ##               Student Answer Attempts                     ##
 3285: ###############################################################
 3286: 
 3287: =pod
 3288: 
 3289: =head1 Alternate Problem Views
 3290: 
 3291: =over 4
 3292: 
 3293: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3294:     $getattempt, $regexp, $gradesub)
 3295: 
 3296: Return string with previous attempt on problem. Arguments:
 3297: 
 3298: =over 4
 3299: 
 3300: =item * $symb: Problem, including path
 3301: 
 3302: =item * $username: username of the desired student
 3303: 
 3304: =item * $domain: domain of the desired student
 3305: 
 3306: =item * $course: Course ID
 3307: 
 3308: =item * $getattempt: Leave blank for all attempts, otherwise put
 3309:     something
 3310: 
 3311: =item * $regexp: if string matches this regexp, the string will be
 3312:     sent to $gradesub
 3313: 
 3314: =item * $gradesub: routine that processes the string if it matches $regexp
 3315: 
 3316: =back
 3317: 
 3318: The output string is a table containing all desired attempts, if any.
 3319: 
 3320: =cut
 3321: 
 3322: sub get_previous_attempt {
 3323:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3324:   my $prevattempts='';
 3325:   no strict 'refs';
 3326:   if ($symb) {
 3327:     my (%returnhash)=
 3328:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3329:     if ($returnhash{'version'}) {
 3330:       my %lasthash=();
 3331:       my $version;
 3332:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3333:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3334: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3335:         }
 3336:       }
 3337:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3338:       $prevattempts.='<th>'.&mt('History').'</th>';
 3339:       foreach my $key (sort(keys(%lasthash))) {
 3340: 	my ($ign,@parts) = split(/\./,$key);
 3341: 	if ($#parts > 0) {
 3342: 	  my $data=$parts[-1];
 3343: 	  pop(@parts);
 3344: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3345: 	} else {
 3346: 	  if ($#parts == 0) {
 3347: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3348: 	  } else {
 3349: 	    $prevattempts.='<th>'.$ign.'</th>';
 3350: 	  }
 3351: 	}
 3352:       }
 3353:       $prevattempts.=&end_data_table_header_row();
 3354:       if ($getattempt eq '') {
 3355: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3356: 	  $prevattempts.=&start_data_table_row().
 3357: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3358: 	    foreach my $key (sort(keys(%lasthash))) {
 3359: 		my $value = &format_previous_attempt_value($key,
 3360: 							   $returnhash{$version.':'.$key});
 3361: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3362: 	    }
 3363: 	  $prevattempts.=&end_data_table_row();
 3364: 	 }
 3365:       }
 3366:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3367:       foreach my $key (sort(keys(%lasthash))) {
 3368: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3369: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3370: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3371:       }
 3372:       $prevattempts.= &end_data_table_row().&end_data_table();
 3373:     } else {
 3374:       $prevattempts=
 3375: 	  &start_data_table().&start_data_table_row().
 3376: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3377: 	  &end_data_table_row().&end_data_table();
 3378:     }
 3379:   } else {
 3380:     $prevattempts=
 3381: 	  &start_data_table().&start_data_table_row().
 3382: 	  '<td>'.&mt('No data.').'</td>'.
 3383: 	  &end_data_table_row().&end_data_table();
 3384:   }
 3385: }
 3386: 
 3387: sub format_previous_attempt_value {
 3388:     my ($key,$value) = @_;
 3389:     if ($key =~ /timestamp/) {
 3390: 	$value = &Apache::lonlocal::locallocaltime($value);
 3391:     } elsif (ref($value) eq 'ARRAY') {
 3392: 	$value = '('.join(', ', @{ $value }).')';
 3393:     } else {
 3394: 	$value = &unescape($value);
 3395:     }
 3396:     return $value;
 3397: }
 3398: 
 3399: 
 3400: sub relative_to_absolute {
 3401:     my ($url,$output)=@_;
 3402:     my $parser=HTML::TokeParser->new(\$output);
 3403:     my $token;
 3404:     my $thisdir=$url;
 3405:     my @rlinks=();
 3406:     while ($token=$parser->get_token) {
 3407: 	if ($token->[0] eq 'S') {
 3408: 	    if ($token->[1] eq 'a') {
 3409: 		if ($token->[2]->{'href'}) {
 3410: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3411: 		}
 3412: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3413: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3414: 	    } elsif ($token->[1] eq 'base') {
 3415: 		$thisdir=$token->[2]->{'href'};
 3416: 	    }
 3417: 	}
 3418:     }
 3419:     $thisdir=~s-/[^/]*$--;
 3420:     foreach my $link (@rlinks) {
 3421: 	unless (($link=~/^https?\:\/\//i) ||
 3422: 		($link=~/^\//) ||
 3423: 		($link=~/^javascript:/i) ||
 3424: 		($link=~/^mailto:/i) ||
 3425: 		($link=~/^\#/)) {
 3426: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3427: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3428: 	}
 3429:     }
 3430: # -------------------------------------------------- Deal with Applet codebases
 3431:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3432:     return $output;
 3433: }
 3434: 
 3435: =pod
 3436: 
 3437: =item * &get_student_view()
 3438: 
 3439: show a snapshot of what student was looking at
 3440: 
 3441: =cut
 3442: 
 3443: sub get_student_view {
 3444:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3445:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3446:   my (%form);
 3447:   my @elements=('symb','courseid','domain','username');
 3448:   foreach my $element (@elements) {
 3449:       $form{'grade_'.$element}=eval '$'.$element #'
 3450:   }
 3451:   if (defined($moreenv)) {
 3452:       %form=(%form,%{$moreenv});
 3453:   }
 3454:   if (defined($target)) { $form{'grade_target'} = $target; }
 3455:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3456:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3457:   $userview=~s/\<body[^\>]*\>//gi;
 3458:   $userview=~s/\<\/body\>//gi;
 3459:   $userview=~s/\<html\>//gi;
 3460:   $userview=~s/\<\/html\>//gi;
 3461:   $userview=~s/\<head\>//gi;
 3462:   $userview=~s/\<\/head\>//gi;
 3463:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3464:   $userview=&relative_to_absolute($feedurl,$userview);
 3465:   if (wantarray) {
 3466:      return ($userview,$response);
 3467:   } else {
 3468:      return $userview;
 3469:   }
 3470: }
 3471: 
 3472: sub get_student_view_with_retries {
 3473:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3474: 
 3475:     my $ok = 0;                 # True if we got a good response.
 3476:     my $content;
 3477:     my $response;
 3478: 
 3479:     # Try to get the student_view done. within the retries count:
 3480:     
 3481:     do {
 3482:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3483:          $ok      = $response->is_success;
 3484:          if (!$ok) {
 3485:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3486:          }
 3487:          $retries--;
 3488:     } while (!$ok && ($retries > 0));
 3489:     
 3490:     if (!$ok) {
 3491:        $content = '';          # On error return an empty content.
 3492:     }
 3493:     if (wantarray) {
 3494:        return ($content, $response);
 3495:     } else {
 3496:        return $content;
 3497:     }
 3498: }
 3499: 
 3500: =pod
 3501: 
 3502: =item * &get_student_answers() 
 3503: 
 3504: show a snapshot of how student was answering problem
 3505: 
 3506: =cut
 3507: 
 3508: sub get_student_answers {
 3509:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3510:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3511:   my (%moreenv);
 3512:   my @elements=('symb','courseid','domain','username');
 3513:   foreach my $element (@elements) {
 3514:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3515:   }
 3516:   $moreenv{'grade_target'}='answer';
 3517:   %moreenv=(%form,%moreenv);
 3518:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3519:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3520:   return $userview;
 3521: }
 3522: 
 3523: =pod
 3524: 
 3525: =item * &submlink()
 3526: 
 3527: Inputs: $text $uname $udom $symb $target
 3528: 
 3529: Returns: A link to grades.pm such as to see the SUBM view of a student
 3530: 
 3531: =cut
 3532: 
 3533: ###############################################
 3534: sub submlink {
 3535:     my ($text,$uname,$udom,$symb,$target)=@_;
 3536:     if (!($uname && $udom)) {
 3537: 	(my $cursymb, my $courseid,$udom,$uname)=
 3538: 	    &Apache::lonnet::whichuser($symb);
 3539: 	if (!$symb) { $symb=$cursymb; }
 3540:     }
 3541:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3542:     $symb=&escape($symb);
 3543:     if ($target) { $target="target=\"$target\""; }
 3544:     return '<a href="/adm/grades?&command=submission&'.
 3545: 	'symb='.$symb.'&student='.$uname.
 3546: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3547: }
 3548: ##############################################
 3549: 
 3550: =pod
 3551: 
 3552: =item * &pgrdlink()
 3553: 
 3554: Inputs: $text $uname $udom $symb $target
 3555: 
 3556: Returns: A link to grades.pm such as to see the PGRD view of a student
 3557: 
 3558: =cut
 3559: 
 3560: ###############################################
 3561: sub pgrdlink {
 3562:     my $link=&submlink(@_);
 3563:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3564:     return $link;
 3565: }
 3566: ##############################################
 3567: 
 3568: =pod
 3569: 
 3570: =item * &pprmlink()
 3571: 
 3572: Inputs: $text $uname $udom $symb $target
 3573: 
 3574: Returns: A link to parmset.pm such as to see the PPRM view of a
 3575: student and a specific resource
 3576: 
 3577: =cut
 3578: 
 3579: ###############################################
 3580: sub pprmlink {
 3581:     my ($text,$uname,$udom,$symb,$target)=@_;
 3582:     if (!($uname && $udom)) {
 3583: 	(my $cursymb, my $courseid,$udom,$uname)=
 3584: 	    &Apache::lonnet::whichuser($symb);
 3585: 	if (!$symb) { $symb=$cursymb; }
 3586:     }
 3587:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3588:     $symb=&escape($symb);
 3589:     if ($target) { $target="target=\"$target\""; }
 3590:     return '<a href="/adm/parmset?command=set&amp;'.
 3591: 	'symb='.$symb.'&amp;uname='.$uname.
 3592: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3593: }
 3594: ##############################################
 3595: 
 3596: =pod
 3597: 
 3598: =back
 3599: 
 3600: =cut
 3601: 
 3602: ###############################################
 3603: 
 3604: 
 3605: sub timehash {
 3606:     my ($thistime) = @_;
 3607:     my $timezone = &Apache::lonlocal::gettimezone();
 3608:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3609:                      ->set_time_zone($timezone);
 3610:     my $wday = $dt->day_of_week();
 3611:     if ($wday == 7) { $wday = 0; }
 3612:     return ( 'second' => $dt->second(),
 3613:              'minute' => $dt->minute(),
 3614:              'hour'   => $dt->hour(),
 3615:              'day'     => $dt->day_of_month(),
 3616:              'month'   => $dt->month(),
 3617:              'year'    => $dt->year(),
 3618:              'weekday' => $wday,
 3619:              'dayyear' => $dt->day_of_year(),
 3620:              'dlsav'   => $dt->is_dst() );
 3621: }
 3622: 
 3623: sub utc_string {
 3624:     my ($date)=@_;
 3625:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3626: }
 3627: 
 3628: sub maketime {
 3629:     my %th=@_;
 3630:     my ($epoch_time,$timezone,$dt);
 3631:     $timezone = &Apache::lonlocal::gettimezone();
 3632:     eval {
 3633:         $dt = DateTime->new( year   => $th{'year'},
 3634:                              month  => $th{'month'},
 3635:                              day    => $th{'day'},
 3636:                              hour   => $th{'hour'},
 3637:                              minute => $th{'minute'},
 3638:                              second => $th{'second'},
 3639:                              time_zone => $timezone,
 3640:                          );
 3641:     };
 3642:     if (!$@) {
 3643:         $epoch_time = $dt->epoch;
 3644:         if ($epoch_time) {
 3645:             return $epoch_time;
 3646:         }
 3647:     }
 3648:     return POSIX::mktime(
 3649:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3650:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3651: }
 3652: 
 3653: #########################################
 3654: 
 3655: sub findallcourses {
 3656:     my ($roles,$uname,$udom) = @_;
 3657:     my %roles;
 3658:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3659:     my %courses;
 3660:     my $now=time;
 3661:     if (!defined($uname)) {
 3662:         $uname = $env{'user.name'};
 3663:     }
 3664:     if (!defined($udom)) {
 3665:         $udom = $env{'user.domain'};
 3666:     }
 3667:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3668:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3669:         if (!%roles) {
 3670:             %roles = (
 3671:                        cc => 1,
 3672:                        in => 1,
 3673:                        ep => 1,
 3674:                        ta => 1,
 3675:                        cr => 1,
 3676:                        st => 1,
 3677:              );
 3678:         }
 3679:         foreach my $entry (keys(%roleshash)) {
 3680:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3681:             if ($trole =~ /^cr/) { 
 3682:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3683:             } else {
 3684:                 next if (!exists($roles{$trole}));
 3685:             }
 3686:             if ($tend) {
 3687:                 next if ($tend < $now);
 3688:             }
 3689:             if ($tstart) {
 3690:                 next if ($tstart > $now);
 3691:             }
 3692:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3693:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3694:             if ($secpart eq '') {
 3695:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3696:                 $sec = 'none';
 3697:                 $realsec = '';
 3698:             } else {
 3699:                 $cnum = $cnumpart;
 3700:                 ($sec,$role) = split(/_/,$secpart);
 3701:                 $realsec = $sec;
 3702:             }
 3703:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3704:         }
 3705:     } else {
 3706:         foreach my $key (keys(%env)) {
 3707: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3708:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3709: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3710: 	        next if ($role eq 'ca' || $role eq 'aa');
 3711: 	        next if (%roles && !exists($roles{$role}));
 3712: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3713:                 my $active=1;
 3714:                 if ($starttime) {
 3715: 		    if ($now<$starttime) { $active=0; }
 3716:                 }
 3717:                 if ($endtime) {
 3718:                     if ($now>$endtime) { $active=0; }
 3719:                 }
 3720:                 if ($active) {
 3721:                     if ($sec eq '') {
 3722:                         $sec = 'none';
 3723:                     }
 3724:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3725:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3726:                 }
 3727:             }
 3728:         }
 3729:     }
 3730:     return %courses;
 3731: }
 3732: 
 3733: ###############################################
 3734: 
 3735: sub blockcheck {
 3736:     my ($setters,$activity,$uname,$udom) = @_;
 3737: 
 3738:     if (!defined($udom)) {
 3739:         $udom = $env{'user.domain'};
 3740:     }
 3741:     if (!defined($uname)) {
 3742:         $uname = $env{'user.name'};
 3743:     }
 3744: 
 3745:     # If uname and udom are for a course, check for blocks in the course.
 3746: 
 3747:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3748:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3749:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3750:         return ($startblock,$endblock);
 3751:     }
 3752: 
 3753:     my $startblock = 0;
 3754:     my $endblock = 0;
 3755:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3756: 
 3757:     # If uname is for a user, and activity is course-specific, i.e.,
 3758:     # boards, chat or groups, check for blocking in current course only.
 3759: 
 3760:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3761:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3762:         foreach my $key (keys(%live_courses)) {
 3763:             if ($key ne $env{'request.course.id'}) {
 3764:                 delete($live_courses{$key});
 3765:             }
 3766:         }
 3767:     }
 3768: 
 3769:     my $otheruser = 0;
 3770:     my %own_courses;
 3771:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3772:         # Resource belongs to user other than current user.
 3773:         $otheruser = 1;
 3774:         # Gather courses for current user
 3775:         %own_courses = 
 3776:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3777:     }
 3778: 
 3779:     # Gather active course roles - course coordinator, instructor, 
 3780:     # exam proctor, ta, student, or custom role.
 3781: 
 3782:     foreach my $course (keys(%live_courses)) {
 3783:         my ($cdom,$cnum);
 3784:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3785:             $cdom = $env{'course.'.$course.'.domain'};
 3786:             $cnum = $env{'course.'.$course.'.num'};
 3787:         } else {
 3788:             ($cdom,$cnum) = split(/_/,$course); 
 3789:         }
 3790:         my $no_ownblock = 0;
 3791:         my $no_userblock = 0;
 3792:         if ($otheruser && $activity ne 'com') {
 3793:             # Check if current user has 'evb' priv for this
 3794:             if (defined($own_courses{$course})) {
 3795:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3796:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3797:                     if ($sec ne 'none') {
 3798:                         $checkrole .= '/'.$sec;
 3799:                     }
 3800:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3801:                         $no_ownblock = 1;
 3802:                         last;
 3803:                     }
 3804:                 }
 3805:             }
 3806:             # if they have 'evb' priv and are currently not playing student
 3807:             next if (($no_ownblock) &&
 3808:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3809:         }
 3810:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3811:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3812:             if ($sec ne 'none') {
 3813:                 $checkrole .= '/'.$sec;
 3814:             }
 3815:             if ($otheruser) {
 3816:                 # Resource belongs to user other than current user.
 3817:                 # Assemble privs for that user, and check for 'evb' priv.
 3818:                 my ($trole,$tdom,$tnum,$tsec);
 3819:                 my $entry = $live_courses{$course}{$sec};
 3820:                 if ($entry =~ /^cr/) {
 3821:                     ($trole,$tdom,$tnum,$tsec) = 
 3822:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3823:                 } else {
 3824:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3825:                 }
 3826:                 my ($spec,$area,$trest,%allroles,%userroles);
 3827:                 $area = '/'.$tdom.'/'.$tnum;
 3828:                 $trest = $tnum;
 3829:                 if ($tsec ne '') {
 3830:                     $area .= '/'.$tsec;
 3831:                     $trest .= '/'.$tsec;
 3832:                 }
 3833:                 $spec = $trole.'.'.$area;
 3834:                 if ($trole =~ /^cr/) {
 3835:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3836:                                                       $tdom,$spec,$trest,$area);
 3837:                 } else {
 3838:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3839:                                                        $tdom,$spec,$trest,$area);
 3840:                 }
 3841:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3842:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3843:                     if ($1) {
 3844:                         $no_userblock = 1;
 3845:                         last;
 3846:                     }
 3847:                 }
 3848:             } else {
 3849:                 # Resource belongs to current user
 3850:                 # Check for 'evb' priv via lonnet::allowed().
 3851:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3852:                     $no_ownblock = 1;
 3853:                     last;
 3854:                 }
 3855:             }
 3856:         }
 3857:         # if they have the evb priv and are currently not playing student
 3858:         next if (($no_ownblock) &&
 3859:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3860:         next if ($no_userblock);
 3861: 
 3862:         # Retrieve blocking times and identity of blocker for course
 3863:         # of specified user, unless user has 'evb' privilege.
 3864:         
 3865:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3866:         if (($start != 0) && 
 3867:             (($startblock == 0) || ($startblock > $start))) {
 3868:             $startblock = $start;
 3869:         }
 3870:         if (($end != 0)  &&
 3871:             (($endblock == 0) || ($endblock < $end))) {
 3872:             $endblock = $end;
 3873:         }
 3874:     }
 3875:     return ($startblock,$endblock);
 3876: }
 3877: 
 3878: sub get_blocks {
 3879:     my ($setters,$activity,$cdom,$cnum) = @_;
 3880:     my $startblock = 0;
 3881:     my $endblock = 0;
 3882:     my $course = $cdom.'_'.$cnum;
 3883:     $setters->{$course} = {};
 3884:     $setters->{$course}{'staff'} = [];
 3885:     $setters->{$course}{'times'} = [];
 3886:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3887:     foreach my $record (keys(%records)) {
 3888:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3889:         if ($start <= time && $end >= time) {
 3890:             my ($staff_name,$staff_dom,$title,$blocks) =
 3891:                 &parse_block_record($records{$record});
 3892:             if ($blocks->{$activity} eq 'on') {
 3893:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3894:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3895:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3896:                     $startblock = $start;
 3897:                 }
 3898:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3899:                     $endblock = $end;
 3900:                 }
 3901:             }
 3902:         }
 3903:     }
 3904:     return ($startblock,$endblock);
 3905: }
 3906: 
 3907: sub parse_block_record {
 3908:     my ($record) = @_;
 3909:     my ($setuname,$setudom,$title,$blocks);
 3910:     if (ref($record) eq 'HASH') {
 3911:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3912:         $title = &unescape($record->{'event'});
 3913:         $blocks = $record->{'blocks'};
 3914:     } else {
 3915:         my @data = split(/:/,$record,3);
 3916:         if (scalar(@data) eq 2) {
 3917:             $title = $data[1];
 3918:             ($setuname,$setudom) = split(/@/,$data[0]);
 3919:         } else {
 3920:             ($setuname,$setudom,$title) = @data;
 3921:         }
 3922:         $blocks = { 'com' => 'on' };
 3923:     }
 3924:     return ($setuname,$setudom,$title,$blocks);
 3925: }
 3926: 
 3927: sub build_block_table {
 3928:     my ($startblock,$endblock,$setters) = @_;
 3929:     my %lt = &Apache::lonlocal::texthash(
 3930:         'cacb' => 'Currently active communication blocks',
 3931:         'cour' => 'Course',
 3932:         'dura' => 'Duration',
 3933:         'blse' => 'Block set by'
 3934:     );
 3935:     my $output;
 3936:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3937:     $output .= &start_data_table();
 3938:     $output .= '
 3939: <tr>
 3940:  <th>'.$lt{'cour'}.'</th>
 3941:  <th>'.$lt{'dura'}.'</th>
 3942:  <th>'.$lt{'blse'}.'</th>
 3943: </tr>
 3944: ';
 3945:     foreach my $course (keys(%{$setters})) {
 3946:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3947:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3948:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3949:             my $fullname = &plainname($uname,$udom);
 3950:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3951:                 && $env{'user.name'} ne 'public' 
 3952:                 && $env{'user.domain'} ne 'public') {
 3953:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3954:             }
 3955:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3956:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3957:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3958:             $output .= &Apache::loncommon::start_data_table_row().
 3959:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3960:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3961:                        '<td>'.$fullname.'</td>'.
 3962:                         &Apache::loncommon::end_data_table_row();
 3963:         }
 3964:     }
 3965:     $output .= &end_data_table();
 3966: }
 3967: 
 3968: sub blocking_status {
 3969:     my ($activity,$uname,$udom) = @_;
 3970:     my %setters;
 3971:     my ($blocked,$output,$ownitem,$is_course);
 3972:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3973:     if ($startblock && $endblock) {
 3974:         $blocked = 1;
 3975:         if (wantarray) {
 3976:             my $category;
 3977:             if ($activity eq 'boards') {
 3978:                 $category = 'Discussion posts in this course';
 3979:             } elsif ($activity eq 'blogs') {
 3980:                 $category = 'Blogs';
 3981:             } elsif ($activity eq 'port') {
 3982:                 if (defined($uname) && defined($udom)) {
 3983:                     if ($uname eq $env{'user.name'} &&
 3984:                         $udom eq $env{'user.domain'}) {
 3985:                         $ownitem = 1;
 3986:                     }
 3987:                 }
 3988:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3989:                 if ($ownitem) { 
 3990:                     $category = 'Your portfolio files';  
 3991:                 } elsif ($is_course) {
 3992:                     my $coursedesc;
 3993:                     foreach my $course (keys(%setters)) {
 3994:                         my %courseinfo =
 3995:                              &Apache::lonnet::coursedescription($course);
 3996:                         $coursedesc = $courseinfo{'description'};
 3997:                     }
 3998:                     $category = "Group portfolio files in the course '$coursedesc'";
 3999:                 } else {
 4000:                     $category = 'Portfolio files belonging to ';
 4001:                     if ($env{'user.name'} eq 'public' && 
 4002:                         $env{'user.domain'} eq 'public') {
 4003:                         $category .= &plainname($uname,$udom);
 4004:                     } else {
 4005:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 4006:                     }
 4007:                 }
 4008:             } elsif ($activity eq 'groups') {
 4009:                 $category = 'Groups in this course';
 4010:             }
 4011:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 4012:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 4013:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 4014:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 4015:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 4016:             }
 4017:         }
 4018:     }
 4019:     if (wantarray) {
 4020:         return ($blocked,$output);
 4021:     } else {
 4022:         return $blocked;
 4023:     }
 4024: }
 4025: 
 4026: ###############################################
 4027: 
 4028: sub check_ip_acc {
 4029:     my ($acc)=@_;
 4030:     &Apache::lonxml::debug("acc is $acc");
 4031:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4032:         return 1;
 4033:     }
 4034:     my $allowed=0;
 4035:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4036: 
 4037:     my $name;
 4038:     foreach my $pattern (split(',',$acc)) {
 4039:         $pattern =~ s/^\s*//;
 4040:         $pattern =~ s/\s*$//;
 4041:         if ($pattern =~ /\*$/) {
 4042:             #35.8.*
 4043:             $pattern=~s/\*//;
 4044:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4045:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4046:             #35.8.3.[34-56]
 4047:             my $low=$2;
 4048:             my $high=$3;
 4049:             $pattern=$1;
 4050:             if ($ip =~ /^\Q$pattern\E/) {
 4051:                 my $last=(split(/\./,$ip))[3];
 4052:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4053:             }
 4054:         } elsif ($pattern =~ /^\*/) {
 4055:             #*.msu.edu
 4056:             $pattern=~s/\*//;
 4057:             if (!defined($name)) {
 4058:                 use Socket;
 4059:                 my $netaddr=inet_aton($ip);
 4060:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4061:             }
 4062:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4063:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4064:             #127.0.0.1
 4065:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4066:         } else {
 4067:             #some.name.com
 4068:             if (!defined($name)) {
 4069:                 use Socket;
 4070:                 my $netaddr=inet_aton($ip);
 4071:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4072:             }
 4073:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4074:         }
 4075:         if ($allowed) { last; }
 4076:     }
 4077:     return $allowed;
 4078: }
 4079: 
 4080: ###############################################
 4081: 
 4082: =pod
 4083: 
 4084: =head1 Domain Template Functions
 4085: 
 4086: =over 4
 4087: 
 4088: =item * &determinedomain()
 4089: 
 4090: Inputs: $domain (usually will be undef)
 4091: 
 4092: Returns: Determines which domain should be used for designs
 4093: 
 4094: =cut
 4095: 
 4096: ###############################################
 4097: sub determinedomain {
 4098:     my $domain=shift;
 4099:     if (! $domain) {
 4100:         # Determine domain if we have not been given one
 4101:         $domain = &Apache::lonnet::default_login_domain();
 4102:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4103:         if ($env{'request.role.domain'}) { 
 4104:             $domain=$env{'request.role.domain'}; 
 4105:         }
 4106:     }
 4107:     return $domain;
 4108: }
 4109: ###############################################
 4110: 
 4111: sub devalidate_domconfig_cache {
 4112:     my ($udom)=@_;
 4113:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4114: }
 4115: 
 4116: # ---------------------- Get domain configuration for a domain
 4117: sub get_domainconf {
 4118:     my ($udom) = @_;
 4119:     my $cachetime=1800;
 4120:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4121:     if (defined($cached)) { return %{$result}; }
 4122: 
 4123:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4124: 					     ['login','rolecolors'],$udom);
 4125:     my (%designhash,%legacy);
 4126:     if (keys(%domconfig) > 0) {
 4127:         if (ref($domconfig{'login'}) eq 'HASH') {
 4128:             if (keys(%{$domconfig{'login'}})) {
 4129:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4130:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4131:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4132:                             $designhash{$udom.'.login.'.$key.'_'.$img} =
 4133:                                 $domconfig{'login'}{$key}{$img};
 4134:                         }
 4135:                     } else {
 4136:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4137:                     }
 4138:                 }
 4139:             } else {
 4140:                 $legacy{'login'} = 1;
 4141:             }
 4142:         } else {
 4143:             $legacy{'login'} = 1;
 4144:         }
 4145:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4146:             if (keys(%{$domconfig{'rolecolors'}})) {
 4147:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4148:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4149:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4150:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4151:                         }
 4152:                     }
 4153:                 }
 4154:             } else {
 4155:                 $legacy{'rolecolors'} = 1;
 4156:             }
 4157:         } else {
 4158:             $legacy{'rolecolors'} = 1;
 4159:         }
 4160:         if (keys(%legacy) > 0) {
 4161:             my %legacyhash = &get_legacy_domconf($udom);
 4162:             foreach my $item (keys(%legacyhash)) {
 4163:                 if ($item =~ /^\Q$udom\E\.login/) {
 4164:                     if ($legacy{'login'}) { 
 4165:                         $designhash{$item} = $legacyhash{$item};
 4166:                     }
 4167:                 } else {
 4168:                     if ($legacy{'rolecolors'}) {
 4169:                         $designhash{$item} = $legacyhash{$item};
 4170:                     }
 4171:                 }
 4172:             }
 4173:         }
 4174:     } else {
 4175:         %designhash = &get_legacy_domconf($udom); 
 4176:     }
 4177:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4178: 				  $cachetime);
 4179:     return %designhash;
 4180: }
 4181: 
 4182: sub get_legacy_domconf {
 4183:     my ($udom) = @_;
 4184:     my %legacyhash;
 4185:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4186:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4187:     if (-e $designfile) {
 4188:         if ( open (my $fh,"<$designfile") ) {
 4189:             while (my $line = <$fh>) {
 4190:                 next if ($line =~ /^\#/);
 4191:                 chomp($line);
 4192:                 my ($key,$val)=(split(/\=/,$line));
 4193:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4194:             }
 4195:             close($fh);
 4196:         }
 4197:     }
 4198:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4199:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4200:     }
 4201:     return %legacyhash;
 4202: }
 4203: 
 4204: =pod
 4205: 
 4206: =item * &domainlogo()
 4207: 
 4208: Inputs: $domain (usually will be undef)
 4209: 
 4210: Returns: A link to a domain logo, if the domain logo exists.
 4211: If the domain logo does not exist, a description of the domain.
 4212: 
 4213: =cut
 4214: 
 4215: ###############################################
 4216: sub domainlogo {
 4217:     my $domain = &determinedomain(shift);
 4218:     my %designhash = &get_domainconf($domain);    
 4219:     # See if there is a logo
 4220:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4221:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4222:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4223: 	    if ($imgsrc =~ m{^/res/}) {
 4224: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4225: 		&Apache::lonnet::repcopy($local_name);
 4226: 	    }
 4227: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4228:         } 
 4229:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4230:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4231:         return &Apache::lonnet::domain($domain,'description');
 4232:     } else {
 4233:         return '';
 4234:     }
 4235: }
 4236: ##############################################
 4237: 
 4238: =pod
 4239: 
 4240: =item * &designparm()
 4241: 
 4242: Inputs: $which parameter; $domain (usually will be undef)
 4243: 
 4244: Returns: value of designparamter $which
 4245: 
 4246: =cut
 4247: 
 4248: 
 4249: ##############################################
 4250: sub designparm {
 4251:     my ($which,$domain)=@_;
 4252:     if ($env{'browser.blackwhite'} eq 'on') {
 4253: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4254: 	    return '#000000';
 4255: 	}
 4256: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4257: 	    return '#FFFFFF';
 4258: 	}
 4259: 	if ($which=~/\.tabbg$/) {
 4260: 	    return '#CCCCCC';
 4261: 	}
 4262:     }
 4263:     if (exists($env{'environment.color.'.$which})) {
 4264: 	return $env{'environment.color.'.$which};
 4265:     }
 4266:     $domain=&determinedomain($domain);
 4267:     my %domdesign = &get_domainconf($domain);
 4268:     my $output;
 4269:     if ($domdesign{$domain.'.'.$which} ne '') {
 4270: 	$output = $domdesign{$domain.'.'.$which};
 4271:     } else {
 4272:         $output = $defaultdesign{$which};
 4273:     }
 4274:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4275:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4276:         if ($output =~ m{^/(adm|res)/}) {
 4277: 	    if ($output =~ m{^/res/}) {
 4278: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4279: 		&Apache::lonnet::repcopy($local_name);
 4280: 	    }
 4281:             $output = &lonhttpdurl($output);
 4282:         }
 4283:     }
 4284:     return $output;
 4285: }
 4286: 
 4287: ###############################################
 4288: ###############################################
 4289: 
 4290: =pod
 4291: 
 4292: =back
 4293: 
 4294: =head1 HTML Helpers
 4295: 
 4296: =over 4
 4297: 
 4298: =item * &bodytag()
 4299: 
 4300: Returns a uniform header for LON-CAPA web pages.
 4301: 
 4302: Inputs: 
 4303: 
 4304: =over 4
 4305: 
 4306: =item * $title, A title to be displayed on the page.
 4307: 
 4308: =item * $function, the current role (can be undef).
 4309: 
 4310: =item * $addentries, extra parameters for the <body> tag.
 4311: 
 4312: =item * $bodyonly, if defined, only return the <body> tag.
 4313: 
 4314: =item * $domain, if defined, force a given domain.
 4315: 
 4316: =item * $forcereg, if page should register as content page (relevant for 
 4317:             text interface only)
 4318: 
 4319: =item * $customtitle, alternate text to use instead of $title
 4320:                       in the title box that appears, this text
 4321:                       is not auto translated like the $title is
 4322: 
 4323: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4324:                    navigational links
 4325: 
 4326: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4327: 
 4328: =item * $notitle, if true keep the nav controls, but remove the title bar
 4329: 
 4330: =item * $no_inline_link, if true and in remote mode, don't show the 
 4331:          'Switch To Inline Menu' link
 4332: 
 4333: =item * $args, optional argument valid values are
 4334:             no_auto_mt_title -> prevents &mt()ing the title arg
 4335:             inherit_jsmath -> when creating popup window in a page,
 4336:                               should it have jsmath forced on by the
 4337:                               current page
 4338: 
 4339: =back
 4340: 
 4341: Returns: A uniform header for LON-CAPA web pages.  
 4342: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4343: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4344: other decorations will be returned.
 4345: 
 4346: =cut
 4347: 
 4348: sub bodytag {
 4349:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4350: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4351: 
 4352:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4353: 
 4354:     $function = &get_users_function() if (!$function);
 4355:     my $img =    &designparm($function.'.img',$domain);
 4356:     my $font =   &designparm($function.'.font',$domain);
 4357:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4358: 
 4359:     my %design = ( 'style'   => 'margin-top: 0',
 4360: 		   'bgcolor' => $pgbg,
 4361: 		   'text'    => $font,
 4362:                    'alink'   => &designparm($function.'.alink',$domain),
 4363: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4364: 		   'link'    => &designparm($function.'.link',$domain),);
 4365:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4366: 
 4367:  # role and realm
 4368:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4369:     if ($role  eq 'ca') {
 4370:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4371:         $realm = &plainname($rname,$rdom);
 4372:     } 
 4373: # realm
 4374:     if ($env{'request.course.id'}) {
 4375:         if ($env{'request.role'} !~ /^cr/) {
 4376:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4377:         }
 4378: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4379:     } else {
 4380:         $role = &Apache::lonnet::plaintext($role);
 4381:     }
 4382: 
 4383:     if (!$realm) { $realm='&nbsp;'; }
 4384: # Set messages
 4385:     my $messages=&domainlogo($domain);
 4386: 
 4387:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4388: 
 4389: # construct main body tag
 4390:     my $bodytag = "<body $extra_body_attr>".
 4391: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4392: 
 4393:     if ($bodyonly) {
 4394:         return $bodytag;
 4395:     } elsif ($env{'browser.interface'} eq 'textual') {
 4396: # Accessibility
 4397:           
 4398: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4399: 	if (!$notitle) {
 4400: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4401: 	}
 4402: 	return $bodytag;
 4403:     }
 4404: 
 4405:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4406:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4407: 	undef($role);
 4408:     } else {
 4409: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4410:     }
 4411:     
 4412:     my $roleinfo=(<<ENDROLE);
 4413: <td class="LC_title_bar_who">
 4414: <div class="LC_title_bar_name">
 4415:     $name
 4416:     &nbsp;
 4417: </div>
 4418: <div class="LC_title_bar_role">
 4419: $role&nbsp;
 4420: </div>
 4421: <div class="LC_title_bar_realm">
 4422: $realm&nbsp;
 4423: </div>
 4424: </td>
 4425: ENDROLE
 4426: 
 4427:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4428:     if ($customtitle) {
 4429:         $titleinfo = $customtitle;
 4430:     }
 4431:     #
 4432:     # Extra info if you are the DC
 4433:     my $dc_info = '';
 4434:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4435:                         $env{'course.'.$env{'request.course.id'}.
 4436:                                  '.domain'}.'/'})) {
 4437:         my $cid = $env{'request.course.id'};
 4438:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4439:         $dc_info =~ s/\s+$//;
 4440:         $dc_info = '('.$dc_info.')';
 4441:     }
 4442: 
 4443:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4444:         # No Remote
 4445: 	if ($env{'request.state'} eq 'construct') {
 4446: 	    $forcereg=1;
 4447: 	}
 4448: 
 4449: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4450: 	    # this is for resources; directories have customtitle, and crumbs
 4451:             # and select recent are created in lonpubdir.pm  
 4452: 	    my ($uname,$thisdisfn)=
 4453: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4454: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4455: 	    $formaction=~s/\/+/\//g;
 4456: 
 4457: 	    my $parentpath = '';
 4458: 	    my $lastitem = '';
 4459: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4460: 		$parentpath = $1;
 4461: 		$lastitem = $2;
 4462: 	    } else {
 4463: 		$lastitem = $thisdisfn;
 4464: 	    }
 4465: 	    $titleinfo = 
 4466: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4467: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4468: 		.'<form name="dirs" method="post" action="'.$formaction
 4469: 		.'" target="_top"><tt><b>'
 4470: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4471: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4472: 		.'</form>'
 4473: 		.&Apache::lonmenu::constspaceform();
 4474:         }
 4475: 
 4476:         my $titletable;
 4477: 	if (!$notitle) {
 4478: 	    $titletable =
 4479: 		'<table id="LC_title_bar">'.
 4480:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4481: 			 '</tr></table>';
 4482: 	}
 4483: 	if ($notopbar) {
 4484: 	    $bodytag .= $titletable;
 4485: 	} else {
 4486: 	    if ($env{'request.state'} eq 'construct') {
 4487:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4488: 							  $titletable);
 4489:             } else {
 4490:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4491: 		    $titletable;
 4492:             }
 4493:         }
 4494:         return $bodytag;
 4495:     }
 4496: 
 4497: #
 4498: # Top frame rendering, Remote is up
 4499: #
 4500: 
 4501:     my $imgsrc = $img;
 4502:     if ($img =~ /^\/adm/) {
 4503:         $imgsrc = &lonhttpdurl($img);
 4504:     }
 4505:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4506: 
 4507:     # Explicit link to get inline menu
 4508:     my $menu= ($no_inline_link?''
 4509: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4510:     #
 4511:     if ($notitle) {
 4512: 	return $bodytag;
 4513:     }
 4514:     return(<<ENDBODY);
 4515: $bodytag
 4516: <table id="LC_title_bar" class="LC_with_remote">
 4517: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4518:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4519: </tr>
 4520: <tr><td>$titleinfo $dc_info $menu</td>
 4521: $roleinfo
 4522: </tr>
 4523: </table>
 4524: ENDBODY
 4525: }
 4526: 
 4527: sub make_attr_string {
 4528:     my ($register,$attr_ref) = @_;
 4529: 
 4530:     if ($attr_ref && !ref($attr_ref)) {
 4531: 	die("addentries Must be a hash ref ".
 4532: 	    join(':',caller(1))." ".
 4533: 	    join(':',caller(0))." ");
 4534:     }
 4535: 
 4536:     if ($register) {
 4537: 	my ($on_load,$on_unload);
 4538: 	foreach my $key (keys(%{$attr_ref})) {
 4539: 	    if      (lc($key) eq 'onload') {
 4540: 		$on_load.=$attr_ref->{$key}.';';
 4541: 		delete($attr_ref->{$key});
 4542: 
 4543: 	    } elsif (lc($key) eq 'onunload') {
 4544: 		$on_unload.=$attr_ref->{$key}.';';
 4545: 		delete($attr_ref->{$key});
 4546: 	    }
 4547: 	}
 4548: 	$attr_ref->{'onload'}  =
 4549: 	    &Apache::lonmenu::loadevents().  $on_load;
 4550: 	$attr_ref->{'onunload'}=
 4551: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4552:     }
 4553: 
 4554: # Accessibility font enhance
 4555:     if ($env{'browser.fontenhance'} eq 'on') {
 4556: 	my $style;
 4557: 	foreach my $key (keys(%{$attr_ref})) {
 4558: 	    if (lc($key) eq 'style') {
 4559: 		$style.=$attr_ref->{$key}.';';
 4560: 		delete($attr_ref->{$key});
 4561: 	    }
 4562: 	}
 4563: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4564:     }
 4565: 
 4566:     if ($env{'browser.blackwhite'} eq 'on') {
 4567: 	delete($attr_ref->{'font'});
 4568: 	delete($attr_ref->{'link'});
 4569: 	delete($attr_ref->{'alink'});
 4570: 	delete($attr_ref->{'vlink'});
 4571: 	delete($attr_ref->{'bgcolor'});
 4572: 	delete($attr_ref->{'background'});
 4573:     }
 4574: 
 4575:     my $attr_string;
 4576:     foreach my $attr (keys(%$attr_ref)) {
 4577: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4578:     }
 4579:     return $attr_string;
 4580: }
 4581: 
 4582: 
 4583: ###############################################
 4584: ###############################################
 4585: 
 4586: =pod
 4587: 
 4588: =item * &endbodytag()
 4589: 
 4590: Returns a uniform footer for LON-CAPA web pages.
 4591: 
 4592: Inputs: 1 - optional reference to an args hash
 4593: If in the hash, key for noredirectlink has a value which evaluates to true,
 4594: a 'Continue' link is not displayed if the page contains an
 4595: internal redirect in the <head></head> section,
 4596: i.e., $env{'internal.head.redirect'} exists   
 4597: 
 4598: =cut
 4599: 
 4600: sub endbodytag {
 4601:     my ($args) = @_;
 4602:     my $endbodytag='</body>';
 4603:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4604:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4605:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4606: 	    $endbodytag=
 4607: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4608: 	        &mt('Continue').'</a>'.
 4609: 	        $endbodytag;
 4610:         }
 4611:     }
 4612:     return $endbodytag;
 4613: }
 4614: 
 4615: =pod
 4616: 
 4617: =item * &standard_css()
 4618: 
 4619: Returns a style sheet
 4620: 
 4621: Inputs: (all optional)
 4622:             domain         -> force to color decorate a page for a specific
 4623:                                domain
 4624:             function       -> force usage of a specific rolish color scheme
 4625:             bgcolor        -> override the default page bgcolor
 4626: 
 4627: =cut
 4628: 
 4629: sub standard_css {
 4630:     my ($function,$domain,$bgcolor) = @_;
 4631:     $function  = &get_users_function() if (!$function);
 4632:     my $img    = &designparm($function.'.img',   $domain);
 4633:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4634:     my $font   = &designparm($function.'.font',  $domain);
 4635:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4636:     my $pgbg_or_bgcolor =
 4637: 	         $bgcolor ||
 4638: 	         &designparm($function.'.pgbg',  $domain);
 4639:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4640:     my $alink  = &designparm($function.'.alink', $domain);
 4641:     my $vlink  = &designparm($function.'.vlink', $domain);
 4642:     my $link   = &designparm($function.'.link',  $domain);
 4643: 
 4644:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4645:     my $mono                 = 'monospace';
 4646:     my $data_table_head      = $tabbg;
 4647:     my $data_table_light     = '#FAFAFA';
 4648:     my $data_table_dark      = '#F0F0F0';
 4649:     my $data_table_darker    = '#CCCCCC';
 4650:     my $data_table_highlight = '#FFFF00';
 4651:     my $mail_new             = '#FFBB77';
 4652:     my $mail_new_hover       = '#DD9955';
 4653:     my $mail_read            = '#BBBB77';
 4654:     my $mail_read_hover      = '#999944';
 4655:     my $mail_replied         = '#AAAA88';
 4656:     my $mail_replied_hover   = '#888855';
 4657:     my $mail_other           = '#99BBBB';
 4658:     my $mail_other_hover     = '#669999';
 4659:     my $table_header         = '#DDDDDD';
 4660:     my $feedback_link_bg     = '#BBBBBB';
 4661:     my $lg_border_color      = '#C8C8C8';
 4662: 
 4663:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4664: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4665: 	                                                 : '0 3px 0 4px';
 4666: 
 4667: 
 4668:     return <<END;
 4669: h1, h2, h3, th { font-family: $sans }
 4670: a:focus { color: red; background: yellow } 
 4671: 
 4672: hr {
 4673:   clear: both;
 4674:   color: $tabbg;
 4675:   background-color: $tabbg;
 4676:   height: 3px;
 4677:   border: none;
 4678: }
 4679: 
 4680: table.thinborder,
 4681: 
 4682: table.thinborder tr th {
 4683:   border-style: solid;
 4684:   border-width: 1px;
 4685:   background: $tabbg;
 4686: }
 4687: table.thinborder tr td {
 4688:   border-style: solid;
 4689:   border-width: 1px
 4690: }
 4691: 
 4692: form, .inline { display: inline; }
 4693: .center { text-align: center; }
 4694: .LC_filename {font-family: $mono; white-space:pre;}
 4695: .LC_error {
 4696:   color: red;
 4697:   font-size: larger;
 4698: }
 4699: .LC_warning,
 4700: .LC_diff_removed {
 4701:   color: red;
 4702: }
 4703: 
 4704: .LC_info,
 4705: .LC_success,
 4706: .LC_diff_added {
 4707:   color: green;
 4708: }
 4709: 
 4710: div.LC_confirm_box {
 4711:   background-color: #FAFAFA;
 4712:   border: 1px solid $lg_border_color;
 4713:   margin-right: 0;
 4714:   padding: 5px;
 4715: }
 4716: 
 4717: div.LC_confirm_box .LC_error img,
 4718: div.LC_confirm_box .LC_success img {
 4719:   vertical-align: middle;
 4720: }
 4721: 
 4722: .LC_icon {
 4723:   border: none;
 4724: }
 4725: .LC_indexer_icon {
 4726:   border: 0;
 4727:   height: 22px;
 4728: }
 4729: .LC_docs_spacer {
 4730:   width: 25px;
 4731:   height: 1px;
 4732:   border: none;
 4733: }
 4734: 
 4735: .LC_internal_info {
 4736:   color: #999999;
 4737: }
 4738: 
 4739: table.LC_pastsubmission {
 4740:   border: 1px solid black;
 4741:   margin: 2px;
 4742: }
 4743: 
 4744: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4745:   width: 100%;
 4746:   background: $pgbg;
 4747:   border: 2px;
 4748:   border-collapse: separate;
 4749:   padding: 0;
 4750: }
 4751: 
 4752: table#LC_title_bar, table.LC_breadcrumbs, 
 4753: table#LC_title_bar.LC_with_remote {
 4754:   width: 100%;
 4755:   border-color: $pgbg;
 4756:   border-style: solid;
 4757:   border-width: $border;
 4758: 
 4759:   background: $pgbg;
 4760:   font-family: $sans;
 4761:   border-collapse: collapse;
 4762:   padding: 0;
 4763: }
 4764: 
 4765: table.LC_docs_path {
 4766:   width: 100%;
 4767:   border: 0;
 4768:   background: $pgbg;
 4769:   font-family: $sans;
 4770:   border-collapse: collapse;
 4771:   padding: 0;
 4772: }
 4773: 
 4774: table#LC_title_bar td {
 4775:   background: $tabbg;
 4776: }
 4777: table#LC_title_bar td.LC_title_bar_who {
 4778:   background: $tabbg;
 4779:   color: $font;
 4780:   font: small $sans;
 4781:   text-align: right;
 4782: }
 4783: span.LC_metadata {
 4784:     font-family: $sans;
 4785: }
 4786: span.LC_title_bar_title {
 4787:   font: bold x-large $sans;
 4788: }
 4789: table#LC_title_bar td.LC_title_bar_domain_logo {
 4790:   background: $sidebg;
 4791:   text-align: right;
 4792:   padding: 0;
 4793: }
 4794: table#LC_title_bar td.LC_title_bar_role_logo {
 4795:   background: $sidebg;
 4796:   padding: 0;
 4797: }
 4798: 
 4799: table#LC_menubuttons_mainmenu {
 4800:   width: 100%;
 4801:   border: 0;
 4802:   border-spacing: 1px;
 4803:   padding: 0 1px;
 4804:   margin: 0;
 4805:   border-collapse: separate;
 4806: }
 4807: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4808:   border: none;
 4809: }
 4810: table#LC_top_nav td {
 4811:   background: $tabbg;
 4812:   border: none;
 4813:   font-size: small;
 4814: }
 4815: table#LC_top_nav td a, div#LC_top_nav a {
 4816:   color: $font;
 4817:   font-family: $sans;
 4818: }
 4819: table#LC_top_nav td.LC_top_nav_logo {
 4820:   background: $tabbg;
 4821:   text-align: left;
 4822:   white-space: nowrap;
 4823:   width: 31px;
 4824: }
 4825: table#LC_top_nav td.LC_top_nav_logo img {
 4826:   border: none;
 4827:   vertical-align: bottom;
 4828: }
 4829: table#LC_top_nav td.LC_top_nav_exit,
 4830: table#LC_top_nav td.LC_top_nav_help {
 4831:   width: 2.0em;
 4832: }
 4833: table#LC_top_nav td.LC_top_nav_login {
 4834:   width: 4.0em;
 4835:   text-align: center;
 4836: }
 4837: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4838:   background: $tabbg;
 4839:   color: $font;
 4840:   font-family: $sans;
 4841:   font-size: smaller;
 4842: }
 4843: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4844: table.LC_docs_path td.LC_docs_path_component {
 4845:   background: $tabbg;
 4846:   color: $font;
 4847:   font-family: $sans;
 4848:   font-size: larger;
 4849:   text-align: right;
 4850: }
 4851: td.LC_table_cell_checkbox {
 4852:   text-align: center;
 4853: }
 4854: table#LC_mainmenu td.LC_mainmenu_column {
 4855:     vertical-align: top;
 4856: }
 4857: 
 4858: .LC_menubuttons_inline_text {
 4859:   color: $font;
 4860:   font-family: $sans;
 4861:   font-size: smaller;
 4862: }
 4863: 
 4864: .LC_menubuttons_link {
 4865:   text-decoration: none;
 4866: }
 4867: /*2008--9-5: new menu style sheet.Changed category*/
 4868: .LC_menubuttons_category {
 4869:   color: $font;
 4870:   background: $pgbg;
 4871:   font-family: $sans;
 4872:   font-size: larger;
 4873:   font-weight: bold;
 4874: }
 4875: 
 4876: td.LC_menubuttons_text {
 4877:   width: 90%;
 4878:   color: $font;
 4879:   font-family: $sans;
 4880: }
 4881: 
 4882: td.LC_menubuttons_img {
 4883: }
 4884: 
 4885: .LC_current_location {
 4886:   font-family: $sans;
 4887:   background: $tabbg;
 4888: }
 4889: .LC_new_mail {
 4890:   font-family: $sans;
 4891:   background: $tabbg;
 4892:   font-weight: bold;
 4893: }
 4894: 
 4895: .LC_dropadd_labeltext {
 4896:   font-family: $sans;
 4897:   text-align: right;
 4898: }
 4899: 
 4900: .LC_preferences_labeltext {
 4901:   font-family: $sans;
 4902:   text-align: right;
 4903: }
 4904: 
 4905: .LC_roleslog_note {
 4906:   font-size: smaller;
 4907: }
 4908: 
 4909: .LC_mail_functions {
 4910:     font-weight: bold;
 4911: }
 4912: 
 4913: table.LC_aboutme_port {
 4914:   border: none;
 4915:   border-collapse: collapse;
 4916:   border-spacing: 0;
 4917: }
 4918: table.LC_data_table, table.LC_mail_list {
 4919:   border: 1px solid #000000;
 4920:   border-collapse: separate;
 4921:   border-spacing: 1px;
 4922:   background: $pgbg;
 4923: }
 4924: .LC_data_table_dense {
 4925:   font-size: small;
 4926: }
 4927: table.LC_nested_outer {
 4928:   border: 1px solid #000000;
 4929:   border-collapse: collapse;
 4930:   border-spacing: 0;
 4931:   width: 100%;
 4932: }
 4933: table.LC_innerpickbox,
 4934: table.LC_nested {
 4935:   border: none;
 4936:   border-collapse: collapse;
 4937:   border-spacing: 0;
 4938:   width: 100%;
 4939: }
 4940: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4941: table.LC_prior_tries tr th,
 4942: table.LC_innerpickbox tr th {
 4943:   font-weight: bold;
 4944:   background-color: $data_table_head;
 4945:   font-size: smaller;
 4946: }
 4947: table.LC_innerpickbox tr th,
 4948: table.LC_innerpickbox tr td {
 4949:   vertical-align: top;
 4950: }
 4951: table.LC_data_table tr.LC_info_row > td {
 4952:   background-color: #CCCCCC;
 4953:   font-weight: bold;
 4954:   text-align: left;
 4955: }
 4956: table.LC_data_table tr.LC_odd_row > td, 
 4957: table.LC_pick_box tr > td.LC_odd_row,
 4958: table.LC_aboutme_port tr td {
 4959:   background-color: $data_table_light;
 4960:   padding: 2px;
 4961: }
 4962: table.LC_data_table tr.LC_even_row > td,
 4963: table.LC_pick_box tr > td.LC_even_row,
 4964: table.LC_aboutme_port tr.LC_even_row td {
 4965:   background-color: $data_table_dark;
 4966:   padding: 2px;
 4967: }
 4968: table.LC_data_table tr.LC_data_table_highlight td {
 4969:   background-color: $data_table_darker;
 4970: }
 4971: table.LC_data_table tr td.LC_leftcol_header {
 4972:   background-color: $data_table_head;
 4973:   font-weight: bold;
 4974: }
 4975: table.LC_data_table tr.LC_empty_row td,
 4976: table.LC_nested tr.LC_empty_row td {
 4977:   background-color: #FFFFFF;
 4978:   font-weight: bold;
 4979:   font-style: italic;
 4980:   text-align: center;
 4981:   padding: 8px;
 4982: }
 4983: table.LC_nested tr.LC_empty_row td {
 4984:   padding: 4ex
 4985: }
 4986: table.LC_nested_outer tr th {
 4987:   font-weight: bold;
 4988:   background-color: $data_table_head;
 4989:   font-size: smaller;
 4990:   border-bottom: 1px solid #000000;
 4991: }
 4992: table.LC_nested_outer tr td.LC_subheader {
 4993:   background-color: $data_table_head;
 4994:   font-weight: bold;
 4995:   font-size: small;
 4996:   border-bottom: 1px solid #000000;
 4997:   text-align: right;
 4998: }
 4999: table.LC_nested tr.LC_info_row td {
 5000:   background-color: #CCCCCC;
 5001:   font-weight: bold;
 5002:   font-size: small;
 5003:   text-align: center;
 5004: }
 5005: table.LC_nested tr.LC_info_row td.LC_left_item,
 5006: table.LC_nested_outer tr th.LC_left_item {
 5007:   text-align: left;
 5008: }
 5009: table.LC_nested td {
 5010:   background-color: #FFFFFF;
 5011:   font-size: small;
 5012: }
 5013: table.LC_nested_outer tr th.LC_right_item,
 5014: table.LC_nested tr.LC_info_row td.LC_right_item,
 5015: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5016: table.LC_nested tr td.LC_right_item {
 5017:   text-align: right;
 5018: }
 5019: 
 5020: table.LC_nested tr.LC_odd_row td {
 5021:   background-color: #EEEEEE;
 5022: }
 5023: 
 5024: table.LC_createuser {
 5025: }
 5026: 
 5027: table.LC_createuser tr.LC_section_row td {
 5028:   font-size: smaller;
 5029: }
 5030: 
 5031: table.LC_createuser tr.LC_info_row td  {
 5032:   background-color: #CCCCCC;
 5033:   font-weight: bold;
 5034:   text-align: center;
 5035: }
 5036: 
 5037: table.LC_calendar {
 5038:   border: 1px solid #000000;
 5039:   border-collapse: collapse;
 5040: }
 5041: table.LC_calendar_pickdate {
 5042:   font-size: xx-small;
 5043: }
 5044: table.LC_calendar tr td {
 5045:   border: 1px solid #000000;
 5046:   vertical-align: top;
 5047: }
 5048: table.LC_calendar tr td.LC_calendar_day_empty {
 5049:   background-color: $data_table_dark;
 5050: }
 5051: table.LC_calendar tr td.LC_calendar_day_current {
 5052:   background-color: $data_table_highlight;
 5053: }
 5054: 
 5055: table.LC_mail_list tr.LC_mail_new {
 5056:   background-color: $mail_new;
 5057: }
 5058: table.LC_mail_list tr.LC_mail_new:hover {
 5059:   background-color: $mail_new_hover;
 5060: }
 5061: table.LC_mail_list tr.LC_mail_read {
 5062:   background-color: $mail_read;
 5063: }
 5064: table.LC_mail_list tr.LC_mail_read:hover {
 5065:   background-color: $mail_read_hover;
 5066: }
 5067: table.LC_mail_list tr.LC_mail_replied {
 5068:   background-color: $mail_replied;
 5069: }
 5070: table.LC_mail_list tr.LC_mail_replied:hover {
 5071:   background-color: $mail_replied_hover;
 5072: }
 5073: table.LC_mail_list tr.LC_mail_other {
 5074:   background-color: $mail_other;
 5075: }
 5076: table.LC_mail_list tr.LC_mail_other:hover {
 5077:   background-color: $mail_other_hover;
 5078: }
 5079: table.LC_mail_list tr.LC_mail_even {
 5080: }
 5081: table.LC_mail_list tr.LC_mail_odd {
 5082: }
 5083: 
 5084: 
 5085: table#LC_portfolio_actions {
 5086:   width: auto;
 5087:   background: $pgbg;
 5088:   border: none;
 5089:   border-spacing: 2px 2px;
 5090:   padding: 0;
 5091:   margin: 0;
 5092:   border-collapse: separate;
 5093: }
 5094: table#LC_portfolio_actions td.LC_label {
 5095:   background: $tabbg;
 5096:   text-align: right;
 5097: }
 5098: table#LC_portfolio_actions td.LC_value {
 5099:   background: $tabbg;
 5100: }
 5101: 
 5102: table#LC_cstr_controls {
 5103:   width: 100%;
 5104:   border-collapse: collapse;
 5105: }
 5106: table#LC_cstr_controls tr td {
 5107:   border: 4px solid $pgbg;
 5108:   padding: 4px;
 5109:   text-align: center;
 5110:   background: $tabbg;
 5111: }
 5112: table#LC_cstr_controls tr th {
 5113:   border: 4px solid $pgbg;
 5114:   background: $table_header;
 5115:   text-align: center;
 5116:   font-family: $sans;
 5117:   font-size: smaller;
 5118: }
 5119: 
 5120: table#LC_browser {
 5121:  
 5122: }
 5123: table#LC_browser tr th {
 5124:   background: $table_header;
 5125: }
 5126: table#LC_browser tr td {
 5127:   padding: 2px;
 5128: }
 5129: table#LC_browser tr.LC_browser_file,
 5130: table#LC_browser tr.LC_browser_file_published {
 5131:   background: #CCFF88;
 5132: }
 5133: table#LC_browser tr.LC_browser_file_locked,
 5134: table#LC_browser tr.LC_browser_file_unpublished {
 5135:   background: #FFAA99;
 5136: }
 5137: table#LC_browser tr.LC_browser_file_obsolete {
 5138:   background: #AAAAAA;
 5139: }
 5140: table#LC_browser tr.LC_browser_file_modified,
 5141: table#LC_browser tr.LC_browser_file_metamodified {
 5142:   background: #FFFF77;
 5143: }
 5144: table#LC_browser tr.LC_browser_folder {
 5145:   background: #CCCCFF;
 5146: }
 5147: 
 5148: table.LC_data_table tr > td.LC_roles_is {
 5149: /*  background: #77FF77; */
 5150: }
 5151: table.LC_data_table tr > td.LC_roles_future {
 5152:   background: #FFFF77;
 5153: }
 5154: table.LC_data_table tr > td.LC_roles_will {
 5155:   background: #FFAA77;
 5156: }
 5157: table.LC_data_table tr > td.LC_roles_expired {
 5158:   background: #FF7777;
 5159: }
 5160: table.LC_data_table tr > td.LC_roles_will_not {
 5161:   background: #AAFF77;
 5162: }
 5163: table.LC_data_table tr > td.LC_roles_selected {
 5164:   background: #11CC55;
 5165: }
 5166: 
 5167: span.LC_current_location {
 5168:   font-size: x-large;
 5169:   background: $pgbg;
 5170: }
 5171: 
 5172: span.LC_parm_menu_item {
 5173:   font-size: larger;
 5174:   font-family: $sans;
 5175: }
 5176: span.LC_parm_scope_all {
 5177:   color: red;
 5178: }
 5179: span.LC_parm_scope_folder {
 5180:   color: green;
 5181: }
 5182: span.LC_parm_scope_resource {
 5183:   color: orange;
 5184: }
 5185: span.LC_parm_part {
 5186:   color: blue;
 5187: }
 5188: span.LC_parm_folder, span.LC_parm_symb {
 5189:   font-size: x-small;
 5190:   font-family: $mono;
 5191:   color: #AAAAAA;
 5192: }
 5193: 
 5194: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 5195: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 5196:   border: 1px solid black;
 5197:   border-collapse: collapse;
 5198: }
 5199: table.LC_parm_overview_restrictions td {
 5200:   border-width: 1px 4px 1px 4px;
 5201:   border-style: solid;
 5202:   border-color: $pgbg;
 5203:   text-align: center;
 5204: }
 5205: table.LC_parm_overview_restrictions th {
 5206:   background: $tabbg;
 5207:   border-width: 1px 4px 1px 4px;
 5208:   border-style: solid;
 5209:   border-color: $pgbg;
 5210: }
 5211: table#LC_helpmenu {
 5212:   border: none;
 5213:   height: 55px;
 5214:   border-spacing: 0;
 5215: }
 5216: 
 5217: table#LC_helpmenu fieldset legend {
 5218:   font-size: larger;
 5219:   font-weight: bold;
 5220: }
 5221: table#LC_helpmenu_links {
 5222:   width: 100%;
 5223:   border: 1px solid black;
 5224:   background: $pgbg;
 5225:   padding: 0;
 5226:   border-spacing: 1px;
 5227: }
 5228: table#LC_helpmenu_links tr td {
 5229:   padding: 1px;
 5230:   background: $tabbg;
 5231:   text-align: center;
 5232:   font-weight: bold;
 5233: }
 5234: 
 5235: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5236: table#LC_helpmenu_links a:active {
 5237:   text-decoration: none;
 5238:   color: $font;
 5239: }
 5240: table#LC_helpmenu_links a:hover {
 5241:   text-decoration: underline;
 5242:   color: $vlink;
 5243: }
 5244: 
 5245: .LC_chrt_popup_exists {
 5246:   border: 1px solid #339933;
 5247:   margin: -1px;
 5248: }
 5249: .LC_chrt_popup_up {
 5250:   border: 1px solid yellow;
 5251:   margin: -1px;
 5252: }
 5253: .LC_chrt_popup {
 5254:   border: 1px solid #8888FF;
 5255:   background: #CCCCFF;
 5256: }
 5257: table.LC_pick_box {
 5258:   border-collapse: separate;
 5259:   background: white;
 5260:   border: 1px solid black;
 5261:   border-spacing: 1px;
 5262: }
 5263: table.LC_pick_box td.LC_pick_box_title {
 5264:   background: $tabbg;
 5265:   font-weight: bold;
 5266:   text-align: right;
 5267:   vertical-align: top;
 5268:   width: 184px;
 5269:   padding: 8px;
 5270: }
 5271: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5272:   background: $tabbg;
 5273:   font-weight: bold;
 5274:   text-align: right;
 5275:   width: 350px;
 5276:   padding: 8px;
 5277: }
 5278: 
 5279: table.LC_pick_box td.LC_pick_box_value {
 5280:   text-align: left;
 5281:   padding: 8px;
 5282: }
 5283: table.LC_pick_box td.LC_pick_box_select {
 5284:   text-align: left;
 5285:   padding: 8px;
 5286: }
 5287: table.LC_pick_box td.LC_pick_box_separator {
 5288:   padding: 0;
 5289:   height: 1px;
 5290:   background: black;
 5291: }
 5292: table.LC_pick_box td.LC_pick_box_submit {
 5293:   text-align: right;
 5294: }
 5295: table.LC_pick_box td.LC_evenrow_value {
 5296:   text-align: left;
 5297:   padding: 8px;
 5298:   background-color: $data_table_light;
 5299: }
 5300: table.LC_pick_box td.LC_oddrow_value {
 5301:   text-align: left;
 5302:   padding: 8px;
 5303:   background-color: $data_table_light;
 5304: }
 5305: table.LC_helpform_receipt {
 5306:   width: 620px;
 5307:   border-collapse: separate;
 5308:   background: white;
 5309:   border: 1px solid black;
 5310:   border-spacing: 1px;
 5311: }
 5312: table.LC_helpform_receipt td.LC_pick_box_title {
 5313:   background: $tabbg;
 5314:   font-weight: bold;
 5315:   text-align: right;
 5316:   width: 184px;
 5317:   padding: 8px;
 5318: }
 5319: table.LC_helpform_receipt td.LC_evenrow_value {
 5320:   text-align: left;
 5321:   padding: 8px;
 5322:   background-color: $data_table_light;
 5323: }
 5324: table.LC_helpform_receipt td.LC_oddrow_value {
 5325:   text-align: left;
 5326:   padding: 8px;
 5327:   background-color: $data_table_light;
 5328: }
 5329: table.LC_helpform_receipt td.LC_pick_box_separator {
 5330:   padding: 0;
 5331:   height: 1px;
 5332:   background: black;
 5333: }
 5334: span.LC_helpform_receipt_cat {
 5335:   font-weight: bold;
 5336: }
 5337: table.LC_group_priv_box {
 5338:   background: white;
 5339:   border: 1px solid black;
 5340:   border-spacing: 1px;
 5341: }
 5342: table.LC_group_priv_box td.LC_pick_box_title {
 5343:   background: $tabbg;
 5344:   font-weight: bold;
 5345:   text-align: right;
 5346:   width: 184px;
 5347: }
 5348: table.LC_group_priv_box td.LC_groups_fixed {
 5349:   background: $data_table_light;
 5350:   text-align: center;
 5351: }
 5352: table.LC_group_priv_box td.LC_groups_optional {
 5353:   background: $data_table_dark;
 5354:   text-align: center;
 5355: }
 5356: table.LC_group_priv_box td.LC_groups_functionality {
 5357:   background: $data_table_darker;
 5358:   text-align: center;
 5359:   font-weight: bold;
 5360: }
 5361: table.LC_group_priv td {
 5362:   text-align: left;
 5363:   padding: 0;
 5364: }
 5365: 
 5366: table.LC_notify_front_page {
 5367:   background: white;
 5368:   border: 1px solid black;
 5369:   padding: 8px;
 5370: }
 5371: table.LC_notify_front_page td {
 5372:   padding: 8px;
 5373: }
 5374: .LC_navbuttons {
 5375:   margin: 2ex 0ex 2ex 0ex;
 5376: }
 5377: .LC_topic_bar {
 5378:   font-family: $sans;
 5379:   font-weight: bold;
 5380:   width: 100%;
 5381:   background: $tabbg;
 5382:   vertical-align: middle;
 5383:   margin: 2ex 0ex 2ex 0ex;
 5384:   padding: 3px;
 5385: }
 5386: .LC_topic_bar span {
 5387:   vertical-align: middle;
 5388: }
 5389: .LC_topic_bar img {
 5390:   vertical-align: bottom;
 5391: }
 5392: table.LC_course_group_status {
 5393:   margin: 20px;
 5394: }
 5395: table.LC_status_selector td {
 5396:   vertical-align: top;
 5397:   text-align: center;
 5398:   padding: 4px;
 5399: }
 5400: table.LC_descriptive_input td.LC_description {
 5401:   vertical-align: top;
 5402:   text-align: right;
 5403:   font-weight: bold;
 5404: }
 5405: div.LC_feedback_link {
 5406:   clear: both;
 5407:   background: white;
 5408:   width: 100%;  
 5409: }
 5410: span.LC_feedback_link {
 5411:   background: $feedback_link_bg;
 5412:   font-size: larger;
 5413: }
 5414: span.LC_message_link {
 5415:   background: $feedback_link_bg;
 5416:   font-size: larger;
 5417:   position: absolute;
 5418:   right: 1em;
 5419: }
 5420: 
 5421: table.LC_prior_tries {
 5422:   border: 1px solid #000000;
 5423:   border-collapse: separate;
 5424:   border-spacing: 1px;
 5425: }
 5426: 
 5427: table.LC_prior_tries td {
 5428:   padding: 2px;
 5429: }
 5430: 
 5431: .LC_answer_correct {
 5432:   background: #AAFFAA;
 5433:   color: black;
 5434: }
 5435: .LC_answer_charged_try {
 5436:   background: #FFAAAA ! important;
 5437:   color: black;
 5438: }
 5439: .LC_answer_not_charged_try, 
 5440: .LC_answer_no_grade,
 5441: .LC_answer_late {
 5442:   background: #FFFFAA;
 5443:   color: black;
 5444: }
 5445: .LC_answer_previous {
 5446:   background: #AAAAFF;
 5447:   color: black;
 5448: }
 5449: .LC_answer_no_message {
 5450:   background: #FFFFFF;
 5451:   color: black;
 5452: }
 5453: .LC_answer_unknown {
 5454:   background: orange;
 5455:   color: black;
 5456: }
 5457: 
 5458: 
 5459: span.LC_prior_numerical,
 5460: span.LC_prior_string,
 5461: span.LC_prior_custom,
 5462: span.LC_prior_reaction,
 5463: span.LC_prior_math {
 5464:   font-family: monospace;
 5465:   white-space: pre;
 5466: }
 5467: 
 5468: span.LC_prior_string {
 5469:   font-family: monospace;
 5470:   white-space: pre;
 5471: }
 5472: 
 5473: table.LC_prior_option {
 5474:   width: 100%;
 5475:   border-collapse: collapse;
 5476: }
 5477: table.LC_prior_rank, table.LC_prior_match {
 5478:   border-collapse: collapse;
 5479: }
 5480: table.LC_prior_option tr td,
 5481: table.LC_prior_rank tr td,
 5482: table.LC_prior_match tr td {
 5483:   border: 1px solid #000000;
 5484: }
 5485: 
 5486: span.LC_nobreak {
 5487:   white-space: nowrap;
 5488: }
 5489: 
 5490: span.LC_cusr_emph {
 5491:   font-style: italic;
 5492: }
 5493: 
 5494: span.LC_cusr_subheading {
 5495:   font-weight: normal;
 5496:   font-size: 85%;
 5497: }
 5498: 
 5499: table.LC_docs_documents {
 5500:   background: #BBBBBB;
 5501:   border-width: 0;
 5502:   border-collapse: collapse;
 5503: }
 5504: 
 5505: table.LC_docs_documents td.LC_docs_document {
 5506:   border: 2px solid black;
 5507:   padding: 4px;
 5508: }
 5509: 
 5510: .LC_docs_course_commands div {
 5511:   float: left;
 5512:   border: 4px solid #AAAAAA;
 5513:   padding: 4px;
 5514:   background: #DDDDCC;
 5515: }
 5516: 
 5517: .LC_docs_entry_move {
 5518:   border: none;
 5519:   border-collapse: collapse;
 5520: }
 5521: 
 5522: .LC_docs_entry_move td {
 5523:   border: 2px solid #BBBBBB;
 5524:   background: #DDDDDD;
 5525: }
 5526: 
 5527: .LC_docs_editor td.LC_docs_entry_commands {
 5528:   background: #DDDDDD;
 5529:   font-size: x-small;
 5530: }
 5531: .LC_docs_copy {
 5532:   color: #000099;
 5533: }
 5534: .LC_docs_cut {
 5535:   color: #550044;
 5536: }
 5537: .LC_docs_rename {
 5538:   color: #009900;
 5539: }
 5540: .LC_docs_remove {
 5541:   color: #990000;
 5542: }
 5543: 
 5544: .LC_docs_reinit_warn,
 5545: .LC_docs_ext_edit {
 5546:   font-size: x-small;
 5547: }
 5548: 
 5549: .LC_docs_editor td.LC_docs_entry_title,
 5550: .LC_docs_editor td.LC_docs_entry_icon {
 5551:   background: #FFFFBB;
 5552: }
 5553: .LC_docs_editor td.LC_docs_entry_parameter {
 5554:   background: #BBBBFF;
 5555:   font-size: x-small;
 5556:   white-space: nowrap;
 5557: }
 5558: 
 5559: table.LC_docs_adddocs td,
 5560: table.LC_docs_adddocs th {
 5561:   border: 1px solid #BBBBBB;
 5562:   padding: 4px;
 5563:   background: #DDDDDD;
 5564: }
 5565: 
 5566: table.LC_sty_begin {
 5567:   background: #BBFFBB;
 5568: }
 5569: table.LC_sty_end {
 5570:   background: #FFBBBB;
 5571: }
 5572: 
 5573: table.LC_double_column {
 5574:   border-width: 0;
 5575:   border-collapse: collapse;
 5576:   width: 100%;
 5577:   padding: 2px;
 5578: }
 5579: 
 5580: table.LC_double_column tr td.LC_left_col {
 5581:   top: 2px;
 5582:   left: 2px;
 5583:   width: 47%;
 5584:   vertical-align: top;
 5585: }
 5586: 
 5587: table.LC_double_column tr td.LC_right_col {
 5588:   top: 2px;
 5589:   right: 2px; 
 5590:   width: 47%;
 5591:   vertical-align: top;
 5592: }
 5593: 
 5594: span.LC_role_level {
 5595:   font-weight: bold;
 5596: }
 5597: 
 5598: div.LC_left_float {
 5599:   float: left;
 5600:   padding-right: 5%;
 5601:   padding-bottom: 4px;
 5602: }
 5603: 
 5604: div.LC_clear_float_header {
 5605:   padding-bottom: 2px;
 5606: }
 5607: 
 5608: div.LC_clear_float_footer {
 5609:   padding-top: 10px;
 5610:   clear: both;
 5611: }
 5612: 
 5613: 
 5614: div.LC_grade_select_mode {
 5615:   font-family: $sans;
 5616: }
 5617: div.LC_grade_select_mode div div {
 5618:   margin: 5px;
 5619: }
 5620: div.LC_grade_select_mode_selector {
 5621:   margin: 5px;
 5622:   float: left;
 5623: }
 5624: div.LC_grade_select_mode_selector_header {
 5625:   font: bold medium $sans;
 5626: }
 5627: div.LC_grade_select_mode_type {
 5628:   clear: left;
 5629: }
 5630: 
 5631: div.LC_grade_show_user {
 5632:   margin-top: 20px;
 5633:   border: 1px solid black;
 5634: }
 5635: div.LC_grade_user_name {
 5636:   background: #DDDDEE;
 5637:   border-bottom: 1px solid black;
 5638:   font: bold large $sans;
 5639: }
 5640: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5641:   background: #DDEEDD;
 5642: }
 5643: 
 5644: div.LC_grade_show_problem,
 5645: div.LC_grade_submissions,
 5646: div.LC_grade_message_center,
 5647: div.LC_grade_info_links,
 5648: div.LC_grade_assign {
 5649:   margin: 5px;
 5650:   width: 99%;
 5651:   background: #FFFFFF;
 5652: }
 5653: div.LC_grade_show_problem_header,
 5654: div.LC_grade_submissions_header,
 5655: div.LC_grade_message_center_header,
 5656: div.LC_grade_assign_header {
 5657:   font: bold large $sans;
 5658: }
 5659: div.LC_grade_show_problem_problem,
 5660: div.LC_grade_submissions_body,
 5661: div.LC_grade_message_center_body,
 5662: div.LC_grade_assign_body {
 5663:   border: 1px solid black;
 5664:   width: 99%;
 5665:   background: #FFFFFF;
 5666: }
 5667: span.LC_grade_check_note {
 5668:   font: normal medium $sans;
 5669:   display: inline;
 5670:   position: absolute;
 5671:   right: 1em;
 5672: }
 5673: 
 5674: table.LC_scantron_action {
 5675:   width: 100%;
 5676: }
 5677: table.LC_scantron_action tr th {
 5678:   font: normal bold $sans;
 5679: }
 5680: 
 5681: div.LC_edit_problem_header, 
 5682: div.LC_edit_problem_footer {
 5683:   font: normal medium $sans;
 5684:   margin: 2px;
 5685: }
 5686: div.LC_edit_problem_header,
 5687: div.LC_edit_problem_header div,
 5688: div.LC_edit_problem_footer,
 5689: div.LC_edit_problem_footer div,
 5690: div.LC_edit_problem_editxml_header,
 5691: div.LC_edit_problem_editxml_header div {
 5692:   margin-top: 5px;
 5693: }
 5694: div.LC_edit_problem_header_edit_row {
 5695:   background: $tabbg;
 5696:   padding: 3px;
 5697:   margin-bottom: 5px;
 5698: }
 5699: div.LC_edit_problem_header_title {
 5700:   font: larger bold $sans;
 5701:   background: $tabbg;
 5702:   padding: 3px;
 5703: }
 5704: table.LC_edit_problem_header_title {
 5705:   font: larger bold $sans;
 5706:   width: 100%;
 5707:   border-color: $pgbg;
 5708:   border-style: solid;
 5709:   border-width: $border;
 5710: 
 5711:   background: $tabbg;
 5712:   border-collapse: collapse;
 5713:   padding: 0;
 5714: }
 5715: 
 5716: div.LC_edit_problem_discards {
 5717:   float: left;
 5718:   padding-bottom: 5px;
 5719: }
 5720: div.LC_edit_problem_saves {
 5721:   float: right;
 5722:   padding-bottom: 5px;
 5723: }
 5724: hr.LC_edit_problem_divide {
 5725:   clear: both;
 5726:   color: $tabbg;
 5727:   background-color: $tabbg;
 5728:   height: 3px;
 5729:   border: none;
 5730: }
 5731: img.stift{
 5732:   border-width:0;
 5733:   vertical-align:middle;
 5734: }
 5735: 
 5736: table#LC_mainmenu{
 5737:  margin-top:10px;
 5738:  width:80%;
 5739: 
 5740: }
 5741: 
 5742: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5743:   vertical-align: top;
 5744:   width: 45%;
 5745: }
 5746: .LC_mainmenu_fieldset_category {
 5747:   color: $font;
 5748:   background: $pgbg;
 5749:   font-family: $sans;
 5750:   font-size: small;
 5751:   font-weight: bold;
 5752: }
 5753: fieldset#LC_mainmenu_fieldset {
 5754:   margin:0 10px 10px 0;
 5755: 
 5756: }
 5757: 
 5758: div.LC_createcourse {
 5759:     margin: 10px 10px 10px 10px;
 5760: }
 5761: 
 5762: END
 5763: }
 5764: 
 5765: =pod
 5766: 
 5767: =item * &headtag()
 5768: 
 5769: Returns a uniform footer for LON-CAPA web pages.
 5770: 
 5771: Inputs: $title - optional title for the head
 5772:         $head_extra - optional extra HTML to put inside the <head>
 5773:         $args - optional arguments
 5774:             force_register - if is true call registerurl so the remote is 
 5775:                              informed
 5776:             redirect       -> array ref of
 5777:                                    1- seconds before redirect occurs
 5778:                                    2- url to redirect to
 5779:                                    3- whether the side effect should occur
 5780:                            (side effect of setting 
 5781:                                $env{'internal.head.redirect'} to the url 
 5782:                                redirected too)
 5783:             domain         -> force to color decorate a page for a specific
 5784:                                domain
 5785:             function       -> force usage of a specific rolish color scheme
 5786:             bgcolor        -> override the default page bgcolor
 5787:             no_auto_mt_title
 5788:                            -> prevent &mt()ing the title arg
 5789: 
 5790: =cut
 5791: 
 5792: sub headtag {
 5793:     my ($title,$head_extra,$args) = @_;
 5794:     
 5795:     my $function = $args->{'function'} || &get_users_function();
 5796:     my $domain   = $args->{'domain'}   || &determinedomain();
 5797:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5798:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5799: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5800: 		   #time(),
 5801: 		   $env{'environment.color.timestamp'},
 5802: 		   $function,$domain,$bgcolor);
 5803: 
 5804:     $url = '/adm/css/'.&escape($url).'.css';
 5805: 
 5806:     my $result =
 5807: 	'<head>'.
 5808: 	&font_settings();
 5809: 
 5810:     if (!$args->{'frameset'}) {
 5811: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5812:     }
 5813:     if ($args->{'force_register'}) {
 5814: 	$result .= &Apache::lonmenu::registerurl(1);
 5815:     }
 5816:     if (!$args->{'no_nav_bar'} 
 5817: 	&& !$args->{'only_body'}
 5818: 	&& !$args->{'frameset'}) {
 5819: 	$result .= &help_menu_js();
 5820:     }
 5821: 
 5822:     if (ref($args->{'redirect'})) {
 5823: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5824: 	$url = &Apache::lonenc::check_encrypt($url);
 5825: 	if (!$inhibit_continue) {
 5826: 	    $env{'internal.head.redirect'} = $url;
 5827: 	}
 5828: 	$result.=<<ADDMETA
 5829: <meta http-equiv="pragma" content="no-cache" />
 5830: <meta http-equiv="Refresh" content="$time; url=$url" />
 5831: ADDMETA
 5832:     }
 5833:     if (!defined($title)) {
 5834: 	$title = 'The LearningOnline Network with CAPA';
 5835:     }
 5836:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5837:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5838: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5839: 	.$head_extra;
 5840:     return $result;
 5841: }
 5842: 
 5843: =pod
 5844: 
 5845: =item * &font_settings()
 5846: 
 5847: Returns neccessary <meta> to set the proper encoding
 5848: 
 5849: Inputs: none
 5850: 
 5851: =cut
 5852: 
 5853: sub font_settings {
 5854:     my $headerstring='';
 5855:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5856: 	$headerstring.=
 5857: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5858:     }
 5859:     return $headerstring;
 5860: }
 5861: 
 5862: =pod
 5863: 
 5864: =item * &xml_begin()
 5865: 
 5866: Returns the needed doctype and <html>
 5867: 
 5868: Inputs: none
 5869: 
 5870: =cut
 5871: 
 5872: sub xml_begin {
 5873:     my $output='';
 5874: 
 5875:     if ($env{'internal.start_page'}==1) {
 5876: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5877:     }
 5878: 
 5879:     if ($env{'browser.mathml'}) {
 5880: 	$output='<?xml version="1.0"?>'
 5881:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5882: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5883:             
 5884: #	    .'<!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">] >'
 5885: 	    .'<!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">'
 5886:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5887: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5888:     } else {
 5889: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
 5890:             '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 5891:     }
 5892:     return $output;
 5893: }
 5894: 
 5895: =pod
 5896: 
 5897: =item * &endheadtag()
 5898: 
 5899: Returns a uniform </head> for LON-CAPA web pages.
 5900: 
 5901: Inputs: none
 5902: 
 5903: =cut
 5904: 
 5905: sub endheadtag {
 5906:     return '</head>';
 5907: }
 5908: 
 5909: =pod
 5910: 
 5911: =item * &head()
 5912: 
 5913: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5914: 
 5915: Inputs:
 5916: 
 5917: =over 4
 5918: 
 5919: $title - optional title for the page
 5920: 
 5921: $head_extra - optional extra HTML to put inside the <head>
 5922: 
 5923: =back
 5924: 
 5925: =cut
 5926: 
 5927: sub head {
 5928:     my ($title,$head_extra,$args) = @_;
 5929:     return &headtag($title,$head_extra,$args).&endheadtag();
 5930: }
 5931: 
 5932: =pod
 5933: 
 5934: =item * &start_page()
 5935: 
 5936: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5937: 
 5938: Inputs:
 5939: 
 5940: =over 4
 5941: 
 5942: $title - optional title for the page
 5943: 
 5944: $head_extra - optional extra HTML to incude inside the <head>
 5945: 
 5946: $args - additional optional args supported are:
 5947: 
 5948: =over 8
 5949: 
 5950:              only_body      -> is true will set &bodytag() onlybodytag
 5951:                                     arg on
 5952:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5953:              add_entries    -> additional attributes to add to the  <body>
 5954:              domain         -> force to color decorate a page for a 
 5955:                                     specific domain
 5956:              function       -> force usage of a specific rolish color
 5957:                                     scheme
 5958:              redirect       -> see &headtag()
 5959:              bgcolor        -> override the default page bg color
 5960:              js_ready       -> return a string ready for being used in 
 5961:                                     a javascript writeln
 5962:              html_encode    -> return a string ready for being used in 
 5963:                                     a html attribute
 5964:              force_register -> if is true will turn on the &bodytag()
 5965:                                     $forcereg arg
 5966:              body_title     -> alternate text to use instead of $title
 5967:                                     in the title box that appears, this text
 5968:                                     is not auto translated like the $title is
 5969:              frameset       -> if true will start with a <frameset>
 5970:                                     rather than <body>
 5971:              no_title       -> if true the title bar won't be shown
 5972:              skip_phases    -> hash ref of 
 5973:                                     head -> skip the <html><head> generation
 5974:                                     body -> skip all <body> generation
 5975:              no_inline_link -> if true and in remote mode, don't show the 
 5976:                                     'Switch To Inline Menu' link
 5977:              no_auto_mt_title -> prevent &mt()ing the title arg
 5978:              inherit_jsmath -> when creating popup window in a page,
 5979:                                     should it have jsmath forced on by the
 5980:                                     current page
 5981: 
 5982: =back
 5983: 
 5984: =back
 5985: 
 5986: =cut
 5987: 
 5988: sub start_page {
 5989:     my ($title,$head_extra,$args) = @_;
 5990:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5991:     my %head_args;
 5992:     foreach my $arg ('redirect','force_register','domain','function',
 5993: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5994: 		     'no_auto_mt_title') {
 5995: 	if (defined($args->{$arg})) {
 5996: 	    $head_args{$arg} = $args->{$arg};
 5997: 	}
 5998:     }
 5999: 
 6000:     $env{'internal.start_page'}++;
 6001:     my $result;
 6002:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6003: 	$result.=
 6004: 	    &xml_begin().
 6005: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6006:     }
 6007:     
 6008:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6009: 	if ($args->{'frameset'}) {
 6010: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6011: 						$args->{'add_entries'});
 6012: 	    $result .= "\n<frameset $attr_string>\n";
 6013: 	} else {
 6014: 	    $result .=
 6015: 		&bodytag($title, 
 6016: 			 $args->{'function'},       $args->{'add_entries'},
 6017: 			 $args->{'only_body'},      $args->{'domain'},
 6018: 			 $args->{'force_register'}, $args->{'body_title'},
 6019: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6020: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6021: 			 $args);
 6022: 	}
 6023:     }
 6024: 
 6025:     if ($args->{'js_ready'}) {
 6026: 	$result = &js_ready($result);
 6027:     }
 6028:     if ($args->{'html_encode'}) {
 6029: 	$result = &html_encode($result);
 6030:     }
 6031:     #Breadcrumbs
 6032:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6033:         &Apache::lonhtmlcommon::clear_breadcrumbs();
 6034:         #if any br links exists, add them to the breadcrumbs
 6035:         if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6036:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6037:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6038:             }
 6039:         }
 6040: 
 6041:         #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6042:         if (exists($args->{'bread_crumbs_component'})){
 6043:             $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6044:         } else {
 6045:             $result .= &Apache::lonhtmlcommon::breadcrumbs();
 6046:         }
 6047:     }
 6048:     return $result;
 6049: }
 6050: 
 6051: =pod
 6052: 
 6053: =item * &head()
 6054: 
 6055: Returns a complete </body></html> section for LON-CAPA web pages.
 6056: 
 6057: Inputs:         $args - additional optional args supported are:
 6058:                  js_ready     -> return a string ready for being used in 
 6059:                                  a javascript writeln
 6060:                  html_encode  -> return a string ready for being used in 
 6061:                                  a html attribute
 6062:                  frameset     -> if true will start with a <frameset>
 6063:                                  rather than <body>
 6064:                  dicsussion   -> if true will get discussion from
 6065:                                   lonxml::xmlend
 6066:                                  (you can pass the target and parser arguments
 6067:                                   through optional 'target' and 'parser' args
 6068:                                   to this routine)
 6069: 
 6070: =cut
 6071: 
 6072: sub end_page {
 6073:     my ($args) = @_;
 6074:     $env{'internal.end_page'}++;
 6075:     my $result;
 6076:     if ($args->{'discussion'}) {
 6077: 	my ($target,$parser);
 6078: 	if (ref($args->{'discussion'})) {
 6079: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6080: 				$args->{'discussion'}{'parser'});
 6081: 	}
 6082: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6083:     }
 6084: 
 6085:     if ($args->{'frameset'}) {
 6086: 	$result .= '</frameset>';
 6087:     } else {
 6088: 	$result .= &endbodytag($args);
 6089:     }
 6090:     $result .= "\n</html>";
 6091: 
 6092:     if ($args->{'js_ready'}) {
 6093: 	$result = &js_ready($result);
 6094:     }
 6095: 
 6096:     if ($args->{'html_encode'}) {
 6097: 	$result = &html_encode($result);
 6098:     }
 6099: 
 6100:     return $result;
 6101: }
 6102: 
 6103: sub html_encode {
 6104:     my ($result) = @_;
 6105: 
 6106:     $result = &HTML::Entities::encode($result,'<>&"');
 6107:     
 6108:     return $result;
 6109: }
 6110: sub js_ready {
 6111:     my ($result) = @_;
 6112: 
 6113:     $result =~ s/[\n\r]/ /xmsg;
 6114:     $result =~ s/\\/\\\\/xmsg;
 6115:     $result =~ s/'/\\'/xmsg;
 6116:     $result =~ s{</}{<\\/}xmsg;
 6117:     
 6118:     return $result;
 6119: }
 6120: 
 6121: sub validate_page {
 6122:     if (  exists($env{'internal.start_page'})
 6123: 	  &&     $env{'internal.start_page'} > 1) {
 6124: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6125: 				 $env{'internal.start_page'}.' '.
 6126: 				 $ENV{'request.filename'});
 6127:     }
 6128:     if (  exists($env{'internal.end_page'})
 6129: 	  &&     $env{'internal.end_page'} > 1) {
 6130: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6131: 				 $env{'internal.end_page'}.' '.
 6132: 				 $env{'request.filename'});
 6133:     }
 6134:     if (     exists($env{'internal.start_page'})
 6135: 	&& ! exists($env{'internal.end_page'})) {
 6136: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6137: 				 $env{'request.filename'});
 6138:     }
 6139:     if (   ! exists($env{'internal.start_page'})
 6140: 	&&   exists($env{'internal.end_page'})) {
 6141: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6142: 				 $env{'request.filename'});
 6143:     }
 6144: }
 6145: 
 6146: sub simple_error_page {
 6147:     my ($r,$title,$msg) = @_;
 6148:     my $page =
 6149: 	&Apache::loncommon::start_page($title).
 6150: 	&mt($msg).
 6151: 	&Apache::loncommon::end_page();
 6152:     if (ref($r)) {
 6153: 	$r->print($page);
 6154: 	return;
 6155:     }
 6156:     return $page;
 6157: }
 6158: 
 6159: {
 6160:     my @row_count;
 6161:     sub start_data_table {
 6162: 	my ($add_class) = @_;
 6163: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6164: 	unshift(@row_count,0);
 6165: 	return '<table class="'.$css_class.'">'."\n";
 6166:     }
 6167: 
 6168:     sub end_data_table {
 6169: 	shift(@row_count);
 6170: 	return '</table>'."\n";;
 6171:     }
 6172: 
 6173:     sub start_data_table_row {
 6174: 	my ($add_class) = @_;
 6175: 	$row_count[0]++;
 6176: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6177: 	$css_class = (join(' ',$css_class,$add_class));
 6178: 	return  '<tr class="'.$css_class.'">'."\n";;
 6179:     }
 6180:     
 6181:     sub continue_data_table_row {
 6182: 	my ($add_class) = @_;
 6183: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6184: 	$css_class = (join(' ',$css_class,$add_class));
 6185: 	return  '<tr class="'.$css_class.'">'."\n";;
 6186:     }
 6187: 
 6188:     sub end_data_table_row {
 6189: 	return '</tr>'."\n";;
 6190:     }
 6191: 
 6192:     sub start_data_table_empty_row {
 6193: 	$row_count[0]++;
 6194: 	return  '<tr class="LC_empty_row" >'."\n";;
 6195:     }
 6196: 
 6197:     sub end_data_table_empty_row {
 6198: 	return '</tr>'."\n";;
 6199:     }
 6200: 
 6201:     sub start_data_table_header_row {
 6202: 	return  '<tr class="LC_header_row">'."\n";;
 6203:     }
 6204: 
 6205:     sub end_data_table_header_row {
 6206: 	return '</tr>'."\n";;
 6207:     }
 6208: }
 6209: 
 6210: =pod
 6211: 
 6212: =item * &inhibit_menu_check($arg)
 6213: 
 6214: Checks for a inhibitmenu state and generates output to preserve it
 6215: 
 6216: Inputs:         $arg - can be any of
 6217:                      - undef - in which case the return value is a string 
 6218:                                to add  into arguments list of a uri
 6219:                      - 'input' - in which case the return value is a HTML
 6220:                                  <form> <input> field of type hidden to
 6221:                                  preserve the value
 6222:                      - a url - in which case the return value is the url with
 6223:                                the neccesary cgi args added to preserve the
 6224:                                inhibitmenu state
 6225:                      - a ref to a url - no return value, but the string is
 6226:                                         updated to include the neccessary cgi
 6227:                                         args to preserve the inhibitmenu state
 6228: 
 6229: =cut
 6230: 
 6231: sub inhibit_menu_check {
 6232:     my ($arg) = @_;
 6233:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6234:     if ($arg eq 'input') {
 6235: 	if ($env{'form.inhibitmenu'}) {
 6236: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6237: 	} else {
 6238: 	    return
 6239: 	}
 6240:     }
 6241:     if ($env{'form.inhibitmenu'}) {
 6242: 	if (ref($arg)) {
 6243: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6244: 	} elsif ($arg eq '') {
 6245: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6246: 	} else {
 6247: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6248: 	}
 6249:     }
 6250:     if (!ref($arg)) {
 6251: 	return $arg;
 6252:     }
 6253: }
 6254: 
 6255: ###############################################
 6256: 
 6257: =pod
 6258: 
 6259: =back
 6260: 
 6261: =head1 User Information Routines
 6262: 
 6263: =over 4
 6264: 
 6265: =item * &get_users_function()
 6266: 
 6267: Used by &bodytag to determine the current users primary role.
 6268: Returns either 'student','coordinator','admin', or 'author'.
 6269: 
 6270: =cut
 6271: 
 6272: ###############################################
 6273: sub get_users_function {
 6274:     my $function = 'student';
 6275:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6276:         $function='coordinator';
 6277:     }
 6278:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6279:         $function='admin';
 6280:     }
 6281:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 6282:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6283:         $function='author';
 6284:     }
 6285:     return $function;
 6286: }
 6287: 
 6288: ###############################################
 6289: 
 6290: =pod
 6291: 
 6292: =item * &show_course()
 6293: 
 6294: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 6295: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 6296: Inputs:
 6297: None
 6298: 
 6299: Outputs:
 6300: Scalar: 1 if 'Course' to be used, 0 otherwise.
 6301: 
 6302: =cut
 6303: 
 6304: ###############################################
 6305: sub show_course {
 6306:     my $course = !$env{'user.adv'};
 6307:     if (!$env{'user.adv'}) {
 6308:         foreach my $env (keys(%env)) {
 6309:             next if ($env !~ m/^user\.priv\./);
 6310:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 6311:                 $course = 0;
 6312:                 last;
 6313:             }
 6314:         }
 6315:     }
 6316:     return $course;
 6317: }
 6318: 
 6319: ###############################################
 6320: 
 6321: =pod
 6322: 
 6323: =item * &check_user_status()
 6324: 
 6325: Determines current status of supplied role for a
 6326: specific user. Roles can be active, previous or future.
 6327: 
 6328: Inputs: 
 6329: user's domain, user's username, course's domain,
 6330: course's number, optional section ID.
 6331: 
 6332: Outputs:
 6333: role status: active, previous or future. 
 6334: 
 6335: =cut
 6336: 
 6337: sub check_user_status {
 6338:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6339:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6340:     my @uroles = keys %userinfo;
 6341:     my $srchstr;
 6342:     my $active_chk = 'none';
 6343:     my $now = time;
 6344:     if (@uroles > 0) {
 6345:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6346:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6347:         } else {
 6348:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6349:         }
 6350:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6351:             my $role_end = 0;
 6352:             my $role_start = 0;
 6353:             $active_chk = 'active';
 6354:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6355:                 $role_end = $1;
 6356:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6357:                     $role_start = $1;
 6358:                 }
 6359:             }
 6360:             if ($role_start > 0) {
 6361:                 if ($now < $role_start) {
 6362:                     $active_chk = 'future';
 6363:                 }
 6364:             }
 6365:             if ($role_end > 0) {
 6366:                 if ($now > $role_end) {
 6367:                     $active_chk = 'previous';
 6368:                 }
 6369:             }
 6370:         }
 6371:     }
 6372:     return $active_chk;
 6373: }
 6374: 
 6375: ###############################################
 6376: 
 6377: =pod
 6378: 
 6379: =item * &get_sections()
 6380: 
 6381: Determines all the sections for a course including
 6382: sections with students and sections containing other roles.
 6383: Incoming parameters: 
 6384: 
 6385: 1. domain
 6386: 2. course number 
 6387: 3. reference to array containing roles for which sections should 
 6388: be gathered (optional).
 6389: 4. reference to array containing status types for which sections 
 6390: should be gathered (optional).
 6391: 
 6392: If the third argument is undefined, sections are gathered for any role. 
 6393: If the fourth argument is undefined, sections are gathered for any status.
 6394: Permissible values are 'active' or 'future' or 'previous'.
 6395:  
 6396: Returns section hash (keys are section IDs, values are
 6397: number of users in each section), subject to the
 6398: optional roles filter, optional status filter 
 6399: 
 6400: =cut
 6401: 
 6402: ###############################################
 6403: sub get_sections {
 6404:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6405:     if (!defined($cdom) || !defined($cnum)) {
 6406:         my $cid =  $env{'request.course.id'};
 6407: 
 6408: 	return if (!defined($cid));
 6409: 
 6410:         $cdom = $env{'course.'.$cid.'.domain'};
 6411:         $cnum = $env{'course.'.$cid.'.num'};
 6412:     }
 6413: 
 6414:     my %sectioncount;
 6415:     my $now = time;
 6416: 
 6417:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6418: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6419: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6420: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6421:         my $start_index = &Apache::loncoursedata::CL_START();
 6422:         my $end_index = &Apache::loncoursedata::CL_END();
 6423:         my $status;
 6424: 	while (my ($student,$data) = each(%$classlist)) {
 6425: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6426: 				                     $data->[$status_index],
 6427:                                                      $data->[$start_index],
 6428:                                                      $data->[$end_index]);
 6429:             if ($stu_status eq 'Active') {
 6430:                 $status = 'active';
 6431:             } elsif ($end < $now) {
 6432:                 $status = 'previous';
 6433:             } elsif ($start > $now) {
 6434:                 $status = 'future';
 6435:             } 
 6436: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6437:                 if ((!defined($possible_status)) || (($status ne '') && 
 6438:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6439: 		    $sectioncount{$section}++;
 6440:                 }
 6441: 	    }
 6442: 	}
 6443:     }
 6444:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6445:     foreach my $user (sort(keys(%courseroles))) {
 6446: 	if ($user !~ /^(\w{2})/) { next; }
 6447: 	my ($role) = ($user =~ /^(\w{2})/);
 6448: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6449: 	my ($section,$status);
 6450: 	if ($role eq 'cr' &&
 6451: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6452: 	    $section=$1;
 6453: 	}
 6454: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6455: 	if (!defined($section) || $section eq '-1') { next; }
 6456:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6457:         if ($end == -1 && $start == -1) {
 6458:             next; #deleted role
 6459:         }
 6460:         if (!defined($possible_status)) { 
 6461:             $sectioncount{$section}++;
 6462:         } else {
 6463:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6464:                 $status = 'active';
 6465:             } elsif ($end < $now) {
 6466:                 $status = 'future';
 6467:             } elsif ($start > $now) {
 6468:                 $status = 'previous';
 6469:             }
 6470:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6471:                 $sectioncount{$section}++;
 6472:             }
 6473:         }
 6474:     }
 6475:     return %sectioncount;
 6476: }
 6477: 
 6478: ###############################################
 6479: 
 6480: =pod
 6481: 
 6482: =item * &get_course_users()
 6483: 
 6484: Retrieves usernames:domains for users in the specified course
 6485: with specific role(s), and access status. 
 6486: 
 6487: Incoming parameters:
 6488: 1. course domain
 6489: 2. course number
 6490: 3. access status: users must have - either active, 
 6491: previous, future, or all.
 6492: 4. reference to array of permissible roles
 6493: 5. reference to array of section restrictions (optional)
 6494: 6. reference to results object (hash of hashes).
 6495: 7. reference to optional userdata hash
 6496: 8. reference to optional statushash
 6497: 9. flag if privileged users (except those set to unhide in
 6498:    course settings) should be excluded    
 6499: Keys of top level results hash are roles.
 6500: Keys of inner hashes are username:domain, with 
 6501: values set to access type.
 6502: Optional userdata hash returns an array with arguments in the 
 6503: same order as loncoursedata::get_classlist() for student data.
 6504: 
 6505: Optional statushash returns
 6506: 
 6507: Entries for end, start, section and status are blank because
 6508: of the possibility of multiple values for non-student roles.
 6509: 
 6510: =cut
 6511: 
 6512: ###############################################
 6513: 
 6514: sub get_course_users {
 6515:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6516:     my %idx = ();
 6517:     my %seclists;
 6518: 
 6519:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6520:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6521:     $idx{end} = &Apache::loncoursedata::CL_END();
 6522:     $idx{start} = &Apache::loncoursedata::CL_START();
 6523:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6524:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6525:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6526:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6527: 
 6528:     if (grep(/^st$/,@{$roles})) {
 6529:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6530:         my $now = time;
 6531:         foreach my $student (keys(%{$classlist})) {
 6532:             my $match = 0;
 6533:             my $secmatch = 0;
 6534:             my $section = $$classlist{$student}[$idx{section}];
 6535:             my $status = $$classlist{$student}[$idx{status}];
 6536:             if ($section eq '') {
 6537:                 $section = 'none';
 6538:             }
 6539:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6540:                 if (grep(/^all$/,@{$sections})) {
 6541:                     $secmatch = 1;
 6542:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6543:                     if (grep(/^none$/,@{$sections})) {
 6544:                         $secmatch = 1;
 6545:                     }
 6546:                 } else {  
 6547: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6548: 		        $secmatch = 1;
 6549:                     }
 6550: 		}
 6551:                 if (!$secmatch) {
 6552:                     next;
 6553:                 }
 6554:             }
 6555:             if (defined($$types{'active'})) {
 6556:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6557:                     push(@{$$users{st}{$student}},'active');
 6558:                     $match = 1;
 6559:                 }
 6560:             }
 6561:             if (defined($$types{'previous'})) {
 6562:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6563:                     push(@{$$users{st}{$student}},'previous');
 6564:                     $match = 1;
 6565:                 }
 6566:             }
 6567:             if (defined($$types{'future'})) {
 6568:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6569:                     push(@{$$users{st}{$student}},'future');
 6570:                     $match = 1;
 6571:                 }
 6572:             }
 6573:             if ($match) {
 6574:                 push(@{$seclists{$student}},$section);
 6575:                 if (ref($userdata) eq 'HASH') {
 6576:                     $$userdata{$student} = $$classlist{$student};
 6577:                 }
 6578:                 if (ref($statushash) eq 'HASH') {
 6579:                     $statushash->{$student}{'st'}{$section} = $status;
 6580:                 }
 6581:             }
 6582:         }
 6583:     }
 6584:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6585:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6586:         my $now = time;
 6587:         my %displaystatus = ( previous => 'Expired',
 6588:                               active   => 'Active',
 6589:                               future   => 'Future',
 6590:                             );
 6591:         my %nothide;
 6592:         if ($hidepriv) {
 6593:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6594:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6595:                 if ($user !~ /:/) {
 6596:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6597:                 } else {
 6598:                     $nothide{$user} = 1;
 6599:                 }
 6600:             }
 6601:         }
 6602:         foreach my $person (sort(keys(%coursepersonnel))) {
 6603:             my $match = 0;
 6604:             my $secmatch = 0;
 6605:             my $status;
 6606:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6607:             $user =~ s/:$//;
 6608:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6609:             if ($end == -1 || $start == -1) {
 6610:                 next;
 6611:             }
 6612:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6613:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6614:                 my ($uname,$udom) = split(/:/,$user);
 6615:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6616:                     if (grep(/^all$/,@{$sections})) {
 6617:                         $secmatch = 1;
 6618:                     } elsif ($usec eq '') {
 6619:                         if (grep(/^none$/,@{$sections})) {
 6620:                             $secmatch = 1;
 6621:                         }
 6622:                     } else {
 6623:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6624:                             $secmatch = 1;
 6625:                         }
 6626:                     }
 6627:                     if (!$secmatch) {
 6628:                         next;
 6629:                     }
 6630:                 }
 6631:                 if ($usec eq '') {
 6632:                     $usec = 'none';
 6633:                 }
 6634:                 if ($uname ne '' && $udom ne '') {
 6635:                     if ($hidepriv) {
 6636:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6637:                             (!$nothide{$uname.':'.$udom})) {
 6638:                             next;
 6639:                         }
 6640:                     }
 6641:                     if ($end > 0 && $end < $now) {
 6642:                         $status = 'previous';
 6643:                     } elsif ($start > $now) {
 6644:                         $status = 'future';
 6645:                     } else {
 6646:                         $status = 'active';
 6647:                     }
 6648:                     foreach my $type (keys(%{$types})) { 
 6649:                         if ($status eq $type) {
 6650:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6651:                                 push(@{$$users{$role}{$user}},$type);
 6652:                             }
 6653:                             $match = 1;
 6654:                         }
 6655:                     }
 6656:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6657:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6658: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6659:                         }
 6660:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6661:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6662:                         }
 6663:                         if (ref($statushash) eq 'HASH') {
 6664:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6665:                         }
 6666:                     }
 6667:                 }
 6668:             }
 6669:         }
 6670:         if (grep(/^ow$/,@{$roles})) {
 6671:             if ((defined($cdom)) && (defined($cnum))) {
 6672:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6673:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6674:                     my $owner = $csettings{'internal.courseowner'};
 6675:                     next if ($owner eq '');
 6676:                     my ($ownername,$ownerdom);
 6677:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6678:                         $ownername = $1;
 6679:                         $ownerdom = $2;
 6680:                     } else {
 6681:                         $ownername = $owner;
 6682:                         $ownerdom = $cdom;
 6683:                         $owner = $ownername.':'.$ownerdom;
 6684:                     }
 6685:                     @{$$users{'ow'}{$owner}} = 'any';
 6686:                     if (defined($userdata) && 
 6687: 			!exists($$userdata{$owner})) {
 6688: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6689:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6690:                             push(@{$seclists{$owner}},'none');
 6691:                         }
 6692:                         if (ref($statushash) eq 'HASH') {
 6693:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6694:                         }
 6695: 		    }
 6696:                 }
 6697:             }
 6698:         }
 6699:         foreach my $user (keys(%seclists)) {
 6700:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6701:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6702:         }
 6703:     }
 6704:     return;
 6705: }
 6706: 
 6707: sub get_user_info {
 6708:     my ($udom,$uname,$idx,$userdata) = @_;
 6709:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6710: 	&plainname($uname,$udom,'lastname');
 6711:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6712:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6713:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6714:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6715:     return;
 6716: }
 6717: 
 6718: ###############################################
 6719: 
 6720: =pod
 6721: 
 6722: =item * &get_user_quota()
 6723: 
 6724: Retrieves quota assigned for storage of portfolio files for a user  
 6725: 
 6726: Incoming parameters:
 6727: 1. user's username
 6728: 2. user's domain
 6729: 
 6730: Returns:
 6731: 1. Disk quota (in Mb) assigned to student.
 6732: 2. (Optional) Type of setting: custom or default
 6733:    (individually assigned or default for user's 
 6734:    institutional status).
 6735: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6736:    or student - types as defined in localenroll::inst_usertypes 
 6737:    for user's domain, which determines default quota for user.
 6738: 4. (Optional) - Default quota which would apply to the user.
 6739: 
 6740: If a value has been stored in the user's environment, 
 6741: it will return that, otherwise it returns the maximal default
 6742: defined for the user's instituional status(es) in the domain.
 6743: 
 6744: =cut
 6745: 
 6746: ###############################################
 6747: 
 6748: 
 6749: sub get_user_quota {
 6750:     my ($uname,$udom) = @_;
 6751:     my ($quota,$quotatype,$settingstatus,$defquota);
 6752:     if (!defined($udom)) {
 6753:         $udom = $env{'user.domain'};
 6754:     }
 6755:     if (!defined($uname)) {
 6756:         $uname = $env{'user.name'};
 6757:     }
 6758:     if (($udom eq '' || $uname eq '') ||
 6759:         ($udom eq 'public') && ($uname eq 'public')) {
 6760:         $quota = 0;
 6761:         $quotatype = 'default';
 6762:         $defquota = 0; 
 6763:     } else {
 6764:         my $inststatus;
 6765:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6766:             $quota = $env{'environment.portfolioquota'};
 6767:             $inststatus = $env{'environment.inststatus'};
 6768:         } else {
 6769:             my %userenv = 
 6770:                 &Apache::lonnet::get('environment',['portfolioquota',
 6771:                                      'inststatus'],$udom,$uname);
 6772:             my ($tmp) = keys(%userenv);
 6773:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6774:                 $quota = $userenv{'portfolioquota'};
 6775:                 $inststatus = $userenv{'inststatus'};
 6776:             } else {
 6777:                 undef(%userenv);
 6778:             }
 6779:         }
 6780:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6781:         if ($quota eq '') {
 6782:             $quota = $defquota;
 6783:             $quotatype = 'default';
 6784:         } else {
 6785:             $quotatype = 'custom';
 6786:         }
 6787:     }
 6788:     if (wantarray) {
 6789:         return ($quota,$quotatype,$settingstatus,$defquota);
 6790:     } else {
 6791:         return $quota;
 6792:     }
 6793: }
 6794: 
 6795: ###############################################
 6796: 
 6797: =pod
 6798: 
 6799: =item * &default_quota()
 6800: 
 6801: Retrieves default quota assigned for storage of user portfolio files,
 6802: given an (optional) user's institutional status.
 6803: 
 6804: Incoming parameters:
 6805: 1. domain
 6806: 2. (Optional) institutional status(es).  This is a : separated list of 
 6807:    status types (e.g., faculty, staff, student etc.)
 6808:    which apply to the user for whom the default is being retrieved.
 6809:    If the institutional status string in undefined, the domain
 6810:    default quota will be returned. 
 6811: 
 6812: Returns:
 6813: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6814: 2. (Optional) institutional type which determined the value of the
 6815:    default quota.
 6816: 
 6817: If a value has been stored in the domain's configuration db,
 6818: it will return that, otherwise it returns 20 (for backwards 
 6819: compatibility with domains which have not set up a configuration
 6820: db file; the original statically defined portfolio quota was 20 Mb). 
 6821: 
 6822: If the user's status includes multiple types (e.g., staff and student),
 6823: the largest default quota which applies to the user determines the
 6824: default quota returned.
 6825: 
 6826: =back
 6827: 
 6828: =cut
 6829: 
 6830: ###############################################
 6831: 
 6832: 
 6833: sub default_quota {
 6834:     my ($udom,$inststatus) = @_;
 6835:     my ($defquota,$settingstatus);
 6836:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6837:                                             ['quotas'],$udom);
 6838:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6839:         if ($inststatus ne '') {
 6840:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 6841:             foreach my $item (@statuses) {
 6842:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6843:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6844:                         if ($defquota eq '') {
 6845:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6846:                             $settingstatus = $item;
 6847:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6848:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6849:                             $settingstatus = $item;
 6850:                         }
 6851:                     }
 6852:                 } else {
 6853:                     if ($quotahash{'quotas'}{$item} ne '') {
 6854:                         if ($defquota eq '') {
 6855:                             $defquota = $quotahash{'quotas'}{$item};
 6856:                             $settingstatus = $item;
 6857:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6858:                             $defquota = $quotahash{'quotas'}{$item};
 6859:                             $settingstatus = $item;
 6860:                         }
 6861:                     }
 6862:                 }
 6863:             }
 6864:         }
 6865:         if ($defquota eq '') {
 6866:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6867:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6868:             } else {
 6869:                 $defquota = $quotahash{'quotas'}{'default'};
 6870:             }
 6871:             $settingstatus = 'default';
 6872:         }
 6873:     } else {
 6874:         $settingstatus = 'default';
 6875:         $defquota = 20;
 6876:     }
 6877:     if (wantarray) {
 6878:         return ($defquota,$settingstatus);
 6879:     } else {
 6880:         return $defquota;
 6881:     }
 6882: }
 6883: 
 6884: sub get_secgrprole_info {
 6885:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6886:     my %sections_count = &get_sections($cdom,$cnum);
 6887:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6888:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6889:     my @groups = sort(keys(%curr_groups));
 6890:     my $allroles = [];
 6891:     my $rolehash;
 6892:     my $accesshash = {
 6893:                      active => 'Currently has access',
 6894:                      future => 'Will have future access',
 6895:                      previous => 'Previously had access',
 6896:                   };
 6897:     if ($needroles) {
 6898:         $rolehash = {'all' => 'all'};
 6899:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6900: 	if (&Apache::lonnet::error(%user_roles)) {
 6901: 	    undef(%user_roles);
 6902: 	}
 6903:         foreach my $item (keys(%user_roles)) {
 6904:             my ($role)=split(/\:/,$item,2);
 6905:             if ($role eq 'cr') { next; }
 6906:             if ($role =~ /^cr/) {
 6907:                 $$rolehash{$role} = (split('/',$role))[3];
 6908:             } else {
 6909:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6910:             }
 6911:         }
 6912:         foreach my $key (sort(keys(%{$rolehash}))) {
 6913:             push(@{$allroles},$key);
 6914:         }
 6915:         push (@{$allroles},'st');
 6916:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6917:     }
 6918:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6919: }
 6920: 
 6921: sub user_picker {
 6922:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6923:     my $currdom = $dom;
 6924:     my %curr_selected = (
 6925:                         srchin => 'dom',
 6926:                         srchby => 'lastname',
 6927:                       );
 6928:     my $srchterm;
 6929:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6930:         if ($srch->{'srchby'} ne '') {
 6931:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6932:         }
 6933:         if ($srch->{'srchin'} ne '') {
 6934:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6935:         }
 6936:         if ($srch->{'srchtype'} ne '') {
 6937:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6938:         }
 6939:         if ($srch->{'srchdomain'} ne '') {
 6940:             $currdom = $srch->{'srchdomain'};
 6941:         }
 6942:         $srchterm = $srch->{'srchterm'};
 6943:     }
 6944:     my %lt=&Apache::lonlocal::texthash(
 6945:                     'usr'       => 'Search criteria',
 6946:                     'doma'      => 'Domain/institution to search',
 6947:                     'uname'     => 'username',
 6948:                     'lastname'  => 'last name',
 6949:                     'lastfirst' => 'last name, first name',
 6950:                     'crs'       => 'in this course',
 6951:                     'dom'       => 'in selected LON-CAPA domain', 
 6952:                     'alc'       => 'all LON-CAPA',
 6953:                     'instd'     => 'in institutional directory for selected domain',
 6954:                     'exact'     => 'is',
 6955:                     'contains'  => 'contains',
 6956:                     'begins'    => 'begins with',
 6957:                     'youm'      => "You must include some text to search for.",
 6958:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6959:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6960:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6961:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6962:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6963:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6964:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6965:                                        );
 6966:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6967:     my $srchinsel = ' <select name="srchin">';
 6968: 
 6969:     my @srchins = ('crs','dom','alc','instd');
 6970: 
 6971:     foreach my $option (@srchins) {
 6972:         # FIXME 'alc' option unavailable until 
 6973:         #       loncreateuser::print_user_query_page()
 6974:         #       has been completed.
 6975:         next if ($option eq 'alc');
 6976:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
 6977:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6978:         if ($curr_selected{'srchin'} eq $option) {
 6979:             $srchinsel .= ' 
 6980:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6981:         } else {
 6982:             $srchinsel .= '
 6983:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6984:         }
 6985:     }
 6986:     $srchinsel .= "\n  </select>\n";
 6987: 
 6988:     my $srchbysel =  ' <select name="srchby">';
 6989:     foreach my $option ('lastname','lastfirst','uname') {
 6990:         if ($curr_selected{'srchby'} eq $option) {
 6991:             $srchbysel .= '
 6992:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6993:         } else {
 6994:             $srchbysel .= '
 6995:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6996:          }
 6997:     }
 6998:     $srchbysel .= "\n  </select>\n";
 6999: 
 7000:     my $srchtypesel = ' <select name="srchtype">';
 7001:     foreach my $option ('begins','contains','exact') {
 7002:         if ($curr_selected{'srchtype'} eq $option) {
 7003:             $srchtypesel .= '
 7004:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7005:         } else {
 7006:             $srchtypesel .= '
 7007:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7008:         }
 7009:     }
 7010:     $srchtypesel .= "\n  </select>\n";
 7011: 
 7012:     my ($newuserscript,$new_user_create);
 7013: 
 7014:     if ($forcenewuser) {
 7015:         if (ref($srch) eq 'HASH') {
 7016:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7017:                 if ($cancreate) {
 7018:                     $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>';
 7019:                 } else {
 7020:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7021:                     my %usertypetext = (
 7022:                         official   => 'institutional',
 7023:                         unofficial => 'non-institutional',
 7024:                     );
 7025:                     $new_user_create = '<p class="LC_warning">'.
 7026:                                        &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
 7027:                                        &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
 7028:                 }
 7029:             }
 7030:         }
 7031: 
 7032:         $newuserscript = <<"ENDSCRIPT";
 7033: 
 7034: function setSearch(createnew,callingForm) {
 7035:     if (createnew == 1) {
 7036:         for (var i=0; i<callingForm.srchby.length; i++) {
 7037:             if (callingForm.srchby.options[i].value == 'uname') {
 7038:                 callingForm.srchby.selectedIndex = i;
 7039:             }
 7040:         }
 7041:         for (var i=0; i<callingForm.srchin.length; i++) {
 7042:             if ( callingForm.srchin.options[i].value == 'dom') {
 7043: 		callingForm.srchin.selectedIndex = i;
 7044:             }
 7045:         }
 7046:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7047:             if (callingForm.srchtype.options[i].value == 'exact') {
 7048:                 callingForm.srchtype.selectedIndex = i;
 7049:             }
 7050:         }
 7051:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7052:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7053:                 callingForm.srchdomain.selectedIndex = i;
 7054:             }
 7055:         }
 7056:     }
 7057: }
 7058: ENDSCRIPT
 7059: 
 7060:     }
 7061: 
 7062:     my $output = <<"END_BLOCK";
 7063: <script type="text/javascript">
 7064: // <![CDATA[
 7065: function validateEntry(callingForm) {
 7066: 
 7067:     var checkok = 1;
 7068:     var srchin;
 7069:     for (var i=0; i<callingForm.srchin.length; i++) {
 7070: 	if ( callingForm.srchin[i].checked ) {
 7071: 	    srchin = callingForm.srchin[i].value;
 7072: 	}
 7073:     }
 7074: 
 7075:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7076:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7077:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7078:     var srchterm =  callingForm.srchterm.value;
 7079:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7080:     var msg = "";
 7081: 
 7082:     if (srchterm == "") {
 7083:         checkok = 0;
 7084:         msg += "$lt{'youm'}\\n";
 7085:     }
 7086: 
 7087:     if (srchtype== 'begins') {
 7088:         if (srchterm.length < 2) {
 7089:             checkok = 0;
 7090:             msg += "$lt{'thte'}\\n";
 7091:         }
 7092:     }
 7093: 
 7094:     if (srchtype== 'contains') {
 7095:         if (srchterm.length < 3) {
 7096:             checkok = 0;
 7097:             msg += "$lt{'thet'}\\n";
 7098:         }
 7099:     }
 7100:     if (srchin == 'instd') {
 7101:         if (srchdomain == '') {
 7102:             checkok = 0;
 7103:             msg += "$lt{'yomc'}\\n";
 7104:         }
 7105:     }
 7106:     if (srchin == 'dom') {
 7107:         if (srchdomain == '') {
 7108:             checkok = 0;
 7109:             msg += "$lt{'ymcd'}\\n";
 7110:         }
 7111:     }
 7112:     if (srchby == 'lastfirst') {
 7113:         if (srchterm.indexOf(",") == -1) {
 7114:             checkok = 0;
 7115:             msg += "$lt{'whus'}\\n";
 7116:         }
 7117:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7118:             checkok = 0;
 7119:             msg += "$lt{'whse'}\\n";
 7120:         }
 7121:     }
 7122:     if (checkok == 0) {
 7123:         alert("$lt{'thfo'}\\n"+msg);
 7124:         return;
 7125:     }
 7126:     if (checkok == 1) {
 7127:         callingForm.submit();
 7128:     }
 7129: }
 7130: 
 7131: $newuserscript
 7132: 
 7133: // ]]>
 7134: </script>
 7135: 
 7136: $new_user_create
 7137: 
 7138: END_BLOCK
 7139: 
 7140:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7141:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7142:                $domform.
 7143:                &Apache::lonhtmlcommon::row_closure().
 7144:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7145:                $srchbysel.
 7146:                $srchtypesel.
 7147:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7148:                $srchinsel.
 7149:                &Apache::lonhtmlcommon::row_closure(1).
 7150:                &Apache::lonhtmlcommon::end_pick_box().
 7151:                '<br />';
 7152:     return $output;
 7153: }
 7154: 
 7155: sub user_rule_check {
 7156:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7157:     my $response;
 7158:     if (ref($usershash) eq 'HASH') {
 7159:         foreach my $user (keys(%{$usershash})) {
 7160:             my ($uname,$udom) = split(/:/,$user);
 7161:             next if ($udom eq '' || $uname eq '');
 7162:             my ($id,$newuser);
 7163:             if (ref($usershash->{$user}) eq 'HASH') {
 7164:                 $newuser = $usershash->{$user}->{'newuser'};
 7165:                 $id = $usershash->{$user}->{'id'};
 7166:             }
 7167:             my $inst_response;
 7168:             if (ref($checks) eq 'HASH') {
 7169:                 if (defined($checks->{'username'})) {
 7170:                     ($inst_response,%{$inst_results->{$user}}) = 
 7171:                         &Apache::lonnet::get_instuser($udom,$uname);
 7172:                 } elsif (defined($checks->{'id'})) {
 7173:                     ($inst_response,%{$inst_results->{$user}}) =
 7174:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7175:                 }
 7176:             } else {
 7177:                 ($inst_response,%{$inst_results->{$user}}) =
 7178:                     &Apache::lonnet::get_instuser($udom,$uname);
 7179:                 return;
 7180:             }
 7181:             if (!$got_rules->{$udom}) {
 7182:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7183:                                                   ['usercreation'],$udom);
 7184:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7185:                     foreach my $item ('username','id') {
 7186:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7187:                             $$curr_rules{$udom}{$item} = 
 7188:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7189:                         }
 7190:                     }
 7191:                 }
 7192:                 $got_rules->{$udom} = 1;  
 7193:             }
 7194:             foreach my $item (keys(%{$checks})) {
 7195:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7196:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7197:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7198:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7199:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7200:                                 if ($rule_check{$rule}) {
 7201:                                     $$rulematch{$user}{$item} = $rule;
 7202:                                     if ($inst_response eq 'ok') {
 7203:                                         if (ref($inst_results) eq 'HASH') {
 7204:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7205:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7206:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7207:                                                 }
 7208:                                             }
 7209:                                         }
 7210:                                     }
 7211:                                     last;
 7212:                                 }
 7213:                             }
 7214:                         }
 7215:                     }
 7216:                 }
 7217:             }
 7218:         }
 7219:     }
 7220:     return;
 7221: }
 7222: 
 7223: sub user_rule_formats {
 7224:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7225:     my %text = ( 
 7226:                  'username' => 'Usernames',
 7227:                  'id'       => 'IDs',
 7228:                );
 7229:     my $output;
 7230:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7231:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7232:         if (@{$ruleorder} > 0) {
 7233:             $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>';
 7234:             foreach my $rule (@{$ruleorder}) {
 7235:                 if (ref($curr_rules) eq 'ARRAY') {
 7236:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7237:                         if (ref($rules->{$rule}) eq 'HASH') {
 7238:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7239:                                         $rules->{$rule}{'desc'}.'</li>';
 7240:                         }
 7241:                     }
 7242:                 }
 7243:             }
 7244:             $output .= '</ul>';
 7245:         }
 7246:     }
 7247:     return $output;
 7248: }
 7249: 
 7250: sub instrule_disallow_msg {
 7251:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7252:     my $response;
 7253:     my %text = (
 7254:                   item   => 'username',
 7255:                   items  => 'usernames',
 7256:                   match  => 'matches',
 7257:                   do     => 'does',
 7258:                   action => 'a username',
 7259:                   one    => 'one',
 7260:                );
 7261:     if ($count > 1) {
 7262:         $text{'item'} = 'usernames';
 7263:         $text{'match'} ='match';
 7264:         $text{'do'} = 'do';
 7265:         $text{'action'} = 'usernames',
 7266:         $text{'one'} = 'ones';
 7267:     }
 7268:     if ($checkitem eq 'id') {
 7269:         $text{'items'} = 'IDs';
 7270:         $text{'item'} = 'ID';
 7271:         $text{'action'} = 'an ID';
 7272:         if ($count > 1) {
 7273:             $text{'item'} = 'IDs';
 7274:             $text{'action'} = 'IDs';
 7275:         }
 7276:     }
 7277:     $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 />';
 7278:     if ($mode eq 'upload') {
 7279:         if ($checkitem eq 'username') {
 7280:             $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'}.");
 7281:         } elsif ($checkitem eq 'id') {
 7282:             $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.");
 7283:         }
 7284:     } elsif ($mode eq 'selfcreate') {
 7285:         if ($checkitem eq 'id') {
 7286:             $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.");
 7287:         }
 7288:     } else {
 7289:         if ($checkitem eq 'username') {
 7290:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7291:         } elsif ($checkitem eq 'id') {
 7292:             $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.");
 7293:         }
 7294:     }
 7295:     return $response;
 7296: }
 7297: 
 7298: sub personal_data_fieldtitles {
 7299:     my %fieldtitles = &Apache::lonlocal::texthash (
 7300:                         id => 'Student/Employee ID',
 7301:                         permanentemail => 'E-mail address',
 7302:                         lastname => 'Last Name',
 7303:                         firstname => 'First Name',
 7304:                         middlename => 'Middle Name',
 7305:                         generation => 'Generation',
 7306:                         gen => 'Generation',
 7307:                         inststatus => 'Affiliation',
 7308:                    );
 7309:     return %fieldtitles;
 7310: }
 7311: 
 7312: sub sorted_inst_types {
 7313:     my ($dom) = @_;
 7314:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7315:     my $othertitle = &mt('All users');
 7316:     if ($env{'request.course.id'}) {
 7317:         $othertitle  = &mt('Any users');
 7318:     }
 7319:     my @types;
 7320:     if (ref($order) eq 'ARRAY') {
 7321:         @types = @{$order};
 7322:     }
 7323:     if (@types == 0) {
 7324:         if (ref($usertypes) eq 'HASH') {
 7325:             @types = sort(keys(%{$usertypes}));
 7326:         }
 7327:     }
 7328:     if (keys(%{$usertypes}) > 0) {
 7329:         $othertitle = &mt('Other users');
 7330:     }
 7331:     return ($othertitle,$usertypes,\@types);
 7332: }
 7333: 
 7334: sub get_institutional_codes {
 7335:     my ($settings,$allcourses,$LC_code) = @_;
 7336: # Get complete list of course sections to update
 7337:     my @currsections = ();
 7338:     my @currxlists = ();
 7339:     my $coursecode = $$settings{'internal.coursecode'};
 7340: 
 7341:     if ($$settings{'internal.sectionnums'} ne '') {
 7342:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7343:     }
 7344: 
 7345:     if ($$settings{'internal.crosslistings'} ne '') {
 7346:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7347:     }
 7348: 
 7349:     if (@currxlists > 0) {
 7350:         foreach (@currxlists) {
 7351:             if (m/^([^:]+):(\w*)$/) {
 7352:                 unless (grep/^$1$/,@{$allcourses}) {
 7353:                     push @{$allcourses},$1;
 7354:                     $$LC_code{$1} = $2;
 7355:                 }
 7356:             }
 7357:         }
 7358:     }
 7359:  
 7360:     if (@currsections > 0) {
 7361:         foreach (@currsections) {
 7362:             if (m/^(\w+):(\w*)$/) {
 7363:                 my $sec = $coursecode.$1;
 7364:                 my $lc_sec = $2;
 7365:                 unless (grep/^$sec$/,@{$allcourses}) {
 7366:                     push @{$allcourses},$sec;
 7367:                     $$LC_code{$sec} = $lc_sec;
 7368:                 }
 7369:             }
 7370:         }
 7371:     }
 7372:     return;
 7373: }
 7374: 
 7375: =pod
 7376: 
 7377: =head1 Slot Helpers
 7378: 
 7379: =over 4
 7380: 
 7381: =item * sorted_slots()
 7382: 
 7383: Sorts an array of slot names in order of slot start time (earliest first).
 7384: 
 7385: Inputs:
 7386: 
 7387: =over 4
 7388: 
 7389: slotsarr  - Reference to array of unsorted slot names.
 7390: 
 7391: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7392: 
 7393: =back
 7394: 
 7395: Returns:
 7396: 
 7397: =over 4
 7398: 
 7399: sorted   - An array of slot names sorted by the start time of the slot.
 7400: 
 7401: =back
 7402: 
 7403: =back
 7404: 
 7405: =cut
 7406: 
 7407: 
 7408: sub sorted_slots {
 7409:     my ($slotsarr,$slots) = @_;
 7410:     my @sorted;
 7411:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7412:         @sorted =
 7413:             sort {
 7414:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7415:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7416:                      }
 7417:                      if (ref($slots->{$a})) { return -1;}
 7418:                      if (ref($slots->{$b})) { return 1;}
 7419:                      return 0;
 7420:                  } @{$slotsarr};
 7421:     }
 7422:     return @sorted;
 7423: }
 7424: 
 7425: =pod
 7426: 
 7427: =head1 HTTP Helpers
 7428: 
 7429: =over 4
 7430: 
 7431: =item * &get_unprocessed_cgi($query,$possible_names)
 7432: 
 7433: Modify the %env hash to contain unprocessed CGI form parameters held in
 7434: $query.  The parameters listed in $possible_names (an array reference),
 7435: will be set in $env{'form.name'} if they do not already exist.
 7436: 
 7437: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7438: $possible_names is an ref to an array of form element names.  As an example:
 7439: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7440: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7441: 
 7442: =cut
 7443: 
 7444: sub get_unprocessed_cgi {
 7445:   my ($query,$possible_names)= @_;
 7446:   # $Apache::lonxml::debug=1;
 7447:   foreach my $pair (split(/&/,$query)) {
 7448:     my ($name, $value) = split(/=/,$pair);
 7449:     $name = &unescape($name);
 7450:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7451:       $value =~ tr/+/ /;
 7452:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7453:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7454:     }
 7455:   }
 7456: }
 7457: 
 7458: =pod
 7459: 
 7460: =item * &cacheheader() 
 7461: 
 7462: returns cache-controlling header code
 7463: 
 7464: =cut
 7465: 
 7466: sub cacheheader {
 7467:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7468:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7469:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7470:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7471:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7472:     return $output;
 7473: }
 7474: 
 7475: =pod
 7476: 
 7477: =item * &no_cache($r) 
 7478: 
 7479: specifies header code to not have cache
 7480: 
 7481: =cut
 7482: 
 7483: sub no_cache {
 7484:     my ($r) = @_;
 7485:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7486: 	$env{'request.method'} ne 'GET') { return ''; }
 7487:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7488:     $r->no_cache(1);
 7489:     $r->header_out("Expires" => $date);
 7490:     $r->header_out("Pragma" => "no-cache");
 7491: }
 7492: 
 7493: sub content_type {
 7494:     my ($r,$type,$charset) = @_;
 7495:     if ($r) {
 7496: 	#  Note that printout.pl calls this with undef for $r.
 7497: 	&no_cache($r);
 7498:     }
 7499:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7500:     unless ($charset) {
 7501: 	$charset=&Apache::lonlocal::current_encoding;
 7502:     }
 7503:     if ($charset) { $type.='; charset='.$charset; }
 7504:     if ($r) {
 7505: 	$r->content_type($type);
 7506:     } else {
 7507: 	print("Content-type: $type\n\n");
 7508:     }
 7509: }
 7510: 
 7511: =pod
 7512: 
 7513: =item * &add_to_env($name,$value) 
 7514: 
 7515: adds $name to the %env hash with value
 7516: $value, if $name already exists, the entry is converted to an array
 7517: reference and $value is added to the array.
 7518: 
 7519: =cut
 7520: 
 7521: sub add_to_env {
 7522:   my ($name,$value)=@_;
 7523:   if (defined($env{$name})) {
 7524:     if (ref($env{$name})) {
 7525:       #already have multiple values
 7526:       push(@{ $env{$name} },$value);
 7527:     } else {
 7528:       #first time seeing multiple values, convert hash entry to an arrayref
 7529:       my $first=$env{$name};
 7530:       undef($env{$name});
 7531:       push(@{ $env{$name} },$first,$value);
 7532:     }
 7533:   } else {
 7534:     $env{$name}=$value;
 7535:   }
 7536: }
 7537: 
 7538: =pod
 7539: 
 7540: =item * &get_env_multiple($name) 
 7541: 
 7542: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7543: values may be defined and end up as an array ref.
 7544: 
 7545: returns an array of values
 7546: 
 7547: =cut
 7548: 
 7549: sub get_env_multiple {
 7550:     my ($name) = @_;
 7551:     my @values;
 7552:     if (defined($env{$name})) {
 7553:         # exists is it an array
 7554:         if (ref($env{$name})) {
 7555:             @values=@{ $env{$name} };
 7556:         } else {
 7557:             $values[0]=$env{$name};
 7558:         }
 7559:     }
 7560:     return(@values);
 7561: }
 7562: 
 7563: sub ask_for_embedded_content {
 7564:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7565:     my $upload_output = '
 7566:    <form name="upload_embedded" action="'.$actionurl.'"
 7567:                   method="post" enctype="multipart/form-data">';
 7568:     $upload_output .= $state;
 7569:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7570: 
 7571:     my $num = 0;
 7572:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7573:         $upload_output .= &start_data_table_row().
 7574:             '<td>'.$embed_file.'</td><td>';
 7575:         if ($args->{'ignore_remote_references'}
 7576:             && $embed_file =~ m{^\w+://}) {
 7577:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7578:         } elsif ($args->{'error_on_invalid_names'}
 7579:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7580: 
 7581:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7582: 
 7583:         } else {
 7584:             $upload_output .='
 7585:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7586:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7587:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7588:             $upload_output .=
 7589:                 "\n\t\t".
 7590:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7591:                 $attrib.'" />';
 7592:             if (exists($$codebase{$embed_file})) {
 7593:                 $upload_output .=
 7594:                     "\n\t\t".
 7595:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7596:                     &escape($$codebase{$embed_file}).'" />';
 7597:             }
 7598:         }
 7599:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7600:         $num++;
 7601:     }
 7602:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7603:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7604:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7605:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7606:    </form>';
 7607:     return $upload_output;
 7608: }
 7609: 
 7610: sub upload_embedded {
 7611:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7612:         $current_disk_usage) = @_;
 7613:     my $output;
 7614:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7615:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7616:         my $orig_uploaded_filename =
 7617:             $env{'form.embedded_item_'.$i.'.filename'};
 7618: 
 7619:         $env{'form.embedded_orig_'.$i} =
 7620:             &unescape($env{'form.embedded_orig_'.$i});
 7621:         my ($path,$fname) =
 7622:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7623:         # no path, whole string is fname
 7624:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7625: 
 7626:         $path = $env{'form.currentpath'}.$path;
 7627:         $fname = &Apache::lonnet::clean_filename($fname);
 7628:         # See if there is anything left
 7629:         next if ($fname eq '');
 7630: 
 7631:         # Check if file already exists as a file or directory.
 7632:         my ($state,$msg);
 7633:         if ($context eq 'portfolio') {
 7634:             my $port_path = $dirpath;
 7635:             if ($group ne '') {
 7636:                 $port_path = "groups/$group/$port_path";
 7637:             }
 7638:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7639:                                               $dir_root,$port_path,$disk_quota,
 7640:                                               $current_disk_usage,$uname,$udom);
 7641:             if ($state eq 'will_exceed_quota'
 7642:                 || $state eq 'file_locked'
 7643:                 || $state eq 'file_exists' ) {
 7644:                 $output .= $msg;
 7645:                 next;
 7646:             }
 7647:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7648:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7649:             if ($state eq 'exists') {
 7650:                 $output .= $msg;
 7651:                 next;
 7652:             }
 7653:         }
 7654:         # Check if extension is valid
 7655:         if (($fname =~ /\.(\w+)$/) &&
 7656:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7657:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7658:             next;
 7659:         } elsif (($fname =~ /\.(\w+)$/) &&
 7660:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7661:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7662:             next;
 7663:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7664:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7665:             next;
 7666:         }
 7667: 
 7668:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7669:         if ($context eq 'portfolio') {
 7670:             my $result=
 7671:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7672:                                                 $dirpath.$path);
 7673:             if ($result !~ m|^/uploaded/|) {
 7674:                 $output .= '<span class="LC_error">'
 7675:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7676:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7677:                       .'</span><br />';
 7678:                 next;
 7679:             } else {
 7680:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7681:                            $path.$fname.'</span>').'</p>';     
 7682:             }
 7683:         } else {
 7684: # Save the file
 7685:             my $target = $env{'form.embedded_item_'.$i};
 7686:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7687:             my $dest = $fullpath.$fname;
 7688:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7689:             my @parts=split(/\//,$fullpath);
 7690:             my $count;
 7691:             my $filepath = $dir_root;
 7692:             for ($count=4;$count<=$#parts;$count++) {
 7693:                 $filepath .= "/$parts[$count]";
 7694:                 if ((-e $filepath)!=1) {
 7695:                     mkdir($filepath,0770);
 7696:                 }
 7697:             }
 7698:             my $fh;
 7699:             if (!open($fh,'>'.$dest)) {
 7700:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7701:                 $output .= '<span class="LC_error">'.
 7702:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7703:                            '</span><br />';
 7704:             } else {
 7705:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7706:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7707:                     $output .= '<span class="LC_error">'.
 7708:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7709:                               '</span><br />';
 7710:                 } else {
 7711:                     if ($context eq 'testbank') {
 7712:                         $output .= &mt('Embedded file uploaded successfully:').
 7713:                                    '&nbsp;<a href="'.$url.'">'.
 7714:                                    $orig_uploaded_filename.'</a><br />';
 7715:                     } else {
 7716:                         $output .= '<font size="+2">'.
 7717:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7718:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7719:                     }
 7720:                 }
 7721:                 close($fh);
 7722:             }
 7723:         }
 7724:     }
 7725:     return $output;
 7726: }
 7727: 
 7728: sub check_for_existing {
 7729:     my ($path,$fname,$element) = @_;
 7730:     my ($state,$msg);
 7731:     if (-d $path.'/'.$fname) {
 7732:         $state = 'exists';
 7733:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7734:     } elsif (-e $path.'/'.$fname) {
 7735:         $state = 'exists';
 7736:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7737:     }
 7738:     if ($state eq 'exists') {
 7739:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7740:     }
 7741:     return ($state,$msg);
 7742: }
 7743: 
 7744: sub check_for_upload {
 7745:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7746:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7747:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7748:     my $getpropath = 1;
 7749:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7750:                                             $getpropath);
 7751:     my $found_file = 0;
 7752:     my $locked_file = 0;
 7753:     foreach my $line (@dir_list) {
 7754:         my ($file_name)=split(/\&/,$line,2);
 7755:         if ($file_name eq $fname){
 7756:             $file_name = $path.$file_name;
 7757:             if ($group ne '') {
 7758:                 $file_name = $group.$file_name;
 7759:             }
 7760:             $found_file = 1;
 7761:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7762:                 $locked_file = 1;
 7763:             }
 7764:         }
 7765:     }
 7766:     if (($current_disk_usage + $filesize) > $disk_quota){
 7767:         my $msg = '<span class="LC_error">'.
 7768:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7769:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7770:         return ('will_exceed_quota',$msg);
 7771:     } elsif ($found_file) {
 7772:         if ($locked_file) {
 7773:             my $msg = '<span class="LC_error">';
 7774:             $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>');
 7775:             $msg .= '</span><br />';
 7776:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7777:             return ('file_locked',$msg);
 7778:         } else {
 7779:             my $msg = '<span class="LC_error">';
 7780:             $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'});
 7781:             $msg .= '</span>';
 7782:             $msg .= '<br />';
 7783:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7784:             return ('file_exists',$msg);
 7785:         }
 7786:     }
 7787: }
 7788: 
 7789: 
 7790: =pod
 7791: 
 7792: =back
 7793: 
 7794: =head1 CSV Upload/Handling functions
 7795: 
 7796: =over 4
 7797: 
 7798: =item * &upfile_store($r)
 7799: 
 7800: Store uploaded file, $r should be the HTTP Request object,
 7801: needs $env{'form.upfile'}
 7802: returns $datatoken to be put into hidden field
 7803: 
 7804: =cut
 7805: 
 7806: sub upfile_store {
 7807:     my $r=shift;
 7808:     $env{'form.upfile'}=~s/\r/\n/gs;
 7809:     $env{'form.upfile'}=~s/\f/\n/gs;
 7810:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7811:     $env{'form.upfile'}=~s/\n+$//gs;
 7812: 
 7813:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7814: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7815:     {
 7816:         my $datafile = $r->dir_config('lonDaemons').
 7817:                            '/tmp/'.$datatoken.'.tmp';
 7818:         if ( open(my $fh,">$datafile") ) {
 7819:             print $fh $env{'form.upfile'};
 7820:             close($fh);
 7821:         }
 7822:     }
 7823:     return $datatoken;
 7824: }
 7825: 
 7826: =pod
 7827: 
 7828: =item * &load_tmp_file($r)
 7829: 
 7830: Load uploaded file from tmp, $r should be the HTTP Request object,
 7831: needs $env{'form.datatoken'},
 7832: sets $env{'form.upfile'} to the contents of the file
 7833: 
 7834: =cut
 7835: 
 7836: sub load_tmp_file {
 7837:     my $r=shift;
 7838:     my @studentdata=();
 7839:     {
 7840:         my $studentfile = $r->dir_config('lonDaemons').
 7841:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7842:         if ( open(my $fh,"<$studentfile") ) {
 7843:             @studentdata=<$fh>;
 7844:             close($fh);
 7845:         }
 7846:     }
 7847:     $env{'form.upfile'}=join('',@studentdata);
 7848: }
 7849: 
 7850: =pod
 7851: 
 7852: =item * &upfile_record_sep()
 7853: 
 7854: Separate uploaded file into records
 7855: returns array of records,
 7856: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7857: 
 7858: =cut
 7859: 
 7860: sub upfile_record_sep {
 7861:     if ($env{'form.upfiletype'} eq 'xml') {
 7862:     } else {
 7863: 	my @records;
 7864: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7865: 	    if ($line=~/^\s*$/) { next; }
 7866: 	    push(@records,$line);
 7867: 	}
 7868: 	return @records;
 7869:     }
 7870: }
 7871: 
 7872: =pod
 7873: 
 7874: =item * &record_sep($record)
 7875: 
 7876: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7877: 
 7878: =cut
 7879: 
 7880: sub takeleft {
 7881:     my $index=shift;
 7882:     return substr('0000'.$index,-4,4);
 7883: }
 7884: 
 7885: sub record_sep {
 7886:     my $record=shift;
 7887:     my %components=();
 7888:     if ($env{'form.upfiletype'} eq 'xml') {
 7889:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7890:         my $i=0;
 7891:         foreach my $field (split(/\s+/,$record)) {
 7892:             $field=~s/^(\"|\')//;
 7893:             $field=~s/(\"|\')$//;
 7894:             $components{&takeleft($i)}=$field;
 7895:             $i++;
 7896:         }
 7897:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7898:         my $i=0;
 7899:         foreach my $field (split(/\t/,$record)) {
 7900:             $field=~s/^(\"|\')//;
 7901:             $field=~s/(\"|\')$//;
 7902:             $components{&takeleft($i)}=$field;
 7903:             $i++;
 7904:         }
 7905:     } else {
 7906:         my $separator=',';
 7907:         if ($env{'form.upfiletype'} eq 'semisv') {
 7908:             $separator=';';
 7909:         }
 7910:         my $i=0;
 7911: # the character we are looking for to indicate the end of a quote or a record 
 7912:         my $looking_for=$separator;
 7913: # do not add the characters to the fields
 7914:         my $ignore=0;
 7915: # we just encountered a separator (or the beginning of the record)
 7916:         my $just_found_separator=1;
 7917: # store the field we are working on here
 7918:         my $field='';
 7919: # work our way through all characters in record
 7920:         foreach my $character ($record=~/(.)/g) {
 7921:             if ($character eq $looking_for) {
 7922:                if ($character ne $separator) {
 7923: # Found the end of a quote, again looking for separator
 7924:                   $looking_for=$separator;
 7925:                   $ignore=1;
 7926:                } else {
 7927: # Found a separator, store away what we got
 7928:                   $components{&takeleft($i)}=$field;
 7929: 	          $i++;
 7930:                   $just_found_separator=1;
 7931:                   $ignore=0;
 7932:                   $field='';
 7933:                }
 7934:                next;
 7935:             }
 7936: # single or double quotation marks after a separator indicate beginning of a quote
 7937: # we are now looking for the end of the quote and need to ignore separators
 7938:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7939:                $looking_for=$character;
 7940:                next;
 7941:             }
 7942: # ignore would be true after we reached the end of a quote
 7943:             if ($ignore) { next; }
 7944:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7945:             $field.=$character;
 7946:             $just_found_separator=0; 
 7947:         }
 7948: # catch the very last entry, since we never encountered the separator
 7949:         $components{&takeleft($i)}=$field;
 7950:     }
 7951:     return %components;
 7952: }
 7953: 
 7954: ######################################################
 7955: ######################################################
 7956: 
 7957: =pod
 7958: 
 7959: =item * &upfile_select_html()
 7960: 
 7961: Return HTML code to select a file from the users machine and specify 
 7962: the file type.
 7963: 
 7964: =cut
 7965: 
 7966: ######################################################
 7967: ######################################################
 7968: sub upfile_select_html {
 7969:     my %Types = (
 7970:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7971:                  semisv => &mt('Semicolon separated values'),
 7972:                  space => &mt('Space separated'),
 7973:                  tab   => &mt('Tabulator separated'),
 7974: #                 xml   => &mt('HTML/XML'),
 7975:                  );
 7976:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7977:         '<br />'.&mt('Type').': <select name="upfiletype">';
 7978:     foreach my $type (sort(keys(%Types))) {
 7979:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7980:     }
 7981:     $Str .= "</select>\n";
 7982:     return $Str;
 7983: }
 7984: 
 7985: sub get_samples {
 7986:     my ($records,$toget) = @_;
 7987:     my @samples=({});
 7988:     my $got=0;
 7989:     foreach my $rec (@$records) {
 7990: 	my %temp = &record_sep($rec);
 7991: 	if (! grep(/\S/, values(%temp))) { next; }
 7992: 	if (%temp) {
 7993: 	    $samples[$got]=\%temp;
 7994: 	    $got++;
 7995: 	    if ($got == $toget) { last; }
 7996: 	}
 7997:     }
 7998:     return \@samples;
 7999: }
 8000: 
 8001: ######################################################
 8002: ######################################################
 8003: 
 8004: =pod
 8005: 
 8006: =item * &csv_print_samples($r,$records)
 8007: 
 8008: Prints a table of sample values from each column uploaded $r is an
 8009: Apache Request ref, $records is an arrayref from
 8010: &Apache::loncommon::upfile_record_sep
 8011: 
 8012: =cut
 8013: 
 8014: ######################################################
 8015: ######################################################
 8016: sub csv_print_samples {
 8017:     my ($r,$records) = @_;
 8018:     my $samples = &get_samples($records,5);
 8019: 
 8020:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8021:               &start_data_table_header_row());
 8022:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8023:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
 8024:     }
 8025:     $r->print(&end_data_table_header_row());
 8026:     foreach my $hash (@$samples) {
 8027: 	$r->print(&start_data_table_row());
 8028: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8029: 	    $r->print('<td>');
 8030: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8031: 	    $r->print('</td>');
 8032: 	}
 8033: 	$r->print(&end_data_table_row());
 8034:     }
 8035:     $r->print(&end_data_table().'<br />'."\n");
 8036: }
 8037: 
 8038: ######################################################
 8039: ######################################################
 8040: 
 8041: =pod
 8042: 
 8043: =item * &csv_print_select_table($r,$records,$d)
 8044: 
 8045: Prints a table to create associations between values and table columns.
 8046: 
 8047: $r is an Apache Request ref,
 8048: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8049: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8050: 
 8051: =cut
 8052: 
 8053: ######################################################
 8054: ######################################################
 8055: sub csv_print_select_table {
 8056:     my ($r,$records,$d) = @_;
 8057:     my $i=0;
 8058:     my $samples = &get_samples($records,1);
 8059:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8060: 	      &start_data_table().&start_data_table_header_row().
 8061:               '<th>'.&mt('Attribute').'</th>'.
 8062:               '<th>'.&mt('Column').'</th>'.
 8063:               &end_data_table_header_row()."\n");
 8064:     foreach my $array_ref (@$d) {
 8065: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8066: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8067: 
 8068: 	$r->print('<td><select name"f'.$i.'"'.
 8069: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8070: 	$r->print('<option value="none"></option>');
 8071: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8072: 	    $r->print('<option value="'.$sample.'"'.
 8073:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8074:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8075: 	}
 8076: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8077: 	$i++;
 8078:     }
 8079:     $r->print(&end_data_table());
 8080:     $i--;
 8081:     return $i;
 8082: }
 8083: 
 8084: ######################################################
 8085: ######################################################
 8086: 
 8087: =pod
 8088: 
 8089: =item * &csv_samples_select_table($r,$records,$d)
 8090: 
 8091: Prints a table of sample values from the upload and can make associate samples to internal names.
 8092: 
 8093: $r is an Apache Request ref,
 8094: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8095: $d is an array of 2 element arrays (internal name, displayed name)
 8096: 
 8097: =cut
 8098: 
 8099: ######################################################
 8100: ######################################################
 8101: sub csv_samples_select_table {
 8102:     my ($r,$records,$d) = @_;
 8103:     my $i=0;
 8104:     #
 8105:     my $max_samples = 5;
 8106:     my $samples = &get_samples($records,$max_samples);
 8107:     $r->print(&start_data_table().
 8108:               &start_data_table_header_row().'<th>'.
 8109:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8110:               &end_data_table_header_row());
 8111: 
 8112:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8113: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8114: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8115: 	foreach my $option (@$d) {
 8116: 	    my ($value,$display,$defaultcol)=@{ $option };
 8117: 	    $r->print('<option value="'.$value.'"'.
 8118:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8119:                       $display.'</option>');
 8120: 	}
 8121: 	$r->print('</select></td><td>');
 8122: 	foreach my $line (0..($max_samples-1)) {
 8123: 	    if (defined($samples->[$line]{$key})) { 
 8124: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8125: 	    }
 8126: 	}
 8127: 	$r->print('</td>'.&end_data_table_row());
 8128: 	$i++;
 8129:     }
 8130:     $r->print(&end_data_table());
 8131:     $i--;
 8132:     return($i);
 8133: }
 8134: 
 8135: ######################################################
 8136: ######################################################
 8137: 
 8138: =pod
 8139: 
 8140: =item * &clean_excel_name($name)
 8141: 
 8142: Returns a replacement for $name which does not contain any illegal characters.
 8143: 
 8144: =cut
 8145: 
 8146: ######################################################
 8147: ######################################################
 8148: sub clean_excel_name {
 8149:     my ($name) = @_;
 8150:     $name =~ s/[:\*\?\/\\]//g;
 8151:     if (length($name) > 31) {
 8152:         $name = substr($name,0,31);
 8153:     }
 8154:     return $name;
 8155: }
 8156: 
 8157: =pod
 8158: 
 8159: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8160: 
 8161: Returns either 1 or undef
 8162: 
 8163: 1 if the part is to be hidden, undef if it is to be shown
 8164: 
 8165: Arguments are:
 8166: 
 8167: $id the id of the part to be checked
 8168: $symb, optional the symb of the resource to check
 8169: $udom, optional the domain of the user to check for
 8170: $uname, optional the username of the user to check for
 8171: 
 8172: =cut
 8173: 
 8174: sub check_if_partid_hidden {
 8175:     my ($id,$symb,$udom,$uname) = @_;
 8176:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8177: 					 $symb,$udom,$uname);
 8178:     my $truth=1;
 8179:     #if the string starts with !, then the list is the list to show not hide
 8180:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8181:     my @hiddenlist=split(/,/,$hiddenparts);
 8182:     foreach my $checkid (@hiddenlist) {
 8183: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8184:     }
 8185:     return !$truth;
 8186: }
 8187: 
 8188: 
 8189: ############################################################
 8190: ############################################################
 8191: 
 8192: =pod
 8193: 
 8194: =back 
 8195: 
 8196: =head1 cgi-bin script and graphing routines
 8197: 
 8198: =over 4
 8199: 
 8200: =item * &get_cgi_id()
 8201: 
 8202: Inputs: none
 8203: 
 8204: Returns an id which can be used to pass environment variables
 8205: to various cgi-bin scripts.  These environment variables will
 8206: be removed from the users environment after a given time by
 8207: the routine &Apache::lonnet::transfer_profile_to_env.
 8208: 
 8209: =cut
 8210: 
 8211: ############################################################
 8212: ############################################################
 8213: my $uniq=0;
 8214: sub get_cgi_id {
 8215:     $uniq=($uniq+1)%100000;
 8216:     return (time.'_'.$$.'_'.$uniq);
 8217: }
 8218: 
 8219: ############################################################
 8220: ############################################################
 8221: 
 8222: =pod
 8223: 
 8224: =item * &DrawBarGraph()
 8225: 
 8226: Facilitates the plotting of data in a (stacked) bar graph.
 8227: Puts plot definition data into the users environment in order for 
 8228: graph.png to plot it.  Returns an <img> tag for the plot.
 8229: The bars on the plot are labeled '1','2',...,'n'.
 8230: 
 8231: Inputs:
 8232: 
 8233: =over 4
 8234: 
 8235: =item $Title: string, the title of the plot
 8236: 
 8237: =item $xlabel: string, text describing the X-axis of the plot
 8238: 
 8239: =item $ylabel: string, text describing the Y-axis of the plot
 8240: 
 8241: =item $Max: scalar, the maximum Y value to use in the plot
 8242: If $Max is < any data point, the graph will not be rendered.
 8243: 
 8244: =item $colors: array ref holding the colors to be used for the data sets when
 8245: they are plotted.  If undefined, default values will be used.
 8246: 
 8247: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8248: 
 8249: =item @Values: An array of array references.  Each array reference holds data
 8250: to be plotted in a stacked bar chart.
 8251: 
 8252: =item If the final element of @Values is a hash reference the key/value
 8253: pairs will be added to the graph definition.
 8254: 
 8255: =back
 8256: 
 8257: Returns:
 8258: 
 8259: An <img> tag which references graph.png and the appropriate identifying
 8260: information for the plot.
 8261: 
 8262: =cut
 8263: 
 8264: ############################################################
 8265: ############################################################
 8266: sub DrawBarGraph {
 8267:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8268:     #
 8269:     if (! defined($colors)) {
 8270:         $colors = ['#33ff00', 
 8271:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8272:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8273:                   ]; 
 8274:     }
 8275:     my $extra_settings = {};
 8276:     if (ref($Values[-1]) eq 'HASH') {
 8277:         $extra_settings = pop(@Values);
 8278:     }
 8279:     #
 8280:     my $identifier = &get_cgi_id();
 8281:     my $id = 'cgi.'.$identifier;        
 8282:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8283:         return '';
 8284:     }
 8285:     #
 8286:     my @Labels;
 8287:     if (defined($labels)) {
 8288:         @Labels = @$labels;
 8289:     } else {
 8290:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8291:             push (@Labels,$i+1);
 8292:         }
 8293:     }
 8294:     #
 8295:     my $NumBars = scalar(@{$Values[0]});
 8296:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8297:     my %ValuesHash;
 8298:     my $NumSets=1;
 8299:     foreach my $array (@Values) {
 8300:         next if (! ref($array));
 8301:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8302:             join(',',@$array);
 8303:     }
 8304:     #
 8305:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8306:     if ($NumBars < 3) {
 8307:         $width = 120+$NumBars*32;
 8308:         $xskip = 1;
 8309:         $bar_width = 30;
 8310:     } elsif ($NumBars < 5) {
 8311:         $width = 120+$NumBars*20;
 8312:         $xskip = 1;
 8313:         $bar_width = 20;
 8314:     } elsif ($NumBars < 10) {
 8315:         $width = 120+$NumBars*15;
 8316:         $xskip = 1;
 8317:         $bar_width = 15;
 8318:     } elsif ($NumBars <= 25) {
 8319:         $width = 120+$NumBars*11;
 8320:         $xskip = 5;
 8321:         $bar_width = 8;
 8322:     } elsif ($NumBars <= 50) {
 8323:         $width = 120+$NumBars*8;
 8324:         $xskip = 5;
 8325:         $bar_width = 4;
 8326:     } else {
 8327:         $width = 120+$NumBars*8;
 8328:         $xskip = 5;
 8329:         $bar_width = 4;
 8330:     }
 8331:     #
 8332:     $Max = 1 if ($Max < 1);
 8333:     if ( int($Max) < $Max ) {
 8334:         $Max++;
 8335:         $Max = int($Max);
 8336:     }
 8337:     $Title  = '' if (! defined($Title));
 8338:     $xlabel = '' if (! defined($xlabel));
 8339:     $ylabel = '' if (! defined($ylabel));
 8340:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8341:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8342:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8343:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8344:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8345:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8346:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8347:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8348:     $ValuesHash{$id.'.height'}   = $height;
 8349:     $ValuesHash{$id.'.width'}    = $width;
 8350:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8351:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8352:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8353:     #
 8354:     # Deal with other parameters
 8355:     while (my ($key,$value) = each(%$extra_settings)) {
 8356:         $ValuesHash{$id.'.'.$key} = $value;
 8357:     }
 8358:     #
 8359:     &Apache::lonnet::appenv(\%ValuesHash);
 8360:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8361: }
 8362: 
 8363: ############################################################
 8364: ############################################################
 8365: 
 8366: =pod
 8367: 
 8368: =item * &DrawXYGraph()
 8369: 
 8370: Facilitates the plotting of data in an XY graph.
 8371: Puts plot definition data into the users environment in order for 
 8372: graph.png to plot it.  Returns an <img> tag for the plot.
 8373: 
 8374: Inputs:
 8375: 
 8376: =over 4
 8377: 
 8378: =item $Title: string, the title of the plot
 8379: 
 8380: =item $xlabel: string, text describing the X-axis of the plot
 8381: 
 8382: =item $ylabel: string, text describing the Y-axis of the plot
 8383: 
 8384: =item $Max: scalar, the maximum Y value to use in the plot
 8385: If $Max is < any data point, the graph will not be rendered.
 8386: 
 8387: =item $colors: Array ref containing the hex color codes for the data to be 
 8388: plotted in.  If undefined, default values will be used.
 8389: 
 8390: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8391: 
 8392: =item $Ydata: Array ref containing Array refs.  
 8393: Each of the contained arrays will be plotted as a separate curve.
 8394: 
 8395: =item %Values: hash indicating or overriding any default values which are 
 8396: passed to graph.png.  
 8397: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8398: 
 8399: =back
 8400: 
 8401: Returns:
 8402: 
 8403: An <img> tag which references graph.png and the appropriate identifying
 8404: information for the plot.
 8405: 
 8406: =cut
 8407: 
 8408: ############################################################
 8409: ############################################################
 8410: sub DrawXYGraph {
 8411:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8412:     #
 8413:     # Create the identifier for the graph
 8414:     my $identifier = &get_cgi_id();
 8415:     my $id = 'cgi.'.$identifier;
 8416:     #
 8417:     $Title  = '' if (! defined($Title));
 8418:     $xlabel = '' if (! defined($xlabel));
 8419:     $ylabel = '' if (! defined($ylabel));
 8420:     my %ValuesHash = 
 8421:         (
 8422:          $id.'.title'  => &escape($Title),
 8423:          $id.'.xlabel' => &escape($xlabel),
 8424:          $id.'.ylabel' => &escape($ylabel),
 8425:          $id.'.y_max_value'=> $Max,
 8426:          $id.'.labels'     => join(',',@$Xlabels),
 8427:          $id.'.PlotType'   => 'XY',
 8428:          );
 8429:     #
 8430:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8431:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8432:     }
 8433:     #
 8434:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8435:         return '';
 8436:     }
 8437:     my $NumSets=1;
 8438:     foreach my $array (@{$Ydata}){
 8439:         next if (! ref($array));
 8440:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8441:     }
 8442:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8443:     #
 8444:     # Deal with other parameters
 8445:     while (my ($key,$value) = each(%Values)) {
 8446:         $ValuesHash{$id.'.'.$key} = $value;
 8447:     }
 8448:     #
 8449:     &Apache::lonnet::appenv(\%ValuesHash);
 8450:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8451: }
 8452: 
 8453: ############################################################
 8454: ############################################################
 8455: 
 8456: =pod
 8457: 
 8458: =item * &DrawXYYGraph()
 8459: 
 8460: Facilitates the plotting of data in an XY graph with two Y axes.
 8461: Puts plot definition data into the users environment in order for 
 8462: graph.png to plot it.  Returns an <img> tag for the plot.
 8463: 
 8464: Inputs:
 8465: 
 8466: =over 4
 8467: 
 8468: =item $Title: string, the title of the plot
 8469: 
 8470: =item $xlabel: string, text describing the X-axis of the plot
 8471: 
 8472: =item $ylabel: string, text describing the Y-axis of the plot
 8473: 
 8474: =item $colors: Array ref containing the hex color codes for the data to be 
 8475: plotted in.  If undefined, default values will be used.
 8476: 
 8477: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8478: 
 8479: =item $Ydata1: The first data set
 8480: 
 8481: =item $Min1: The minimum value of the left Y-axis
 8482: 
 8483: =item $Max1: The maximum value of the left Y-axis
 8484: 
 8485: =item $Ydata2: The second data set
 8486: 
 8487: =item $Min2: The minimum value of the right Y-axis
 8488: 
 8489: =item $Max2: The maximum value of the left Y-axis
 8490: 
 8491: =item %Values: hash indicating or overriding any default values which are 
 8492: passed to graph.png.  
 8493: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8494: 
 8495: =back
 8496: 
 8497: Returns:
 8498: 
 8499: An <img> tag which references graph.png and the appropriate identifying
 8500: information for the plot.
 8501: 
 8502: =cut
 8503: 
 8504: ############################################################
 8505: ############################################################
 8506: sub DrawXYYGraph {
 8507:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8508:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8509:     #
 8510:     # Create the identifier for the graph
 8511:     my $identifier = &get_cgi_id();
 8512:     my $id = 'cgi.'.$identifier;
 8513:     #
 8514:     $Title  = '' if (! defined($Title));
 8515:     $xlabel = '' if (! defined($xlabel));
 8516:     $ylabel = '' if (! defined($ylabel));
 8517:     my %ValuesHash = 
 8518:         (
 8519:          $id.'.title'  => &escape($Title),
 8520:          $id.'.xlabel' => &escape($xlabel),
 8521:          $id.'.ylabel' => &escape($ylabel),
 8522:          $id.'.labels' => join(',',@$Xlabels),
 8523:          $id.'.PlotType' => 'XY',
 8524:          $id.'.NumSets' => 2,
 8525:          $id.'.two_axes' => 1,
 8526:          $id.'.y1_max_value' => $Max1,
 8527:          $id.'.y1_min_value' => $Min1,
 8528:          $id.'.y2_max_value' => $Max2,
 8529:          $id.'.y2_min_value' => $Min2,
 8530:          );
 8531:     #
 8532:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8533:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8534:     }
 8535:     #
 8536:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8537:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8538:         return '';
 8539:     }
 8540:     my $NumSets=1;
 8541:     foreach my $array ($Ydata1,$Ydata2){
 8542:         next if (! ref($array));
 8543:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8544:     }
 8545:     #
 8546:     # Deal with other parameters
 8547:     while (my ($key,$value) = each(%Values)) {
 8548:         $ValuesHash{$id.'.'.$key} = $value;
 8549:     }
 8550:     #
 8551:     &Apache::lonnet::appenv(\%ValuesHash);
 8552:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8553: }
 8554: 
 8555: ############################################################
 8556: ############################################################
 8557: 
 8558: =pod
 8559: 
 8560: =back 
 8561: 
 8562: =head1 Statistics helper routines?  
 8563: 
 8564: Bad place for them but what the hell.
 8565: 
 8566: =over 4
 8567: 
 8568: =item * &chartlink()
 8569: 
 8570: Returns a link to the chart for a specific student.  
 8571: 
 8572: Inputs:
 8573: 
 8574: =over 4
 8575: 
 8576: =item $linktext: The text of the link
 8577: 
 8578: =item $sname: The students username
 8579: 
 8580: =item $sdomain: The students domain
 8581: 
 8582: =back
 8583: 
 8584: =back
 8585: 
 8586: =cut
 8587: 
 8588: ############################################################
 8589: ############################################################
 8590: sub chartlink {
 8591:     my ($linktext, $sname, $sdomain) = @_;
 8592:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8593:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8594:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8595:        '">'.$linktext.'</a>';
 8596: }
 8597: 
 8598: #######################################################
 8599: #######################################################
 8600: 
 8601: =pod
 8602: 
 8603: =head1 Course Environment Routines
 8604: 
 8605: =over 4
 8606: 
 8607: =item * &restore_course_settings()
 8608: 
 8609: =item * &store_course_settings()
 8610: 
 8611: Restores/Store indicated form parameters from the course environment.
 8612: Will not overwrite existing values of the form parameters.
 8613: 
 8614: Inputs: 
 8615: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8616: 
 8617: a hash ref describing the data to be stored.  For example:
 8618:    
 8619: %Save_Parameters = ('Status' => 'scalar',
 8620:     'chartoutputmode' => 'scalar',
 8621:     'chartoutputdata' => 'scalar',
 8622:     'Section' => 'array',
 8623:     'Group' => 'array',
 8624:     'StudentData' => 'array',
 8625:     'Maps' => 'array');
 8626: 
 8627: Returns: both routines return nothing
 8628: 
 8629: =back
 8630: 
 8631: =cut
 8632: 
 8633: #######################################################
 8634: #######################################################
 8635: sub store_course_settings {
 8636:     return &store_settings($env{'request.course.id'},@_);
 8637: }
 8638: 
 8639: sub store_settings {
 8640:     # save to the environment
 8641:     # appenv the same items, just to be safe
 8642:     my $udom  = $env{'user.domain'};
 8643:     my $uname = $env{'user.name'};
 8644:     my ($context,$prefix,$Settings) = @_;
 8645:     my %SaveHash;
 8646:     my %AppHash;
 8647:     while (my ($setting,$type) = each(%$Settings)) {
 8648:         my $basename = join('.','internal',$context,$prefix,$setting);
 8649:         my $envname = 'environment.'.$basename;
 8650:         if (exists($env{'form.'.$setting})) {
 8651:             # Save this value away
 8652:             if ($type eq 'scalar' &&
 8653:                 (! exists($env{$envname}) || 
 8654:                  $env{$envname} ne $env{'form.'.$setting})) {
 8655:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8656:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8657:             } elsif ($type eq 'array') {
 8658:                 my $stored_form;
 8659:                 if (ref($env{'form.'.$setting})) {
 8660:                     $stored_form = join(',',
 8661:                                         map {
 8662:                                             &escape($_);
 8663:                                         } sort(@{$env{'form.'.$setting}}));
 8664:                 } else {
 8665:                     $stored_form = 
 8666:                         &escape($env{'form.'.$setting});
 8667:                 }
 8668:                 # Determine if the array contents are the same.
 8669:                 if ($stored_form ne $env{$envname}) {
 8670:                     $SaveHash{$basename} = $stored_form;
 8671:                     $AppHash{$envname}   = $stored_form;
 8672:                 }
 8673:             }
 8674:         }
 8675:     }
 8676:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8677:                                           $udom,$uname);
 8678:     if ($put_result !~ /^(ok|delayed)/) {
 8679:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8680:                                  'got error:'.$put_result);
 8681:     }
 8682:     # Make sure these settings stick around in this session, too
 8683:     &Apache::lonnet::appenv(\%AppHash);
 8684:     return;
 8685: }
 8686: 
 8687: sub restore_course_settings {
 8688:     return &restore_settings($env{'request.course.id'},@_);
 8689: }
 8690: 
 8691: sub restore_settings {
 8692:     my ($context,$prefix,$Settings) = @_;
 8693:     while (my ($setting,$type) = each(%$Settings)) {
 8694:         next if (exists($env{'form.'.$setting}));
 8695:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8696:             '.'.$setting;
 8697:         if (exists($env{$envname})) {
 8698:             if ($type eq 'scalar') {
 8699:                 $env{'form.'.$setting} = $env{$envname};
 8700:             } elsif ($type eq 'array') {
 8701:                 $env{'form.'.$setting} = [ 
 8702:                                            map { 
 8703:                                                &unescape($_); 
 8704:                                            } split(',',$env{$envname})
 8705:                                            ];
 8706:             }
 8707:         }
 8708:     }
 8709: }
 8710: 
 8711: #######################################################
 8712: #######################################################
 8713: 
 8714: =pod
 8715: 
 8716: =head1 Domain E-mail Routines  
 8717: 
 8718: =over 4
 8719: 
 8720: =item * &build_recipient_list()
 8721: 
 8722: Build recipient lists for five types of e-mail:
 8723: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8724: (d) Help requests, (e) Course requests needing approval,  generated by
 8725: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
 8726: loncoursequeueadmin.pm respectively.
 8727: 
 8728: Inputs:
 8729: defmail (scalar - email address of default recipient), 
 8730: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8731: defdom (domain for which to retrieve configuration settings),
 8732: origmail (scalar - email address of recipient from loncapa.conf, 
 8733: i.e., predates configuration by DC via domainprefs.pm 
 8734: 
 8735: Returns: comma separated list of addresses to which to send e-mail.
 8736: 
 8737: =back
 8738: 
 8739: =cut
 8740: 
 8741: ############################################################
 8742: ############################################################
 8743: sub build_recipient_list {
 8744:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8745:     my @recipients;
 8746:     my $otheremails;
 8747:     my %domconfig =
 8748:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8749:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8750:         if (exists($domconfig{'contacts'}{$mailing})) {
 8751:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8752:                 my @contacts = ('adminemail','supportemail');
 8753:                 foreach my $item (@contacts) {
 8754:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8755:                         my $addr = $domconfig{'contacts'}{$item};
 8756:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8757:                             push(@recipients,$addr);
 8758:                         }
 8759:                     }
 8760:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8761:                 }
 8762:             }
 8763:         } elsif ($origmail ne '') {
 8764:             push(@recipients,$origmail);
 8765:         }
 8766:     } elsif ($origmail ne '') {
 8767:         push(@recipients,$origmail);
 8768:     }
 8769:     if (defined($defmail)) {
 8770:         if ($defmail ne '') {
 8771:             push(@recipients,$defmail);
 8772:         }
 8773:     }
 8774:     if ($otheremails) {
 8775:         my @others;
 8776:         if ($otheremails =~ /,/) {
 8777:             @others = split(/,/,$otheremails);
 8778:         } else {
 8779:             push(@others,$otheremails);
 8780:         }
 8781:         foreach my $addr (@others) {
 8782:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8783:                 push(@recipients,$addr);
 8784:             }
 8785:         }
 8786:     }
 8787:     my $recipientlist = join(',',@recipients); 
 8788:     return $recipientlist;
 8789: }
 8790: 
 8791: ############################################################
 8792: ############################################################
 8793: 
 8794: =pod
 8795: 
 8796: =head1 Course Catalog Routines
 8797: 
 8798: =over 4
 8799: 
 8800: =item * &gather_categories()
 8801: 
 8802: Converts category definitions - keys of categories hash stored in  
 8803: coursecategories in configuration.db on the primary library server in a 
 8804: domain - to an array.  Also generates javascript and idx hash used to 
 8805: generate Domain Coordinator interface for editing Course Categories.
 8806: 
 8807: Inputs:
 8808: 
 8809: categories (reference to hash of category definitions).
 8810: 
 8811: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8812:       categories and subcategories).
 8813: 
 8814: idx (reference to hash of counters used in Domain Coordinator interface for 
 8815:       editing Course Categories).
 8816: 
 8817: jsarray (reference to array of categories used to create Javascript arrays for
 8818:          Domain Coordinator interface for editing Course Categories).
 8819: 
 8820: Returns: nothing
 8821: 
 8822: Side effects: populates cats, idx and jsarray. 
 8823: 
 8824: =cut
 8825: 
 8826: sub gather_categories {
 8827:     my ($categories,$cats,$idx,$jsarray) = @_;
 8828:     my %counters;
 8829:     my $num = 0;
 8830:     foreach my $item (keys(%{$categories})) {
 8831:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8832:         if ($container eq '' && $depth == 0) {
 8833:             $cats->[$depth][$categories->{$item}] = $cat;
 8834:         } else {
 8835:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8836:         }
 8837:         my ($escitem,$tail) = split(/:/,$item,2);
 8838:         if ($counters{$tail} eq '') {
 8839:             $counters{$tail} = $num;
 8840:             $num ++;
 8841:         }
 8842:         if (ref($idx) eq 'HASH') {
 8843:             $idx->{$item} = $counters{$tail};
 8844:         }
 8845:         if (ref($jsarray) eq 'ARRAY') {
 8846:             push(@{$jsarray->[$counters{$tail}]},$item);
 8847:         }
 8848:     }
 8849:     return;
 8850: }
 8851: 
 8852: =pod
 8853: 
 8854: =item * &extract_categories()
 8855: 
 8856: Used to generate breadcrumb trails for course categories.
 8857: 
 8858: Inputs:
 8859: 
 8860: categories (reference to hash of category definitions).
 8861: 
 8862: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8863:       categories and subcategories).
 8864: 
 8865: trails (reference to array of breacrumb trails for each category).
 8866: 
 8867: allitems (reference to hash - key is category key 
 8868:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8869: 
 8870: idx (reference to hash of counters used in Domain Coordinator interface for
 8871:       editing Course Categories).
 8872: 
 8873: jsarray (reference to array of categories used to create Javascript arrays for
 8874:          Domain Coordinator interface for editing Course Categories).
 8875: 
 8876: subcats (reference to hash of arrays containing all subcategories within each 
 8877:          category, -recursive)
 8878: 
 8879: Returns: nothing
 8880: 
 8881: Side effects: populates trails and allitems hash references.
 8882: 
 8883: =cut
 8884: 
 8885: sub extract_categories {
 8886:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8887:     if (ref($categories) eq 'HASH') {
 8888:         &gather_categories($categories,$cats,$idx,$jsarray);
 8889:         if (ref($cats->[0]) eq 'ARRAY') {
 8890:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8891:                 my $name = $cats->[0][$i];
 8892:                 my $item = &escape($name).'::0';
 8893:                 my $trailstr;
 8894:                 if ($name eq 'instcode') {
 8895:                     $trailstr = &mt('Official courses (with institutional codes)');
 8896:                 } else {
 8897:                     $trailstr = $name;
 8898:                 }
 8899:                 if ($allitems->{$item} eq '') {
 8900:                     push(@{$trails},$trailstr);
 8901:                     $allitems->{$item} = scalar(@{$trails})-1;
 8902:                 }
 8903:                 my @parents = ($name);
 8904:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8905:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8906:                         my $category = $cats->[1]{$name}[$j];
 8907:                         if (ref($subcats) eq 'HASH') {
 8908:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8909:                         }
 8910:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8911:                     }
 8912:                 } else {
 8913:                     if (ref($subcats) eq 'HASH') {
 8914:                         $subcats->{$item} = [];
 8915:                     }
 8916:                 }
 8917:             }
 8918:         }
 8919:     }
 8920:     return;
 8921: }
 8922: 
 8923: =pod
 8924: 
 8925: =item *&recurse_categories()
 8926: 
 8927: Recursively used to generate breadcrumb trails for course categories.
 8928: 
 8929: Inputs:
 8930: 
 8931: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8932:       categories and subcategories).
 8933: 
 8934: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8935: 
 8936: category (current course category, for which breadcrumb trail is being generated).
 8937: 
 8938: trails (reference to array of breadcrumb trails for each category).
 8939: 
 8940: allitems (reference to hash - key is category key
 8941:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8942: 
 8943: parents (array containing containers directories for current category, 
 8944:          back to top level). 
 8945: 
 8946: Returns: nothing
 8947: 
 8948: Side effects: populates trails and allitems hash references
 8949: 
 8950: =cut
 8951: 
 8952: sub recurse_categories {
 8953:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8954:     my $shallower = $depth - 1;
 8955:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8956:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8957:             my $name = $cats->[$depth]{$category}[$k];
 8958:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8959:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8960:             if ($allitems->{$item} eq '') {
 8961:                 push(@{$trails},$trailstr);
 8962:                 $allitems->{$item} = scalar(@{$trails})-1;
 8963:             }
 8964:             my $deeper = $depth+1;
 8965:             push(@{$parents},$category);
 8966:             if (ref($subcats) eq 'HASH') {
 8967:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8968:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8969:                     my $higher;
 8970:                     if ($j > 0) {
 8971:                         $higher = &escape($parents->[$j]).':'.
 8972:                                   &escape($parents->[$j-1]).':'.$j;
 8973:                     } else {
 8974:                         $higher = &escape($parents->[$j]).'::'.$j;
 8975:                     }
 8976:                     push(@{$subcats->{$higher}},$subcat);
 8977:                 }
 8978:             }
 8979:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8980:                                 $subcats);
 8981:             pop(@{$parents});
 8982:         }
 8983:     } else {
 8984:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8985:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8986:         if ($allitems->{$item} eq '') {
 8987:             push(@{$trails},$trailstr);
 8988:             $allitems->{$item} = scalar(@{$trails})-1;
 8989:         }
 8990:     }
 8991:     return;
 8992: }
 8993: 
 8994: =pod
 8995: 
 8996: =item *&assign_categories_table()
 8997: 
 8998: Create a datatable for display of hierarchical categories in a domain,
 8999: with checkboxes to allow a course to be categorized. 
 9000: 
 9001: Inputs:
 9002: 
 9003: cathash - reference to hash of categories defined for the domain (from
 9004:           configuration.db)
 9005: 
 9006: currcat - scalar with an & separated list of categories assigned to a course. 
 9007: 
 9008: Returns: $output (markup to be displayed) 
 9009: 
 9010: =cut
 9011: 
 9012: sub assign_categories_table {
 9013:     my ($cathash,$currcat) = @_;
 9014:     my $output;
 9015:     if (ref($cathash) eq 'HASH') {
 9016:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9017:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9018:         $maxdepth = scalar(@cats);
 9019:         if (@cats > 0) {
 9020:             my $itemcount = 0;
 9021:             if (ref($cats[0]) eq 'ARRAY') {
 9022:                 $output = &Apache::loncommon::start_data_table();
 9023:                 my @currcategories;
 9024:                 if ($currcat ne '') {
 9025:                     @currcategories = split('&',$currcat);
 9026:                 }
 9027:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9028:                     my $parent = $cats[0][$i];
 9029:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9030:                     next if ($parent eq 'instcode');
 9031:                     my $item = &escape($parent).'::0';
 9032:                     my $checked = '';
 9033:                     if (@currcategories > 0) {
 9034:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9035:                             $checked = ' checked="checked" ';
 9036:                         }
 9037:                     }
 9038:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9039:                                '<input type="checkbox" name="usecategory" value="'.
 9040:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9041:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9042:                     my $depth = 1;
 9043:                     push(@path,$parent);
 9044:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9045:                     pop(@path);
 9046:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9047:                     $itemcount ++;
 9048:                 }
 9049:                 $output .= &Apache::loncommon::end_data_table();
 9050:             }
 9051:         }
 9052:     }
 9053:     return $output;
 9054: }
 9055: 
 9056: =pod
 9057: 
 9058: =item *&assign_category_rows()
 9059: 
 9060: Create a datatable row for display of nested categories in a domain,
 9061: with checkboxes to allow a course to be categorized,called recursively.
 9062: 
 9063: Inputs:
 9064: 
 9065: itemcount - track row number for alternating colors
 9066: 
 9067: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9068:       categories and subcategories.
 9069: 
 9070: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9071: 
 9072: parent - parent of current category item
 9073: 
 9074: path - Array containing all categories back up through the hierarchy from the
 9075:        current category to the top level.
 9076: 
 9077: currcategories - reference to array of current categories assigned to the course
 9078: 
 9079: Returns: $output (markup to be displayed).
 9080: 
 9081: =cut
 9082: 
 9083: sub assign_category_rows {
 9084:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9085:     my ($text,$name,$item,$chgstr);
 9086:     if (ref($cats) eq 'ARRAY') {
 9087:         my $maxdepth = scalar(@{$cats});
 9088:         if (ref($cats->[$depth]) eq 'HASH') {
 9089:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9090:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9091:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9092:                 $text .= '<td><table class="LC_datatable">';
 9093:                 for (my $j=0; $j<$numchildren; $j++) {
 9094:                     $name = $cats->[$depth]{$parent}[$j];
 9095:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9096:                     my $deeper = $depth+1;
 9097:                     my $checked = '';
 9098:                     if (ref($currcategories) eq 'ARRAY') {
 9099:                         if (@{$currcategories} > 0) {
 9100:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9101:                                 $checked = ' checked="checked" ';
 9102:                             }
 9103:                         }
 9104:                     }
 9105:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9106:                              '<input type="checkbox" name="usecategory" value="'.
 9107:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9108:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9109:                              '</td><td>';
 9110:                     if (ref($path) eq 'ARRAY') {
 9111:                         push(@{$path},$name);
 9112:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9113:                         pop(@{$path});
 9114:                     }
 9115:                     $text .= '</td></tr>';
 9116:                 }
 9117:                 $text .= '</table></td>';
 9118:             }
 9119:         }
 9120:     }
 9121:     return $text;
 9122: }
 9123: 
 9124: ############################################################
 9125: ############################################################
 9126: 
 9127: 
 9128: sub commit_customrole {
 9129:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9130:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9131:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9132:                          ($end?', ending '.localtime($end):'').': <b>'.
 9133:               &Apache::lonnet::assigncustomrole(
 9134:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9135:                  '</b><br />';
 9136:     return $output;
 9137: }
 9138: 
 9139: sub commit_standardrole {
 9140:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9141:     my ($output,$logmsg,$linefeed);
 9142:     if ($context eq 'auto') {
 9143:         $linefeed = "\n";
 9144:     } else {
 9145:         $linefeed = "<br />\n";
 9146:     }  
 9147:     if ($three eq 'st') {
 9148:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9149:                                          $one,$two,$sec,$context);
 9150:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9151:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9152:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9153:         } else {
 9154:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9155:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9156:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9157:             if ($context eq 'auto') {
 9158:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9159:             } else {
 9160:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9161:                &mt('Add to classlist').': <b>ok</b>';
 9162:             }
 9163:             $output .= $linefeed;
 9164:         }
 9165:     } else {
 9166:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9167:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9168:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9169:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9170:         if ($context eq 'auto') {
 9171:             $output .= $result.$linefeed;
 9172:         } else {
 9173:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9174:         }
 9175:     }
 9176:     return $output;
 9177: }
 9178: 
 9179: sub commit_studentrole {
 9180:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9181:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9182:     if ($context eq 'auto') {
 9183:         $linefeed = "\n";
 9184:     } else {
 9185:         $linefeed = '<br />'."\n";
 9186:     }
 9187:     if (defined($one) && defined($two)) {
 9188:         my $cid=$one.'_'.$two;
 9189:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9190:         my $secchange = 0;
 9191:         my $expire_role_result;
 9192:         my $modify_section_result;
 9193:         if ($oldsec ne '-1') { 
 9194:             if ($oldsec ne $sec) {
 9195:                 $secchange = 1;
 9196:                 my $now = time;
 9197:                 my $uurl='/'.$cid;
 9198:                 $uurl=~s/\_/\//g;
 9199:                 if ($oldsec) {
 9200:                     $uurl.='/'.$oldsec;
 9201:                 }
 9202:                 $oldsecurl = $uurl;
 9203:                 $expire_role_result = 
 9204:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9205:                 if ($env{'request.course.sec'} ne '') { 
 9206:                     if ($expire_role_result eq 'refused') {
 9207:                         my @roles = ('st');
 9208:                         my @statuses = ('previous');
 9209:                         my @roledoms = ($one);
 9210:                         my $withsec = 1;
 9211:                         my %roleshash = 
 9212:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9213:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9214:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9215:                             my ($oldstart,$oldend) = 
 9216:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9217:                             if ($oldend > 0 && $oldend <= $now) {
 9218:                                 $expire_role_result = 'ok';
 9219:                             }
 9220:                         }
 9221:                     }
 9222:                 }
 9223:                 $result = $expire_role_result;
 9224:             }
 9225:         }
 9226:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9227:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9228:             if ($modify_section_result =~ /^ok/) {
 9229:                 if ($secchange == 1) {
 9230:                     if ($sec eq '') {
 9231:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9232:                     } else {
 9233:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9234:                     }
 9235:                 } elsif ($oldsec eq '-1') {
 9236:                     if ($sec eq '') {
 9237:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9238:                     } else {
 9239:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9240:                     }
 9241:                 } else {
 9242:                     if ($sec eq '') {
 9243:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9244:                     } else {
 9245:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9246:                     }
 9247:                 }
 9248:             } else {
 9249:                 if ($secchange) {       
 9250:                     $$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;
 9251:                 } else {
 9252:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9253:                 }
 9254:             }
 9255:             $result = $modify_section_result;
 9256:         } elsif ($secchange == 1) {
 9257:             if ($oldsec eq '') {
 9258:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9259:             } else {
 9260:                 $$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;
 9261:             }
 9262:             if ($expire_role_result eq 'refused') {
 9263:                 my $newsecurl = '/'.$cid;
 9264:                 $newsecurl =~ s/\_/\//g;
 9265:                 if ($sec ne '') {
 9266:                     $newsecurl.='/'.$sec;
 9267:                 }
 9268:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9269:                     if ($sec eq '') {
 9270:                         $$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;
 9271:                     } else {
 9272:                         $$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;
 9273:                     }
 9274:                 }
 9275:             }
 9276:         }
 9277:     } else {
 9278:         $$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;
 9279:         $result = "error: incomplete course id\n";
 9280:     }
 9281:     return $result;
 9282: }
 9283: 
 9284: ############################################################
 9285: ############################################################
 9286: 
 9287: sub check_clone {
 9288:     my ($args,$linefeed) = @_;
 9289:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9290:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9291:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9292:     my $clonemsg;
 9293:     my $can_clone = 0;
 9294: 
 9295:     if ($clonehome eq 'no_host') {
 9296:         $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'});     
 9297:     } else {
 9298: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9299:         if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
 9300:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
 9301:  	    $can_clone = 1;
 9302: 	} else {
 9303: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9304: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9305: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9306:             if (grep(/^\*$/,@cloners)) {
 9307:                 $can_clone = 1;
 9308:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9309:                 $can_clone = 1;
 9310:             } else {
 9311: 	        my %roleshash =
 9312: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9313: 					 $args->{'ccdomain'},
 9314:                                          'userroles',['active'],['cc'],
 9315: 					 [$args->{'clonedomain'}]);
 9316: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9317: 		    $can_clone = 1;
 9318: 	        } else {
 9319:                     $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'});
 9320: 	        }
 9321: 	    }
 9322:         }
 9323:     }
 9324:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9325: }
 9326: 
 9327: sub construct_course {
 9328:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
 9329:     my $outcome;
 9330:     my $linefeed =  '<br />'."\n";
 9331:     if ($context eq 'auto') {
 9332:         $linefeed = "\n";
 9333:     }
 9334: 
 9335: #
 9336: # Are we cloning?
 9337: #
 9338:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9339:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9340: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9341: 	if ($context ne 'auto') {
 9342:             if ($clonemsg ne '') {
 9343: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9344:             }
 9345: 	}
 9346: 	$outcome .= $clonemsg.$linefeed;
 9347: 
 9348:         if (!$can_clone) {
 9349: 	    return (0,$outcome);
 9350: 	}
 9351:     }
 9352: 
 9353: #
 9354: # Open course
 9355: #
 9356:     my $crstype = lc($args->{'crstype'});
 9357:     my %cenv=();
 9358:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9359:                                              $args->{'cdescr'},
 9360:                                              $args->{'curl'},
 9361:                                              $args->{'course_home'},
 9362:                                              $args->{'nonstandard'},
 9363:                                              $args->{'crscode'},
 9364:                                              $args->{'ccuname'}.':'.
 9365:                                              $args->{'ccdomain'},
 9366:                                              $args->{'crstype'},
 9367:                                              $cnum,$context,$category);
 9368: 
 9369: 
 9370:     # Note: The testing routines depend on this being output; see 
 9371:     # Utils::Course. This needs to at least be output as a comment
 9372:     # if anyone ever decides to not show this, and Utils::Course::new
 9373:     # will need to be suitably modified.
 9374:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9375: #
 9376: # Check if created correctly
 9377: #
 9378:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9379:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9380:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9381: 
 9382: #
 9383: # Do the cloning
 9384: #   
 9385:     if ($can_clone && $cloneid) {
 9386: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9387: 	if ($context ne 'auto') {
 9388: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9389: 	}
 9390: 	$outcome .= $clonemsg.$linefeed;
 9391: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9392: # Copy all files
 9393: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9394: # Restore URL
 9395: 	$cenv{'url'}=$oldcenv{'url'};
 9396: # Restore title
 9397: 	$cenv{'description'}=$oldcenv{'description'};
 9398: # Mark as cloned
 9399: 	$cenv{'clonedfrom'}=$cloneid;
 9400: # Need to clone grading mode
 9401:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9402:         $cenv{'grading'}=$newenv{'grading'};
 9403: # Do not clone these environment entries
 9404:         &Apache::lonnet::del('environment',
 9405:                   ['default_enrollment_start_date',
 9406:                    'default_enrollment_end_date',
 9407:                    'question.email',
 9408:                    'policy.email',
 9409:                    'comment.email',
 9410:                    'pch.users.denied',
 9411:                    'plc.users.denied',
 9412:                    'hidefromcat',
 9413:                    'categories'],
 9414:                    $$crsudom,$$crsunum);
 9415:     }
 9416: 
 9417: #
 9418: # Set environment (will override cloned, if existing)
 9419: #
 9420:     my @sections = ();
 9421:     my @xlists = ();
 9422:     if ($args->{'crstype'}) {
 9423:         $cenv{'type'}=$args->{'crstype'};
 9424:     }
 9425:     if ($args->{'crsid'}) {
 9426:         $cenv{'courseid'}=$args->{'crsid'};
 9427:     }
 9428:     if ($args->{'crscode'}) {
 9429:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9430:     }
 9431:     if ($args->{'crsquota'} ne '') {
 9432:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9433:     } else {
 9434:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9435:     }
 9436:     if ($args->{'ccuname'}) {
 9437:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9438:                                         ':'.$args->{'ccdomain'};
 9439:     } else {
 9440:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9441:     }
 9442:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9443:     if ($args->{'crssections'}) {
 9444:         $cenv{'internal.sectionnums'} = '';
 9445:         if ($args->{'crssections'} =~ m/,/) {
 9446:             @sections = split/,/,$args->{'crssections'};
 9447:         } else {
 9448:             $sections[0] = $args->{'crssections'};
 9449:         }
 9450:         if (@sections > 0) {
 9451:             foreach my $item (@sections) {
 9452:                 my ($sec,$gp) = split/:/,$item;
 9453:                 my $class = $args->{'crscode'}.$sec;
 9454:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9455:                 $cenv{'internal.sectionnums'} .= $item.',';
 9456:                 unless ($addcheck eq 'ok') {
 9457:                     push @badclasses, $class;
 9458:                 }
 9459:             }
 9460:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9461:         }
 9462:     }
 9463: # do not hide course coordinator from staff listing, 
 9464: # even if privileged
 9465:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9466: # add crosslistings
 9467:     if ($args->{'crsxlist'}) {
 9468:         $cenv{'internal.crosslistings'}='';
 9469:         if ($args->{'crsxlist'} =~ m/,/) {
 9470:             @xlists = split/,/,$args->{'crsxlist'};
 9471:         } else {
 9472:             $xlists[0] = $args->{'crsxlist'};
 9473:         }
 9474:         if (@xlists > 0) {
 9475:             foreach my $item (@xlists) {
 9476:                 my ($xl,$gp) = split/:/,$item;
 9477:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9478:                 $cenv{'internal.crosslistings'} .= $item.',';
 9479:                 unless ($addcheck eq 'ok') {
 9480:                     push @badclasses, $xl;
 9481:                 }
 9482:             }
 9483:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9484:         }
 9485:     }
 9486:     if ($args->{'autoadds'}) {
 9487:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9488:     }
 9489:     if ($args->{'autodrops'}) {
 9490:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9491:     }
 9492: # check for notification of enrollment changes
 9493:     my @notified = ();
 9494:     if ($args->{'notify_owner'}) {
 9495:         if ($args->{'ccuname'} ne '') {
 9496:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9497:         }
 9498:     }
 9499:     if ($args->{'notify_dc'}) {
 9500:         if ($uname ne '') { 
 9501:             push(@notified,$uname.':'.$udom);
 9502:         }
 9503:     }
 9504:     if (@notified > 0) {
 9505:         my $notifylist;
 9506:         if (@notified > 1) {
 9507:             $notifylist = join(',',@notified);
 9508:         } else {
 9509:             $notifylist = $notified[0];
 9510:         }
 9511:         $cenv{'internal.notifylist'} = $notifylist;
 9512:     }
 9513:     if (@badclasses > 0) {
 9514:         my %lt=&Apache::lonlocal::texthash(
 9515:                 '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',
 9516:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9517:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9518:         );
 9519:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9520:                            ' ('.$lt{'adby'}.')';
 9521:         if ($context eq 'auto') {
 9522:             $outcome .= $badclass_msg.$linefeed;
 9523:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9524:             foreach my $item (@badclasses) {
 9525:                 if ($context eq 'auto') {
 9526:                     $outcome .= " - $item\n";
 9527:                 } else {
 9528:                     $outcome .= "<li>$item</li>\n";
 9529:                 }
 9530:             }
 9531:             if ($context eq 'auto') {
 9532:                 $outcome .= $linefeed;
 9533:             } else {
 9534:                 $outcome .= "</ul><br /><br /></div>\n";
 9535:             }
 9536:         } 
 9537:     }
 9538:     if ($args->{'no_end_date'}) {
 9539:         $args->{'endaccess'} = 0;
 9540:     }
 9541:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9542:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9543:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9544:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9545:     if ($args->{'showphotos'}) {
 9546:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9547:     }
 9548:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9549:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9550:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9551:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9552:             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'); 
 9553:             if ($context eq 'auto') {
 9554:                 $outcome .= $krb_msg;
 9555:             } else {
 9556:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9557:             }
 9558:             $outcome .= $linefeed;
 9559:         }
 9560:     }
 9561:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9562:        if ($args->{'setpolicy'}) {
 9563:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9564:        }
 9565:        if ($args->{'setcontent'}) {
 9566:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9567:        }
 9568:     }
 9569:     if ($args->{'reshome'}) {
 9570: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9571: 	$cenv{'reshome'}=~s/\/+$/\//;
 9572:     }
 9573: #
 9574: # course has keyed access
 9575: #
 9576:     if ($args->{'setkeys'}) {
 9577:        $cenv{'keyaccess'}='yes';
 9578:     }
 9579: # if specified, key authority is not course, but user
 9580: # only active if keyaccess is yes
 9581:     if ($args->{'keyauth'}) {
 9582: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9583: 	$user = &LONCAPA::clean_username($user);
 9584: 	$domain = &LONCAPA::clean_username($domain);
 9585: 	if ($user ne '' && $domain ne '') {
 9586: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9587: 	}
 9588:     }
 9589: 
 9590:     if ($args->{'disresdis'}) {
 9591:         $cenv{'pch.roles.denied'}='st';
 9592:     }
 9593:     if ($args->{'disablechat'}) {
 9594:         $cenv{'plc.roles.denied'}='st';
 9595:     }
 9596: 
 9597:     # Record we've not yet viewed the Course Initialization Helper for this 
 9598:     # course
 9599:     $cenv{'course.helper.not.run'} = 1;
 9600:     #
 9601:     # Use new Randomseed
 9602:     #
 9603:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9604:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9605:     #
 9606:     # The encryption code and receipt prefix for this course
 9607:     #
 9608:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9609:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9610:     #
 9611:     # By default, use standard grading
 9612:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9613: 
 9614:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9615:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9616: #
 9617: # Open all assignments
 9618: #
 9619:     if ($args->{'openall'}) {
 9620:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9621:        my %storecontent = ($storeunder         => time,
 9622:                            $storeunder.'.type' => 'date_start');
 9623:        
 9624:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9625:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9626:    }
 9627: #
 9628: # Set first page
 9629: #
 9630:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9631: 	    || ($cloneid)) {
 9632: 	use LONCAPA::map;
 9633: 	$outcome .= &mt('Setting first resource').': ';
 9634: 
 9635: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9636:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9637: 
 9638:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9639:         my $title; my $url;
 9640:         if ($args->{'firstres'} eq 'syl') {
 9641: 	    $title=&mt('Syllabus');
 9642:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9643:         } else {
 9644:             $title=&mt('Navigate Contents');
 9645:             $url='/adm/navmaps';
 9646:         }
 9647: 
 9648:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9649: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9650: 
 9651: 	if ($errtext) { $fatal=2; }
 9652:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9653:     }
 9654: 
 9655:     return (1,$outcome);
 9656: }
 9657: 
 9658: ############################################################
 9659: ############################################################
 9660: 
 9661: sub course_type {
 9662:     my ($cid) = @_;
 9663:     if (!defined($cid)) {
 9664:         $cid = $env{'request.course.id'};
 9665:     }
 9666:     if (defined($env{'course.'.$cid.'.type'})) {
 9667:         return $env{'course.'.$cid.'.type'};
 9668:     } else {
 9669:         return 'Course';
 9670:     }
 9671: }
 9672: 
 9673: sub group_term {
 9674:     my $crstype = &course_type();
 9675:     my %names = (
 9676:                   'Course'    => 'group',
 9677:                   'Community' => 'group',
 9678:                 );
 9679:     return $names{$crstype};
 9680: }
 9681: 
 9682: sub icon {
 9683:     my ($file)=@_;
 9684:     my $curfext = lc((split(/\./,$file))[-1]);
 9685:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9686:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9687:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9688: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9689: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9690: 	            $curfext.".gif") {
 9691: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9692: 		$curfext.".gif";
 9693: 	}
 9694:     }
 9695:     return &lonhttpdurl($iconname);
 9696: } 
 9697: 
 9698: sub lonhttpdurl {
 9699: #
 9700: # Had been used for "small fry" static images on separate port 8080.
 9701: # Modify here if lightweight http functionality desired again.
 9702: # Currently eliminated due to increasing firewall issues.
 9703: #
 9704:     my ($url)=@_;
 9705:     return $url;
 9706: }
 9707: 
 9708: sub connection_aborted {
 9709:     my ($r)=@_;
 9710:     $r->print(" ");$r->rflush();
 9711:     my $c = $r->connection;
 9712:     return $c->aborted();
 9713: }
 9714: 
 9715: #    Escapes strings that may have embedded 's that will be put into
 9716: #    strings as 'strings'.
 9717: sub escape_single {
 9718:     my ($input) = @_;
 9719:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9720:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9721:     return $input;
 9722: }
 9723: 
 9724: #  Same as escape_single, but escape's "'s  This 
 9725: #  can be used for  "strings"
 9726: sub escape_double {
 9727:     my ($input) = @_;
 9728:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9729:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9730:     return $input;
 9731: }
 9732:  
 9733: #   Escapes the last element of a full URL.
 9734: sub escape_url {
 9735:     my ($url)   = @_;
 9736:     my @urlslices = split(/\//, $url,-1);
 9737:     my $lastitem = &escape(pop(@urlslices));
 9738:     return join('/',@urlslices).'/'.$lastitem;
 9739: }
 9740: 
 9741: sub compare_arrays {
 9742:     my ($arrayref1,$arrayref2) = @_;
 9743:     my (@difference,%count);
 9744:     @difference = ();
 9745:     %count = ();
 9746:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
 9747:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
 9748:         foreach my $element (keys(%count)) {
 9749:             if ($count{$element} == 1) {
 9750:                 push(@difference,$element);
 9751:             }
 9752:         }
 9753:     }
 9754:     return @difference;
 9755: }
 9756: 
 9757: # -------------------------------------------------------- Initliaze user login
 9758: sub init_user_environment {
 9759:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9760:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9761: 
 9762:     my $public=($username eq 'public' && $domain eq 'public');
 9763: 
 9764: # See if old ID present, if so, remove
 9765: 
 9766:     my ($filename,$cookie,$userroles);
 9767:     my $now=time;
 9768: 
 9769:     if ($public) {
 9770: 	my $max_public=100;
 9771: 	my $oldest;
 9772: 	my $oldest_time=0;
 9773: 	for(my $next=1;$next<=$max_public;$next++) {
 9774: 	    if (-e $lonids."/publicuser_$next.id") {
 9775: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9776: 		if ($mtime<$oldest_time || !$oldest_time) {
 9777: 		    $oldest_time=$mtime;
 9778: 		    $oldest=$next;
 9779: 		}
 9780: 	    } else {
 9781: 		$cookie="publicuser_$next";
 9782: 		last;
 9783: 	    }
 9784: 	}
 9785: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9786:     } else {
 9787: 	# if this isn't a robot, kill any existing non-robot sessions
 9788: 	if (!$args->{'robot'}) {
 9789: 	    opendir(DIR,$lonids);
 9790: 	    while ($filename=readdir(DIR)) {
 9791: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9792: 		    unlink($lonids.'/'.$filename);
 9793: 		}
 9794: 	    }
 9795: 	    closedir(DIR);
 9796: 	}
 9797: # Give them a new cookie
 9798: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9799: 		                   : $now.$$.int(rand(10000)));
 9800: 	$cookie="$username\_$id\_$domain\_$authhost";
 9801:     
 9802: # Initialize roles
 9803: 
 9804: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9805:     }
 9806: # ------------------------------------ Check browser type and MathML capability
 9807: 
 9808:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9809:         $clientunicode,$clientos) = &decode_user_agent($r);
 9810: 
 9811: # -------------------------------------- Any accessibility options to remember?
 9812:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9813: 	foreach my $option ('imagesuppress','appletsuppress',
 9814: 			    'embedsuppress','fontenhance','blackwhite') {
 9815: 	    if ($form->{$option} eq 'true') {
 9816: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9817: 				     $domain,$username);
 9818: 	    } else {
 9819: 		&Apache::lonnet::del('environment',[$option],
 9820: 				     $domain,$username);
 9821: 	    }
 9822: 	}
 9823:     }
 9824: # ------------------------------------------------------------- Get environment
 9825: 
 9826:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9827:     my ($tmp) = keys(%userenv);
 9828:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9829: 	# default remote control to off
 9830: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9831:     } else {
 9832: 	undef(%userenv);
 9833:     }
 9834:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9835: 	$form->{'interface'}=$userenv{'interface'};
 9836:     }
 9837:     $env{'environment.remote'}=$userenv{'remote'};
 9838:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9839: 
 9840: # --------------- Do not trust query string to be put directly into environment
 9841:     foreach my $option ('imagesuppress','appletsuppress',
 9842: 			'embedsuppress','fontenhance','blackwhite',
 9843: 			'interface','localpath','localres') {
 9844: 	$form->{$option}=~s/[\n\r\=]//gs;
 9845:     }
 9846: # --------------------------------------------------------- Write first profile
 9847: 
 9848:     {
 9849: 	my %initial_env = 
 9850: 	    ("user.name"          => $username,
 9851: 	     "user.domain"        => $domain,
 9852: 	     "user.home"          => $authhost,
 9853: 	     "browser.type"       => $clientbrowser,
 9854: 	     "browser.version"    => $clientversion,
 9855: 	     "browser.mathml"     => $clientmathml,
 9856: 	     "browser.unicode"    => $clientunicode,
 9857: 	     "browser.os"         => $clientos,
 9858: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9859: 	     "request.course.fn"  => '',
 9860: 	     "request.course.uri" => '',
 9861: 	     "request.course.sec" => '',
 9862: 	     "request.role"       => 'cm',
 9863: 	     "request.role.adv"   => $env{'user.adv'},
 9864: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9865: 
 9866:         if ($form->{'localpath'}) {
 9867: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9868: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9869:         }
 9870: 	
 9871: 	if ($public) {
 9872: 	    $initial_env{"environment.remote"} = "off";
 9873: 	}
 9874: 	if ($form->{'interface'}) {
 9875: 	    $form->{'interface'}=~s/\W//gs;
 9876: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9877: 	    $env{'browser.interface'}=$form->{'interface'};
 9878: 	    foreach my $option ('imagesuppress','appletsuppress',
 9879: 				'embedsuppress','fontenhance','blackwhite') {
 9880: 		if (($form->{$option} eq 'true') ||
 9881: 		    ($userenv{$option} eq 'on')) {
 9882: 		    $initial_env{"browser.$option"} = "on";
 9883: 		}
 9884: 	    }
 9885: 	}
 9886: 
 9887:         foreach my $tool ('aboutme','blog','portfolio') {
 9888:             $userenv{'availabletools.'.$tool} =
 9889:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9890:         }
 9891: 
 9892:         foreach my $crstype ('official','unofficial','community') {
 9893:             $userenv{'canrequest.'.$crstype} =
 9894:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
 9895:                                                   'reload','requestcourses');
 9896:         }
 9897: 
 9898: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9899: 	
 9900: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9901: 		 &GDBM_WRCREAT(),0640)) {
 9902: 	    &_add_to_env(\%disk_env,\%initial_env);
 9903: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9904: 	    &_add_to_env(\%disk_env,$userroles);
 9905: 	    if (ref($args->{'extra_env'})) {
 9906: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9907: 	    }
 9908: 	    untie(%disk_env);
 9909: 	} else {
 9910: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9911: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9912: 	    return 'error: '.$!;
 9913: 	}
 9914:     }
 9915:     $env{'request.role'}='cm';
 9916:     $env{'request.role.adv'}=$env{'user.adv'};
 9917:     $env{'browser.type'}=$clientbrowser;
 9918: 
 9919:     return $cookie;
 9920: 
 9921: }
 9922: 
 9923: sub _add_to_env {
 9924:     my ($idf,$env_data,$prefix) = @_;
 9925:     if (ref($env_data) eq 'HASH') {
 9926:         while (my ($key,$value) = each(%$env_data)) {
 9927: 	    $idf->{$prefix.$key} = $value;
 9928: 	    $env{$prefix.$key}   = $value;
 9929:         }
 9930:     }
 9931: }
 9932: 
 9933: # --- Get the symbolic name of a problem and the url
 9934: sub get_symb {
 9935:     my ($request,$silent) = @_;
 9936:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9937:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9938:     if ($symb eq '') {
 9939:         if (!$silent) {
 9940:             $request->print("Unable to handle ambiguous references:$url:.");
 9941:             return ();
 9942:         }
 9943:     }
 9944:     &Apache::lonenc::check_decrypt(\$symb);
 9945:     return ($symb);
 9946: }
 9947: 
 9948: # --------------------------------------------------------------Get annotation
 9949: 
 9950: sub get_annotation {
 9951:     my ($symb,$enc) = @_;
 9952: 
 9953:     my $key = $symb;
 9954:     if (!$enc) {
 9955:         $key =
 9956:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9957:     }
 9958:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9959:     return $annotation{$key};
 9960: }
 9961: 
 9962: sub clean_symb {
 9963:     my ($symb,$delete_enc) = @_;
 9964: 
 9965:     &Apache::lonenc::check_decrypt(\$symb);
 9966:     my $enc = $env{'request.enc'};
 9967:     if ($delete_enc) {
 9968:         delete($env{'request.enc'});
 9969:     }
 9970: 
 9971:     return ($symb,$enc);
 9972: }
 9973: 
 9974: =pod
 9975: 
 9976: =back
 9977: 
 9978: =cut
 9979: 
 9980: 1;
 9981: __END__;
 9982: 

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