File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.692.4.17: download - view: text, annotated - select for diffs
Mon Sep 7 13:13:58 2009 UTC (14 years, 9 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.692: preferred, unified
- Backport 1.886, 1.887, 1.888.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.692.4.17 2009/09/07 13:13:58 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 domainfilter = getDomainFromSelectbox(formname,udom);
  496:         if (domainfilter != null) {
  497:            if (domainfilter != '') {
  498:                url += 'domainfilter='+domainfilter+'&';
  499: 	   }
  500:         }
  501:         url += 'form=' + formname + '&cnumelement='+uname+
  502: 	                            '&cdomelement='+udom+
  503:                                     '&cnameelement='+desc;
  504:         if (extra_element !=null && extra_element != '') {
  505:             if (formname == 'rolechoice' || formname == 'studentform') {
  506:                 url += '&roleelement='+extra_element;
  507:                 if (domainfilter == null || domainfilter == '') {
  508:                     url += '&domainfilter='+extra_element;
  509:                 }
  510:             }
  511:             else {
  512:                 if (formname == 'portform') {
  513:                     url += '&setroles='+extra_element;
  514:                 }
  515:             }     
  516:         }
  517:         if (formname == 'ccrs') {
  518:             var ownername = document.forms[formid].ccuname.value;
  519:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  520:             url += '&cloner='+ownername+':'+ownerdom;
  521:         }
  522:         if (multflag !=null && multflag != '') {
  523:             url += '&multiple='+multflag;
  524:         }
  525:         if (crstype == 'Course/Community') {
  526:             if (formname == 'cu') {
  527:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  528:                 if (crstype == "") {
  529:                     alert("$crs_or_grp_alert");
  530:                     return;
  531:                 }
  532:             }
  533:         }
  534:         if (crstype !=null && crstype != '') {
  535:             url += '&type='+crstype;
  536:         }
  537:         var title = 'Course_Browser';
  538:         var options = 'scrollbars=1,resizable=1,menubar=0';
  539:         options += ',width=700,height=600';
  540:         stdeditbrowser = open(url,title,options,'1');
  541:         stdeditbrowser.focus();
  542:     }
  543: $id_functions
  544: ENDSTDBRW
  545:     if ($sec_element ne '') {
  546:         $output .= &setsec_javascript($sec_element,$formname);
  547:     }
  548:     $output .= '
  549: // ]]>
  550: </script>';
  551:     return $output;
  552: }
  553: 
  554: sub javascript_index_functions {
  555:     return <<"ENDJS";
  556: 
  557: function getFormIdByName(formname) {
  558:     for (var i=0;i<document.forms.length;i++) {
  559:         if (document.forms[i].name == formname) {
  560:             return i;
  561:         }
  562:     }
  563:     return -1;
  564: }
  565: 
  566: function getIndexByName(formid,item) {
  567:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  568:         if (document.forms[formid].elements[i].name == item) {
  569:             return i;
  570:         }
  571:     }
  572:     return -1;
  573: }
  574: 
  575: function getDomainFromSelectbox(formname,udom) {
  576:     var userdom;
  577:     var formid = getFormIdByName(formname);
  578:     if (formid > -1) {
  579:         var domid = getIndexByName(formid,udom);
  580:         if (domid > -1) {
  581:             if (document.forms[formid].elements[domid].type == 'select-one') {
  582:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  583:             }
  584:             if (document.forms[formid].elements[domid].type == 'hidden') {
  585:                 userdom=document.forms[formid].elements[domid].value;
  586:             }
  587:         }
  588:     }
  589:     return userdom;
  590: }
  591: 
  592: ENDJS
  593: 
  594: }
  595: 
  596: sub userbrowser_javascript {
  597:     my $id_functions = &javascript_index_functions();
  598:     return <<"ENDUSERBRW";
  599: 
  600: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  601:     var url = '/adm/pickuser?';
  602:     var userdom = getDomainFromSelectbox(formname,udom);
  603:     if (userdom != null) {
  604:        if (userdom != '') {
  605:            url += 'srchdom='+userdom+'&';
  606:        }
  607:     }
  608:     url += 'form=' + formname + '&unameelement='+uname+
  609:                                 '&udomelement='+udom+
  610:                                 '&ulastelement='+ulast+
  611:                                 '&ufirstelement='+ufirst+
  612:                                 '&uemailelement='+uemail+
  613:                                 '&hideudomelement='+hideudom+
  614:                                 '&coursedom='+crsdom;
  615:     if ((caller != null) && (caller != undefined)) {
  616:         url += '&caller='+caller;
  617:     }
  618:     var title = 'User_Browser';
  619:     var options = 'scrollbars=1,resizable=1,menubar=0';
  620:     options += ',width=700,height=600';
  621:     var stdeditbrowser = open(url,title,options,'1');
  622:     stdeditbrowser.focus();
  623: }
  624: 
  625: function fix_domain (formname,udom,origdom,uname) {
  626:     var formid = getFormIdByName(formname);
  627:     if (formid > -1) {
  628:         var unameid = getIndexByName(formid,uname);
  629:         var domid = getIndexByName(formid,udom);
  630:         var hidedomid = getIndexByName(formid,origdom);
  631:         if (hidedomid > -1) {
  632:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  633:             var unameval = document.forms[formid].elements[unameid].value;
  634:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  635:                 if (domid > -1) {
  636:                     var slct = document.forms[formid].elements[domid];
  637:                     if (slct.type == 'select-one') {
  638:                         var i;
  639:                         for (i=0;i<slct.length;i++) {
  640:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  641:                         }
  642:                     }
  643:                     if (slct.type == 'hidden') {
  644:                         slct.value = fixeddom;
  645:                     }
  646:                 }
  647:             }
  648:         }
  649:     }
  650:     return;
  651: }
  652: 
  653: $id_functions
  654: ENDUSERBRW
  655: }
  656: 
  657: 
  658: sub setsec_javascript {
  659:     my ($sec_element,$formname) = @_;
  660:     my $setsections = qq|
  661: function setSect(sectionlist) {
  662:     var sectionsArray = new Array();
  663:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  664:         sectionsArray = sectionlist.split(",");
  665:     }
  666:     var numSections = sectionsArray.length;
  667:     document.$formname.$sec_element.length = 0;
  668:     if (numSections == 0) {
  669:         document.$formname.$sec_element.multiple=false;
  670:         document.$formname.$sec_element.size=1;
  671:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  672:     } else {
  673:         if (numSections == 1) {
  674:             document.$formname.$sec_element.multiple=false;
  675:             document.$formname.$sec_element.size=1;
  676:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  677:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  678:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  679:         } else {
  680:             for (var i=0; i<numSections; i++) {
  681:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  682:             }
  683:             document.$formname.$sec_element.multiple=true
  684:             if (numSections < 3) {
  685:                 document.$formname.$sec_element.size=numSections;
  686:             } else {
  687:                 document.$formname.$sec_element.size=3;
  688:             }
  689:             document.$formname.$sec_element.options[0].selected = false
  690:         }
  691:     }
  692: }
  693: |;
  694:     return $setsections;
  695: }
  696: 
  697: 
  698: sub selectcourse_link {
  699:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  700:    my $linktext = &mt('Select Course');
  701:    if ($selecttype eq 'Community') {
  702:        $linktext = &mt('Select Community');
  703:    }
  704:    return '<span class="LC_nobreak">'
  705:          ."<a href='"
  706:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  707:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  708:          .'","'.$multflag.'","'.$selecttype.'");'
  709:          ."'>".$linktext.'</a>'
  710:          .'</span>';
  711: }
  712: 
  713: sub selectauthor_link {
  714:    my ($form,$udom)=@_;
  715:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  716:           &mt('Select Author').'</a>';
  717: }
  718: 
  719: sub selectuser_link {
  720:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  721:         $coursedom,$linktext,$caller) = @_;
  722:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  723:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  724:            ');">'.$linktext.'</a>';
  725: }
  726: 
  727: sub check_uncheck_jscript {
  728:     my $jscript = <<"ENDSCRT";
  729: function checkAll(field) {
  730:     if (field.length > 0) {
  731:         for (i = 0; i < field.length; i++) {
  732:             field[i].checked = true ;
  733:         }
  734:     } else {
  735:         field.checked = true
  736:     }
  737: }
  738:  
  739: function uncheckAll(field) {
  740:     if (field.length > 0) {
  741:         for (i = 0; i < field.length; i++) {
  742:             field[i].checked = false ;
  743:         }
  744:     } else {
  745:         field.checked = false ;
  746:     }
  747: }
  748: ENDSCRT
  749:     return $jscript;
  750: }
  751: 
  752: sub select_timezone {
  753:    my ($name,$selected,$onchange,$includeempty)=@_;
  754:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  755:    if ($includeempty) {
  756:        $output .= '<option value=""';
  757:        if (($selected eq '') || ($selected eq 'local')) {
  758:            $output .= ' selected="selected" ';
  759:        }
  760:        $output .= '> </option>';
  761:    }
  762:    my @timezones = DateTime::TimeZone->all_names;
  763:    foreach my $tzone (@timezones) {
  764:        $output.= '<option value="'.$tzone.'"';
  765:        if ($tzone eq $selected) {
  766:            $output.=' selected="selected"';
  767:        }
  768:        $output.=">$tzone</option>\n";
  769:    }
  770:    $output.="</select>";
  771:    return $output;
  772: }
  773: 
  774: sub select_datelocale {
  775:     my ($name,$selected,$onchange,$includeempty)=@_;
  776:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  777:     if ($includeempty) {
  778:         $output .= '<option value=""';
  779:         if ($selected eq '') {
  780:             $output .= ' selected="selected" ';
  781:         }
  782:         $output .= '> </option>';
  783:     }
  784:     my (@possibles,%locale_names);
  785:     my @locales = DateTime::Locale::Catalog::Locales;
  786:     foreach my $locale (@locales) {
  787:         if (ref($locale) eq 'HASH') {
  788:             my $id = $locale->{'id'};
  789:             if ($id ne '') {
  790:                 my $en_terr = $locale->{'en_territory'};
  791:                 my $native_terr = $locale->{'native_territory'};
  792:                 my @languages = &Apache::lonlocal::preferred_languages();
  793:                 if (grep(/^en$/,@languages) || !@languages) {
  794:                     if ($en_terr ne '') {
  795:                         $locale_names{$id} = '('.$en_terr.')';
  796:                     } elsif ($native_terr ne '') {
  797:                         $locale_names{$id} = $native_terr;
  798:                     }
  799:                 } else {
  800:                     if ($native_terr ne '') {
  801:                         $locale_names{$id} = $native_terr.' ';
  802:                     } elsif ($en_terr ne '') {
  803:                         $locale_names{$id} = '('.$en_terr.')';
  804:                     }
  805:                 }
  806:                 push (@possibles,$id);
  807:             }
  808:         }
  809:     }
  810:     foreach my $item (sort(@possibles)) {
  811:         $output.= '<option value="'.$item.'"';
  812:         if ($item eq $selected) {
  813:             $output.=' selected="selected"';
  814:         }
  815:         $output.=">$item";
  816:         if ($locale_names{$item} ne '') {
  817:             $output.="  $locale_names{$item}</option>\n";
  818:         }
  819:         $output.="</option>\n";
  820:     }
  821:     $output.="</select>";
  822:     return $output;
  823: }
  824: 
  825: sub select_language {
  826:     my ($name,$selected,$includeempty) = @_;
  827:     my %langchoices;
  828:     if ($includeempty) {
  829:         %langchoices = ('' => 'No language preference');
  830:     }
  831:     foreach my $id (&languageids()) {
  832:         my $code = &supportedlanguagecode($id);
  833:         if ($code) {
  834:             $langchoices{$code} = &plainlanguagedescription($id);
  835:         }
  836:     }
  837:     return &select_form($selected,$name,%langchoices);
  838: }
  839: 
  840: =pod
  841: 
  842: =item * &linked_select_forms(...)
  843: 
  844: linked_select_forms returns a string containing a <script></script> block
  845: and html for two <select> menus.  The select menus will be linked in that
  846: changing the value of the first menu will result in new values being placed
  847: in the second menu.  The values in the select menu will appear in alphabetical
  848: order unless a defined order is provided.
  849: 
  850: linked_select_forms takes the following ordered inputs:
  851: 
  852: =over 4
  853: 
  854: =item * $formname, the name of the <form> tag
  855: 
  856: =item * $middletext, the text which appears between the <select> tags
  857: 
  858: =item * $firstdefault, the default value for the first menu
  859: 
  860: =item * $firstselectname, the name of the first <select> tag
  861: 
  862: =item * $secondselectname, the name of the second <select> tag
  863: 
  864: =item * $hashref, a reference to a hash containing the data for the menus.
  865: 
  866: =item * $menuorder, the order of values in the first menu
  867: 
  868: =back 
  869: 
  870: Below is an example of such a hash.  Only the 'text', 'default', and 
  871: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  872: values for the first select menu.  The text that coincides with the 
  873: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  874: and text for the second menu are given in the hash pointed to by 
  875: $menu{$choice1}->{'select2'}.  
  876: 
  877:  my %menu = ( A1 => { text =>"Choice A1" ,
  878:                        default => "B3",
  879:                        select2 => { 
  880:                            B1 => "Choice B1",
  881:                            B2 => "Choice B2",
  882:                            B3 => "Choice B3",
  883:                            B4 => "Choice B4"
  884:                            },
  885:                        order => ['B4','B3','B1','B2'],
  886:                    },
  887:                A2 => { text =>"Choice A2" ,
  888:                        default => "C2",
  889:                        select2 => { 
  890:                            C1 => "Choice C1",
  891:                            C2 => "Choice C2",
  892:                            C3 => "Choice C3"
  893:                            },
  894:                        order => ['C2','C1','C3'],
  895:                    },
  896:                A3 => { text =>"Choice A3" ,
  897:                        default => "D6",
  898:                        select2 => { 
  899:                            D1 => "Choice D1",
  900:                            D2 => "Choice D2",
  901:                            D3 => "Choice D3",
  902:                            D4 => "Choice D4",
  903:                            D5 => "Choice D5",
  904:                            D6 => "Choice D6",
  905:                            D7 => "Choice D7"
  906:                            },
  907:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  908:                    }
  909:                );
  910: 
  911: =cut
  912: 
  913: sub linked_select_forms {
  914:     my ($formname,
  915:         $middletext,
  916:         $firstdefault,
  917:         $firstselectname,
  918:         $secondselectname, 
  919:         $hashref,
  920:         $menuorder,
  921:         ) = @_;
  922:     my $second = "document.$formname.$secondselectname";
  923:     my $first = "document.$formname.$firstselectname";
  924:     # output the javascript to do the changing
  925:     my $result = '';
  926:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  927:     $result.="// <![CDATA[\n";
  928:     $result.="var select2data = new Object();\n";
  929:     $" = '","';
  930:     my $debug = '';
  931:     foreach my $s1 (sort(keys(%$hashref))) {
  932:         $result.="select2data.d_$s1 = new Object();\n";        
  933:         $result.="select2data.d_$s1.def = new String('".
  934:             $hashref->{$s1}->{'default'}."');\n";
  935:         $result.="select2data.d_$s1.values = new Array(";
  936:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  937:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  938:             @s2values = @{$hashref->{$s1}->{'order'}};
  939:         }
  940:         $result.="\"@s2values\");\n";
  941:         $result.="select2data.d_$s1.texts = new Array(";        
  942:         my @s2texts;
  943:         foreach my $value (@s2values) {
  944:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  945:         }
  946:         $result.="\"@s2texts\");\n";
  947:     }
  948:     $"=' ';
  949:     $result.= <<"END";
  950: 
  951: function select1_changed() {
  952:     // Determine new choice
  953:     var newvalue = "d_" + $first.value;
  954:     // update select2
  955:     var values     = select2data[newvalue].values;
  956:     var texts      = select2data[newvalue].texts;
  957:     var select2def = select2data[newvalue].def;
  958:     var i;
  959:     // out with the old
  960:     for (i = 0; i < $second.options.length; i++) {
  961:         $second.options[i] = null;
  962:     }
  963:     // in with the nuclear
  964:     for (i=0;i<values.length; i++) {
  965:         $second.options[i] = new Option(values[i]);
  966:         $second.options[i].value = values[i];
  967:         $second.options[i].text = texts[i];
  968:         if (values[i] == select2def) {
  969:             $second.options[i].selected = true;
  970:         }
  971:     }
  972: }
  973: // ]]>
  974: </script>
  975: END
  976:     # output the initial values for the selection lists
  977:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  978:     my @order = sort(keys(%{$hashref}));
  979:     if (ref($menuorder) eq 'ARRAY') {
  980:         @order = @{$menuorder};
  981:     }
  982:     foreach my $value (@order) {
  983:         $result.="    <option value=\"$value\" ";
  984:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  985:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  986:     }
  987:     $result .= "</select>\n";
  988:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  989:     $result .= $middletext;
  990:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  991:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  992:     
  993:     my @secondorder = sort(keys(%select2));
  994:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  995:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  996:     }
  997:     foreach my $value (@secondorder) {
  998:         $result.="    <option value=\"$value\" ";        
  999:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1000:         $result.=">".&mt($select2{$value})."</option>\n";
 1001:     }
 1002:     $result .= "</select>\n";
 1003:     #    return $debug;
 1004:     return $result;
 1005: }   #  end of sub linked_select_forms {
 1006: 
 1007: =pod
 1008: 
 1009: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
 1010: 
 1011: Returns a string corresponding to an HTML link to the given help
 1012: $topic, where $topic corresponds to the name of a .tex file in
 1013: /home/httpd/html/adm/help/tex, with underscores replaced by
 1014: spaces. 
 1015: 
 1016: $text will optionally be linked to the same topic, allowing you to
 1017: link text in addition to the graphic. If you do not want to link
 1018: text, but wish to specify one of the later parameters, pass an
 1019: empty string. 
 1020: 
 1021: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1022: the link will not open a new window. If false, the link will open
 1023: a new window using Javascript. (Default is false.) 
 1024: 
 1025: $width and $height are optional numerical parameters that will
 1026: override the width and height of the popped up window, which may
 1027: be useful for certain help topics with big pictures included. 
 1028: 
 1029: =cut
 1030: 
 1031: sub help_open_topic {
 1032:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1033:     $text = "" if (not defined $text);
 1034:     $stayOnPage = 0 if (not defined $stayOnPage);
 1035:     if ($env{'browser.interface'} eq 'textual') {
 1036: 	$stayOnPage=1;
 1037:     }
 1038:     $width = 350 if (not defined $width);
 1039:     $height = 400 if (not defined $height);
 1040:     my $filename = $topic;
 1041:     $filename =~ s/ /_/g;
 1042: 
 1043:     my $template = "";
 1044:     my $link;
 1045:     
 1046:     $topic=~s/\W/\_/g;
 1047: 
 1048:     if (!$stayOnPage) {
 1049: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1050:     } else {
 1051: 	$link = "/adm/help/${filename}.hlp";
 1052:     }
 1053: 
 1054:     # Add the text
 1055:     if ($text ne "") {
 1056: 	$template .= 
 1057:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
 1058:             "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1059:     }
 1060: 
 1061:     # Add the graphic
 1062:     my $title = &mt('Online Help');
 1063:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1064:     $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
 1065:                  '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
 1066:                  '" title="'.$title.'" /></a>';
 1067:     if ($text ne '') {
 1068:         $template.='</span></td></tr></table>';
 1069:     }
 1070:     return $template;
 1071: 
 1072: }
 1073: 
 1074: # This is a quicky function for Latex cheatsheet editing, since it 
 1075: # appears in at least four places
 1076: sub helpLatexCheatsheet {
 1077:     my ($topic,$text,$not_author) = @_;
 1078:     my $out;
 1079:     my $addOther = '';
 1080:     if ($topic) {
 1081: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
 1082: 						       undef, undef, 600) .
 1083: 							   '</td><td>';
 1084:     }
 1085:     $out = '<table><tr><td>'.
 1086:            $addOther .
 1087:            &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
 1088:                                                undef,undef,600).
 1089:            '</td><td>'.
 1090:            &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
 1091:                                                undef,undef,600).
 1092:            '</td>';
 1093:     unless ($not_author) {
 1094:         $out .= '<td>'.
 1095:                 &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
 1096:                                                     undef,undef,600).
 1097:                 '</td>';
 1098:     }
 1099:     $out .= '</tr></table>';
 1100:     return $out;
 1101: }
 1102: 
 1103: sub general_help {
 1104:     my $helptopic='Student_Intro';
 1105:     if ($env{'request.role'}=~/^(ca|au)/) {
 1106: 	$helptopic='Authoring_Intro';
 1107:     } elsif ($env{'request.role'}=~/^cc/) {
 1108: 	$helptopic='Course_Coordination_Intro';
 1109:     } elsif ($env{'request.role'}=~/^dc/) {
 1110:         $helptopic='Domain_Coordination_Intro';
 1111:     }
 1112:     return $helptopic;
 1113: }
 1114: 
 1115: sub update_help_link {
 1116:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1117:     my $origurl = $ENV{'REQUEST_URI'};
 1118:     $origurl=~s|^/~|/priv/|;
 1119:     my $timestamp = time;
 1120:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1121:         $$datum = &escape($$datum);
 1122:     }
 1123: 
 1124:     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";
 1125:     my $output .= <<"ENDOUTPUT";
 1126: <script type="text/javascript">
 1127: // <![CDATA[
 1128: banner_link = '$banner_link';
 1129: // ]]>
 1130: </script>
 1131: ENDOUTPUT
 1132:     return $output;
 1133: }
 1134: 
 1135: # now just updates the help link and generates a blue icon
 1136: sub help_open_menu {
 1137:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1138: 	= @_;    
 1139:     $stayOnPage = 0 if (not defined $stayOnPage);
 1140:     # only use pop-up help (stayOnPage == 0)
 1141:     # if environment.remote is on (using remote control UI)
 1142:     if ($env{'browser.interface'} eq 'textual' ||
 1143:     	$env{'environment.remote'} eq 'off' ) {
 1144:         $stayOnPage=1;
 1145:     }
 1146:     my $output;
 1147:     if ($component_help) {
 1148: 	if (!$text) {
 1149: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1150: 				       $width,$height);
 1151: 	} else {
 1152: 	    my $help_text;
 1153: 	    $help_text=&unescape($topic);
 1154: 	    $output='<table><tr><td>'.
 1155: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1156: 				 $width,$height).'</td></tr></table>';
 1157: 	}
 1158:     }
 1159:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1160:     return $output.$banner_link;
 1161: }
 1162: 
 1163: sub top_nav_help {
 1164:     my ($text) = @_;
 1165:     $text = &mt($text);
 1166:     my $stay_on_page = 
 1167: 	($env{'browser.interface'}  eq 'textual' ||
 1168: 	 $env{'environment.remote'} eq 'off' );
 1169:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1170: 	                     : "javascript:helpMenu('open')";
 1171:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1172: 
 1173:     my $title = &mt('Get help');
 1174: 
 1175:     return <<"END";
 1176: $banner_link
 1177:  <a href="$link" title="$title">$text</a>
 1178: END
 1179: }
 1180: 
 1181: sub help_menu_js {
 1182:     my ($text) = @_;
 1183: 
 1184:     my $stayOnPage = 
 1185: 	($env{'browser.interface'}  eq 'textual' ||
 1186: 	 $env{'environment.remote'} eq 'off' );
 1187: 
 1188:     my $width = 620;
 1189:     my $height = 600;
 1190:     my $helptopic=&general_help();
 1191:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1192:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1193:     my $start_page =
 1194:         &Apache::loncommon::start_page('Help Menu', undef,
 1195: 				       {'frameset'    => 1,
 1196: 					'js_ready'    => 1,
 1197: 					'add_entries' => {
 1198: 					    'border' => '0',
 1199: 					    'rows'   => "110,*",},});
 1200:     my $end_page =
 1201:         &Apache::loncommon::end_page({'frameset' => 1,
 1202: 				      'js_ready' => 1,});
 1203: 
 1204:     my $template .= <<"ENDTEMPLATE";
 1205: <script type="text/javascript">
 1206: // <![CDATA[
 1207: // <!-- BEGIN LON-CAPA Internal
 1208: var banner_link = '';
 1209: function helpMenu(target) {
 1210:     var caller = this;
 1211:     if (target == 'open') {
 1212:         var newWindow = null;
 1213:         try {
 1214:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1215:         }
 1216:         catch(error) {
 1217:             writeHelp(caller);
 1218:             return;
 1219:         }
 1220:         if (newWindow) {
 1221:             caller = newWindow;
 1222:         }
 1223:     }
 1224:     writeHelp(caller);
 1225:     return;
 1226: }
 1227: function writeHelp(caller) {
 1228:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1229:     caller.document.close()
 1230:     caller.focus()
 1231: }
 1232: // END LON-CAPA Internal -->
 1233: // ]]>
 1234: </script>
 1235: ENDTEMPLATE
 1236:     return $template;
 1237: }
 1238: 
 1239: sub help_open_bug {
 1240:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1241:     unless ($env{'user.adv'}) { return ''; }
 1242:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1243:     $text = "" if (not defined $text);
 1244:     $stayOnPage = 0 if (not defined $stayOnPage);
 1245:     if ($env{'browser.interface'} eq 'textual' ||
 1246: 	$env{'environment.remote'} eq 'off' ) {
 1247: 	$stayOnPage=1;
 1248:     }
 1249:     $width = 600 if (not defined $width);
 1250:     $height = 600 if (not defined $height);
 1251: 
 1252:     $topic=~s/\W+/\+/g;
 1253:     my $link='';
 1254:     my $template='';
 1255:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1256: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1257:     if (!$stayOnPage)
 1258:     {
 1259: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1260:     }
 1261:     else
 1262:     {
 1263: 	$link = $url;
 1264:     }
 1265:     # Add the text
 1266:     if ($text ne "")
 1267:     {
 1268: 	$template .= 
 1269:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1270:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1271:     }
 1272: 
 1273:     # Add the graphic
 1274:     my $title = &mt('Report a Bug');
 1275:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1276:     $template .= <<"ENDTEMPLATE";
 1277:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1278: ENDTEMPLATE
 1279:     if ($text ne '') { $template.='</td></tr></table>' };
 1280:     return $template;
 1281: 
 1282: }
 1283: 
 1284: sub help_open_faq {
 1285:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1286:     unless ($env{'user.adv'}) { return ''; }
 1287:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1288:     $text = "" if (not defined $text);
 1289:     $stayOnPage = 0 if (not defined $stayOnPage);
 1290:     if ($env{'browser.interface'} eq 'textual' ||
 1291: 	$env{'environment.remote'} eq 'off' ) {
 1292: 	$stayOnPage=1;
 1293:     }
 1294:     $width = 350 if (not defined $width);
 1295:     $height = 400 if (not defined $height);
 1296: 
 1297:     $topic=~s/\W+/\+/g;
 1298:     my $link='';
 1299:     my $template='';
 1300:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1301:     if (!$stayOnPage)
 1302:     {
 1303: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1304:     }
 1305:     else
 1306:     {
 1307: 	$link = $url;
 1308:     }
 1309: 
 1310:     # Add the text
 1311:     if ($text ne "")
 1312:     {
 1313: 	$template .= 
 1314:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1315:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1316:     }
 1317: 
 1318:     # Add the graphic
 1319:     my $title = &mt('View the FAQ');
 1320:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1321:     $template .= <<"ENDTEMPLATE";
 1322:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1323: ENDTEMPLATE
 1324:     if ($text ne '') { $template.='</td></tr></table>' };
 1325:     return $template;
 1326: 
 1327: }
 1328: 
 1329: ###############################################################
 1330: ###############################################################
 1331: 
 1332: =pod
 1333: 
 1334: =item * &change_content_javascript():
 1335: 
 1336: This and the next function allow you to create small sections of an
 1337: otherwise static HTML page that you can update on the fly with
 1338: Javascript, even in Netscape 4.
 1339: 
 1340: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1341: must be written to the HTML page once. It will prove the Javascript
 1342: function "change(name, content)". Calling the change function with the
 1343: name of the section 
 1344: you want to update, matching the name passed to C<changable_area>, and
 1345: the new content you want to put in there, will put the content into
 1346: that area.
 1347: 
 1348: B<Note>: Netscape 4 only reserves enough space for the changable area
 1349: to contain room for the original contents. You need to "make space"
 1350: for whatever changes you wish to make, and be B<sure> to check your
 1351: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1352: it's adequate for updating a one-line status display, but little more.
 1353: This script will set the space to 100% width, so you only need to
 1354: worry about height in Netscape 4.
 1355: 
 1356: Modern browsers are much less limiting, and if you can commit to the
 1357: user not using Netscape 4, this feature may be used freely with
 1358: pretty much any HTML.
 1359: 
 1360: =cut
 1361: 
 1362: sub change_content_javascript {
 1363:     # If we're on Netscape 4, we need to use Layer-based code
 1364:     if ($env{'browser.type'} eq 'netscape' &&
 1365: 	$env{'browser.version'} =~ /^4\./) {
 1366: 	return (<<NETSCAPE4);
 1367: 	function change(name, content) {
 1368: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1369: 	    doc.open();
 1370: 	    doc.write(content);
 1371: 	    doc.close();
 1372: 	}
 1373: NETSCAPE4
 1374:     } else {
 1375: 	# Otherwise, we need to use semi-standards-compliant code
 1376: 	# (technically, "innerHTML" isn't standard but the equivalent
 1377: 	# is really scary, and every useful browser supports it
 1378: 	return (<<DOMBASED);
 1379: 	function change(name, content) {
 1380: 	    element = document.getElementById(name);
 1381: 	    element.innerHTML = content;
 1382: 	}
 1383: DOMBASED
 1384:     }
 1385: }
 1386: 
 1387: =pod
 1388: 
 1389: =item * &changable_area($name,$origContent):
 1390: 
 1391: This provides a "changable area" that can be modified on the fly via
 1392: the Javascript code provided in C<change_content_javascript>. $name is
 1393: the name you will use to reference the area later; do not repeat the
 1394: same name on a given HTML page more then once. $origContent is what
 1395: the area will originally contain, which can be left blank.
 1396: 
 1397: =cut
 1398: 
 1399: sub changable_area {
 1400:     my ($name, $origContent) = @_;
 1401: 
 1402:     if ($env{'browser.type'} eq 'netscape' &&
 1403: 	$env{'browser.version'} =~ /^4\./) {
 1404: 	# If this is netscape 4, we need to use the Layer tag
 1405: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1406:     } else {
 1407: 	return "<span id='$name'>$origContent</span>";
 1408:     }
 1409: }
 1410: 
 1411: =pod
 1412: 
 1413: =item * &viewport_geometry_js 
 1414: 
 1415: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1416: 
 1417: =cut
 1418: 
 1419: 
 1420: sub viewport_geometry_js { 
 1421:     return <<"GEOMETRY";
 1422: var Geometry = {};
 1423: function init_geometry() {
 1424:     if (Geometry.init) { return };
 1425:     Geometry.init=1;
 1426:     if (window.innerHeight) {
 1427:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1428:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1429:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1430:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1431:     }
 1432:     else if (document.documentElement && document.documentElement.clientHeight) {
 1433:         Geometry.getViewportHeight =
 1434:             function() { return document.documentElement.clientHeight; };
 1435:         Geometry.getViewportWidth =
 1436:             function() { return document.documentElement.clientWidth; };
 1437: 
 1438:         Geometry.getHorizontalScroll =
 1439:             function() { return document.documentElement.scrollLeft; };
 1440:         Geometry.getVerticalScroll =
 1441:             function() { return document.documentElement.scrollTop; };
 1442:     }
 1443:     else if (document.body.clientHeight) {
 1444:         Geometry.getViewportHeight =
 1445:             function() { return document.body.clientHeight; };
 1446:         Geometry.getViewportWidth =
 1447:             function() { return document.body.clientWidth; };
 1448:         Geometry.getHorizontalScroll =
 1449:             function() { return document.body.scrollLeft; };
 1450:         Geometry.getVerticalScroll =
 1451:             function() { return document.body.scrollTop; };
 1452:     }
 1453: }
 1454: 
 1455: GEOMETRY
 1456: }
 1457: 
 1458: =pod
 1459: 
 1460: =item * &viewport_size_js()
 1461: 
 1462: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1463: 
 1464: =cut
 1465: 
 1466: sub viewport_size_js {
 1467:     my $geometry = &viewport_geometry_js();
 1468:     return <<"DIMS";
 1469: 
 1470: $geometry
 1471: 
 1472: function getViewportDims(width,height) {
 1473:     init_geometry();
 1474:     width.value = Geometry.getViewportWidth();
 1475:     height.value = Geometry.getViewportHeight();
 1476:     return;
 1477: }
 1478: 
 1479: DIMS
 1480: }
 1481: 
 1482: =pod
 1483: 
 1484: =item * &resize_textarea_js()
 1485: 
 1486: emits the needed javascript to resize a textarea to be as big as possible
 1487: 
 1488: creates a function resize_textrea that takes two IDs first should be
 1489: the id of the element to resize, second should be the id of a div that
 1490: surrounds everything that comes after the textarea, this routine needs
 1491: to be attached to the <body> for the onload and onresize events.
 1492: 
 1493: =back
 1494: 
 1495: =cut
 1496: 
 1497: sub resize_textarea_js {
 1498:     my $geometry = &viewport_geometry_js();
 1499:     return <<"RESIZE";
 1500:     <script type="text/javascript">
 1501: // <![CDATA[
 1502: $geometry
 1503: 
 1504: function getX(element) {
 1505:     var x = 0;
 1506:     while (element) {
 1507: 	x += element.offsetLeft;
 1508: 	element = element.offsetParent;
 1509:     }
 1510:     return x;
 1511: }
 1512: function getY(element) {
 1513:     var y = 0;
 1514:     while (element) {
 1515: 	y += element.offsetTop;
 1516: 	element = element.offsetParent;
 1517:     }
 1518:     return y;
 1519: }
 1520: 
 1521: 
 1522: function resize_textarea(textarea_id,bottom_id) {
 1523:     init_geometry();
 1524:     var textarea        = document.getElementById(textarea_id);
 1525:     //alert(textarea);
 1526: 
 1527:     var textarea_top    = getY(textarea);
 1528:     var textarea_height = textarea.offsetHeight;
 1529:     var bottom          = document.getElementById(bottom_id);
 1530:     var bottom_top      = getY(bottom);
 1531:     var bottom_height   = bottom.offsetHeight;
 1532:     var window_height   = Geometry.getViewportHeight();
 1533:     var fudge           = 23;
 1534:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1535:     if (new_height < 300) {
 1536: 	new_height = 300;
 1537:     }
 1538:     textarea.style.height=new_height+'px';
 1539: }
 1540: // ]]>
 1541: </script>
 1542: RESIZE
 1543: 
 1544: }
 1545: 
 1546: =pod
 1547: 
 1548: =head1 Excel and CSV file utility routines
 1549: 
 1550: =over 4
 1551: 
 1552: =cut
 1553: 
 1554: ###############################################################
 1555: ###############################################################
 1556: 
 1557: =pod
 1558: 
 1559: =item * &csv_translate($text) 
 1560: 
 1561: Translate $text to allow it to be output as a 'comma separated values' 
 1562: format.
 1563: 
 1564: =cut
 1565: 
 1566: ###############################################################
 1567: ###############################################################
 1568: sub csv_translate {
 1569:     my $text = shift;
 1570:     $text =~ s/\"/\"\"/g;
 1571:     $text =~ s/\n/ /g;
 1572:     return $text;
 1573: }
 1574: 
 1575: ###############################################################
 1576: ###############################################################
 1577: 
 1578: =pod
 1579: 
 1580: =item * &define_excel_formats()
 1581: 
 1582: Define some commonly used Excel cell formats.
 1583: 
 1584: Currently supported formats:
 1585: 
 1586: =over 4
 1587: 
 1588: =item header
 1589: 
 1590: =item bold
 1591: 
 1592: =item h1
 1593: 
 1594: =item h2
 1595: 
 1596: =item h3
 1597: 
 1598: =item h4
 1599: 
 1600: =item i
 1601: 
 1602: =item date
 1603: 
 1604: =back
 1605: 
 1606: Inputs: $workbook
 1607: 
 1608: Returns: $format, a hash reference.
 1609: 
 1610: =cut
 1611: 
 1612: ###############################################################
 1613: ###############################################################
 1614: sub define_excel_formats {
 1615:     my ($workbook) = @_;
 1616:     my $format;
 1617:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1618:                                                 bottom    => 1,
 1619:                                                 align     => 'center');
 1620:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1621:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1622:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1623:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1624:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1625:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1626:     $format->{'date'} = $workbook->add_format(num_format=>
 1627:                                             'mm/dd/yyyy hh:mm:ss');
 1628:     return $format;
 1629: }
 1630: 
 1631: ###############################################################
 1632: ###############################################################
 1633: 
 1634: =pod
 1635: 
 1636: =item * &create_workbook()
 1637: 
 1638: Create an Excel worksheet.  If it fails, output message on the
 1639: request object and return undefs.
 1640: 
 1641: Inputs: Apache request object
 1642: 
 1643: Returns (undef) on failure, 
 1644:     Excel worksheet object, scalar with filename, and formats 
 1645:     from &Apache::loncommon::define_excel_formats on success
 1646: 
 1647: =cut
 1648: 
 1649: ###############################################################
 1650: ###############################################################
 1651: sub create_workbook {
 1652:     my ($r) = @_;
 1653:         #
 1654:     # Create the excel spreadsheet
 1655:     my $filename = '/prtspool/'.
 1656:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1657:         time.'_'.rand(1000000000).'.xls';
 1658:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1659:     if (! defined($workbook)) {
 1660:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1661:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1662:                             "This error has been logged.  ".
 1663:                             "Please alert your LON-CAPA administrator").
 1664:                   '</p>');
 1665:         return (undef);
 1666:     }
 1667:     #
 1668:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1669:     #
 1670:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1671:     return ($workbook,$filename,$format);
 1672: }
 1673: 
 1674: ###############################################################
 1675: ###############################################################
 1676: 
 1677: =pod
 1678: 
 1679: =item * &create_text_file()
 1680: 
 1681: Create a file to write to and eventually make available to the user.
 1682: If file creation fails, outputs an error message on the request object and 
 1683: return undefs.
 1684: 
 1685: Inputs: Apache request object, and file suffix
 1686: 
 1687: Returns (undef) on failure, 
 1688:     Filehandle and filename on success.
 1689: 
 1690: =cut
 1691: 
 1692: ###############################################################
 1693: ###############################################################
 1694: sub create_text_file {
 1695:     my ($r,$suffix) = @_;
 1696:     if (! defined($suffix)) { $suffix = 'txt'; };
 1697:     my $fh;
 1698:     my $filename = '/prtspool/'.
 1699:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1700:         time.'_'.rand(1000000000).'.'.$suffix;
 1701:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1702:     if (! defined($fh)) {
 1703:         $r->log_error("Couldn't open $filename for output $!");
 1704:         $r->print(&mt('Problems occurred in creating the output file. '
 1705:                      .'This error has been logged. '
 1706:                      .'Please alert your LON-CAPA administrator.'));
 1707:     }
 1708:     return ($fh,$filename)
 1709: }
 1710: 
 1711: 
 1712: =pod 
 1713: 
 1714: =back
 1715: 
 1716: =cut
 1717: 
 1718: ###############################################################
 1719: ##        Home server <option> list generating code          ##
 1720: ###############################################################
 1721: 
 1722: # ------------------------------------------
 1723: 
 1724: sub domain_select {
 1725:     my ($name,$value,$multiple)=@_;
 1726:     my %domains=map { 
 1727: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1728:     } &Apache::lonnet::all_domains();
 1729:     if ($multiple) {
 1730: 	$domains{''}=&mt('Any domain');
 1731: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1732: 	return &multiple_select_form($name,$value,4,\%domains);
 1733:     } else {
 1734: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1735: 	return &select_form($name,$value,%domains);
 1736:     }
 1737: }
 1738: 
 1739: #-------------------------------------------
 1740: 
 1741: =pod
 1742: 
 1743: =head1 Routines for form select boxes
 1744: 
 1745: =over 4
 1746: 
 1747: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1748: 
 1749: Returns a string containing a <select> element int multiple mode
 1750: 
 1751: 
 1752: Args:
 1753:   $name - name of the <select> element
 1754:   $value - scalar or array ref of values that should already be selected
 1755:   $size - number of rows long the select element is
 1756:   $hash - the elements should be 'option' => 'shown text'
 1757:           (shown text should already have been &mt())
 1758:   $order - (optional) array ref of the order to show the elements in
 1759: 
 1760: =cut
 1761: 
 1762: #-------------------------------------------
 1763: sub multiple_select_form {
 1764:     my ($name,$value,$size,$hash,$order)=@_;
 1765:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1766:     my $output='';
 1767:     if (! defined($size)) {
 1768:         $size = 4;
 1769:         if (scalar(keys(%$hash))<4) {
 1770:             $size = scalar(keys(%$hash));
 1771:         }
 1772:     }
 1773:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1774:     my @order;
 1775:     if (ref($order) eq 'ARRAY')  {
 1776:         @order = @{$order};
 1777:     } else {
 1778:         @order = sort(keys(%$hash));
 1779:     }
 1780:     if (exists($$hash{'select_form_order'})) {
 1781:         @order = @{$$hash{'select_form_order'}};
 1782:     }
 1783:         
 1784:     foreach my $key (@order) {
 1785:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1786:         $output.='selected="selected" ' if ($selected{$key});
 1787:         $output.='>'.$hash->{$key}."</option>\n";
 1788:     }
 1789:     $output.="</select>\n";
 1790:     return $output;
 1791: }
 1792: 
 1793: #-------------------------------------------
 1794: 
 1795: =pod
 1796: 
 1797: =item * &select_form($defdom,$name,%hash)
 1798: 
 1799: Returns a string containing a <select name='$name' size='1'> form to 
 1800: allow a user to select options from a hash option_name => displayed text.  
 1801: See lonrights.pm for an example invocation and use.
 1802: 
 1803: =cut
 1804: 
 1805: #-------------------------------------------
 1806: sub select_form {
 1807:     my ($def,$name,%hash) = @_;
 1808:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1809:     my @keys;
 1810:     if (exists($hash{'select_form_order'})) {
 1811: 	@keys=@{$hash{'select_form_order'}};
 1812:     } else {
 1813: 	@keys=sort(keys(%hash));
 1814:     }
 1815:     foreach my $key (@keys) {
 1816:         $selectform.=
 1817: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1818:             ($key eq $def ? 'selected="selected" ' : '').
 1819:                 ">".&mt($hash{$key})."</option>\n";
 1820:     }
 1821:     $selectform.="</select>";
 1822:     return $selectform;
 1823: }
 1824: 
 1825: # For display filters
 1826: 
 1827: sub display_filter {
 1828:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1829:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1830:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1831: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1832: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1833: 	   '</label></span> <span class="LC_nobreak">'.
 1834:            &mt('Filter [_1]',
 1835: 	   &select_form($env{'form.displayfilter'},
 1836: 			'displayfilter',
 1837: 			('currentfolder' => 'Current folder/page',
 1838: 			 'containing' => 'Containing phrase',
 1839: 			 'none' => 'None'))).
 1840: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1841: }
 1842: 
 1843: sub gradeleveldescription {
 1844:     my $gradelevel=shift;
 1845:     my %gradelevels=(0 => 'Not specified',
 1846: 		     1 => 'Grade 1',
 1847: 		     2 => 'Grade 2',
 1848: 		     3 => 'Grade 3',
 1849: 		     4 => 'Grade 4',
 1850: 		     5 => 'Grade 5',
 1851: 		     6 => 'Grade 6',
 1852: 		     7 => 'Grade 7',
 1853: 		     8 => 'Grade 8',
 1854: 		     9 => 'Grade 9',
 1855: 		     10 => 'Grade 10',
 1856: 		     11 => 'Grade 11',
 1857: 		     12 => 'Grade 12',
 1858: 		     13 => 'Grade 13',
 1859: 		     14 => '100 Level',
 1860: 		     15 => '200 Level',
 1861: 		     16 => '300 Level',
 1862: 		     17 => '400 Level',
 1863: 		     18 => 'Graduate Level');
 1864:     return &mt($gradelevels{$gradelevel});
 1865: }
 1866: 
 1867: sub select_level_form {
 1868:     my ($deflevel,$name)=@_;
 1869:     unless ($deflevel) { $deflevel=0; }
 1870:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1871:     for (my $i=0; $i<=18; $i++) {
 1872:         $selectform.="<option value=\"$i\" ".
 1873:             ($i==$deflevel ? 'selected="selected" ' : '').
 1874:                 ">".&gradeleveldescription($i)."</option>\n";
 1875:     }
 1876:     $selectform.="</select>";
 1877:     return $selectform;
 1878: }
 1879: 
 1880: #-------------------------------------------
 1881: 
 1882: =pod
 1883: 
 1884: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange)
 1885: 
 1886: Returns a string containing a <select name='$name' size='1'> form to 
 1887: allow a user to select the domain to preform an operation in.  
 1888: See loncreateuser.pm for an example invocation and use.
 1889: 
 1890: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1891: selected");
 1892: 
 1893: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1894: 
 1895: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
 1896: 
 1897: =cut
 1898: 
 1899: #-------------------------------------------
 1900: sub select_dom_form {
 1901:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange) = @_;
 1902:     if ($onchange) {
 1903:         $onchange = ' onchange="'.$onchange.'"';
 1904:     }
 1905:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1906:     if ($includeempty) { @domains=('',@domains); }
 1907:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1908:     foreach my $dom (@domains) {
 1909:         $selectdomain.="<option value=\"$dom\" ".
 1910:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1911:         if ($showdomdesc) {
 1912:             if ($dom ne '') {
 1913:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1914:                 if ($domdesc ne '') {
 1915:                     $selectdomain .= ' ('.$domdesc.')';
 1916:                 }
 1917:             } 
 1918:         }
 1919:         $selectdomain .= "</option>\n";
 1920:     }
 1921:     $selectdomain.="</select>";
 1922:     return $selectdomain;
 1923: }
 1924: 
 1925: #-------------------------------------------
 1926: 
 1927: =pod
 1928: 
 1929: =item * &home_server_form_item($domain,$name,$defaultflag)
 1930: 
 1931: input: 4 arguments (two required, two optional) - 
 1932:     $domain - domain of new user
 1933:     $name - name of form element
 1934:     $default - Value of 'default' causes a default item to be first 
 1935:                             option, and selected by default. 
 1936:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1937:                             if 1 server found, or default, if 0 found.
 1938: output: returns 2 items: 
 1939: (a) form element which contains either:
 1940:    (i) <select name="$name">
 1941:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1942:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1943:        </select>
 1944:        form item if there are multiple library servers in $domain, or
 1945:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1946:        if there is only one library server in $domain.
 1947: 
 1948: (b) number of library servers found.
 1949: 
 1950: See loncreateuser.pm for example of use.
 1951: 
 1952: =cut
 1953: 
 1954: #-------------------------------------------
 1955: sub home_server_form_item {
 1956:     my ($domain,$name,$default,$hide) = @_;
 1957:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1958:     my $result;
 1959:     my $numlib = keys(%servers);
 1960:     if ($numlib > 1) {
 1961:         $result .= '<select name="'.$name.'" />'."\n";
 1962:         if ($default) {
 1963:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1964:                        '</option>'."\n";
 1965:         }
 1966:         foreach my $hostid (sort(keys(%servers))) {
 1967:             $result.= '<option value="'.$hostid.'">'.
 1968: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1969:         }
 1970:         $result .= '</select>'."\n";
 1971:     } elsif ($numlib == 1) {
 1972:         my $hostid;
 1973:         foreach my $item (keys(%servers)) {
 1974:             $hostid = $item;
 1975:         }
 1976:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1977:                    $hostid.'" />';
 1978:                    if (!$hide) {
 1979:                        $result .= $hostid.' '.$servers{$hostid};
 1980:                    }
 1981:                    $result .= "\n";
 1982:     } elsif ($default) {
 1983:         $result .= '<input type="hidden" name="'.$name.
 1984:                    '" value="default" />';
 1985:                    if (!$hide) {
 1986:                        $result .= &mt('default');
 1987:                    }
 1988:                    $result .= "\n";
 1989:     }
 1990:     return ($result,$numlib);
 1991: }
 1992: 
 1993: =pod
 1994: 
 1995: =back 
 1996: 
 1997: =cut
 1998: 
 1999: ###############################################################
 2000: ##                  Decoding User Agent                      ##
 2001: ###############################################################
 2002: 
 2003: =pod
 2004: 
 2005: =head1 Decoding the User Agent
 2006: 
 2007: =over 4
 2008: 
 2009: =item * &decode_user_agent()
 2010: 
 2011: Inputs: $r
 2012: 
 2013: Outputs:
 2014: 
 2015: =over 4
 2016: 
 2017: =item * $httpbrowser
 2018: 
 2019: =item * $clientbrowser
 2020: 
 2021: =item * $clientversion
 2022: 
 2023: =item * $clientmathml
 2024: 
 2025: =item * $clientunicode
 2026: 
 2027: =item * $clientos
 2028: 
 2029: =back
 2030: 
 2031: =back 
 2032: 
 2033: =cut
 2034: 
 2035: ###############################################################
 2036: ###############################################################
 2037: sub decode_user_agent {
 2038:     my ($r)=@_;
 2039:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2040:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2041:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2042:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2043:     my $clientbrowser='unknown';
 2044:     my $clientversion='0';
 2045:     my $clientmathml='';
 2046:     my $clientunicode='0';
 2047:     for (my $i=0;$i<=$#browsertype;$i++) {
 2048:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2049: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2050: 	    $clientbrowser=$bname;
 2051:             $httpbrowser=~/$vreg/i;
 2052: 	    $clientversion=$1;
 2053:             $clientmathml=($clientversion>=$minv);
 2054:             $clientunicode=($clientversion>=$univ);
 2055: 	}
 2056:     }
 2057:     my $clientos='unknown';
 2058:     if (($httpbrowser=~/linux/i) ||
 2059:         ($httpbrowser=~/unix/i) ||
 2060:         ($httpbrowser=~/ux/i) ||
 2061:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2062:     if (($httpbrowser=~/vax/i) ||
 2063:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2064:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2065:     if (($httpbrowser=~/mac/i) ||
 2066:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2067:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2068:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2069:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2070:             $clientunicode,$clientos,);
 2071: }
 2072: 
 2073: ###############################################################
 2074: ##    Authentication changing form generation subroutines    ##
 2075: ###############################################################
 2076: ##
 2077: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2078: ## hash, and have reasonable default values.
 2079: ##
 2080: ##    formname = the name given in the <form> tag.
 2081: #-------------------------------------------
 2082: 
 2083: =pod
 2084: 
 2085: =head1 Authentication Routines
 2086: 
 2087: =over 4
 2088: 
 2089: =item * &authform_xxxxxx()
 2090: 
 2091: The authform_xxxxxx subroutines provide javascript and html forms which 
 2092: handle some of the conveniences required for authentication forms.  
 2093: This is not an optimal method, but it works.  
 2094: 
 2095: =over 4
 2096: 
 2097: =item * authform_header
 2098: 
 2099: =item * authform_authorwarning
 2100: 
 2101: =item * authform_nochange
 2102: 
 2103: =item * authform_kerberos
 2104: 
 2105: =item * authform_internal
 2106: 
 2107: =item * authform_filesystem
 2108: 
 2109: =back
 2110: 
 2111: See loncreateuser.pm for invocation and use examples.
 2112: 
 2113: =cut
 2114: 
 2115: #-------------------------------------------
 2116: sub authform_header{  
 2117:     my %in = (
 2118:         formname => 'cu',
 2119:         kerb_def_dom => '',
 2120:         @_,
 2121:     );
 2122:     $in{'formname'} = 'document.' . $in{'formname'};
 2123:     my $result='';
 2124: 
 2125: #---------------------------------------------- Code for upper case translation
 2126:     my $Javascript_toUpperCase;
 2127:     unless ($in{kerb_def_dom}) {
 2128:         $Javascript_toUpperCase =<<"END";
 2129:         switch (choice) {
 2130:            case 'krb': currentform.elements[choicearg].value =
 2131:                currentform.elements[choicearg].value.toUpperCase();
 2132:                break;
 2133:            default:
 2134:         }
 2135: END
 2136:     } else {
 2137:         $Javascript_toUpperCase = "";
 2138:     }
 2139: 
 2140:     my $radioval = "'nochange'";
 2141:     if (defined($in{'curr_authtype'})) {
 2142:         if ($in{'curr_authtype'} ne '') {
 2143:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2144:         }
 2145:     }
 2146:     my $argfield = 'null';
 2147:     if (defined($in{'mode'})) {
 2148:         if ($in{'mode'} eq 'modifycourse')  {
 2149:             if (defined($in{'curr_autharg'})) {
 2150:                 if ($in{'curr_autharg'} ne '') {
 2151:                     $argfield = "'$in{'curr_autharg'}'";
 2152:                 }
 2153:             }
 2154:         }
 2155:     }
 2156: 
 2157:     $result.=<<"END";
 2158: var current = new Object();
 2159: current.radiovalue = $radioval;
 2160: current.argfield = $argfield;
 2161: 
 2162: function changed_radio(choice,currentform) {
 2163:     var choicearg = choice + 'arg';
 2164:     // If a radio button in changed, we need to change the argfield
 2165:     if (current.radiovalue != choice) {
 2166:         current.radiovalue = choice;
 2167:         if (current.argfield != null) {
 2168:             currentform.elements[current.argfield].value = '';
 2169:         }
 2170:         if (choice == 'nochange') {
 2171:             current.argfield = null;
 2172:         } else {
 2173:             current.argfield = choicearg;
 2174:             switch(choice) {
 2175:                 case 'krb': 
 2176:                     currentform.elements[current.argfield].value = 
 2177:                         "$in{'kerb_def_dom'}";
 2178:                 break;
 2179:               default:
 2180:                 break;
 2181:             }
 2182:         }
 2183:     }
 2184:     return;
 2185: }
 2186: 
 2187: function changed_text(choice,currentform) {
 2188:     var choicearg = choice + 'arg';
 2189:     if (currentform.elements[choicearg].value !='') {
 2190:         $Javascript_toUpperCase
 2191:         // clear old field
 2192:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2193:             currentform.elements[current.argfield].value = '';
 2194:         }
 2195:         current.argfield = choicearg;
 2196:     }
 2197:     set_auth_radio_buttons(choice,currentform);
 2198:     return;
 2199: }
 2200: 
 2201: function set_auth_radio_buttons(newvalue,currentform) {
 2202:     var i=0;
 2203:     while (i < currentform.login.length) {
 2204:         if (currentform.login[i].value == newvalue) { break; }
 2205:         i++;
 2206:     }
 2207:     if (i == currentform.login.length) {
 2208:         return;
 2209:     }
 2210:     current.radiovalue = newvalue;
 2211:     currentform.login[i].checked = true;
 2212:     return;
 2213: }
 2214: END
 2215:     return $result;
 2216: }
 2217: 
 2218: sub authform_authorwarning{
 2219:     my $result='';
 2220:     $result='<i>'.
 2221:         &mt('As a general rule, only authors or co-authors should be '.
 2222:             'filesystem authenticated '.
 2223:             '(which allows access to the server filesystem).')."</i>\n";
 2224:     return $result;
 2225: }
 2226: 
 2227: sub authform_nochange{  
 2228:     my %in = (
 2229:               formname => 'document.cu',
 2230:               kerb_def_dom => 'MSU.EDU',
 2231:               @_,
 2232:           );
 2233:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2234:     my $result;
 2235:     if (keys(%can_assign) == 0) {
 2236:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2237:     } else {
 2238:         $result = '<label>'.&mt('[_1] Do not change login data',
 2239:                   '<input type="radio" name="login" value="nochange" '.
 2240:                   'checked="checked" onclick="'.
 2241:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2242: 	    '</label>';
 2243:     }
 2244:     return $result;
 2245: }
 2246: 
 2247: sub authform_kerberos {
 2248:     my %in = (
 2249:               formname => 'document.cu',
 2250:               kerb_def_dom => 'MSU.EDU',
 2251:               kerb_def_auth => 'krb4',
 2252:               @_,
 2253:               );
 2254:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2255:         $autharg,$jscall);
 2256:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2257:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2258:        $check5 = ' checked="checked"';
 2259:     } else {
 2260:        $check4 = ' checked="checked"';
 2261:     }
 2262:     $krbarg = $in{'kerb_def_dom'};
 2263:     if (defined($in{'curr_authtype'})) {
 2264:         if ($in{'curr_authtype'} eq 'krb') {
 2265:             $krbcheck = ' checked="checked"';
 2266:             if (defined($in{'mode'})) {
 2267:                 if ($in{'mode'} eq 'modifyuser') {
 2268:                     $krbcheck = '';
 2269:                 }
 2270:             }
 2271:             if (defined($in{'curr_kerb_ver'})) {
 2272:                 if ($in{'curr_krb_ver'} eq '5') {
 2273:                     $check5 = ' checked="checked"';
 2274:                     $check4 = '';
 2275:                 } else {
 2276:                     $check4 = ' checked="checked"';
 2277:                     $check5 = '';
 2278:                 }
 2279:             }
 2280:             if (defined($in{'curr_autharg'})) {
 2281:                 $krbarg = $in{'curr_autharg'};
 2282:             }
 2283:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2284:                 if (defined($in{'curr_autharg'})) {
 2285:                     $result = 
 2286:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2287:         $in{'curr_autharg'},$krbver);
 2288:                 } else {
 2289:                     $result =
 2290:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2291:                 }
 2292:                 return $result; 
 2293:             }
 2294:         }
 2295:     } else {
 2296:         if ($authnum == 1) {
 2297:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2298:         }
 2299:     }
 2300:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2301:         return;
 2302:     } elsif ($authtype eq '') {
 2303:         if (defined($in{'mode'})) {
 2304:             if ($in{'mode'} eq 'modifycourse') {
 2305:                 if ($authnum == 1) {
 2306:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2307:                 }
 2308:             }
 2309:         }
 2310:     }
 2311:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2312:     if ($authtype eq '') {
 2313:         $authtype = '<input type="radio" name="login" value="krb" '.
 2314:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2315:                     $krbcheck.' />';
 2316:     }
 2317:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2318:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2319:          $in{'curr_authtype'} eq 'krb5') ||
 2320:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2321:          $in{'curr_authtype'} eq 'krb4')) {
 2322:         $result .= &mt
 2323:         ('[_1] Kerberos authenticated with domain [_2] '.
 2324:          '[_3] Version 4 [_4] Version 5 [_5]',
 2325:          '<label>'.$authtype,
 2326:          '</label><input type="text" size="10" name="krbarg" '.
 2327:              'value="'.$krbarg.'" '.
 2328:              'onchange="'.$jscall.'" />',
 2329:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2330:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2331: 	 '</label>');
 2332:     } elsif ($can_assign{'krb4'}) {
 2333:         $result .= &mt
 2334:         ('[_1] Kerberos authenticated with domain [_2] '.
 2335:          '[_3] Version 4 [_4]',
 2336:          '<label>'.$authtype,
 2337:          '</label><input type="text" size="10" name="krbarg" '.
 2338:              'value="'.$krbarg.'" '.
 2339:              'onchange="'.$jscall.'" />',
 2340:          '<label><input type="hidden" name="krbver" value="4" />',
 2341:          '</label>');
 2342:     } elsif ($can_assign{'krb5'}) {
 2343:         $result .= &mt
 2344:         ('[_1] Kerberos authenticated with domain [_2] '.
 2345:          '[_3] Version 5 [_4]',
 2346:          '<label>'.$authtype,
 2347:          '</label><input type="text" size="10" name="krbarg" '.
 2348:              'value="'.$krbarg.'" '.
 2349:              'onchange="'.$jscall.'" />',
 2350:          '<label><input type="hidden" name="krbver" value="5" />',
 2351:          '</label>');
 2352:     }
 2353:     return $result;
 2354: }
 2355: 
 2356: sub authform_internal{  
 2357:     my %in = (
 2358:                 formname => 'document.cu',
 2359:                 kerb_def_dom => 'MSU.EDU',
 2360:                 @_,
 2361:                 );
 2362:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2363:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2364:     if (defined($in{'curr_authtype'})) {
 2365:         if ($in{'curr_authtype'} eq 'int') {
 2366:             if ($can_assign{'int'}) {
 2367:                 $intcheck = 'checked="checked" ';
 2368:                 if (defined($in{'mode'})) {
 2369:                     if ($in{'mode'} eq 'modifyuser') {
 2370:                         $intcheck = '';
 2371:                     }
 2372:                 }
 2373:                 if (defined($in{'curr_autharg'})) {
 2374:                     $intarg = $in{'curr_autharg'};
 2375:                 }
 2376:             } else {
 2377:                 $result = &mt('Currently internally authenticated.');
 2378:                 return $result;
 2379:             }
 2380:         }
 2381:     } else {
 2382:         if ($authnum == 1) {
 2383:             $authtype = '<input type="hidden" name="login" value="int" />';
 2384:         }
 2385:     }
 2386:     if (!$can_assign{'int'}) {
 2387:         return;
 2388:     } elsif ($authtype eq '') {
 2389:         if (defined($in{'mode'})) {
 2390:             if ($in{'mode'} eq 'modifycourse') {
 2391:                 if ($authnum == 1) {
 2392:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2393:                 }
 2394:             }
 2395:         }
 2396:     }
 2397:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2398:     if ($authtype eq '') {
 2399:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2400:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2401:     }
 2402:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2403:                $intarg.'" onchange="'.$jscall.'" />';
 2404:     $result = &mt
 2405:         ('[_1] Internally authenticated (with initial password [_2])',
 2406:          '<label>'.$authtype,'</label>'.$autharg);
 2407:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 2408:     return $result;
 2409: }
 2410: 
 2411: sub authform_local{  
 2412:     my %in = (
 2413:               formname => 'document.cu',
 2414:               kerb_def_dom => 'MSU.EDU',
 2415:               @_,
 2416:               );
 2417:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2418:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2419:     if (defined($in{'curr_authtype'})) {
 2420:         if ($in{'curr_authtype'} eq 'loc') {
 2421:             if ($can_assign{'loc'}) {
 2422:                 $loccheck = 'checked="checked" ';
 2423:                 if (defined($in{'mode'})) {
 2424:                     if ($in{'mode'} eq 'modifyuser') {
 2425:                         $loccheck = '';
 2426:                     }
 2427:                 }
 2428:                 if (defined($in{'curr_autharg'})) {
 2429:                     $locarg = $in{'curr_autharg'};
 2430:                 }
 2431:             } else {
 2432:                 $result = &mt('Currently using local (institutional) authentication.');
 2433:                 return $result;
 2434:             }
 2435:         }
 2436:     } else {
 2437:         if ($authnum == 1) {
 2438:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2439:         }
 2440:     }
 2441:     if (!$can_assign{'loc'}) {
 2442:         return;
 2443:     } elsif ($authtype eq '') {
 2444:         if (defined($in{'mode'})) {
 2445:             if ($in{'mode'} eq 'modifycourse') {
 2446:                 if ($authnum == 1) {
 2447:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2448:                 }
 2449:             }
 2450:         }
 2451:     }
 2452:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2453:     if ($authtype eq '') {
 2454:         $authtype = '<input type="radio" name="login" value="loc" '.
 2455:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2456:                     $jscall.'" />';
 2457:     }
 2458:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2459:                $locarg.'" onchange="'.$jscall.'" />';
 2460:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2461:                   '<label>'.$authtype,'</label>'.$autharg);
 2462:     return $result;
 2463: }
 2464: 
 2465: sub authform_filesystem{  
 2466:     my %in = (
 2467:               formname => 'document.cu',
 2468:               kerb_def_dom => 'MSU.EDU',
 2469:               @_,
 2470:               );
 2471:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2472:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2473:     if (defined($in{'curr_authtype'})) {
 2474:         if ($in{'curr_authtype'} eq 'fsys') {
 2475:             if ($can_assign{'fsys'}) {
 2476:                 $fsyscheck = 'checked="checked" ';
 2477:                 if (defined($in{'mode'})) {
 2478:                     if ($in{'mode'} eq 'modifyuser') {
 2479:                         $fsyscheck = '';
 2480:                     }
 2481:                 }
 2482:             } else {
 2483:                 $result = &mt('Currently Filesystem Authenticated.');
 2484:                 return $result;
 2485:             }           
 2486:         }
 2487:     } else {
 2488:         if ($authnum == 1) {
 2489:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2490:         }
 2491:     }
 2492:     if (!$can_assign{'fsys'}) {
 2493:         return;
 2494:     } elsif ($authtype eq '') {
 2495:         if (defined($in{'mode'})) {
 2496:             if ($in{'mode'} eq 'modifycourse') {
 2497:                 if ($authnum == 1) {
 2498:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2499:                 }
 2500:             }
 2501:         }
 2502:     }
 2503:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2504:     if ($authtype eq '') {
 2505:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2506:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2507:                     $jscall.'" />';
 2508:     }
 2509:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2510:                ' onchange="'.$jscall.'" />';
 2511:     $result = &mt
 2512:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2513:          '<label><input type="radio" name="login" value="fsys" '.
 2514:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2515:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2516:                   'onchange="'.$jscall.'" />');
 2517:     return $result;
 2518: }
 2519: 
 2520: sub get_assignable_auth {
 2521:     my ($dom) = @_;
 2522:     if ($dom eq '') {
 2523:         $dom = $env{'request.role.domain'};
 2524:     }
 2525:     my %can_assign = (
 2526:                           krb4 => 1,
 2527:                           krb5 => 1,
 2528:                           int  => 1,
 2529:                           loc  => 1,
 2530:                      );
 2531:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2532:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2533:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2534:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2535:             my $context;
 2536:             if ($env{'request.role'} =~ /^au/) {
 2537:                 $context = 'author';
 2538:             } elsif ($env{'request.role'} =~ /^dc/) {
 2539:                 $context = 'domain';
 2540:             } elsif ($env{'request.course.id'}) {
 2541:                 $context = 'course';
 2542:             }
 2543:             if ($context) {
 2544:                 if (ref($authhash->{$context}) eq 'HASH') {
 2545:                    %can_assign = %{$authhash->{$context}}; 
 2546:                 }
 2547:             }
 2548:         }
 2549:     }
 2550:     my $authnum = 0;
 2551:     foreach my $key (keys(%can_assign)) {
 2552:         if ($can_assign{$key}) {
 2553:             $authnum ++;
 2554:         }
 2555:     }
 2556:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2557:         $authnum --;
 2558:     }
 2559:     return ($authnum,%can_assign);
 2560: }
 2561: 
 2562: ###############################################################
 2563: ##    Get Kerberos Defaults for Domain                 ##
 2564: ###############################################################
 2565: ##
 2566: ## Returns default kerberos version and an associated argument
 2567: ## as listed in file domain.tab. If not listed, provides
 2568: ## appropriate default domain and kerberos version.
 2569: ##
 2570: #-------------------------------------------
 2571: 
 2572: =pod
 2573: 
 2574: =item * &get_kerberos_defaults()
 2575: 
 2576: get_kerberos_defaults($target_domain) returns the default kerberos
 2577: version and domain. If not found, it defaults to version 4 and the 
 2578: domain of the server.
 2579: 
 2580: =over 4
 2581: 
 2582: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2583: 
 2584: =back
 2585: 
 2586: =back
 2587: 
 2588: =cut
 2589: 
 2590: #-------------------------------------------
 2591: sub get_kerberos_defaults {
 2592:     my $domain=shift;
 2593:     my ($krbdef,$krbdefdom);
 2594:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2595:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2596:         $krbdef = $domdefaults{'auth_def'};
 2597:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2598:     } else {
 2599:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2600:         my $krbdefdom=$1;
 2601:         $krbdefdom=~tr/a-z/A-Z/;
 2602:         $krbdef = "krb4";
 2603:     }
 2604:     return ($krbdef,$krbdefdom);
 2605: }
 2606: 
 2607: 
 2608: ###############################################################
 2609: ##                Thesaurus Functions                        ##
 2610: ###############################################################
 2611: 
 2612: =pod
 2613: 
 2614: =head1 Thesaurus Functions
 2615: 
 2616: =over 4
 2617: 
 2618: =item * &initialize_keywords()
 2619: 
 2620: Initializes the package variable %Keywords if it is empty.  Uses the
 2621: package variable $thesaurus_db_file.
 2622: 
 2623: =cut
 2624: 
 2625: ###################################################
 2626: 
 2627: sub initialize_keywords {
 2628:     return 1 if (scalar keys(%Keywords));
 2629:     # If we are here, %Keywords is empty, so fill it up
 2630:     #   Make sure the file we need exists...
 2631:     if (! -e $thesaurus_db_file) {
 2632:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2633:                                  " failed because it does not exist");
 2634:         return 0;
 2635:     }
 2636:     #   Set up the hash as a database
 2637:     my %thesaurus_db;
 2638:     if (! tie(%thesaurus_db,'GDBM_File',
 2639:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2640:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2641:                                  $thesaurus_db_file);
 2642:         return 0;
 2643:     } 
 2644:     #  Get the average number of appearances of a word.
 2645:     my $avecount = $thesaurus_db{'average.count'};
 2646:     #  Put keywords (those that appear > average) into %Keywords
 2647:     while (my ($word,$data)=each (%thesaurus_db)) {
 2648:         my ($count,undef) = split /:/,$data;
 2649:         $Keywords{$word}++ if ($count > $avecount);
 2650:     }
 2651:     untie %thesaurus_db;
 2652:     # Remove special values from %Keywords.
 2653:     foreach my $value ('total.count','average.count') {
 2654:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2655:   }
 2656:     return 1;
 2657: }
 2658: 
 2659: ###################################################
 2660: 
 2661: =pod
 2662: 
 2663: =item * &keyword($word)
 2664: 
 2665: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2666: than the average number of times in the thesaurus database.  Calls 
 2667: &initialize_keywords
 2668: 
 2669: =cut
 2670: 
 2671: ###################################################
 2672: 
 2673: sub keyword {
 2674:     return if (!&initialize_keywords());
 2675:     my $word=lc(shift());
 2676:     $word=~s/\W//g;
 2677:     return exists($Keywords{$word});
 2678: }
 2679: 
 2680: ###############################################################
 2681: 
 2682: =pod 
 2683: 
 2684: =item * &get_related_words()
 2685: 
 2686: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2687: an array of words.  If the keyword is not in the thesaurus, an empty array
 2688: will be returned.  The order of the words returned is determined by the
 2689: database which holds them.
 2690: 
 2691: Uses global $thesaurus_db_file.
 2692: 
 2693: =cut
 2694: 
 2695: ###############################################################
 2696: sub get_related_words {
 2697:     my $keyword = shift;
 2698:     my %thesaurus_db;
 2699:     if (! -e $thesaurus_db_file) {
 2700:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2701:                                  "failed because the file does not exist");
 2702:         return ();
 2703:     }
 2704:     if (! tie(%thesaurus_db,'GDBM_File',
 2705:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2706:         return ();
 2707:     } 
 2708:     my @Words=();
 2709:     my $count=0;
 2710:     if (exists($thesaurus_db{$keyword})) {
 2711: 	# The first element is the number of times
 2712: 	# the word appears.  We do not need it now.
 2713: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2714: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2715: 	my $threshold=$mostfrequentcount/10;
 2716:         foreach my $possibleword (@RelatedWords) {
 2717:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2718:             if ($wordcount>$threshold) {
 2719: 		push(@Words,$word);
 2720:                 $count++;
 2721:                 if ($count>10) { last; }
 2722: 	    }
 2723:         }
 2724:     }
 2725:     untie %thesaurus_db;
 2726:     return @Words;
 2727: }
 2728: 
 2729: =pod
 2730: 
 2731: =back
 2732: 
 2733: =cut
 2734: 
 2735: # -------------------------------------------------------------- Plaintext name
 2736: =pod
 2737: 
 2738: =head1 User Name Functions
 2739: 
 2740: =over 4
 2741: 
 2742: =item * &plainname($uname,$udom,$first)
 2743: 
 2744: Takes a users logon name and returns it as a string in
 2745: "first middle last generation" form 
 2746: if $first is set to 'lastname' then it returns it as
 2747: 'lastname generation, firstname middlename' if their is a lastname
 2748: 
 2749: =cut
 2750: 
 2751: 
 2752: ###############################################################
 2753: sub plainname {
 2754:     my ($uname,$udom,$first)=@_;
 2755:     return if (!defined($uname) || !defined($udom));
 2756:     my %names=&getnames($uname,$udom);
 2757:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2758: 					  $names{'middlename'},
 2759: 					  $names{'lastname'},
 2760: 					  $names{'generation'},$first);
 2761:     $name=~s/^\s+//;
 2762:     $name=~s/\s+$//;
 2763:     $name=~s/\s+/ /g;
 2764:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2765:     return $name;
 2766: }
 2767: 
 2768: # -------------------------------------------------------------------- Nickname
 2769: =pod
 2770: 
 2771: =item * &nickname($uname,$udom)
 2772: 
 2773: Gets a users name and returns it as a string as
 2774: 
 2775: "&quot;nickname&quot;"
 2776: 
 2777: if the user has a nickname or
 2778: 
 2779: "first middle last generation"
 2780: 
 2781: if the user does not
 2782: 
 2783: =cut
 2784: 
 2785: sub nickname {
 2786:     my ($uname,$udom)=@_;
 2787:     return if (!defined($uname) || !defined($udom));
 2788:     my %names=&getnames($uname,$udom);
 2789:     my $name=$names{'nickname'};
 2790:     if ($name) {
 2791:        $name='&quot;'.$name.'&quot;'; 
 2792:     } else {
 2793:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2794: 	     $names{'lastname'}.' '.$names{'generation'};
 2795:        $name=~s/\s+$//;
 2796:        $name=~s/\s+/ /g;
 2797:     }
 2798:     return $name;
 2799: }
 2800: 
 2801: sub getnames {
 2802:     my ($uname,$udom)=@_;
 2803:     return if (!defined($uname) || !defined($udom));
 2804:     if ($udom eq 'public' && $uname eq 'public') {
 2805: 	return ('lastname' => &mt('Public'));
 2806:     }
 2807:     my $id=$uname.':'.$udom;
 2808:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2809:     if ($cached) {
 2810: 	return %{$names};
 2811:     } else {
 2812: 	my %loadnames=&Apache::lonnet::get('environment',
 2813:                     ['firstname','middlename','lastname','generation','nickname'],
 2814: 					 $udom,$uname);
 2815: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2816: 	return %loadnames;
 2817:     }
 2818: }
 2819: 
 2820: # -------------------------------------------------------------------- getemails
 2821: 
 2822: =pod
 2823: 
 2824: =item * &getemails($uname,$udom)
 2825: 
 2826: Gets a user's email information and returns it as a hash with keys:
 2827: notification, critnotification, permanentemail
 2828: 
 2829: For notification and critnotification, values are comma-separated lists 
 2830: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2831:  
 2832: 
 2833: =cut
 2834: 
 2835: 
 2836: sub getemails {
 2837:     my ($uname,$udom)=@_;
 2838:     if ($udom eq 'public' && $uname eq 'public') {
 2839: 	return;
 2840:     }
 2841:     if (!$udom) { $udom=$env{'user.domain'}; }
 2842:     if (!$uname) { $uname=$env{'user.name'}; }
 2843:     my $id=$uname.':'.$udom;
 2844:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2845:     if ($cached) {
 2846: 	return %{$names};
 2847:     } else {
 2848: 	my %loadnames=&Apache::lonnet::get('environment',
 2849:                     			   ['notification','critnotification',
 2850: 					    'permanentemail'],
 2851: 					   $udom,$uname);
 2852: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2853: 	return %loadnames;
 2854:     }
 2855: }
 2856: 
 2857: sub flush_email_cache {
 2858:     my ($uname,$udom)=@_;
 2859:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2860:     if (!$uname) { $uname=$env{'user.name'};   }
 2861:     return if ($udom eq 'public' && $uname eq 'public');
 2862:     my $id=$uname.':'.$udom;
 2863:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2864: }
 2865: 
 2866: # -------------------------------------------------------------------- getlangs
 2867: 
 2868: =pod
 2869: 
 2870: =item * &getlangs($uname,$udom)
 2871: 
 2872: Gets a user's language preference and returns it as a hash with key:
 2873: language.
 2874: 
 2875: =cut
 2876: 
 2877: 
 2878: sub getlangs {
 2879:     my ($uname,$udom) = @_;
 2880:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2881:     if (!$uname) { $uname=$env{'user.name'};   }
 2882:     my $id=$uname.':'.$udom;
 2883:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2884:     if ($cached) {
 2885:         return %{$langs};
 2886:     } else {
 2887:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2888:                                            $udom,$uname);
 2889:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2890:         return %loadlangs;
 2891:     }
 2892: }
 2893: 
 2894: sub flush_langs_cache {
 2895:     my ($uname,$udom)=@_;
 2896:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2897:     if (!$uname) { $uname=$env{'user.name'};   }
 2898:     return if ($udom eq 'public' && $uname eq 'public');
 2899:     my $id=$uname.':'.$udom;
 2900:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2901: }
 2902: 
 2903: # ------------------------------------------------------------------ Screenname
 2904: 
 2905: =pod
 2906: 
 2907: =item * &screenname($uname,$udom)
 2908: 
 2909: Gets a users screenname and returns it as a string
 2910: 
 2911: =cut
 2912: 
 2913: sub screenname {
 2914:     my ($uname,$udom)=@_;
 2915:     if ($uname eq $env{'user.name'} &&
 2916: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2917:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2918:     return $names{'screenname'};
 2919: }
 2920: 
 2921: # ------------------------------------------------------------- Confirm Wrapper
 2922: =pod
 2923: 
 2924: =item confirmwrapper
 2925: 
 2926: Wrap messages about completion of operation in box
 2927: 
 2928: =cut
 2929: 
 2930: sub confirmwrapper {
 2931:     my ($message)=@_;
 2932:     if ($message) {
 2933:         return "\n".'<div class="LC_confirm_box">'."\n"
 2934:                .$message."\n"
 2935:                .'</div>'."\n";
 2936:     } else {
 2937:         return $message;
 2938:     }
 2939: }
 2940: 
 2941: # ------------------------------------------------------------- Message Wrapper
 2942: 
 2943: sub messagewrapper {
 2944:     my ($link,$username,$domain,$subject,$text)=@_;
 2945:     return 
 2946:         '<a href="/adm/email?compose=individual&amp;'.
 2947:         'recname='.$username.'&amp;recdom='.$domain.
 2948: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2949:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2950: }
 2951: # --------------------------------------------------------------- Notes Wrapper
 2952: 
 2953: sub noteswrapper {
 2954:     my ($link,$un,$do)=@_;
 2955:     return 
 2956: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2957: }
 2958: # ------------------------------------------------------------- Aboutme Wrapper
 2959: 
 2960: sub aboutmewrapper {
 2961:     my ($link,$username,$domain,$target)=@_;
 2962:     if (!defined($username)  && !defined($domain)) {
 2963:         return;
 2964:     }
 2965:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2966: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2967: }
 2968: 
 2969: # ------------------------------------------------------------ Syllabus Wrapper
 2970: 
 2971: 
 2972: sub syllabuswrapper {
 2973:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2974:     if ($fontcolor) { 
 2975:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2976:     }
 2977:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2978: }
 2979: 
 2980: sub track_student_link {
 2981:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 2982:     my $link ="/adm/trackstudent?";
 2983:     my $title = 'View recent activity';
 2984:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2985:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2986:         $link .= "selected_student=$sname:$sdom";
 2987:         $title .= ' of this student';
 2988:     } 
 2989:     if (defined($target) && $target !~ /^\s*$/) {
 2990:         $target = qq{target="$target"};
 2991:     } else {
 2992:         $target = '';
 2993:     }
 2994:     if ($start) { $link.='&amp;start='.$start; }
 2995:     if ($only_body) { $link .= '&amp;only_body=1'; }
 2996:     $title = &mt($title);
 2997:     $linktext = &mt($linktext);
 2998:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2999: 	&help_open_topic('View_recent_activity');
 3000: }
 3001: 
 3002: sub slot_reservations_link {
 3003:     my ($linktext,$sname,$sdom,$target) = @_;
 3004:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3005:     my $title = 'View slot reservation history';
 3006:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3007:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3008:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3009:         $title .= ' of this student';
 3010:     }
 3011:     if (defined($target) && $target !~ /^\s*$/) {
 3012:         $target = qq{target="$target"};
 3013:     } else {
 3014:         $target = '';
 3015:     }
 3016:     $title = &mt($title);
 3017:     $linktext = &mt($linktext);
 3018:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3019: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3020: 
 3021: }
 3022: 
 3023: # ===================================================== Display a student photo
 3024: 
 3025: 
 3026: sub student_image_tag {
 3027:     my ($domain,$user)=@_;
 3028:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3029:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3030: 	return '<img src="'.$imgsrc.'" align="right" />';
 3031:     } else {
 3032: 	return '';
 3033:     }
 3034: }
 3035: 
 3036: =pod
 3037: 
 3038: =back
 3039: 
 3040: =head1 Access .tab File Data
 3041: 
 3042: =over 4
 3043: 
 3044: =item * &languageids() 
 3045: 
 3046: returns list of all language ids
 3047: 
 3048: =cut
 3049: 
 3050: sub languageids {
 3051:     return sort(keys(%language));
 3052: }
 3053: 
 3054: =pod
 3055: 
 3056: =item * &languagedescription() 
 3057: 
 3058: returns description of a specified language id
 3059: 
 3060: =cut
 3061: 
 3062: sub languagedescription {
 3063:     my $code=shift;
 3064:     return  ($supported_language{$code}?'* ':'').
 3065:             $language{$code}.
 3066: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3067: }
 3068: 
 3069: sub plainlanguagedescription {
 3070:     my $code=shift;
 3071:     return $language{$code};
 3072: }
 3073: 
 3074: sub supportedlanguagecode {
 3075:     my $code=shift;
 3076:     return $supported_language{$code};
 3077: }
 3078: 
 3079: =pod
 3080: 
 3081: =item * &copyrightids() 
 3082: 
 3083: returns list of all copyrights
 3084: 
 3085: =cut
 3086: 
 3087: sub copyrightids {
 3088:     return sort(keys(%cprtag));
 3089: }
 3090: 
 3091: =pod
 3092: 
 3093: =item * &copyrightdescription() 
 3094: 
 3095: returns description of a specified copyright id
 3096: 
 3097: =cut
 3098: 
 3099: sub copyrightdescription {
 3100:     return &mt($cprtag{shift(@_)});
 3101: }
 3102: 
 3103: =pod
 3104: 
 3105: =item * &source_copyrightids() 
 3106: 
 3107: returns list of all source copyrights
 3108: 
 3109: =cut
 3110: 
 3111: sub source_copyrightids {
 3112:     return sort(keys(%scprtag));
 3113: }
 3114: 
 3115: =pod
 3116: 
 3117: =item * &source_copyrightdescription() 
 3118: 
 3119: returns description of a specified source copyright id
 3120: 
 3121: =cut
 3122: 
 3123: sub source_copyrightdescription {
 3124:     return &mt($scprtag{shift(@_)});
 3125: }
 3126: 
 3127: =pod
 3128: 
 3129: =item * &filecategories() 
 3130: 
 3131: returns list of all file categories
 3132: 
 3133: =cut
 3134: 
 3135: sub filecategories {
 3136:     return sort(keys(%category_extensions));
 3137: }
 3138: 
 3139: =pod
 3140: 
 3141: =item * &filecategorytypes() 
 3142: 
 3143: returns list of file types belonging to a given file
 3144: category
 3145: 
 3146: =cut
 3147: 
 3148: sub filecategorytypes {
 3149:     my ($cat) = @_;
 3150:     return @{$category_extensions{lc($cat)}};
 3151: }
 3152: 
 3153: =pod
 3154: 
 3155: =item * &fileembstyle() 
 3156: 
 3157: returns embedding style for a specified file type
 3158: 
 3159: =cut
 3160: 
 3161: sub fileembstyle {
 3162:     return $fe{lc(shift(@_))};
 3163: }
 3164: 
 3165: sub filemimetype {
 3166:     return $fm{lc(shift(@_))};
 3167: }
 3168: 
 3169: 
 3170: sub filecategoryselect {
 3171:     my ($name,$value)=@_;
 3172:     return &select_form($value,$name,
 3173: 			'' => &mt('Any category'),
 3174: 			map { $_,$_ } sort(keys(%category_extensions)));
 3175: }
 3176: 
 3177: =pod
 3178: 
 3179: =item * &filedescription() 
 3180: 
 3181: returns description for a specified file type
 3182: 
 3183: =cut
 3184: 
 3185: sub filedescription {
 3186:     my $file_description = $fd{lc(shift())};
 3187:     $file_description =~ s:([\[\]]):~$1:g;
 3188:     return &mt($file_description);
 3189: }
 3190: 
 3191: =pod
 3192: 
 3193: =item * &filedescriptionex() 
 3194: 
 3195: returns description for a specified file type with
 3196: extra formatting
 3197: 
 3198: =cut
 3199: 
 3200: sub filedescriptionex {
 3201:     my $ex=shift;
 3202:     my $file_description = $fd{lc($ex)};
 3203:     $file_description =~ s:([\[\]]):~$1:g;
 3204:     return '.'.$ex.' '.&mt($file_description);
 3205: }
 3206: 
 3207: # End of .tab access
 3208: =pod
 3209: 
 3210: =back
 3211: 
 3212: =cut
 3213: 
 3214: # ------------------------------------------------------------------ File Types
 3215: sub fileextensions {
 3216:     return sort(keys(%fe));
 3217: }
 3218: 
 3219: # ----------------------------------------------------------- Display Languages
 3220: # returns a hash with all desired display languages
 3221: #
 3222: 
 3223: sub display_languages {
 3224:     my %languages=();
 3225:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3226: 	$languages{$lang}=1;
 3227:     }
 3228:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3229:     if ($env{'form.displaylanguage'}) {
 3230: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3231: 	    $languages{$lang}=1;
 3232:         }
 3233:     }
 3234:     return %languages;
 3235: }
 3236: 
 3237: sub languages {
 3238:     my ($possible_langs) = @_;
 3239:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3240:     if (!ref($possible_langs)) {
 3241: 	if( wantarray ) {
 3242: 	    return @preferred_langs;
 3243: 	} else {
 3244: 	    return $preferred_langs[0];
 3245: 	}
 3246:     }
 3247:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3248:     my @preferred_possibilities;
 3249:     foreach my $preferred_lang (@preferred_langs) {
 3250: 	if (exists($possibilities{$preferred_lang})) {
 3251: 	    push(@preferred_possibilities, $preferred_lang);
 3252: 	}
 3253:     }
 3254:     if( wantarray ) {
 3255: 	return @preferred_possibilities;
 3256:     }
 3257:     return $preferred_possibilities[0];
 3258: }
 3259: 
 3260: sub user_lang {
 3261:     my ($touname,$toudom,$fromcid) = @_;
 3262:     my @userlangs;
 3263:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3264:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3265:                     $env{'course.'.$fromcid.'.languages'}));
 3266:     } else {
 3267:         my %langhash = &getlangs($touname,$toudom);
 3268:         if ($langhash{'languages'} ne '') {
 3269:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3270:         } else {
 3271:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3272:             if ($domdefs{'lang_def'} ne '') {
 3273:                 @userlangs = ($domdefs{'lang_def'});
 3274:             }
 3275:         }
 3276:     }
 3277:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3278:     my $user_lh = Apache::localize->get_handle(@languages);
 3279:     return $user_lh;
 3280: }
 3281: 
 3282: ###############################################################
 3283: ##               Student Answer Attempts                     ##
 3284: ###############################################################
 3285: 
 3286: =pod
 3287: 
 3288: =head1 Alternate Problem Views
 3289: 
 3290: =over 4
 3291: 
 3292: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3293:     $getattempt, $regexp, $gradesub)
 3294: 
 3295: Return string with previous attempt on problem. Arguments:
 3296: 
 3297: =over 4
 3298: 
 3299: =item * $symb: Problem, including path
 3300: 
 3301: =item * $username: username of the desired student
 3302: 
 3303: =item * $domain: domain of the desired student
 3304: 
 3305: =item * $course: Course ID
 3306: 
 3307: =item * $getattempt: Leave blank for all attempts, otherwise put
 3308:     something
 3309: 
 3310: =item * $regexp: if string matches this regexp, the string will be
 3311:     sent to $gradesub
 3312: 
 3313: =item * $gradesub: routine that processes the string if it matches $regexp
 3314: 
 3315: =back
 3316: 
 3317: The output string is a table containing all desired attempts, if any.
 3318: 
 3319: =cut
 3320: 
 3321: sub get_previous_attempt {
 3322:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3323:   my $prevattempts='';
 3324:   no strict 'refs';
 3325:   if ($symb) {
 3326:     my (%returnhash)=
 3327:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3328:     if ($returnhash{'version'}) {
 3329:       my %lasthash=();
 3330:       my $version;
 3331:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3332:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3333: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3334:         }
 3335:       }
 3336:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3337:       $prevattempts.='<th>'.&mt('History').'</th>';
 3338:       foreach my $key (sort(keys(%lasthash))) {
 3339: 	my ($ign,@parts) = split(/\./,$key);
 3340: 	if ($#parts > 0) {
 3341: 	  my $data=$parts[-1];
 3342: 	  pop(@parts);
 3343: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3344: 	} else {
 3345: 	  if ($#parts == 0) {
 3346: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3347: 	  } else {
 3348: 	    $prevattempts.='<th>'.$ign.'</th>';
 3349: 	  }
 3350: 	}
 3351:       }
 3352:       $prevattempts.=&end_data_table_header_row();
 3353:       if ($getattempt eq '') {
 3354: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3355: 	  $prevattempts.=&start_data_table_row().
 3356: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3357: 	    foreach my $key (sort(keys(%lasthash))) {
 3358: 		my $value = &format_previous_attempt_value($key,
 3359: 							   $returnhash{$version.':'.$key});
 3360: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3361: 	    }
 3362: 	  $prevattempts.=&end_data_table_row();
 3363: 	 }
 3364:       }
 3365:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3366:       foreach my $key (sort(keys(%lasthash))) {
 3367: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3368: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3369: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3370:       }
 3371:       $prevattempts.= &end_data_table_row().&end_data_table();
 3372:     } else {
 3373:       $prevattempts=
 3374: 	  &start_data_table().&start_data_table_row().
 3375: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3376: 	  &end_data_table_row().&end_data_table();
 3377:     }
 3378:   } else {
 3379:     $prevattempts=
 3380: 	  &start_data_table().&start_data_table_row().
 3381: 	  '<td>'.&mt('No data.').'</td>'.
 3382: 	  &end_data_table_row().&end_data_table();
 3383:   }
 3384: }
 3385: 
 3386: sub format_previous_attempt_value {
 3387:     my ($key,$value) = @_;
 3388:     if ($key =~ /timestamp/) {
 3389: 	$value = &Apache::lonlocal::locallocaltime($value);
 3390:     } elsif (ref($value) eq 'ARRAY') {
 3391: 	$value = '('.join(', ', @{ $value }).')';
 3392:     } else {
 3393: 	$value = &unescape($value);
 3394:     }
 3395:     return $value;
 3396: }
 3397: 
 3398: 
 3399: sub relative_to_absolute {
 3400:     my ($url,$output)=@_;
 3401:     my $parser=HTML::TokeParser->new(\$output);
 3402:     my $token;
 3403:     my $thisdir=$url;
 3404:     my @rlinks=();
 3405:     while ($token=$parser->get_token) {
 3406: 	if ($token->[0] eq 'S') {
 3407: 	    if ($token->[1] eq 'a') {
 3408: 		if ($token->[2]->{'href'}) {
 3409: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3410: 		}
 3411: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3412: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3413: 	    } elsif ($token->[1] eq 'base') {
 3414: 		$thisdir=$token->[2]->{'href'};
 3415: 	    }
 3416: 	}
 3417:     }
 3418:     $thisdir=~s-/[^/]*$--;
 3419:     foreach my $link (@rlinks) {
 3420: 	unless (($link=~/^https?\:\/\//i) ||
 3421: 		($link=~/^\//) ||
 3422: 		($link=~/^javascript:/i) ||
 3423: 		($link=~/^mailto:/i) ||
 3424: 		($link=~/^\#/)) {
 3425: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3426: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3427: 	}
 3428:     }
 3429: # -------------------------------------------------- Deal with Applet codebases
 3430:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3431:     return $output;
 3432: }
 3433: 
 3434: =pod
 3435: 
 3436: =item * &get_student_view()
 3437: 
 3438: show a snapshot of what student was looking at
 3439: 
 3440: =cut
 3441: 
 3442: sub get_student_view {
 3443:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3444:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3445:   my (%form);
 3446:   my @elements=('symb','courseid','domain','username');
 3447:   foreach my $element (@elements) {
 3448:       $form{'grade_'.$element}=eval '$'.$element #'
 3449:   }
 3450:   if (defined($moreenv)) {
 3451:       %form=(%form,%{$moreenv});
 3452:   }
 3453:   if (defined($target)) { $form{'grade_target'} = $target; }
 3454:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3455:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3456:   $userview=~s/\<body[^\>]*\>//gi;
 3457:   $userview=~s/\<\/body\>//gi;
 3458:   $userview=~s/\<html\>//gi;
 3459:   $userview=~s/\<\/html\>//gi;
 3460:   $userview=~s/\<head\>//gi;
 3461:   $userview=~s/\<\/head\>//gi;
 3462:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3463:   $userview=&relative_to_absolute($feedurl,$userview);
 3464:   if (wantarray) {
 3465:      return ($userview,$response);
 3466:   } else {
 3467:      return $userview;
 3468:   }
 3469: }
 3470: 
 3471: sub get_student_view_with_retries {
 3472:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3473: 
 3474:     my $ok = 0;                 # True if we got a good response.
 3475:     my $content;
 3476:     my $response;
 3477: 
 3478:     # Try to get the student_view done. within the retries count:
 3479:     
 3480:     do {
 3481:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3482:          $ok      = $response->is_success;
 3483:          if (!$ok) {
 3484:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3485:          }
 3486:          $retries--;
 3487:     } while (!$ok && ($retries > 0));
 3488:     
 3489:     if (!$ok) {
 3490:        $content = '';          # On error return an empty content.
 3491:     }
 3492:     if (wantarray) {
 3493:        return ($content, $response);
 3494:     } else {
 3495:        return $content;
 3496:     }
 3497: }
 3498: 
 3499: =pod
 3500: 
 3501: =item * &get_student_answers() 
 3502: 
 3503: show a snapshot of how student was answering problem
 3504: 
 3505: =cut
 3506: 
 3507: sub get_student_answers {
 3508:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3509:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3510:   my (%moreenv);
 3511:   my @elements=('symb','courseid','domain','username');
 3512:   foreach my $element (@elements) {
 3513:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3514:   }
 3515:   $moreenv{'grade_target'}='answer';
 3516:   %moreenv=(%form,%moreenv);
 3517:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3518:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3519:   return $userview;
 3520: }
 3521: 
 3522: =pod
 3523: 
 3524: =item * &submlink()
 3525: 
 3526: Inputs: $text $uname $udom $symb $target
 3527: 
 3528: Returns: A link to grades.pm such as to see the SUBM view of a student
 3529: 
 3530: =cut
 3531: 
 3532: ###############################################
 3533: sub submlink {
 3534:     my ($text,$uname,$udom,$symb,$target)=@_;
 3535:     if (!($uname && $udom)) {
 3536: 	(my $cursymb, my $courseid,$udom,$uname)=
 3537: 	    &Apache::lonnet::whichuser($symb);
 3538: 	if (!$symb) { $symb=$cursymb; }
 3539:     }
 3540:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3541:     $symb=&escape($symb);
 3542:     if ($target) { $target="target=\"$target\""; }
 3543:     return '<a href="/adm/grades?&command=submission&'.
 3544: 	'symb='.$symb.'&student='.$uname.
 3545: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3546: }
 3547: ##############################################
 3548: 
 3549: =pod
 3550: 
 3551: =item * &pgrdlink()
 3552: 
 3553: Inputs: $text $uname $udom $symb $target
 3554: 
 3555: Returns: A link to grades.pm such as to see the PGRD view of a student
 3556: 
 3557: =cut
 3558: 
 3559: ###############################################
 3560: sub pgrdlink {
 3561:     my $link=&submlink(@_);
 3562:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3563:     return $link;
 3564: }
 3565: ##############################################
 3566: 
 3567: =pod
 3568: 
 3569: =item * &pprmlink()
 3570: 
 3571: Inputs: $text $uname $udom $symb $target
 3572: 
 3573: Returns: A link to parmset.pm such as to see the PPRM view of a
 3574: student and a specific resource
 3575: 
 3576: =cut
 3577: 
 3578: ###############################################
 3579: sub pprmlink {
 3580:     my ($text,$uname,$udom,$symb,$target)=@_;
 3581:     if (!($uname && $udom)) {
 3582: 	(my $cursymb, my $courseid,$udom,$uname)=
 3583: 	    &Apache::lonnet::whichuser($symb);
 3584: 	if (!$symb) { $symb=$cursymb; }
 3585:     }
 3586:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3587:     $symb=&escape($symb);
 3588:     if ($target) { $target="target=\"$target\""; }
 3589:     return '<a href="/adm/parmset?command=set&amp;'.
 3590: 	'symb='.$symb.'&amp;uname='.$uname.
 3591: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3592: }
 3593: ##############################################
 3594: 
 3595: =pod
 3596: 
 3597: =back
 3598: 
 3599: =cut
 3600: 
 3601: ###############################################
 3602: 
 3603: 
 3604: sub timehash {
 3605:     my ($thistime) = @_;
 3606:     my $timezone = &Apache::lonlocal::gettimezone();
 3607:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3608:                      ->set_time_zone($timezone);
 3609:     my $wday = $dt->day_of_week();
 3610:     if ($wday == 7) { $wday = 0; }
 3611:     return ( 'second' => $dt->second(),
 3612:              'minute' => $dt->minute(),
 3613:              'hour'   => $dt->hour(),
 3614:              'day'     => $dt->day_of_month(),
 3615:              'month'   => $dt->month(),
 3616:              'year'    => $dt->year(),
 3617:              'weekday' => $wday,
 3618:              'dayyear' => $dt->day_of_year(),
 3619:              'dlsav'   => $dt->is_dst() );
 3620: }
 3621: 
 3622: sub utc_string {
 3623:     my ($date)=@_;
 3624:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3625: }
 3626: 
 3627: sub maketime {
 3628:     my %th=@_;
 3629:     my ($epoch_time,$timezone,$dt);
 3630:     $timezone = &Apache::lonlocal::gettimezone();
 3631:     eval {
 3632:         $dt = DateTime->new( year   => $th{'year'},
 3633:                              month  => $th{'month'},
 3634:                              day    => $th{'day'},
 3635:                              hour   => $th{'hour'},
 3636:                              minute => $th{'minute'},
 3637:                              second => $th{'second'},
 3638:                              time_zone => $timezone,
 3639:                          );
 3640:     };
 3641:     if (!$@) {
 3642:         $epoch_time = $dt->epoch;
 3643:         if ($epoch_time) {
 3644:             return $epoch_time;
 3645:         }
 3646:     }
 3647:     return POSIX::mktime(
 3648:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3649:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3650: }
 3651: 
 3652: #########################################
 3653: 
 3654: sub findallcourses {
 3655:     my ($roles,$uname,$udom) = @_;
 3656:     my %roles;
 3657:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3658:     my %courses;
 3659:     my $now=time;
 3660:     if (!defined($uname)) {
 3661:         $uname = $env{'user.name'};
 3662:     }
 3663:     if (!defined($udom)) {
 3664:         $udom = $env{'user.domain'};
 3665:     }
 3666:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3667:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3668:         if (!%roles) {
 3669:             %roles = (
 3670:                        cc => 1,
 3671:                        in => 1,
 3672:                        ep => 1,
 3673:                        ta => 1,
 3674:                        cr => 1,
 3675:                        st => 1,
 3676:              );
 3677:         }
 3678:         foreach my $entry (keys(%roleshash)) {
 3679:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3680:             if ($trole =~ /^cr/) { 
 3681:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3682:             } else {
 3683:                 next if (!exists($roles{$trole}));
 3684:             }
 3685:             if ($tend) {
 3686:                 next if ($tend < $now);
 3687:             }
 3688:             if ($tstart) {
 3689:                 next if ($tstart > $now);
 3690:             }
 3691:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3692:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3693:             if ($secpart eq '') {
 3694:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3695:                 $sec = 'none';
 3696:                 $realsec = '';
 3697:             } else {
 3698:                 $cnum = $cnumpart;
 3699:                 ($sec,$role) = split(/_/,$secpart);
 3700:                 $realsec = $sec;
 3701:             }
 3702:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3703:         }
 3704:     } else {
 3705:         foreach my $key (keys(%env)) {
 3706: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3707:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3708: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3709: 	        next if ($role eq 'ca' || $role eq 'aa');
 3710: 	        next if (%roles && !exists($roles{$role}));
 3711: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3712:                 my $active=1;
 3713:                 if ($starttime) {
 3714: 		    if ($now<$starttime) { $active=0; }
 3715:                 }
 3716:                 if ($endtime) {
 3717:                     if ($now>$endtime) { $active=0; }
 3718:                 }
 3719:                 if ($active) {
 3720:                     if ($sec eq '') {
 3721:                         $sec = 'none';
 3722:                     }
 3723:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3724:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3725:                 }
 3726:             }
 3727:         }
 3728:     }
 3729:     return %courses;
 3730: }
 3731: 
 3732: ###############################################
 3733: 
 3734: sub blockcheck {
 3735:     my ($setters,$activity,$uname,$udom) = @_;
 3736: 
 3737:     if (!defined($udom)) {
 3738:         $udom = $env{'user.domain'};
 3739:     }
 3740:     if (!defined($uname)) {
 3741:         $uname = $env{'user.name'};
 3742:     }
 3743: 
 3744:     # If uname and udom are for a course, check for blocks in the course.
 3745: 
 3746:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3747:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3748:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3749:         return ($startblock,$endblock);
 3750:     }
 3751: 
 3752:     my $startblock = 0;
 3753:     my $endblock = 0;
 3754:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3755: 
 3756:     # If uname is for a user, and activity is course-specific, i.e.,
 3757:     # boards, chat or groups, check for blocking in current course only.
 3758: 
 3759:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3760:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3761:         foreach my $key (keys(%live_courses)) {
 3762:             if ($key ne $env{'request.course.id'}) {
 3763:                 delete($live_courses{$key});
 3764:             }
 3765:         }
 3766:     }
 3767: 
 3768:     my $otheruser = 0;
 3769:     my %own_courses;
 3770:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3771:         # Resource belongs to user other than current user.
 3772:         $otheruser = 1;
 3773:         # Gather courses for current user
 3774:         %own_courses = 
 3775:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3776:     }
 3777: 
 3778:     # Gather active course roles - course coordinator, instructor, 
 3779:     # exam proctor, ta, student, or custom role.
 3780: 
 3781:     foreach my $course (keys(%live_courses)) {
 3782:         my ($cdom,$cnum);
 3783:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3784:             $cdom = $env{'course.'.$course.'.domain'};
 3785:             $cnum = $env{'course.'.$course.'.num'};
 3786:         } else {
 3787:             ($cdom,$cnum) = split(/_/,$course); 
 3788:         }
 3789:         my $no_ownblock = 0;
 3790:         my $no_userblock = 0;
 3791:         if ($otheruser && $activity ne 'com') {
 3792:             # Check if current user has 'evb' priv for this
 3793:             if (defined($own_courses{$course})) {
 3794:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3795:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3796:                     if ($sec ne 'none') {
 3797:                         $checkrole .= '/'.$sec;
 3798:                     }
 3799:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3800:                         $no_ownblock = 1;
 3801:                         last;
 3802:                     }
 3803:                 }
 3804:             }
 3805:             # if they have 'evb' priv and are currently not playing student
 3806:             next if (($no_ownblock) &&
 3807:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3808:         }
 3809:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3810:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3811:             if ($sec ne 'none') {
 3812:                 $checkrole .= '/'.$sec;
 3813:             }
 3814:             if ($otheruser) {
 3815:                 # Resource belongs to user other than current user.
 3816:                 # Assemble privs for that user, and check for 'evb' priv.
 3817:                 my ($trole,$tdom,$tnum,$tsec);
 3818:                 my $entry = $live_courses{$course}{$sec};
 3819:                 if ($entry =~ /^cr/) {
 3820:                     ($trole,$tdom,$tnum,$tsec) = 
 3821:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3822:                 } else {
 3823:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3824:                 }
 3825:                 my ($spec,$area,$trest,%allroles,%userroles);
 3826:                 $area = '/'.$tdom.'/'.$tnum;
 3827:                 $trest = $tnum;
 3828:                 if ($tsec ne '') {
 3829:                     $area .= '/'.$tsec;
 3830:                     $trest .= '/'.$tsec;
 3831:                 }
 3832:                 $spec = $trole.'.'.$area;
 3833:                 if ($trole =~ /^cr/) {
 3834:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3835:                                                       $tdom,$spec,$trest,$area);
 3836:                 } else {
 3837:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3838:                                                        $tdom,$spec,$trest,$area);
 3839:                 }
 3840:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3841:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3842:                     if ($1) {
 3843:                         $no_userblock = 1;
 3844:                         last;
 3845:                     }
 3846:                 }
 3847:             } else {
 3848:                 # Resource belongs to current user
 3849:                 # Check for 'evb' priv via lonnet::allowed().
 3850:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3851:                     $no_ownblock = 1;
 3852:                     last;
 3853:                 }
 3854:             }
 3855:         }
 3856:         # if they have the evb priv and are currently not playing student
 3857:         next if (($no_ownblock) &&
 3858:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3859:         next if ($no_userblock);
 3860: 
 3861:         # Retrieve blocking times and identity of blocker for course
 3862:         # of specified user, unless user has 'evb' privilege.
 3863:         
 3864:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3865:         if (($start != 0) && 
 3866:             (($startblock == 0) || ($startblock > $start))) {
 3867:             $startblock = $start;
 3868:         }
 3869:         if (($end != 0)  &&
 3870:             (($endblock == 0) || ($endblock < $end))) {
 3871:             $endblock = $end;
 3872:         }
 3873:     }
 3874:     return ($startblock,$endblock);
 3875: }
 3876: 
 3877: sub get_blocks {
 3878:     my ($setters,$activity,$cdom,$cnum) = @_;
 3879:     my $startblock = 0;
 3880:     my $endblock = 0;
 3881:     my $course = $cdom.'_'.$cnum;
 3882:     $setters->{$course} = {};
 3883:     $setters->{$course}{'staff'} = [];
 3884:     $setters->{$course}{'times'} = [];
 3885:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3886:     foreach my $record (keys(%records)) {
 3887:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3888:         if ($start <= time && $end >= time) {
 3889:             my ($staff_name,$staff_dom,$title,$blocks) =
 3890:                 &parse_block_record($records{$record});
 3891:             if ($blocks->{$activity} eq 'on') {
 3892:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3893:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3894:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3895:                     $startblock = $start;
 3896:                 }
 3897:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3898:                     $endblock = $end;
 3899:                 }
 3900:             }
 3901:         }
 3902:     }
 3903:     return ($startblock,$endblock);
 3904: }
 3905: 
 3906: sub parse_block_record {
 3907:     my ($record) = @_;
 3908:     my ($setuname,$setudom,$title,$blocks);
 3909:     if (ref($record) eq 'HASH') {
 3910:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3911:         $title = &unescape($record->{'event'});
 3912:         $blocks = $record->{'blocks'};
 3913:     } else {
 3914:         my @data = split(/:/,$record,3);
 3915:         if (scalar(@data) eq 2) {
 3916:             $title = $data[1];
 3917:             ($setuname,$setudom) = split(/@/,$data[0]);
 3918:         } else {
 3919:             ($setuname,$setudom,$title) = @data;
 3920:         }
 3921:         $blocks = { 'com' => 'on' };
 3922:     }
 3923:     return ($setuname,$setudom,$title,$blocks);
 3924: }
 3925: 
 3926: sub build_block_table {
 3927:     my ($startblock,$endblock,$setters) = @_;
 3928:     my %lt = &Apache::lonlocal::texthash(
 3929:         'cacb' => 'Currently active communication blocks',
 3930:         'cour' => 'Course',
 3931:         'dura' => 'Duration',
 3932:         'blse' => 'Block set by'
 3933:     );
 3934:     my $output;
 3935:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3936:     $output .= &start_data_table();
 3937:     $output .= '
 3938: <tr>
 3939:  <th>'.$lt{'cour'}.'</th>
 3940:  <th>'.$lt{'dura'}.'</th>
 3941:  <th>'.$lt{'blse'}.'</th>
 3942: </tr>
 3943: ';
 3944:     foreach my $course (keys(%{$setters})) {
 3945:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3946:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3947:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3948:             my $fullname = &plainname($uname,$udom);
 3949:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3950:                 && $env{'user.name'} ne 'public' 
 3951:                 && $env{'user.domain'} ne 'public') {
 3952:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3953:             }
 3954:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3955:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3956:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3957:             $output .= &Apache::loncommon::start_data_table_row().
 3958:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3959:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3960:                        '<td>'.$fullname.'</td>'.
 3961:                         &Apache::loncommon::end_data_table_row();
 3962:         }
 3963:     }
 3964:     $output .= &end_data_table();
 3965: }
 3966: 
 3967: sub blocking_status {
 3968:     my ($activity,$uname,$udom) = @_;
 3969:     my %setters;
 3970:     my ($blocked,$output,$ownitem,$is_course);
 3971:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3972:     if ($startblock && $endblock) {
 3973:         $blocked = 1;
 3974:         if (wantarray) {
 3975:             my $category;
 3976:             if ($activity eq 'boards') {
 3977:                 $category = 'Discussion posts in this course';
 3978:             } elsif ($activity eq 'blogs') {
 3979:                 $category = 'Blogs';
 3980:             } elsif ($activity eq 'port') {
 3981:                 if (defined($uname) && defined($udom)) {
 3982:                     if ($uname eq $env{'user.name'} &&
 3983:                         $udom eq $env{'user.domain'}) {
 3984:                         $ownitem = 1;
 3985:                     }
 3986:                 }
 3987:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3988:                 if ($ownitem) { 
 3989:                     $category = 'Your portfolio files';  
 3990:                 } elsif ($is_course) {
 3991:                     my $coursedesc;
 3992:                     foreach my $course (keys(%setters)) {
 3993:                         my %courseinfo =
 3994:                              &Apache::lonnet::coursedescription($course);
 3995:                         $coursedesc = $courseinfo{'description'};
 3996:                     }
 3997:                     $category = "Group portfolio files in the course '$coursedesc'";
 3998:                 } else {
 3999:                     $category = 'Portfolio files belonging to ';
 4000:                     if ($env{'user.name'} eq 'public' && 
 4001:                         $env{'user.domain'} eq 'public') {
 4002:                         $category .= &plainname($uname,$udom);
 4003:                     } else {
 4004:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 4005:                     }
 4006:                 }
 4007:             } elsif ($activity eq 'groups') {
 4008:                 $category = 'Groups in this course';
 4009:             }
 4010:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 4011:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 4012:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 4013:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 4014:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 4015:             }
 4016:         }
 4017:     }
 4018:     if (wantarray) {
 4019:         return ($blocked,$output);
 4020:     } else {
 4021:         return $blocked;
 4022:     }
 4023: }
 4024: 
 4025: ###############################################
 4026: 
 4027: sub check_ip_acc {
 4028:     my ($acc)=@_;
 4029:     &Apache::lonxml::debug("acc is $acc");
 4030:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4031:         return 1;
 4032:     }
 4033:     my $allowed=0;
 4034:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4035: 
 4036:     my $name;
 4037:     foreach my $pattern (split(',',$acc)) {
 4038:         $pattern =~ s/^\s*//;
 4039:         $pattern =~ s/\s*$//;
 4040:         if ($pattern =~ /\*$/) {
 4041:             #35.8.*
 4042:             $pattern=~s/\*//;
 4043:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4044:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4045:             #35.8.3.[34-56]
 4046:             my $low=$2;
 4047:             my $high=$3;
 4048:             $pattern=$1;
 4049:             if ($ip =~ /^\Q$pattern\E/) {
 4050:                 my $last=(split(/\./,$ip))[3];
 4051:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4052:             }
 4053:         } elsif ($pattern =~ /^\*/) {
 4054:             #*.msu.edu
 4055:             $pattern=~s/\*//;
 4056:             if (!defined($name)) {
 4057:                 use Socket;
 4058:                 my $netaddr=inet_aton($ip);
 4059:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4060:             }
 4061:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4062:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4063:             #127.0.0.1
 4064:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4065:         } else {
 4066:             #some.name.com
 4067:             if (!defined($name)) {
 4068:                 use Socket;
 4069:                 my $netaddr=inet_aton($ip);
 4070:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4071:             }
 4072:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4073:         }
 4074:         if ($allowed) { last; }
 4075:     }
 4076:     return $allowed;
 4077: }
 4078: 
 4079: ###############################################
 4080: 
 4081: =pod
 4082: 
 4083: =head1 Domain Template Functions
 4084: 
 4085: =over 4
 4086: 
 4087: =item * &determinedomain()
 4088: 
 4089: Inputs: $domain (usually will be undef)
 4090: 
 4091: Returns: Determines which domain should be used for designs
 4092: 
 4093: =cut
 4094: 
 4095: ###############################################
 4096: sub determinedomain {
 4097:     my $domain=shift;
 4098:     if (! $domain) {
 4099:         # Determine domain if we have not been given one
 4100:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 4101:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4102:         if ($env{'request.role.domain'}) { 
 4103:             $domain=$env{'request.role.domain'}; 
 4104:         }
 4105:     }
 4106:     return $domain;
 4107: }
 4108: ###############################################
 4109: 
 4110: sub devalidate_domconfig_cache {
 4111:     my ($udom)=@_;
 4112:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4113: }
 4114: 
 4115: # ---------------------- Get domain configuration for a domain
 4116: sub get_domainconf {
 4117:     my ($udom) = @_;
 4118:     my $cachetime=1800;
 4119:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4120:     if (defined($cached)) { return %{$result}; }
 4121: 
 4122:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4123: 					     ['login','rolecolors'],$udom);
 4124:     my (%designhash,%legacy);
 4125:     if (keys(%domconfig) > 0) {
 4126:         if (ref($domconfig{'login'}) eq 'HASH') {
 4127:             if (keys(%{$domconfig{'login'}})) {
 4128:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4129:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4130:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4131:                             $designhash{$udom.'.login.'.$key.'_'.$img} =
 4132:                                 $domconfig{'login'}{$key}{$img};
 4133:                         }
 4134:                     } else {
 4135:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4136:                     }
 4137:                 }
 4138:             } else {
 4139:                 $legacy{'login'} = 1;
 4140:             }
 4141:         } else {
 4142:             $legacy{'login'} = 1;
 4143:         }
 4144:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4145:             if (keys(%{$domconfig{'rolecolors'}})) {
 4146:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4147:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4148:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4149:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4150:                         }
 4151:                     }
 4152:                 }
 4153:             } else {
 4154:                 $legacy{'rolecolors'} = 1;
 4155:             }
 4156:         } else {
 4157:             $legacy{'rolecolors'} = 1;
 4158:         }
 4159:         if (keys(%legacy) > 0) {
 4160:             my %legacyhash = &get_legacy_domconf($udom);
 4161:             foreach my $item (keys(%legacyhash)) {
 4162:                 if ($item =~ /^\Q$udom\E\.login/) {
 4163:                     if ($legacy{'login'}) { 
 4164:                         $designhash{$item} = $legacyhash{$item};
 4165:                     }
 4166:                 } else {
 4167:                     if ($legacy{'rolecolors'}) {
 4168:                         $designhash{$item} = $legacyhash{$item};
 4169:                     }
 4170:                 }
 4171:             }
 4172:         }
 4173:     } else {
 4174:         %designhash = &get_legacy_domconf($udom); 
 4175:     }
 4176:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4177: 				  $cachetime);
 4178:     return %designhash;
 4179: }
 4180: 
 4181: sub get_legacy_domconf {
 4182:     my ($udom) = @_;
 4183:     my %legacyhash;
 4184:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4185:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4186:     if (-e $designfile) {
 4187:         if ( open (my $fh,"<$designfile") ) {
 4188:             while (my $line = <$fh>) {
 4189:                 next if ($line =~ /^\#/);
 4190:                 chomp($line);
 4191:                 my ($key,$val)=(split(/\=/,$line));
 4192:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4193:             }
 4194:             close($fh);
 4195:         }
 4196:     }
 4197:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4198:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4199:     }
 4200:     return %legacyhash;
 4201: }
 4202: 
 4203: =pod
 4204: 
 4205: =item * &domainlogo()
 4206: 
 4207: Inputs: $domain (usually will be undef)
 4208: 
 4209: Returns: A link to a domain logo, if the domain logo exists.
 4210: If the domain logo does not exist, a description of the domain.
 4211: 
 4212: =cut
 4213: 
 4214: ###############################################
 4215: sub domainlogo {
 4216:     my $domain = &determinedomain(shift);
 4217:     my %designhash = &get_domainconf($domain);    
 4218:     # See if there is a logo
 4219:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4220:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4221:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4222: 	    if ($imgsrc =~ m{^/res/}) {
 4223: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4224: 		&Apache::lonnet::repcopy($local_name);
 4225: 	    }
 4226: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4227:         } 
 4228:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4229:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4230:         return &Apache::lonnet::domain($domain,'description');
 4231:     } else {
 4232:         return '';
 4233:     }
 4234: }
 4235: ##############################################
 4236: 
 4237: =pod
 4238: 
 4239: =item * &designparm()
 4240: 
 4241: Inputs: $which parameter; $domain (usually will be undef)
 4242: 
 4243: Returns: value of designparamter $which
 4244: 
 4245: =cut
 4246: 
 4247: 
 4248: ##############################################
 4249: sub designparm {
 4250:     my ($which,$domain)=@_;
 4251:     if ($env{'browser.blackwhite'} eq 'on') {
 4252: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4253: 	    return '#000000';
 4254: 	}
 4255: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4256: 	    return '#FFFFFF';
 4257: 	}
 4258: 	if ($which=~/\.tabbg$/) {
 4259: 	    return '#CCCCCC';
 4260: 	}
 4261:     }
 4262:     if (exists($env{'environment.color.'.$which})) {
 4263: 	return $env{'environment.color.'.$which};
 4264:     }
 4265:     $domain=&determinedomain($domain);
 4266:     my %domdesign = &get_domainconf($domain);
 4267:     my $output;
 4268:     if ($domdesign{$domain.'.'.$which} ne '') {
 4269: 	$output = $domdesign{$domain.'.'.$which};
 4270:     } else {
 4271:         $output = $defaultdesign{$which};
 4272:     }
 4273:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4274:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4275:         if ($output =~ m{^/(adm|res)/}) {
 4276: 	    if ($output =~ m{^/res/}) {
 4277: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4278: 		&Apache::lonnet::repcopy($local_name);
 4279: 	    }
 4280:             $output = &lonhttpdurl($output);
 4281:         }
 4282:     }
 4283:     return $output;
 4284: }
 4285: 
 4286: ###############################################
 4287: ###############################################
 4288: 
 4289: =pod
 4290: 
 4291: =back
 4292: 
 4293: =head1 HTML Helpers
 4294: 
 4295: =over 4
 4296: 
 4297: =item * &bodytag()
 4298: 
 4299: Returns a uniform header for LON-CAPA web pages.
 4300: 
 4301: Inputs: 
 4302: 
 4303: =over 4
 4304: 
 4305: =item * $title, A title to be displayed on the page.
 4306: 
 4307: =item * $function, the current role (can be undef).
 4308: 
 4309: =item * $addentries, extra parameters for the <body> tag.
 4310: 
 4311: =item * $bodyonly, if defined, only return the <body> tag.
 4312: 
 4313: =item * $domain, if defined, force a given domain.
 4314: 
 4315: =item * $forcereg, if page should register as content page (relevant for 
 4316:             text interface only)
 4317: 
 4318: =item * $customtitle, alternate text to use instead of $title
 4319:                       in the title box that appears, this text
 4320:                       is not auto translated like the $title is
 4321: 
 4322: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4323:                    navigational links
 4324: 
 4325: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4326: 
 4327: =item * $notitle, if true keep the nav controls, but remove the title bar
 4328: 
 4329: =item * $no_inline_link, if true and in remote mode, don't show the 
 4330:          'Switch To Inline Menu' link
 4331: 
 4332: =item * $args, optional argument valid values are
 4333:             no_auto_mt_title -> prevents &mt()ing the title arg
 4334:             inherit_jsmath -> when creating popup window in a page,
 4335:                               should it have jsmath forced on by the
 4336:                               current page
 4337: 
 4338: =back
 4339: 
 4340: Returns: A uniform header for LON-CAPA web pages.  
 4341: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4342: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4343: other decorations will be returned.
 4344: 
 4345: =cut
 4346: 
 4347: sub bodytag {
 4348:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4349: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4350: 
 4351:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4352: 
 4353:     $function = &get_users_function() if (!$function);
 4354:     my $img =    &designparm($function.'.img',$domain);
 4355:     my $font =   &designparm($function.'.font',$domain);
 4356:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4357: 
 4358:     my %design = ( 'style'   => 'margin-top: 0',
 4359: 		   'bgcolor' => $pgbg,
 4360: 		   'text'    => $font,
 4361:                    'alink'   => &designparm($function.'.alink',$domain),
 4362: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4363: 		   'link'    => &designparm($function.'.link',$domain),);
 4364:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4365: 
 4366:  # role and realm
 4367:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4368:     if ($role  eq 'ca') {
 4369:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4370:         $realm = &plainname($rname,$rdom);
 4371:     } 
 4372: # realm
 4373:     if ($env{'request.course.id'}) {
 4374:         if ($env{'request.role'} !~ /^cr/) {
 4375:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4376:         }
 4377: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4378:     } else {
 4379:         $role = &Apache::lonnet::plaintext($role);
 4380:     }
 4381: 
 4382:     if (!$realm) { $realm='&nbsp;'; }
 4383: # Set messages
 4384:     my $messages=&domainlogo($domain);
 4385: 
 4386:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4387: 
 4388: # construct main body tag
 4389:     my $bodytag = "<body $extra_body_attr>".
 4390: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4391: 
 4392:     if ($bodyonly) {
 4393:         return $bodytag;
 4394:     } elsif ($env{'browser.interface'} eq 'textual') {
 4395: # Accessibility
 4396:           
 4397: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4398: 	if (!$notitle) {
 4399: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4400: 	}
 4401: 	return $bodytag;
 4402:     }
 4403: 
 4404:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4405:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4406: 	undef($role);
 4407:     } else {
 4408: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4409:     }
 4410:     
 4411:     my $roleinfo=(<<ENDROLE);
 4412: <td class="LC_title_bar_who">
 4413: <div class="LC_title_bar_name">
 4414:     $name
 4415:     &nbsp;
 4416: </div>
 4417: <div class="LC_title_bar_role">
 4418: $role&nbsp;
 4419: </div>
 4420: <div class="LC_title_bar_realm">
 4421: $realm&nbsp;
 4422: </div>
 4423: </td>
 4424: ENDROLE
 4425: 
 4426:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4427:     if ($customtitle) {
 4428:         $titleinfo = $customtitle;
 4429:     }
 4430:     #
 4431:     # Extra info if you are the DC
 4432:     my $dc_info = '';
 4433:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4434:                         $env{'course.'.$env{'request.course.id'}.
 4435:                                  '.domain'}.'/'})) {
 4436:         my $cid = $env{'request.course.id'};
 4437:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4438:         $dc_info =~ s/\s+$//;
 4439:         $dc_info = '('.$dc_info.')';
 4440:     }
 4441: 
 4442:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4443:         # No Remote
 4444: 	if ($env{'request.state'} eq 'construct') {
 4445: 	    $forcereg=1;
 4446: 	}
 4447: 
 4448: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4449: 	    # this is for resources; directories have customtitle, and crumbs
 4450:             # and select recent are created in lonpubdir.pm  
 4451: 	    my ($uname,$thisdisfn)=
 4452: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4453: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4454: 	    $formaction=~s/\/+/\//g;
 4455: 
 4456: 	    my $parentpath = '';
 4457: 	    my $lastitem = '';
 4458: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4459: 		$parentpath = $1;
 4460: 		$lastitem = $2;
 4461: 	    } else {
 4462: 		$lastitem = $thisdisfn;
 4463: 	    }
 4464: 	    $titleinfo = 
 4465: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4466: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4467: 		.'<form name="dirs" method="post" action="'.$formaction
 4468: 		.'" target="_top"><tt><b>'
 4469: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4470: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4471: 		.'</form>'
 4472: 		.&Apache::lonmenu::constspaceform();
 4473:         }
 4474: 
 4475:         my $titletable;
 4476: 	if (!$notitle) {
 4477: 	    $titletable =
 4478: 		'<table id="LC_title_bar">'.
 4479:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4480: 			 '</tr></table>';
 4481: 	}
 4482: 	if ($notopbar) {
 4483: 	    $bodytag .= $titletable;
 4484: 	} else {
 4485: 	    if ($env{'request.state'} eq 'construct') {
 4486:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4487: 							  $titletable);
 4488:             } else {
 4489:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4490: 		    $titletable;
 4491:             }
 4492:         }
 4493:         return $bodytag;
 4494:     }
 4495: 
 4496: #
 4497: # Top frame rendering, Remote is up
 4498: #
 4499: 
 4500:     my $imgsrc = $img;
 4501:     if ($img =~ /^\/adm/) {
 4502:         $imgsrc = &lonhttpdurl($img);
 4503:     }
 4504:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4505: 
 4506:     # Explicit link to get inline menu
 4507:     my $menu= ($no_inline_link?''
 4508: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4509:     #
 4510:     if ($notitle) {
 4511: 	return $bodytag;
 4512:     }
 4513:     return(<<ENDBODY);
 4514: $bodytag
 4515: <table id="LC_title_bar" class="LC_with_remote">
 4516: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4517:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4518: </tr>
 4519: <tr><td>$titleinfo $dc_info $menu</td>
 4520: $roleinfo
 4521: </tr>
 4522: </table>
 4523: ENDBODY
 4524: }
 4525: 
 4526: sub make_attr_string {
 4527:     my ($register,$attr_ref) = @_;
 4528: 
 4529:     if ($attr_ref && !ref($attr_ref)) {
 4530: 	die("addentries Must be a hash ref ".
 4531: 	    join(':',caller(1))." ".
 4532: 	    join(':',caller(0))." ");
 4533:     }
 4534: 
 4535:     if ($register) {
 4536: 	my ($on_load,$on_unload);
 4537: 	foreach my $key (keys(%{$attr_ref})) {
 4538: 	    if      (lc($key) eq 'onload') {
 4539: 		$on_load.=$attr_ref->{$key}.';';
 4540: 		delete($attr_ref->{$key});
 4541: 
 4542: 	    } elsif (lc($key) eq 'onunload') {
 4543: 		$on_unload.=$attr_ref->{$key}.';';
 4544: 		delete($attr_ref->{$key});
 4545: 	    }
 4546: 	}
 4547: 	$attr_ref->{'onload'}  =
 4548: 	    &Apache::lonmenu::loadevents().  $on_load;
 4549: 	$attr_ref->{'onunload'}=
 4550: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4551:     }
 4552: 
 4553: # Accessibility font enhance
 4554:     if ($env{'browser.fontenhance'} eq 'on') {
 4555: 	my $style;
 4556: 	foreach my $key (keys(%{$attr_ref})) {
 4557: 	    if (lc($key) eq 'style') {
 4558: 		$style.=$attr_ref->{$key}.';';
 4559: 		delete($attr_ref->{$key});
 4560: 	    }
 4561: 	}
 4562: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4563:     }
 4564: 
 4565:     if ($env{'browser.blackwhite'} eq 'on') {
 4566: 	delete($attr_ref->{'font'});
 4567: 	delete($attr_ref->{'link'});
 4568: 	delete($attr_ref->{'alink'});
 4569: 	delete($attr_ref->{'vlink'});
 4570: 	delete($attr_ref->{'bgcolor'});
 4571: 	delete($attr_ref->{'background'});
 4572:     }
 4573: 
 4574:     my $attr_string;
 4575:     foreach my $attr (keys(%$attr_ref)) {
 4576: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4577:     }
 4578:     return $attr_string;
 4579: }
 4580: 
 4581: 
 4582: ###############################################
 4583: ###############################################
 4584: 
 4585: =pod
 4586: 
 4587: =item * &endbodytag()
 4588: 
 4589: Returns a uniform footer for LON-CAPA web pages.
 4590: 
 4591: Inputs: 1 - optional reference to an args hash
 4592: If in the hash, key for noredirectlink has a value which evaluates to true,
 4593: a 'Continue' link is not displayed if the page contains an
 4594: internal redirect in the <head></head> section,
 4595: i.e., $env{'internal.head.redirect'} exists   
 4596: 
 4597: =cut
 4598: 
 4599: sub endbodytag {
 4600:     my ($args) = @_;
 4601:     my $endbodytag='</body>';
 4602:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4603:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4604:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4605: 	    $endbodytag=
 4606: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4607: 	        &mt('Continue').'</a>'.
 4608: 	        $endbodytag;
 4609:         }
 4610:     }
 4611:     return $endbodytag;
 4612: }
 4613: 
 4614: =pod
 4615: 
 4616: =item * &standard_css()
 4617: 
 4618: Returns a style sheet
 4619: 
 4620: Inputs: (all optional)
 4621:             domain         -> force to color decorate a page for a specific
 4622:                                domain
 4623:             function       -> force usage of a specific rolish color scheme
 4624:             bgcolor        -> override the default page bgcolor
 4625: 
 4626: =cut
 4627: 
 4628: sub standard_css {
 4629:     my ($function,$domain,$bgcolor) = @_;
 4630:     $function  = &get_users_function() if (!$function);
 4631:     my $img    = &designparm($function.'.img',   $domain);
 4632:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4633:     my $font   = &designparm($function.'.font',  $domain);
 4634:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4635:     my $pgbg_or_bgcolor =
 4636: 	         $bgcolor ||
 4637: 	         &designparm($function.'.pgbg',  $domain);
 4638:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4639:     my $alink  = &designparm($function.'.alink', $domain);
 4640:     my $vlink  = &designparm($function.'.vlink', $domain);
 4641:     my $link   = &designparm($function.'.link',  $domain);
 4642: 
 4643:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4644:     my $mono                 = 'monospace';
 4645:     my $data_table_head      = $tabbg;
 4646:     my $data_table_light     = '#FAFAFA';
 4647:     my $data_table_dark      = '#F0F0F0';
 4648:     my $data_table_darker    = '#CCCCCC';
 4649:     my $data_table_highlight = '#FFFF00';
 4650:     my $mail_new             = '#FFBB77';
 4651:     my $mail_new_hover       = '#DD9955';
 4652:     my $mail_read            = '#BBBB77';
 4653:     my $mail_read_hover      = '#999944';
 4654:     my $mail_replied         = '#AAAA88';
 4655:     my $mail_replied_hover   = '#888855';
 4656:     my $mail_other           = '#99BBBB';
 4657:     my $mail_other_hover     = '#669999';
 4658:     my $table_header         = '#DDDDDD';
 4659:     my $feedback_link_bg     = '#BBBBBB';
 4660:     my $lg_border_color      = '#C8C8C8';
 4661: 
 4662:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4663: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4664: 	                                                 : '0 3px 0 4px';
 4665: 
 4666: 
 4667:     return <<END;
 4668: h1, h2, h3, th { font-family: $sans }
 4669: a:focus { color: red; background: yellow } 
 4670: 
 4671: hr {
 4672:   clear: both;
 4673:   color: $tabbg;
 4674:   background-color: $tabbg;
 4675:   height: 3px;
 4676:   border: none;
 4677: }
 4678: 
 4679: table.thinborder,
 4680: 
 4681: table.thinborder tr th {
 4682:   border-style: solid;
 4683:   border-width: 1px;
 4684:   background: $tabbg;
 4685: }
 4686: table.thinborder tr td {
 4687:   border-style: solid;
 4688:   border-width: 1px
 4689: }
 4690: 
 4691: form, .inline { display: inline; }
 4692: .center { text-align: center; }
 4693: .LC_filename {font-family: $mono; white-space:pre;}
 4694: .LC_error {
 4695:   color: red;
 4696:   font-size: larger;
 4697: }
 4698: .LC_warning,
 4699: .LC_diff_removed {
 4700:   color: red;
 4701: }
 4702: 
 4703: .LC_info,
 4704: .LC_success,
 4705: .LC_diff_added {
 4706:   color: green;
 4707: }
 4708: 
 4709: div.LC_confirm_box {
 4710:   background-color: #FAFAFA;
 4711:   border: 1px solid $lg_border_color;
 4712:   margin-right: 0;
 4713:   padding: 5px;
 4714: }
 4715: 
 4716: div.LC_confirm_box .LC_error img,
 4717: div.LC_confirm_box .LC_success img {
 4718:   vertical-align: middle;
 4719: }
 4720: 
 4721: .LC_icon {
 4722:   border: none;
 4723: }
 4724: .LC_indexer_icon {
 4725:   border: 0;
 4726:   height: 22px;
 4727: }
 4728: .LC_docs_spacer {
 4729:   width: 25px;
 4730:   height: 1px;
 4731:   border: none;
 4732: }
 4733: 
 4734: .LC_internal_info {
 4735:   color: #999999;
 4736: }
 4737: 
 4738: table.LC_pastsubmission {
 4739:   border: 1px solid black;
 4740:   margin: 2px;
 4741: }
 4742: 
 4743: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4744:   width: 100%;
 4745:   background: $pgbg;
 4746:   border: 2px;
 4747:   border-collapse: separate;
 4748:   padding: 0;
 4749: }
 4750: 
 4751: table#LC_title_bar, table.LC_breadcrumbs, 
 4752: table#LC_title_bar.LC_with_remote {
 4753:   width: 100%;
 4754:   border-color: $pgbg;
 4755:   border-style: solid;
 4756:   border-width: $border;
 4757: 
 4758:   background: $pgbg;
 4759:   font-family: $sans;
 4760:   border-collapse: collapse;
 4761:   padding: 0;
 4762: }
 4763: 
 4764: table.LC_docs_path {
 4765:   width: 100%;
 4766:   border: 0;
 4767:   background: $pgbg;
 4768:   font-family: $sans;
 4769:   border-collapse: collapse;
 4770:   padding: 0;
 4771: }
 4772: 
 4773: table#LC_title_bar td {
 4774:   background: $tabbg;
 4775: }
 4776: table#LC_title_bar td.LC_title_bar_who {
 4777:   background: $tabbg;
 4778:   color: $font;
 4779:   font: small $sans;
 4780:   text-align: right;
 4781: }
 4782: span.LC_metadata {
 4783:     font-family: $sans;
 4784: }
 4785: span.LC_title_bar_title {
 4786:   font: bold x-large $sans;
 4787: }
 4788: table#LC_title_bar td.LC_title_bar_domain_logo {
 4789:   background: $sidebg;
 4790:   text-align: right;
 4791:   padding: 0;
 4792: }
 4793: table#LC_title_bar td.LC_title_bar_role_logo {
 4794:   background: $sidebg;
 4795:   padding: 0;
 4796: }
 4797: 
 4798: table#LC_menubuttons_mainmenu {
 4799:   width: 100%;
 4800:   border: 0;
 4801:   border-spacing: 1px;
 4802:   padding: 0 1px;
 4803:   margin: 0;
 4804:   border-collapse: separate;
 4805: }
 4806: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4807:   border: none;
 4808: }
 4809: table#LC_top_nav td {
 4810:   background: $tabbg;
 4811:   border: none;
 4812:   font-size: small;
 4813: }
 4814: table#LC_top_nav td a, div#LC_top_nav a {
 4815:   color: $font;
 4816:   font-family: $sans;
 4817: }
 4818: table#LC_top_nav td.LC_top_nav_logo {
 4819:   background: $tabbg;
 4820:   text-align: left;
 4821:   white-space: nowrap;
 4822:   width: 31px;
 4823: }
 4824: table#LC_top_nav td.LC_top_nav_logo img {
 4825:   border: none;
 4826:   vertical-align: bottom;
 4827: }
 4828: table#LC_top_nav td.LC_top_nav_exit,
 4829: table#LC_top_nav td.LC_top_nav_help {
 4830:   width: 2.0em;
 4831: }
 4832: table#LC_top_nav td.LC_top_nav_login {
 4833:   width: 4.0em;
 4834:   text-align: center;
 4835: }
 4836: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4837:   background: $tabbg;
 4838:   color: $font;
 4839:   font-family: $sans;
 4840:   font-size: smaller;
 4841: }
 4842: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4843: table.LC_docs_path td.LC_docs_path_component {
 4844:   background: $tabbg;
 4845:   color: $font;
 4846:   font-family: $sans;
 4847:   font-size: larger;
 4848:   text-align: right;
 4849: }
 4850: td.LC_table_cell_checkbox {
 4851:   text-align: center;
 4852: }
 4853: table#LC_mainmenu td.LC_mainmenu_column {
 4854:     vertical-align: top;
 4855: }
 4856: 
 4857: .LC_menubuttons_inline_text {
 4858:   color: $font;
 4859:   font-family: $sans;
 4860:   font-size: smaller;
 4861: }
 4862: 
 4863: .LC_menubuttons_link {
 4864:   text-decoration: none;
 4865: }
 4866: /*2008--9-5: new menu style sheet.Changed category*/
 4867: .LC_menubuttons_category {
 4868:   color: $font;
 4869:   background: $pgbg;
 4870:   font-family: $sans;
 4871:   font-size: larger;
 4872:   font-weight: bold;
 4873: }
 4874: 
 4875: td.LC_menubuttons_text {
 4876:   width: 90%;
 4877:   color: $font;
 4878:   font-family: $sans;
 4879: }
 4880: 
 4881: td.LC_menubuttons_img {
 4882: }
 4883: 
 4884: .LC_current_location {
 4885:   font-family: $sans;
 4886:   background: $tabbg;
 4887: }
 4888: .LC_new_mail {
 4889:   font-family: $sans;
 4890:   background: $tabbg;
 4891:   font-weight: bold;
 4892: }
 4893: 
 4894: .LC_dropadd_labeltext {
 4895:   font-family: $sans;
 4896:   text-align: right;
 4897: }
 4898: 
 4899: .LC_preferences_labeltext {
 4900:   font-family: $sans;
 4901:   text-align: right;
 4902: }
 4903: 
 4904: .LC_roleslog_note {
 4905:   font-size: smaller;
 4906: }
 4907: 
 4908: .LC_mail_functions {
 4909:     font-weight: bold;
 4910: }
 4911: 
 4912: table.LC_aboutme_port {
 4913:   border: none;
 4914:   border-collapse: collapse;
 4915:   border-spacing: 0;
 4916: }
 4917: table.LC_data_table, table.LC_mail_list {
 4918:   border: 1px solid #000000;
 4919:   border-collapse: separate;
 4920:   border-spacing: 1px;
 4921:   background: $pgbg;
 4922: }
 4923: .LC_data_table_dense {
 4924:   font-size: small;
 4925: }
 4926: table.LC_nested_outer {
 4927:   border: 1px solid #000000;
 4928:   border-collapse: collapse;
 4929:   border-spacing: 0;
 4930:   width: 100%;
 4931: }
 4932: table.LC_innerpickbox,
 4933: table.LC_nested {
 4934:   border: none;
 4935:   border-collapse: collapse;
 4936:   border-spacing: 0;
 4937:   width: 100%;
 4938: }
 4939: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4940: table.LC_prior_tries tr th,
 4941: table.LC_innerpickbox tr th {
 4942:   font-weight: bold;
 4943:   background-color: $data_table_head;
 4944:   font-size: smaller;
 4945: }
 4946: table.LC_innerpickbox tr th,
 4947: table.LC_innerpickbox tr td {
 4948:   vertical-align: top;
 4949: }
 4950: table.LC_data_table tr.LC_info_row > td {
 4951:   background-color: #CCCCCC;
 4952:   font-weight: bold;
 4953:   text-align: left;
 4954: }
 4955: table.LC_data_table tr.LC_odd_row > td, 
 4956: table.LC_pick_box tr > td.LC_odd_row,
 4957: table.LC_aboutme_port tr td {
 4958:   background-color: $data_table_light;
 4959:   padding: 2px;
 4960: }
 4961: table.LC_data_table tr.LC_even_row > td,
 4962: table.LC_pick_box tr > td.LC_even_row,
 4963: table.LC_aboutme_port tr.LC_even_row td {
 4964:   background-color: $data_table_dark;
 4965:   padding: 2px;
 4966: }
 4967: table.LC_data_table tr.LC_data_table_highlight td {
 4968:   background-color: $data_table_darker;
 4969: }
 4970: table.LC_data_table tr td.LC_leftcol_header {
 4971:   background-color: $data_table_head;
 4972:   font-weight: bold;
 4973: }
 4974: table.LC_data_table tr.LC_empty_row td,
 4975: table.LC_nested tr.LC_empty_row td {
 4976:   background-color: #FFFFFF;
 4977:   font-weight: bold;
 4978:   font-style: italic;
 4979:   text-align: center;
 4980:   padding: 8px;
 4981: }
 4982: table.LC_nested tr.LC_empty_row td {
 4983:   padding: 4ex
 4984: }
 4985: table.LC_nested_outer tr th {
 4986:   font-weight: bold;
 4987:   background-color: $data_table_head;
 4988:   font-size: smaller;
 4989:   border-bottom: 1px solid #000000;
 4990: }
 4991: table.LC_nested_outer tr td.LC_subheader {
 4992:   background-color: $data_table_head;
 4993:   font-weight: bold;
 4994:   font-size: small;
 4995:   border-bottom: 1px solid #000000;
 4996:   text-align: right;
 4997: }
 4998: table.LC_nested tr.LC_info_row td {
 4999:   background-color: #CCCCCC;
 5000:   font-weight: bold;
 5001:   font-size: small;
 5002:   text-align: center;
 5003: }
 5004: table.LC_nested tr.LC_info_row td.LC_left_item,
 5005: table.LC_nested_outer tr th.LC_left_item {
 5006:   text-align: left;
 5007: }
 5008: table.LC_nested td {
 5009:   background-color: #FFFFFF;
 5010:   font-size: small;
 5011: }
 5012: table.LC_nested_outer tr th.LC_right_item,
 5013: table.LC_nested tr.LC_info_row td.LC_right_item,
 5014: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5015: table.LC_nested tr td.LC_right_item {
 5016:   text-align: right;
 5017: }
 5018: 
 5019: table.LC_nested tr.LC_odd_row td {
 5020:   background-color: #EEEEEE;
 5021: }
 5022: 
 5023: table.LC_createuser {
 5024: }
 5025: 
 5026: table.LC_createuser tr.LC_section_row td {
 5027:   font-size: smaller;
 5028: }
 5029: 
 5030: table.LC_createuser tr.LC_info_row td  {
 5031:   background-color: #CCCCCC;
 5032:   font-weight: bold;
 5033:   text-align: center;
 5034: }
 5035: 
 5036: table.LC_calendar {
 5037:   border: 1px solid #000000;
 5038:   border-collapse: collapse;
 5039: }
 5040: table.LC_calendar_pickdate {
 5041:   font-size: xx-small;
 5042: }
 5043: table.LC_calendar tr td {
 5044:   border: 1px solid #000000;
 5045:   vertical-align: top;
 5046: }
 5047: table.LC_calendar tr td.LC_calendar_day_empty {
 5048:   background-color: $data_table_dark;
 5049: }
 5050: table.LC_calendar tr td.LC_calendar_day_current {
 5051:   background-color: $data_table_highlight;
 5052: }
 5053: 
 5054: table.LC_mail_list tr.LC_mail_new {
 5055:   background-color: $mail_new;
 5056: }
 5057: table.LC_mail_list tr.LC_mail_new:hover {
 5058:   background-color: $mail_new_hover;
 5059: }
 5060: table.LC_mail_list tr.LC_mail_read {
 5061:   background-color: $mail_read;
 5062: }
 5063: table.LC_mail_list tr.LC_mail_read:hover {
 5064:   background-color: $mail_read_hover;
 5065: }
 5066: table.LC_mail_list tr.LC_mail_replied {
 5067:   background-color: $mail_replied;
 5068: }
 5069: table.LC_mail_list tr.LC_mail_replied:hover {
 5070:   background-color: $mail_replied_hover;
 5071: }
 5072: table.LC_mail_list tr.LC_mail_other {
 5073:   background-color: $mail_other;
 5074: }
 5075: table.LC_mail_list tr.LC_mail_other:hover {
 5076:   background-color: $mail_other_hover;
 5077: }
 5078: table.LC_mail_list tr.LC_mail_even {
 5079: }
 5080: table.LC_mail_list tr.LC_mail_odd {
 5081: }
 5082: 
 5083: 
 5084: table#LC_portfolio_actions {
 5085:   width: auto;
 5086:   background: $pgbg;
 5087:   border: none;
 5088:   border-spacing: 2px 2px;
 5089:   padding: 0;
 5090:   margin: 0;
 5091:   border-collapse: separate;
 5092: }
 5093: table#LC_portfolio_actions td.LC_label {
 5094:   background: $tabbg;
 5095:   text-align: right;
 5096: }
 5097: table#LC_portfolio_actions td.LC_value {
 5098:   background: $tabbg;
 5099: }
 5100: 
 5101: table#LC_cstr_controls {
 5102:   width: 100%;
 5103:   border-collapse: collapse;
 5104: }
 5105: table#LC_cstr_controls tr td {
 5106:   border: 4px solid $pgbg;
 5107:   padding: 4px;
 5108:   text-align: center;
 5109:   background: $tabbg;
 5110: }
 5111: table#LC_cstr_controls tr th {
 5112:   border: 4px solid $pgbg;
 5113:   background: $table_header;
 5114:   text-align: center;
 5115:   font-family: $sans;
 5116:   font-size: smaller;
 5117: }
 5118: 
 5119: table#LC_browser {
 5120:  
 5121: }
 5122: table#LC_browser tr th {
 5123:   background: $table_header;
 5124: }
 5125: table#LC_browser tr td {
 5126:   padding: 2px;
 5127: }
 5128: table#LC_browser tr.LC_browser_file,
 5129: table#LC_browser tr.LC_browser_file_published {
 5130:   background: #CCFF88;
 5131: }
 5132: table#LC_browser tr.LC_browser_file_locked,
 5133: table#LC_browser tr.LC_browser_file_unpublished {
 5134:   background: #FFAA99;
 5135: }
 5136: table#LC_browser tr.LC_browser_file_obsolete {
 5137:   background: #AAAAAA;
 5138: }
 5139: table#LC_browser tr.LC_browser_file_modified,
 5140: table#LC_browser tr.LC_browser_file_metamodified {
 5141:   background: #FFFF77;
 5142: }
 5143: table#LC_browser tr.LC_browser_folder {
 5144:   background: #CCCCFF;
 5145: }
 5146: 
 5147: table.LC_data_table tr > td.LC_roles_is {
 5148: /*  background: #77FF77; */
 5149: }
 5150: table.LC_data_table tr > td.LC_roles_future {
 5151:   background: #FFFF77;
 5152: }
 5153: table.LC_data_table tr > td.LC_roles_will {
 5154:   background: #FFAA77;
 5155: }
 5156: table.LC_data_table tr > td.LC_roles_expired {
 5157:   background: #FF7777;
 5158: }
 5159: table.LC_data_table tr > td.LC_roles_will_not {
 5160:   background: #AAFF77;
 5161: }
 5162: table.LC_data_table tr > td.LC_roles_selected {
 5163:   background: #11CC55;
 5164: }
 5165: 
 5166: span.LC_current_location {
 5167:   font-size: x-large;
 5168:   background: $pgbg;
 5169: }
 5170: 
 5171: span.LC_parm_menu_item {
 5172:   font-size: larger;
 5173:   font-family: $sans;
 5174: }
 5175: span.LC_parm_scope_all {
 5176:   color: red;
 5177: }
 5178: span.LC_parm_scope_folder {
 5179:   color: green;
 5180: }
 5181: span.LC_parm_scope_resource {
 5182:   color: orange;
 5183: }
 5184: span.LC_parm_part {
 5185:   color: blue;
 5186: }
 5187: span.LC_parm_folder, span.LC_parm_symb {
 5188:   font-size: x-small;
 5189:   font-family: $mono;
 5190:   color: #AAAAAA;
 5191: }
 5192: 
 5193: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 5194: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 5195:   border: 1px solid black;
 5196:   border-collapse: collapse;
 5197: }
 5198: table.LC_parm_overview_restrictions td {
 5199:   border-width: 1px 4px 1px 4px;
 5200:   border-style: solid;
 5201:   border-color: $pgbg;
 5202:   text-align: center;
 5203: }
 5204: table.LC_parm_overview_restrictions th {
 5205:   background: $tabbg;
 5206:   border-width: 1px 4px 1px 4px;
 5207:   border-style: solid;
 5208:   border-color: $pgbg;
 5209: }
 5210: table#LC_helpmenu {
 5211:   border: none;
 5212:   height: 55px;
 5213:   border-spacing: 0;
 5214: }
 5215: 
 5216: table#LC_helpmenu fieldset legend {
 5217:   font-size: larger;
 5218:   font-weight: bold;
 5219: }
 5220: table#LC_helpmenu_links {
 5221:   width: 100%;
 5222:   border: 1px solid black;
 5223:   background: $pgbg;
 5224:   padding: 0;
 5225:   border-spacing: 1px;
 5226: }
 5227: table#LC_helpmenu_links tr td {
 5228:   padding: 1px;
 5229:   background: $tabbg;
 5230:   text-align: center;
 5231:   font-weight: bold;
 5232: }
 5233: 
 5234: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5235: table#LC_helpmenu_links a:active {
 5236:   text-decoration: none;
 5237:   color: $font;
 5238: }
 5239: table#LC_helpmenu_links a:hover {
 5240:   text-decoration: underline;
 5241:   color: $vlink;
 5242: }
 5243: 
 5244: .LC_chrt_popup_exists {
 5245:   border: 1px solid #339933;
 5246:   margin: -1px;
 5247: }
 5248: .LC_chrt_popup_up {
 5249:   border: 1px solid yellow;
 5250:   margin: -1px;
 5251: }
 5252: .LC_chrt_popup {
 5253:   border: 1px solid #8888FF;
 5254:   background: #CCCCFF;
 5255: }
 5256: table.LC_pick_box {
 5257:   border-collapse: separate;
 5258:   background: white;
 5259:   border: 1px solid black;
 5260:   border-spacing: 1px;
 5261: }
 5262: table.LC_pick_box td.LC_pick_box_title {
 5263:   background: $tabbg;
 5264:   font-weight: bold;
 5265:   text-align: right;
 5266:   vertical-align: top;
 5267:   width: 184px;
 5268:   padding: 8px;
 5269: }
 5270: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5271:   background: $tabbg;
 5272:   font-weight: bold;
 5273:   text-align: right;
 5274:   width: 350px;
 5275:   padding: 8px;
 5276: }
 5277: 
 5278: table.LC_pick_box td.LC_pick_box_value {
 5279:   text-align: left;
 5280:   padding: 8px;
 5281: }
 5282: table.LC_pick_box td.LC_pick_box_select {
 5283:   text-align: left;
 5284:   padding: 8px;
 5285: }
 5286: table.LC_pick_box td.LC_pick_box_separator {
 5287:   padding: 0;
 5288:   height: 1px;
 5289:   background: black;
 5290: }
 5291: table.LC_pick_box td.LC_pick_box_submit {
 5292:   text-align: right;
 5293: }
 5294: table.LC_pick_box td.LC_evenrow_value {
 5295:   text-align: left;
 5296:   padding: 8px;
 5297:   background-color: $data_table_light;
 5298: }
 5299: table.LC_pick_box td.LC_oddrow_value {
 5300:   text-align: left;
 5301:   padding: 8px;
 5302:   background-color: $data_table_light;
 5303: }
 5304: table.LC_helpform_receipt {
 5305:   width: 620px;
 5306:   border-collapse: separate;
 5307:   background: white;
 5308:   border: 1px solid black;
 5309:   border-spacing: 1px;
 5310: }
 5311: table.LC_helpform_receipt td.LC_pick_box_title {
 5312:   background: $tabbg;
 5313:   font-weight: bold;
 5314:   text-align: right;
 5315:   width: 184px;
 5316:   padding: 8px;
 5317: }
 5318: table.LC_helpform_receipt td.LC_evenrow_value {
 5319:   text-align: left;
 5320:   padding: 8px;
 5321:   background-color: $data_table_light;
 5322: }
 5323: table.LC_helpform_receipt td.LC_oddrow_value {
 5324:   text-align: left;
 5325:   padding: 8px;
 5326:   background-color: $data_table_light;
 5327: }
 5328: table.LC_helpform_receipt td.LC_pick_box_separator {
 5329:   padding: 0;
 5330:   height: 1px;
 5331:   background: black;
 5332: }
 5333: span.LC_helpform_receipt_cat {
 5334:   font-weight: bold;
 5335: }
 5336: table.LC_group_priv_box {
 5337:   background: white;
 5338:   border: 1px solid black;
 5339:   border-spacing: 1px;
 5340: }
 5341: table.LC_group_priv_box td.LC_pick_box_title {
 5342:   background: $tabbg;
 5343:   font-weight: bold;
 5344:   text-align: right;
 5345:   width: 184px;
 5346: }
 5347: table.LC_group_priv_box td.LC_groups_fixed {
 5348:   background: $data_table_light;
 5349:   text-align: center;
 5350: }
 5351: table.LC_group_priv_box td.LC_groups_optional {
 5352:   background: $data_table_dark;
 5353:   text-align: center;
 5354: }
 5355: table.LC_group_priv_box td.LC_groups_functionality {
 5356:   background: $data_table_darker;
 5357:   text-align: center;
 5358:   font-weight: bold;
 5359: }
 5360: table.LC_group_priv td {
 5361:   text-align: left;
 5362:   padding: 0;
 5363: }
 5364: 
 5365: table.LC_notify_front_page {
 5366:   background: white;
 5367:   border: 1px solid black;
 5368:   padding: 8px;
 5369: }
 5370: table.LC_notify_front_page td {
 5371:   padding: 8px;
 5372: }
 5373: .LC_navbuttons {
 5374:   margin: 2ex 0ex 2ex 0ex;
 5375: }
 5376: .LC_topic_bar {
 5377:   font-family: $sans;
 5378:   font-weight: bold;
 5379:   width: 100%;
 5380:   background: $tabbg;
 5381:   vertical-align: middle;
 5382:   margin: 2ex 0ex 2ex 0ex;
 5383:   padding: 3px;
 5384: }
 5385: .LC_topic_bar span {
 5386:   vertical-align: middle;
 5387: }
 5388: .LC_topic_bar img {
 5389:   vertical-align: bottom;
 5390: }
 5391: table.LC_course_group_status {
 5392:   margin: 20px;
 5393: }
 5394: table.LC_status_selector td {
 5395:   vertical-align: top;
 5396:   text-align: center;
 5397:   padding: 4px;
 5398: }
 5399: table.LC_descriptive_input td.LC_description {
 5400:   vertical-align: top;
 5401:   text-align: right;
 5402:   font-weight: bold;
 5403: }
 5404: div.LC_feedback_link {
 5405:   clear: both;
 5406:   background: white;
 5407:   width: 100%;  
 5408: }
 5409: span.LC_feedback_link {
 5410:   background: $feedback_link_bg;
 5411:   font-size: larger;
 5412: }
 5413: span.LC_message_link {
 5414:   background: $feedback_link_bg;
 5415:   font-size: larger;
 5416:   position: absolute;
 5417:   right: 1em;
 5418: }
 5419: 
 5420: table.LC_prior_tries {
 5421:   border: 1px solid #000000;
 5422:   border-collapse: separate;
 5423:   border-spacing: 1px;
 5424: }
 5425: 
 5426: table.LC_prior_tries td {
 5427:   padding: 2px;
 5428: }
 5429: 
 5430: .LC_answer_correct {
 5431:   background: #AAFFAA;
 5432:   color: black;
 5433: }
 5434: .LC_answer_charged_try {
 5435:   background: #FFAAAA ! important;
 5436:   color: black;
 5437: }
 5438: .LC_answer_not_charged_try, 
 5439: .LC_answer_no_grade,
 5440: .LC_answer_late {
 5441:   background: #FFFFAA;
 5442:   color: black;
 5443: }
 5444: .LC_answer_previous {
 5445:   background: #AAAAFF;
 5446:   color: black;
 5447: }
 5448: .LC_answer_no_message {
 5449:   background: #FFFFFF;
 5450:   color: black;
 5451: }
 5452: .LC_answer_unknown {
 5453:   background: orange;
 5454:   color: black;
 5455: }
 5456: 
 5457: 
 5458: span.LC_prior_numerical,
 5459: span.LC_prior_string,
 5460: span.LC_prior_custom,
 5461: span.LC_prior_reaction,
 5462: span.LC_prior_math {
 5463:   font-family: monospace;
 5464:   white-space: pre;
 5465: }
 5466: 
 5467: span.LC_prior_string {
 5468:   font-family: monospace;
 5469:   white-space: pre;
 5470: }
 5471: 
 5472: table.LC_prior_option {
 5473:   width: 100%;
 5474:   border-collapse: collapse;
 5475: }
 5476: table.LC_prior_rank, table.LC_prior_match {
 5477:   border-collapse: collapse;
 5478: }
 5479: table.LC_prior_option tr td,
 5480: table.LC_prior_rank tr td,
 5481: table.LC_prior_match tr td {
 5482:   border: 1px solid #000000;
 5483: }
 5484: 
 5485: span.LC_nobreak {
 5486:   white-space: nowrap;
 5487: }
 5488: 
 5489: span.LC_cusr_emph {
 5490:   font-style: italic;
 5491: }
 5492: 
 5493: span.LC_cusr_subheading {
 5494:   font-weight: normal;
 5495:   font-size: 85%;
 5496: }
 5497: 
 5498: table.LC_docs_documents {
 5499:   background: #BBBBBB;
 5500:   border-width: 0;
 5501:   border-collapse: collapse;
 5502: }
 5503: 
 5504: table.LC_docs_documents td.LC_docs_document {
 5505:   border: 2px solid black;
 5506:   padding: 4px;
 5507: }
 5508: 
 5509: .LC_docs_course_commands div {
 5510:   float: left;
 5511:   border: 4px solid #AAAAAA;
 5512:   padding: 4px;
 5513:   background: #DDDDCC;
 5514: }
 5515: 
 5516: .LC_docs_entry_move {
 5517:   border: none;
 5518:   border-collapse: collapse;
 5519: }
 5520: 
 5521: .LC_docs_entry_move td {
 5522:   border: 2px solid #BBBBBB;
 5523:   background: #DDDDDD;
 5524: }
 5525: 
 5526: .LC_docs_editor td.LC_docs_entry_commands {
 5527:   background: #DDDDDD;
 5528:   font-size: x-small;
 5529: }
 5530: .LC_docs_copy {
 5531:   color: #000099;
 5532: }
 5533: .LC_docs_cut {
 5534:   color: #550044;
 5535: }
 5536: .LC_docs_rename {
 5537:   color: #009900;
 5538: }
 5539: .LC_docs_remove {
 5540:   color: #990000;
 5541: }
 5542: 
 5543: .LC_docs_reinit_warn,
 5544: .LC_docs_ext_edit {
 5545:   font-size: x-small;
 5546: }
 5547: 
 5548: .LC_docs_editor td.LC_docs_entry_title,
 5549: .LC_docs_editor td.LC_docs_entry_icon {
 5550:   background: #FFFFBB;
 5551: }
 5552: .LC_docs_editor td.LC_docs_entry_parameter {
 5553:   background: #BBBBFF;
 5554:   font-size: x-small;
 5555:   white-space: nowrap;
 5556: }
 5557: 
 5558: table.LC_docs_adddocs td,
 5559: table.LC_docs_adddocs th {
 5560:   border: 1px solid #BBBBBB;
 5561:   padding: 4px;
 5562:   background: #DDDDDD;
 5563: }
 5564: 
 5565: table.LC_sty_begin {
 5566:   background: #BBFFBB;
 5567: }
 5568: table.LC_sty_end {
 5569:   background: #FFBBBB;
 5570: }
 5571: 
 5572: table.LC_double_column {
 5573:   border-width: 0;
 5574:   border-collapse: collapse;
 5575:   width: 100%;
 5576:   padding: 2px;
 5577: }
 5578: 
 5579: table.LC_double_column tr td.LC_left_col {
 5580:   top: 2px;
 5581:   left: 2px;
 5582:   width: 47%;
 5583:   vertical-align: top;
 5584: }
 5585: 
 5586: table.LC_double_column tr td.LC_right_col {
 5587:   top: 2px;
 5588:   right: 2px; 
 5589:   width: 47%;
 5590:   vertical-align: top;
 5591: }
 5592: 
 5593: span.LC_role_level {
 5594:   font-weight: bold;
 5595: }
 5596: 
 5597: div.LC_left_float {
 5598:   float: left;
 5599:   padding-right: 5%;
 5600:   padding-bottom: 4px;
 5601: }
 5602: 
 5603: div.LC_clear_float_header {
 5604:   padding-bottom: 2px;
 5605: }
 5606: 
 5607: div.LC_clear_float_footer {
 5608:   padding-top: 10px;
 5609:   clear: both;
 5610: }
 5611: 
 5612: 
 5613: div.LC_grade_select_mode {
 5614:   font-family: $sans;
 5615: }
 5616: div.LC_grade_select_mode div div {
 5617:   margin: 5px;
 5618: }
 5619: div.LC_grade_select_mode_selector {
 5620:   margin: 5px;
 5621:   float: left;
 5622: }
 5623: div.LC_grade_select_mode_selector_header {
 5624:   font: bold medium $sans;
 5625: }
 5626: div.LC_grade_select_mode_type {
 5627:   clear: left;
 5628: }
 5629: 
 5630: div.LC_grade_show_user {
 5631:   margin-top: 20px;
 5632:   border: 1px solid black;
 5633: }
 5634: div.LC_grade_user_name {
 5635:   background: #DDDDEE;
 5636:   border-bottom: 1px solid black;
 5637:   font: bold large $sans;
 5638: }
 5639: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5640:   background: #DDEEDD;
 5641: }
 5642: 
 5643: div.LC_grade_show_problem,
 5644: div.LC_grade_submissions,
 5645: div.LC_grade_message_center,
 5646: div.LC_grade_info_links,
 5647: div.LC_grade_assign {
 5648:   margin: 5px;
 5649:   width: 99%;
 5650:   background: #FFFFFF;
 5651: }
 5652: div.LC_grade_show_problem_header,
 5653: div.LC_grade_submissions_header,
 5654: div.LC_grade_message_center_header,
 5655: div.LC_grade_assign_header {
 5656:   font: bold large $sans;
 5657: }
 5658: div.LC_grade_show_problem_problem,
 5659: div.LC_grade_submissions_body,
 5660: div.LC_grade_message_center_body,
 5661: div.LC_grade_assign_body {
 5662:   border: 1px solid black;
 5663:   width: 99%;
 5664:   background: #FFFFFF;
 5665: }
 5666: span.LC_grade_check_note {
 5667:   font: normal medium $sans;
 5668:   display: inline;
 5669:   position: absolute;
 5670:   right: 1em;
 5671: }
 5672: 
 5673: table.LC_scantron_action {
 5674:   width: 100%;
 5675: }
 5676: table.LC_scantron_action tr th {
 5677:   font: normal bold $sans;
 5678: }
 5679: 
 5680: div.LC_edit_problem_header, 
 5681: div.LC_edit_problem_footer {
 5682:   font: normal medium $sans;
 5683:   margin: 2px;
 5684: }
 5685: div.LC_edit_problem_header,
 5686: div.LC_edit_problem_header div,
 5687: div.LC_edit_problem_footer,
 5688: div.LC_edit_problem_footer div,
 5689: div.LC_edit_problem_editxml_header,
 5690: div.LC_edit_problem_editxml_header div {
 5691:   margin-top: 5px;
 5692: }
 5693: div.LC_edit_problem_header_edit_row {
 5694:   background: $tabbg;
 5695:   padding: 3px;
 5696:   margin-bottom: 5px;
 5697: }
 5698: div.LC_edit_problem_header_title {
 5699:   font: larger bold $sans;
 5700:   background: $tabbg;
 5701:   padding: 3px;
 5702: }
 5703: table.LC_edit_problem_header_title {
 5704:   font: larger bold $sans;
 5705:   width: 100%;
 5706:   border-color: $pgbg;
 5707:   border-style: solid;
 5708:   border-width: $border;
 5709: 
 5710:   background: $tabbg;
 5711:   border-collapse: collapse;
 5712:   padding: 0;
 5713: }
 5714: 
 5715: div.LC_edit_problem_discards {
 5716:   float: left;
 5717:   padding-bottom: 5px;
 5718: }
 5719: div.LC_edit_problem_saves {
 5720:   float: right;
 5721:   padding-bottom: 5px;
 5722: }
 5723: hr.LC_edit_problem_divide {
 5724:   clear: both;
 5725:   color: $tabbg;
 5726:   background-color: $tabbg;
 5727:   height: 3px;
 5728:   border: none;
 5729: }
 5730: img.stift{
 5731:   border-width:0;
 5732:   vertical-align:middle;
 5733: }
 5734: 
 5735: table#LC_mainmenu{
 5736:  margin-top:10px;
 5737:  width:80%;
 5738: 
 5739: }
 5740: 
 5741: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5742:   vertical-align: top;
 5743:   width: 45%;
 5744: }
 5745: .LC_mainmenu_fieldset_category {
 5746:   color: $font;
 5747:   background: $pgbg;
 5748:   font-family: $sans;
 5749:   font-size: small;
 5750:   font-weight: bold;
 5751: }
 5752: fieldset#LC_mainmenu_fieldset {
 5753:   margin:0 10px 10px 0;
 5754: 
 5755: }
 5756: 
 5757: div.LC_createcourse {
 5758:     margin: 10px 10px 10px 10px;
 5759: }
 5760: 
 5761: END
 5762: }
 5763: 
 5764: =pod
 5765: 
 5766: =item * &headtag()
 5767: 
 5768: Returns a uniform footer for LON-CAPA web pages.
 5769: 
 5770: Inputs: $title - optional title for the head
 5771:         $head_extra - optional extra HTML to put inside the <head>
 5772:         $args - optional arguments
 5773:             force_register - if is true call registerurl so the remote is 
 5774:                              informed
 5775:             redirect       -> array ref of
 5776:                                    1- seconds before redirect occurs
 5777:                                    2- url to redirect to
 5778:                                    3- whether the side effect should occur
 5779:                            (side effect of setting 
 5780:                                $env{'internal.head.redirect'} to the url 
 5781:                                redirected too)
 5782:             domain         -> force to color decorate a page for a specific
 5783:                                domain
 5784:             function       -> force usage of a specific rolish color scheme
 5785:             bgcolor        -> override the default page bgcolor
 5786:             no_auto_mt_title
 5787:                            -> prevent &mt()ing the title arg
 5788: 
 5789: =cut
 5790: 
 5791: sub headtag {
 5792:     my ($title,$head_extra,$args) = @_;
 5793:     
 5794:     my $function = $args->{'function'} || &get_users_function();
 5795:     my $domain   = $args->{'domain'}   || &determinedomain();
 5796:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5797:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5798: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5799: 		   #time(),
 5800: 		   $env{'environment.color.timestamp'},
 5801: 		   $function,$domain,$bgcolor);
 5802: 
 5803:     $url = '/adm/css/'.&escape($url).'.css';
 5804: 
 5805:     my $result =
 5806: 	'<head>'.
 5807: 	&font_settings();
 5808: 
 5809:     if (!$args->{'frameset'}) {
 5810: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5811:     }
 5812:     if ($args->{'force_register'}) {
 5813: 	$result .= &Apache::lonmenu::registerurl(1);
 5814:     }
 5815:     if (!$args->{'no_nav_bar'} 
 5816: 	&& !$args->{'only_body'}
 5817: 	&& !$args->{'frameset'}) {
 5818: 	$result .= &help_menu_js();
 5819:     }
 5820: 
 5821:     if (ref($args->{'redirect'})) {
 5822: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5823: 	$url = &Apache::lonenc::check_encrypt($url);
 5824: 	if (!$inhibit_continue) {
 5825: 	    $env{'internal.head.redirect'} = $url;
 5826: 	}
 5827: 	$result.=<<ADDMETA
 5828: <meta http-equiv="pragma" content="no-cache" />
 5829: <meta http-equiv="Refresh" content="$time; url=$url" />
 5830: ADDMETA
 5831:     }
 5832:     if (!defined($title)) {
 5833: 	$title = 'The LearningOnline Network with CAPA';
 5834:     }
 5835:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5836:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5837: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5838: 	.$head_extra;
 5839:     return $result;
 5840: }
 5841: 
 5842: =pod
 5843: 
 5844: =item * &font_settings()
 5845: 
 5846: Returns neccessary <meta> to set the proper encoding
 5847: 
 5848: Inputs: none
 5849: 
 5850: =cut
 5851: 
 5852: sub font_settings {
 5853:     my $headerstring='';
 5854:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5855: 	$headerstring.=
 5856: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5857:     }
 5858:     return $headerstring;
 5859: }
 5860: 
 5861: =pod
 5862: 
 5863: =item * &xml_begin()
 5864: 
 5865: Returns the needed doctype and <html>
 5866: 
 5867: Inputs: none
 5868: 
 5869: =cut
 5870: 
 5871: sub xml_begin {
 5872:     my $output='';
 5873: 
 5874:     if ($env{'internal.start_page'}==1) {
 5875: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5876:     }
 5877: 
 5878:     if ($env{'browser.mathml'}) {
 5879: 	$output='<?xml version="1.0"?>'
 5880:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5881: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5882:             
 5883: #	    .'<!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">] >'
 5884: 	    .'<!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">'
 5885:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5886: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5887:     } else {
 5888: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
 5889:             '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 5890:     }
 5891:     return $output;
 5892: }
 5893: 
 5894: =pod
 5895: 
 5896: =item * &endheadtag()
 5897: 
 5898: Returns a uniform </head> for LON-CAPA web pages.
 5899: 
 5900: Inputs: none
 5901: 
 5902: =cut
 5903: 
 5904: sub endheadtag {
 5905:     return '</head>';
 5906: }
 5907: 
 5908: =pod
 5909: 
 5910: =item * &head()
 5911: 
 5912: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5913: 
 5914: Inputs:
 5915: 
 5916: =over 4
 5917: 
 5918: $title - optional title for the page
 5919: 
 5920: $head_extra - optional extra HTML to put inside the <head>
 5921: 
 5922: =back
 5923: 
 5924: =cut
 5925: 
 5926: sub head {
 5927:     my ($title,$head_extra,$args) = @_;
 5928:     return &headtag($title,$head_extra,$args).&endheadtag();
 5929: }
 5930: 
 5931: =pod
 5932: 
 5933: =item * &start_page()
 5934: 
 5935: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5936: 
 5937: Inputs:
 5938: 
 5939: =over 4
 5940: 
 5941: $title - optional title for the page
 5942: 
 5943: $head_extra - optional extra HTML to incude inside the <head>
 5944: 
 5945: $args - additional optional args supported are:
 5946: 
 5947: =over 8
 5948: 
 5949:              only_body      -> is true will set &bodytag() onlybodytag
 5950:                                     arg on
 5951:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5952:              add_entries    -> additional attributes to add to the  <body>
 5953:              domain         -> force to color decorate a page for a 
 5954:                                     specific domain
 5955:              function       -> force usage of a specific rolish color
 5956:                                     scheme
 5957:              redirect       -> see &headtag()
 5958:              bgcolor        -> override the default page bg color
 5959:              js_ready       -> return a string ready for being used in 
 5960:                                     a javascript writeln
 5961:              html_encode    -> return a string ready for being used in 
 5962:                                     a html attribute
 5963:              force_register -> if is true will turn on the &bodytag()
 5964:                                     $forcereg arg
 5965:              body_title     -> alternate text to use instead of $title
 5966:                                     in the title box that appears, this text
 5967:                                     is not auto translated like the $title is
 5968:              frameset       -> if true will start with a <frameset>
 5969:                                     rather than <body>
 5970:              no_title       -> if true the title bar won't be shown
 5971:              skip_phases    -> hash ref of 
 5972:                                     head -> skip the <html><head> generation
 5973:                                     body -> skip all <body> generation
 5974:              no_inline_link -> if true and in remote mode, don't show the 
 5975:                                     'Switch To Inline Menu' link
 5976:              no_auto_mt_title -> prevent &mt()ing the title arg
 5977:              inherit_jsmath -> when creating popup window in a page,
 5978:                                     should it have jsmath forced on by the
 5979:                                     current page
 5980: 
 5981: =back
 5982: 
 5983: =back
 5984: 
 5985: =cut
 5986: 
 5987: sub start_page {
 5988:     my ($title,$head_extra,$args) = @_;
 5989:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5990:     my %head_args;
 5991:     foreach my $arg ('redirect','force_register','domain','function',
 5992: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5993: 		     'no_auto_mt_title') {
 5994: 	if (defined($args->{$arg})) {
 5995: 	    $head_args{$arg} = $args->{$arg};
 5996: 	}
 5997:     }
 5998: 
 5999:     $env{'internal.start_page'}++;
 6000:     my $result;
 6001:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 6002: 	$result.=
 6003: 	    &xml_begin().
 6004: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 6005:     }
 6006:     
 6007:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 6008: 	if ($args->{'frameset'}) {
 6009: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 6010: 						$args->{'add_entries'});
 6011: 	    $result .= "\n<frameset $attr_string>\n";
 6012: 	} else {
 6013: 	    $result .=
 6014: 		&bodytag($title, 
 6015: 			 $args->{'function'},       $args->{'add_entries'},
 6016: 			 $args->{'only_body'},      $args->{'domain'},
 6017: 			 $args->{'force_register'}, $args->{'body_title'},
 6018: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 6019: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 6020: 			 $args);
 6021: 	}
 6022:     }
 6023: 
 6024:     if ($args->{'js_ready'}) {
 6025: 	$result = &js_ready($result);
 6026:     }
 6027:     if ($args->{'html_encode'}) {
 6028: 	$result = &html_encode($result);
 6029:     }
 6030:     #Breadcrumbs
 6031:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 6032:         &Apache::lonhtmlcommon::clear_breadcrumbs();
 6033:         #if any br links exists, add them to the breadcrumbs
 6034:         if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6035:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
 6036:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
 6037:             }
 6038:         }
 6039: 
 6040:         #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 6041:         if (exists($args->{'bread_crumbs_component'})){
 6042:             $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 6043:         } else {
 6044:             $result .= &Apache::lonhtmlcommon::breadcrumbs();
 6045:         }
 6046:     }
 6047:     return $result;
 6048: }
 6049: 
 6050: =pod
 6051: 
 6052: =item * &head()
 6053: 
 6054: Returns a complete </body></html> section for LON-CAPA web pages.
 6055: 
 6056: Inputs:         $args - additional optional args supported are:
 6057:                  js_ready     -> return a string ready for being used in 
 6058:                                  a javascript writeln
 6059:                  html_encode  -> return a string ready for being used in 
 6060:                                  a html attribute
 6061:                  frameset     -> if true will start with a <frameset>
 6062:                                  rather than <body>
 6063:                  dicsussion   -> if true will get discussion from
 6064:                                   lonxml::xmlend
 6065:                                  (you can pass the target and parser arguments
 6066:                                   through optional 'target' and 'parser' args
 6067:                                   to this routine)
 6068: 
 6069: =cut
 6070: 
 6071: sub end_page {
 6072:     my ($args) = @_;
 6073:     $env{'internal.end_page'}++;
 6074:     my $result;
 6075:     if ($args->{'discussion'}) {
 6076: 	my ($target,$parser);
 6077: 	if (ref($args->{'discussion'})) {
 6078: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 6079: 				$args->{'discussion'}{'parser'});
 6080: 	}
 6081: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 6082:     }
 6083: 
 6084:     if ($args->{'frameset'}) {
 6085: 	$result .= '</frameset>';
 6086:     } else {
 6087: 	$result .= &endbodytag($args);
 6088:     }
 6089:     $result .= "\n</html>";
 6090: 
 6091:     if ($args->{'js_ready'}) {
 6092: 	$result = &js_ready($result);
 6093:     }
 6094: 
 6095:     if ($args->{'html_encode'}) {
 6096: 	$result = &html_encode($result);
 6097:     }
 6098: 
 6099:     return $result;
 6100: }
 6101: 
 6102: sub html_encode {
 6103:     my ($result) = @_;
 6104: 
 6105:     $result = &HTML::Entities::encode($result,'<>&"');
 6106:     
 6107:     return $result;
 6108: }
 6109: sub js_ready {
 6110:     my ($result) = @_;
 6111: 
 6112:     $result =~ s/[\n\r]/ /xmsg;
 6113:     $result =~ s/\\/\\\\/xmsg;
 6114:     $result =~ s/'/\\'/xmsg;
 6115:     $result =~ s{</}{<\\/}xmsg;
 6116:     
 6117:     return $result;
 6118: }
 6119: 
 6120: sub validate_page {
 6121:     if (  exists($env{'internal.start_page'})
 6122: 	  &&     $env{'internal.start_page'} > 1) {
 6123: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6124: 				 $env{'internal.start_page'}.' '.
 6125: 				 $ENV{'request.filename'});
 6126:     }
 6127:     if (  exists($env{'internal.end_page'})
 6128: 	  &&     $env{'internal.end_page'} > 1) {
 6129: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6130: 				 $env{'internal.end_page'}.' '.
 6131: 				 $env{'request.filename'});
 6132:     }
 6133:     if (     exists($env{'internal.start_page'})
 6134: 	&& ! exists($env{'internal.end_page'})) {
 6135: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6136: 				 $env{'request.filename'});
 6137:     }
 6138:     if (   ! exists($env{'internal.start_page'})
 6139: 	&&   exists($env{'internal.end_page'})) {
 6140: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6141: 				 $env{'request.filename'});
 6142:     }
 6143: }
 6144: 
 6145: sub simple_error_page {
 6146:     my ($r,$title,$msg) = @_;
 6147:     my $page =
 6148: 	&Apache::loncommon::start_page($title).
 6149: 	&mt($msg).
 6150: 	&Apache::loncommon::end_page();
 6151:     if (ref($r)) {
 6152: 	$r->print($page);
 6153: 	return;
 6154:     }
 6155:     return $page;
 6156: }
 6157: 
 6158: {
 6159:     my @row_count;
 6160:     sub start_data_table {
 6161: 	my ($add_class) = @_;
 6162: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6163: 	unshift(@row_count,0);
 6164: 	return '<table class="'.$css_class.'">'."\n";
 6165:     }
 6166: 
 6167:     sub end_data_table {
 6168: 	shift(@row_count);
 6169: 	return '</table>'."\n";;
 6170:     }
 6171: 
 6172:     sub start_data_table_row {
 6173: 	my ($add_class) = @_;
 6174: 	$row_count[0]++;
 6175: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6176: 	$css_class = (join(' ',$css_class,$add_class));
 6177: 	return  '<tr class="'.$css_class.'">'."\n";;
 6178:     }
 6179:     
 6180:     sub continue_data_table_row {
 6181: 	my ($add_class) = @_;
 6182: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6183: 	$css_class = (join(' ',$css_class,$add_class));
 6184: 	return  '<tr class="'.$css_class.'">'."\n";;
 6185:     }
 6186: 
 6187:     sub end_data_table_row {
 6188: 	return '</tr>'."\n";;
 6189:     }
 6190: 
 6191:     sub start_data_table_empty_row {
 6192: 	$row_count[0]++;
 6193: 	return  '<tr class="LC_empty_row" >'."\n";;
 6194:     }
 6195: 
 6196:     sub end_data_table_empty_row {
 6197: 	return '</tr>'."\n";;
 6198:     }
 6199: 
 6200:     sub start_data_table_header_row {
 6201: 	return  '<tr class="LC_header_row">'."\n";;
 6202:     }
 6203: 
 6204:     sub end_data_table_header_row {
 6205: 	return '</tr>'."\n";;
 6206:     }
 6207: }
 6208: 
 6209: =pod
 6210: 
 6211: =item * &inhibit_menu_check($arg)
 6212: 
 6213: Checks for a inhibitmenu state and generates output to preserve it
 6214: 
 6215: Inputs:         $arg - can be any of
 6216:                      - undef - in which case the return value is a string 
 6217:                                to add  into arguments list of a uri
 6218:                      - 'input' - in which case the return value is a HTML
 6219:                                  <form> <input> field of type hidden to
 6220:                                  preserve the value
 6221:                      - a url - in which case the return value is the url with
 6222:                                the neccesary cgi args added to preserve the
 6223:                                inhibitmenu state
 6224:                      - a ref to a url - no return value, but the string is
 6225:                                         updated to include the neccessary cgi
 6226:                                         args to preserve the inhibitmenu state
 6227: 
 6228: =cut
 6229: 
 6230: sub inhibit_menu_check {
 6231:     my ($arg) = @_;
 6232:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6233:     if ($arg eq 'input') {
 6234: 	if ($env{'form.inhibitmenu'}) {
 6235: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6236: 	} else {
 6237: 	    return
 6238: 	}
 6239:     }
 6240:     if ($env{'form.inhibitmenu'}) {
 6241: 	if (ref($arg)) {
 6242: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6243: 	} elsif ($arg eq '') {
 6244: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6245: 	} else {
 6246: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6247: 	}
 6248:     }
 6249:     if (!ref($arg)) {
 6250: 	return $arg;
 6251:     }
 6252: }
 6253: 
 6254: ###############################################
 6255: 
 6256: =pod
 6257: 
 6258: =back
 6259: 
 6260: =head1 User Information Routines
 6261: 
 6262: =over 4
 6263: 
 6264: =item * &get_users_function()
 6265: 
 6266: Used by &bodytag to determine the current users primary role.
 6267: Returns either 'student','coordinator','admin', or 'author'.
 6268: 
 6269: =cut
 6270: 
 6271: ###############################################
 6272: sub get_users_function {
 6273:     my $function = 'student';
 6274:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6275:         $function='coordinator';
 6276:     }
 6277:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6278:         $function='admin';
 6279:     }
 6280:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 6281:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6282:         $function='author';
 6283:     }
 6284:     return $function;
 6285: }
 6286: 
 6287: ###############################################
 6288: 
 6289: =pod
 6290: 
 6291: =item * &show_course()
 6292: 
 6293: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 6294: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 6295: Inputs:
 6296: None
 6297: 
 6298: Outputs:
 6299: Scalar: 1 if 'Course' to be used, 0 otherwise.
 6300: 
 6301: =cut
 6302: 
 6303: ###############################################
 6304: sub show_course {
 6305:     my $course = !$env{'user.adv'};
 6306:     if (!$env{'user.adv'}) {
 6307:         foreach my $env (keys(%env)) {
 6308:             next if ($env !~ m/^user\.priv\./);
 6309:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 6310:                 $course = 0;
 6311:                 last;
 6312:             }
 6313:         }
 6314:     }
 6315:     return $course;
 6316: }
 6317: 
 6318: ###############################################
 6319: 
 6320: =pod
 6321: 
 6322: =item * &check_user_status()
 6323: 
 6324: Determines current status of supplied role for a
 6325: specific user. Roles can be active, previous or future.
 6326: 
 6327: Inputs: 
 6328: user's domain, user's username, course's domain,
 6329: course's number, optional section ID.
 6330: 
 6331: Outputs:
 6332: role status: active, previous or future. 
 6333: 
 6334: =cut
 6335: 
 6336: sub check_user_status {
 6337:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6338:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6339:     my @uroles = keys %userinfo;
 6340:     my $srchstr;
 6341:     my $active_chk = 'none';
 6342:     my $now = time;
 6343:     if (@uroles > 0) {
 6344:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6345:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6346:         } else {
 6347:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6348:         }
 6349:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6350:             my $role_end = 0;
 6351:             my $role_start = 0;
 6352:             $active_chk = 'active';
 6353:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6354:                 $role_end = $1;
 6355:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6356:                     $role_start = $1;
 6357:                 }
 6358:             }
 6359:             if ($role_start > 0) {
 6360:                 if ($now < $role_start) {
 6361:                     $active_chk = 'future';
 6362:                 }
 6363:             }
 6364:             if ($role_end > 0) {
 6365:                 if ($now > $role_end) {
 6366:                     $active_chk = 'previous';
 6367:                 }
 6368:             }
 6369:         }
 6370:     }
 6371:     return $active_chk;
 6372: }
 6373: 
 6374: ###############################################
 6375: 
 6376: =pod
 6377: 
 6378: =item * &get_sections()
 6379: 
 6380: Determines all the sections for a course including
 6381: sections with students and sections containing other roles.
 6382: Incoming parameters: 
 6383: 
 6384: 1. domain
 6385: 2. course number 
 6386: 3. reference to array containing roles for which sections should 
 6387: be gathered (optional).
 6388: 4. reference to array containing status types for which sections 
 6389: should be gathered (optional).
 6390: 
 6391: If the third argument is undefined, sections are gathered for any role. 
 6392: If the fourth argument is undefined, sections are gathered for any status.
 6393: Permissible values are 'active' or 'future' or 'previous'.
 6394:  
 6395: Returns section hash (keys are section IDs, values are
 6396: number of users in each section), subject to the
 6397: optional roles filter, optional status filter 
 6398: 
 6399: =cut
 6400: 
 6401: ###############################################
 6402: sub get_sections {
 6403:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6404:     if (!defined($cdom) || !defined($cnum)) {
 6405:         my $cid =  $env{'request.course.id'};
 6406: 
 6407: 	return if (!defined($cid));
 6408: 
 6409:         $cdom = $env{'course.'.$cid.'.domain'};
 6410:         $cnum = $env{'course.'.$cid.'.num'};
 6411:     }
 6412: 
 6413:     my %sectioncount;
 6414:     my $now = time;
 6415: 
 6416:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6417: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6418: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6419: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6420:         my $start_index = &Apache::loncoursedata::CL_START();
 6421:         my $end_index = &Apache::loncoursedata::CL_END();
 6422:         my $status;
 6423: 	while (my ($student,$data) = each(%$classlist)) {
 6424: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6425: 				                     $data->[$status_index],
 6426:                                                      $data->[$start_index],
 6427:                                                      $data->[$end_index]);
 6428:             if ($stu_status eq 'Active') {
 6429:                 $status = 'active';
 6430:             } elsif ($end < $now) {
 6431:                 $status = 'previous';
 6432:             } elsif ($start > $now) {
 6433:                 $status = 'future';
 6434:             } 
 6435: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6436:                 if ((!defined($possible_status)) || (($status ne '') && 
 6437:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6438: 		    $sectioncount{$section}++;
 6439:                 }
 6440: 	    }
 6441: 	}
 6442:     }
 6443:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6444:     foreach my $user (sort(keys(%courseroles))) {
 6445: 	if ($user !~ /^(\w{2})/) { next; }
 6446: 	my ($role) = ($user =~ /^(\w{2})/);
 6447: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6448: 	my ($section,$status);
 6449: 	if ($role eq 'cr' &&
 6450: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6451: 	    $section=$1;
 6452: 	}
 6453: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6454: 	if (!defined($section) || $section eq '-1') { next; }
 6455:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6456:         if ($end == -1 && $start == -1) {
 6457:             next; #deleted role
 6458:         }
 6459:         if (!defined($possible_status)) { 
 6460:             $sectioncount{$section}++;
 6461:         } else {
 6462:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6463:                 $status = 'active';
 6464:             } elsif ($end < $now) {
 6465:                 $status = 'future';
 6466:             } elsif ($start > $now) {
 6467:                 $status = 'previous';
 6468:             }
 6469:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6470:                 $sectioncount{$section}++;
 6471:             }
 6472:         }
 6473:     }
 6474:     return %sectioncount;
 6475: }
 6476: 
 6477: ###############################################
 6478: 
 6479: =pod
 6480: 
 6481: =item * &get_course_users()
 6482: 
 6483: Retrieves usernames:domains for users in the specified course
 6484: with specific role(s), and access status. 
 6485: 
 6486: Incoming parameters:
 6487: 1. course domain
 6488: 2. course number
 6489: 3. access status: users must have - either active, 
 6490: previous, future, or all.
 6491: 4. reference to array of permissible roles
 6492: 5. reference to array of section restrictions (optional)
 6493: 6. reference to results object (hash of hashes).
 6494: 7. reference to optional userdata hash
 6495: 8. reference to optional statushash
 6496: 9. flag if privileged users (except those set to unhide in
 6497:    course settings) should be excluded    
 6498: Keys of top level results hash are roles.
 6499: Keys of inner hashes are username:domain, with 
 6500: values set to access type.
 6501: Optional userdata hash returns an array with arguments in the 
 6502: same order as loncoursedata::get_classlist() for student data.
 6503: 
 6504: Optional statushash returns
 6505: 
 6506: Entries for end, start, section and status are blank because
 6507: of the possibility of multiple values for non-student roles.
 6508: 
 6509: =cut
 6510: 
 6511: ###############################################
 6512: 
 6513: sub get_course_users {
 6514:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6515:     my %idx = ();
 6516:     my %seclists;
 6517: 
 6518:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6519:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6520:     $idx{end} = &Apache::loncoursedata::CL_END();
 6521:     $idx{start} = &Apache::loncoursedata::CL_START();
 6522:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6523:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6524:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6525:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6526: 
 6527:     if (grep(/^st$/,@{$roles})) {
 6528:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6529:         my $now = time;
 6530:         foreach my $student (keys(%{$classlist})) {
 6531:             my $match = 0;
 6532:             my $secmatch = 0;
 6533:             my $section = $$classlist{$student}[$idx{section}];
 6534:             my $status = $$classlist{$student}[$idx{status}];
 6535:             if ($section eq '') {
 6536:                 $section = 'none';
 6537:             }
 6538:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6539:                 if (grep(/^all$/,@{$sections})) {
 6540:                     $secmatch = 1;
 6541:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6542:                     if (grep(/^none$/,@{$sections})) {
 6543:                         $secmatch = 1;
 6544:                     }
 6545:                 } else {  
 6546: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6547: 		        $secmatch = 1;
 6548:                     }
 6549: 		}
 6550:                 if (!$secmatch) {
 6551:                     next;
 6552:                 }
 6553:             }
 6554:             if (defined($$types{'active'})) {
 6555:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6556:                     push(@{$$users{st}{$student}},'active');
 6557:                     $match = 1;
 6558:                 }
 6559:             }
 6560:             if (defined($$types{'previous'})) {
 6561:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6562:                     push(@{$$users{st}{$student}},'previous');
 6563:                     $match = 1;
 6564:                 }
 6565:             }
 6566:             if (defined($$types{'future'})) {
 6567:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6568:                     push(@{$$users{st}{$student}},'future');
 6569:                     $match = 1;
 6570:                 }
 6571:             }
 6572:             if ($match) {
 6573:                 push(@{$seclists{$student}},$section);
 6574:                 if (ref($userdata) eq 'HASH') {
 6575:                     $$userdata{$student} = $$classlist{$student};
 6576:                 }
 6577:                 if (ref($statushash) eq 'HASH') {
 6578:                     $statushash->{$student}{'st'}{$section} = $status;
 6579:                 }
 6580:             }
 6581:         }
 6582:     }
 6583:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6584:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6585:         my $now = time;
 6586:         my %displaystatus = ( previous => 'Expired',
 6587:                               active   => 'Active',
 6588:                               future   => 'Future',
 6589:                             );
 6590:         my %nothide;
 6591:         if ($hidepriv) {
 6592:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6593:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6594:                 if ($user !~ /:/) {
 6595:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6596:                 } else {
 6597:                     $nothide{$user} = 1;
 6598:                 }
 6599:             }
 6600:         }
 6601:         foreach my $person (sort(keys(%coursepersonnel))) {
 6602:             my $match = 0;
 6603:             my $secmatch = 0;
 6604:             my $status;
 6605:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6606:             $user =~ s/:$//;
 6607:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6608:             if ($end == -1 || $start == -1) {
 6609:                 next;
 6610:             }
 6611:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6612:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6613:                 my ($uname,$udom) = split(/:/,$user);
 6614:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6615:                     if (grep(/^all$/,@{$sections})) {
 6616:                         $secmatch = 1;
 6617:                     } elsif ($usec eq '') {
 6618:                         if (grep(/^none$/,@{$sections})) {
 6619:                             $secmatch = 1;
 6620:                         }
 6621:                     } else {
 6622:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6623:                             $secmatch = 1;
 6624:                         }
 6625:                     }
 6626:                     if (!$secmatch) {
 6627:                         next;
 6628:                     }
 6629:                 }
 6630:                 if ($usec eq '') {
 6631:                     $usec = 'none';
 6632:                 }
 6633:                 if ($uname ne '' && $udom ne '') {
 6634:                     if ($hidepriv) {
 6635:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6636:                             (!$nothide{$uname.':'.$udom})) {
 6637:                             next;
 6638:                         }
 6639:                     }
 6640:                     if ($end > 0 && $end < $now) {
 6641:                         $status = 'previous';
 6642:                     } elsif ($start > $now) {
 6643:                         $status = 'future';
 6644:                     } else {
 6645:                         $status = 'active';
 6646:                     }
 6647:                     foreach my $type (keys(%{$types})) { 
 6648:                         if ($status eq $type) {
 6649:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6650:                                 push(@{$$users{$role}{$user}},$type);
 6651:                             }
 6652:                             $match = 1;
 6653:                         }
 6654:                     }
 6655:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6656:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6657: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6658:                         }
 6659:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6660:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6661:                         }
 6662:                         if (ref($statushash) eq 'HASH') {
 6663:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6664:                         }
 6665:                     }
 6666:                 }
 6667:             }
 6668:         }
 6669:         if (grep(/^ow$/,@{$roles})) {
 6670:             if ((defined($cdom)) && (defined($cnum))) {
 6671:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6672:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6673:                     my $owner = $csettings{'internal.courseowner'};
 6674:                     next if ($owner eq '');
 6675:                     my ($ownername,$ownerdom);
 6676:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6677:                         $ownername = $1;
 6678:                         $ownerdom = $2;
 6679:                     } else {
 6680:                         $ownername = $owner;
 6681:                         $ownerdom = $cdom;
 6682:                         $owner = $ownername.':'.$ownerdom;
 6683:                     }
 6684:                     @{$$users{'ow'}{$owner}} = 'any';
 6685:                     if (defined($userdata) && 
 6686: 			!exists($$userdata{$owner})) {
 6687: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6688:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6689:                             push(@{$seclists{$owner}},'none');
 6690:                         }
 6691:                         if (ref($statushash) eq 'HASH') {
 6692:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6693:                         }
 6694: 		    }
 6695:                 }
 6696:             }
 6697:         }
 6698:         foreach my $user (keys(%seclists)) {
 6699:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6700:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6701:         }
 6702:     }
 6703:     return;
 6704: }
 6705: 
 6706: sub get_user_info {
 6707:     my ($udom,$uname,$idx,$userdata) = @_;
 6708:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6709: 	&plainname($uname,$udom,'lastname');
 6710:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6711:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6712:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6713:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6714:     return;
 6715: }
 6716: 
 6717: ###############################################
 6718: 
 6719: =pod
 6720: 
 6721: =item * &get_user_quota()
 6722: 
 6723: Retrieves quota assigned for storage of portfolio files for a user  
 6724: 
 6725: Incoming parameters:
 6726: 1. user's username
 6727: 2. user's domain
 6728: 
 6729: Returns:
 6730: 1. Disk quota (in Mb) assigned to student.
 6731: 2. (Optional) Type of setting: custom or default
 6732:    (individually assigned or default for user's 
 6733:    institutional status).
 6734: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6735:    or student - types as defined in localenroll::inst_usertypes 
 6736:    for user's domain, which determines default quota for user.
 6737: 4. (Optional) - Default quota which would apply to the user.
 6738: 
 6739: If a value has been stored in the user's environment, 
 6740: it will return that, otherwise it returns the maximal default
 6741: defined for the user's instituional status(es) in the domain.
 6742: 
 6743: =cut
 6744: 
 6745: ###############################################
 6746: 
 6747: 
 6748: sub get_user_quota {
 6749:     my ($uname,$udom) = @_;
 6750:     my ($quota,$quotatype,$settingstatus,$defquota);
 6751:     if (!defined($udom)) {
 6752:         $udom = $env{'user.domain'};
 6753:     }
 6754:     if (!defined($uname)) {
 6755:         $uname = $env{'user.name'};
 6756:     }
 6757:     if (($udom eq '' || $uname eq '') ||
 6758:         ($udom eq 'public') && ($uname eq 'public')) {
 6759:         $quota = 0;
 6760:         $quotatype = 'default';
 6761:         $defquota = 0; 
 6762:     } else {
 6763:         my $inststatus;
 6764:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6765:             $quota = $env{'environment.portfolioquota'};
 6766:             $inststatus = $env{'environment.inststatus'};
 6767:         } else {
 6768:             my %userenv = 
 6769:                 &Apache::lonnet::get('environment',['portfolioquota',
 6770:                                      'inststatus'],$udom,$uname);
 6771:             my ($tmp) = keys(%userenv);
 6772:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6773:                 $quota = $userenv{'portfolioquota'};
 6774:                 $inststatus = $userenv{'inststatus'};
 6775:             } else {
 6776:                 undef(%userenv);
 6777:             }
 6778:         }
 6779:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6780:         if ($quota eq '') {
 6781:             $quota = $defquota;
 6782:             $quotatype = 'default';
 6783:         } else {
 6784:             $quotatype = 'custom';
 6785:         }
 6786:     }
 6787:     if (wantarray) {
 6788:         return ($quota,$quotatype,$settingstatus,$defquota);
 6789:     } else {
 6790:         return $quota;
 6791:     }
 6792: }
 6793: 
 6794: ###############################################
 6795: 
 6796: =pod
 6797: 
 6798: =item * &default_quota()
 6799: 
 6800: Retrieves default quota assigned for storage of user portfolio files,
 6801: given an (optional) user's institutional status.
 6802: 
 6803: Incoming parameters:
 6804: 1. domain
 6805: 2. (Optional) institutional status(es).  This is a : separated list of 
 6806:    status types (e.g., faculty, staff, student etc.)
 6807:    which apply to the user for whom the default is being retrieved.
 6808:    If the institutional status string in undefined, the domain
 6809:    default quota will be returned. 
 6810: 
 6811: Returns:
 6812: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6813: 2. (Optional) institutional type which determined the value of the
 6814:    default quota.
 6815: 
 6816: If a value has been stored in the domain's configuration db,
 6817: it will return that, otherwise it returns 20 (for backwards 
 6818: compatibility with domains which have not set up a configuration
 6819: db file; the original statically defined portfolio quota was 20 Mb). 
 6820: 
 6821: If the user's status includes multiple types (e.g., staff and student),
 6822: the largest default quota which applies to the user determines the
 6823: default quota returned.
 6824: 
 6825: =back
 6826: 
 6827: =cut
 6828: 
 6829: ###############################################
 6830: 
 6831: 
 6832: sub default_quota {
 6833:     my ($udom,$inststatus) = @_;
 6834:     my ($defquota,$settingstatus);
 6835:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6836:                                             ['quotas'],$udom);
 6837:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6838:         if ($inststatus ne '') {
 6839:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 6840:             foreach my $item (@statuses) {
 6841:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6842:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6843:                         if ($defquota eq '') {
 6844:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6845:                             $settingstatus = $item;
 6846:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6847:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6848:                             $settingstatus = $item;
 6849:                         }
 6850:                     }
 6851:                 } else {
 6852:                     if ($quotahash{'quotas'}{$item} ne '') {
 6853:                         if ($defquota eq '') {
 6854:                             $defquota = $quotahash{'quotas'}{$item};
 6855:                             $settingstatus = $item;
 6856:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6857:                             $defquota = $quotahash{'quotas'}{$item};
 6858:                             $settingstatus = $item;
 6859:                         }
 6860:                     }
 6861:                 }
 6862:             }
 6863:         }
 6864:         if ($defquota eq '') {
 6865:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6866:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6867:             } else {
 6868:                 $defquota = $quotahash{'quotas'}{'default'};
 6869:             }
 6870:             $settingstatus = 'default';
 6871:         }
 6872:     } else {
 6873:         $settingstatus = 'default';
 6874:         $defquota = 20;
 6875:     }
 6876:     if (wantarray) {
 6877:         return ($defquota,$settingstatus);
 6878:     } else {
 6879:         return $defquota;
 6880:     }
 6881: }
 6882: 
 6883: sub get_secgrprole_info {
 6884:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6885:     my %sections_count = &get_sections($cdom,$cnum);
 6886:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6887:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6888:     my @groups = sort(keys(%curr_groups));
 6889:     my $allroles = [];
 6890:     my $rolehash;
 6891:     my $accesshash = {
 6892:                      active => 'Currently has access',
 6893:                      future => 'Will have future access',
 6894:                      previous => 'Previously had access',
 6895:                   };
 6896:     if ($needroles) {
 6897:         $rolehash = {'all' => 'all'};
 6898:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6899: 	if (&Apache::lonnet::error(%user_roles)) {
 6900: 	    undef(%user_roles);
 6901: 	}
 6902:         foreach my $item (keys(%user_roles)) {
 6903:             my ($role)=split(/\:/,$item,2);
 6904:             if ($role eq 'cr') { next; }
 6905:             if ($role =~ /^cr/) {
 6906:                 $$rolehash{$role} = (split('/',$role))[3];
 6907:             } else {
 6908:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6909:             }
 6910:         }
 6911:         foreach my $key (sort(keys(%{$rolehash}))) {
 6912:             push(@{$allroles},$key);
 6913:         }
 6914:         push (@{$allroles},'st');
 6915:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6916:     }
 6917:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6918: }
 6919: 
 6920: sub user_picker {
 6921:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6922:     my $currdom = $dom;
 6923:     my %curr_selected = (
 6924:                         srchin => 'dom',
 6925:                         srchby => 'lastname',
 6926:                       );
 6927:     my $srchterm;
 6928:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6929:         if ($srch->{'srchby'} ne '') {
 6930:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6931:         }
 6932:         if ($srch->{'srchin'} ne '') {
 6933:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6934:         }
 6935:         if ($srch->{'srchtype'} ne '') {
 6936:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6937:         }
 6938:         if ($srch->{'srchdomain'} ne '') {
 6939:             $currdom = $srch->{'srchdomain'};
 6940:         }
 6941:         $srchterm = $srch->{'srchterm'};
 6942:     }
 6943:     my %lt=&Apache::lonlocal::texthash(
 6944:                     'usr'       => 'Search criteria',
 6945:                     'doma'      => 'Domain/institution to search',
 6946:                     'uname'     => 'username',
 6947:                     'lastname'  => 'last name',
 6948:                     'lastfirst' => 'last name, first name',
 6949:                     'crs'       => 'in this course',
 6950:                     'dom'       => 'in selected LON-CAPA domain', 
 6951:                     'alc'       => 'all LON-CAPA',
 6952:                     'instd'     => 'in institutional directory for selected domain',
 6953:                     'exact'     => 'is',
 6954:                     'contains'  => 'contains',
 6955:                     'begins'    => 'begins with',
 6956:                     'youm'      => "You must include some text to search for.",
 6957:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6958:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6959:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6960:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6961:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6962:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6963:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6964:                                        );
 6965:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6966:     my $srchinsel = ' <select name="srchin">';
 6967: 
 6968:     my @srchins = ('crs','dom','alc','instd');
 6969: 
 6970:     foreach my $option (@srchins) {
 6971:         # FIXME 'alc' option unavailable until 
 6972:         #       loncreateuser::print_user_query_page()
 6973:         #       has been completed.
 6974:         next if ($option eq 'alc');
 6975:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
 6976:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6977:         if ($curr_selected{'srchin'} eq $option) {
 6978:             $srchinsel .= ' 
 6979:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6980:         } else {
 6981:             $srchinsel .= '
 6982:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6983:         }
 6984:     }
 6985:     $srchinsel .= "\n  </select>\n";
 6986: 
 6987:     my $srchbysel =  ' <select name="srchby">';
 6988:     foreach my $option ('lastname','lastfirst','uname') {
 6989:         if ($curr_selected{'srchby'} eq $option) {
 6990:             $srchbysel .= '
 6991:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6992:         } else {
 6993:             $srchbysel .= '
 6994:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6995:          }
 6996:     }
 6997:     $srchbysel .= "\n  </select>\n";
 6998: 
 6999:     my $srchtypesel = ' <select name="srchtype">';
 7000:     foreach my $option ('begins','contains','exact') {
 7001:         if ($curr_selected{'srchtype'} eq $option) {
 7002:             $srchtypesel .= '
 7003:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 7004:         } else {
 7005:             $srchtypesel .= '
 7006:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 7007:         }
 7008:     }
 7009:     $srchtypesel .= "\n  </select>\n";
 7010: 
 7011:     my ($newuserscript,$new_user_create);
 7012: 
 7013:     if ($forcenewuser) {
 7014:         if (ref($srch) eq 'HASH') {
 7015:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 7016:                 if ($cancreate) {
 7017:                     $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>';
 7018:                 } else {
 7019:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 7020:                     my %usertypetext = (
 7021:                         official   => 'institutional',
 7022:                         unofficial => 'non-institutional',
 7023:                     );
 7024:                     $new_user_create = '<p class="LC_warning">'.
 7025:                                        &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
 7026:                                        &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
 7027:                 }
 7028:             }
 7029:         }
 7030: 
 7031:         $newuserscript = <<"ENDSCRIPT";
 7032: 
 7033: function setSearch(createnew,callingForm) {
 7034:     if (createnew == 1) {
 7035:         for (var i=0; i<callingForm.srchby.length; i++) {
 7036:             if (callingForm.srchby.options[i].value == 'uname') {
 7037:                 callingForm.srchby.selectedIndex = i;
 7038:             }
 7039:         }
 7040:         for (var i=0; i<callingForm.srchin.length; i++) {
 7041:             if ( callingForm.srchin.options[i].value == 'dom') {
 7042: 		callingForm.srchin.selectedIndex = i;
 7043:             }
 7044:         }
 7045:         for (var i=0; i<callingForm.srchtype.length; i++) {
 7046:             if (callingForm.srchtype.options[i].value == 'exact') {
 7047:                 callingForm.srchtype.selectedIndex = i;
 7048:             }
 7049:         }
 7050:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 7051:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 7052:                 callingForm.srchdomain.selectedIndex = i;
 7053:             }
 7054:         }
 7055:     }
 7056: }
 7057: ENDSCRIPT
 7058: 
 7059:     }
 7060: 
 7061:     my $output = <<"END_BLOCK";
 7062: <script type="text/javascript">
 7063: // <![CDATA[
 7064: function validateEntry(callingForm) {
 7065: 
 7066:     var checkok = 1;
 7067:     var srchin;
 7068:     for (var i=0; i<callingForm.srchin.length; i++) {
 7069: 	if ( callingForm.srchin[i].checked ) {
 7070: 	    srchin = callingForm.srchin[i].value;
 7071: 	}
 7072:     }
 7073: 
 7074:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 7075:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 7076:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 7077:     var srchterm =  callingForm.srchterm.value;
 7078:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 7079:     var msg = "";
 7080: 
 7081:     if (srchterm == "") {
 7082:         checkok = 0;
 7083:         msg += "$lt{'youm'}\\n";
 7084:     }
 7085: 
 7086:     if (srchtype== 'begins') {
 7087:         if (srchterm.length < 2) {
 7088:             checkok = 0;
 7089:             msg += "$lt{'thte'}\\n";
 7090:         }
 7091:     }
 7092: 
 7093:     if (srchtype== 'contains') {
 7094:         if (srchterm.length < 3) {
 7095:             checkok = 0;
 7096:             msg += "$lt{'thet'}\\n";
 7097:         }
 7098:     }
 7099:     if (srchin == 'instd') {
 7100:         if (srchdomain == '') {
 7101:             checkok = 0;
 7102:             msg += "$lt{'yomc'}\\n";
 7103:         }
 7104:     }
 7105:     if (srchin == 'dom') {
 7106:         if (srchdomain == '') {
 7107:             checkok = 0;
 7108:             msg += "$lt{'ymcd'}\\n";
 7109:         }
 7110:     }
 7111:     if (srchby == 'lastfirst') {
 7112:         if (srchterm.indexOf(",") == -1) {
 7113:             checkok = 0;
 7114:             msg += "$lt{'whus'}\\n";
 7115:         }
 7116:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7117:             checkok = 0;
 7118:             msg += "$lt{'whse'}\\n";
 7119:         }
 7120:     }
 7121:     if (checkok == 0) {
 7122:         alert("$lt{'thfo'}\\n"+msg);
 7123:         return;
 7124:     }
 7125:     if (checkok == 1) {
 7126:         callingForm.submit();
 7127:     }
 7128: }
 7129: 
 7130: $newuserscript
 7131: 
 7132: // ]]>
 7133: </script>
 7134: 
 7135: $new_user_create
 7136: 
 7137: END_BLOCK
 7138: 
 7139:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 7140:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 7141:                $domform.
 7142:                &Apache::lonhtmlcommon::row_closure().
 7143:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 7144:                $srchbysel.
 7145:                $srchtypesel.
 7146:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 7147:                $srchinsel.
 7148:                &Apache::lonhtmlcommon::row_closure(1).
 7149:                &Apache::lonhtmlcommon::end_pick_box().
 7150:                '<br />';
 7151:     return $output;
 7152: }
 7153: 
 7154: sub user_rule_check {
 7155:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7156:     my $response;
 7157:     if (ref($usershash) eq 'HASH') {
 7158:         foreach my $user (keys(%{$usershash})) {
 7159:             my ($uname,$udom) = split(/:/,$user);
 7160:             next if ($udom eq '' || $uname eq '');
 7161:             my ($id,$newuser);
 7162:             if (ref($usershash->{$user}) eq 'HASH') {
 7163:                 $newuser = $usershash->{$user}->{'newuser'};
 7164:                 $id = $usershash->{$user}->{'id'};
 7165:             }
 7166:             my $inst_response;
 7167:             if (ref($checks) eq 'HASH') {
 7168:                 if (defined($checks->{'username'})) {
 7169:                     ($inst_response,%{$inst_results->{$user}}) = 
 7170:                         &Apache::lonnet::get_instuser($udom,$uname);
 7171:                 } elsif (defined($checks->{'id'})) {
 7172:                     ($inst_response,%{$inst_results->{$user}}) =
 7173:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7174:                 }
 7175:             } else {
 7176:                 ($inst_response,%{$inst_results->{$user}}) =
 7177:                     &Apache::lonnet::get_instuser($udom,$uname);
 7178:                 return;
 7179:             }
 7180:             if (!$got_rules->{$udom}) {
 7181:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7182:                                                   ['usercreation'],$udom);
 7183:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7184:                     foreach my $item ('username','id') {
 7185:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7186:                             $$curr_rules{$udom}{$item} = 
 7187:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7188:                         }
 7189:                     }
 7190:                 }
 7191:                 $got_rules->{$udom} = 1;  
 7192:             }
 7193:             foreach my $item (keys(%{$checks})) {
 7194:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7195:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7196:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7197:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7198:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7199:                                 if ($rule_check{$rule}) {
 7200:                                     $$rulematch{$user}{$item} = $rule;
 7201:                                     if ($inst_response eq 'ok') {
 7202:                                         if (ref($inst_results) eq 'HASH') {
 7203:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7204:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7205:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7206:                                                 }
 7207:                                             }
 7208:                                         }
 7209:                                     }
 7210:                                     last;
 7211:                                 }
 7212:                             }
 7213:                         }
 7214:                     }
 7215:                 }
 7216:             }
 7217:         }
 7218:     }
 7219:     return;
 7220: }
 7221: 
 7222: sub user_rule_formats {
 7223:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7224:     my %text = ( 
 7225:                  'username' => 'Usernames',
 7226:                  'id'       => 'IDs',
 7227:                );
 7228:     my $output;
 7229:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7230:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7231:         if (@{$ruleorder} > 0) {
 7232:             $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>';
 7233:             foreach my $rule (@{$ruleorder}) {
 7234:                 if (ref($curr_rules) eq 'ARRAY') {
 7235:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7236:                         if (ref($rules->{$rule}) eq 'HASH') {
 7237:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7238:                                         $rules->{$rule}{'desc'}.'</li>';
 7239:                         }
 7240:                     }
 7241:                 }
 7242:             }
 7243:             $output .= '</ul>';
 7244:         }
 7245:     }
 7246:     return $output;
 7247: }
 7248: 
 7249: sub instrule_disallow_msg {
 7250:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7251:     my $response;
 7252:     my %text = (
 7253:                   item   => 'username',
 7254:                   items  => 'usernames',
 7255:                   match  => 'matches',
 7256:                   do     => 'does',
 7257:                   action => 'a username',
 7258:                   one    => 'one',
 7259:                );
 7260:     if ($count > 1) {
 7261:         $text{'item'} = 'usernames';
 7262:         $text{'match'} ='match';
 7263:         $text{'do'} = 'do';
 7264:         $text{'action'} = 'usernames',
 7265:         $text{'one'} = 'ones';
 7266:     }
 7267:     if ($checkitem eq 'id') {
 7268:         $text{'items'} = 'IDs';
 7269:         $text{'item'} = 'ID';
 7270:         $text{'action'} = 'an ID';
 7271:         if ($count > 1) {
 7272:             $text{'item'} = 'IDs';
 7273:             $text{'action'} = 'IDs';
 7274:         }
 7275:     }
 7276:     $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 />';
 7277:     if ($mode eq 'upload') {
 7278:         if ($checkitem eq 'username') {
 7279:             $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'}.");
 7280:         } elsif ($checkitem eq 'id') {
 7281:             $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.");
 7282:         }
 7283:     } elsif ($mode eq 'selfcreate') {
 7284:         if ($checkitem eq 'id') {
 7285:             $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.");
 7286:         }
 7287:     } else {
 7288:         if ($checkitem eq 'username') {
 7289:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7290:         } elsif ($checkitem eq 'id') {
 7291:             $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.");
 7292:         }
 7293:     }
 7294:     return $response;
 7295: }
 7296: 
 7297: sub personal_data_fieldtitles {
 7298:     my %fieldtitles = &Apache::lonlocal::texthash (
 7299:                         id => 'Student/Employee ID',
 7300:                         permanentemail => 'E-mail address',
 7301:                         lastname => 'Last Name',
 7302:                         firstname => 'First Name',
 7303:                         middlename => 'Middle Name',
 7304:                         generation => 'Generation',
 7305:                         gen => 'Generation',
 7306:                         inststatus => 'Affiliation',
 7307:                    );
 7308:     return %fieldtitles;
 7309: }
 7310: 
 7311: sub sorted_inst_types {
 7312:     my ($dom) = @_;
 7313:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7314:     my $othertitle = &mt('All users');
 7315:     if ($env{'request.course.id'}) {
 7316:         $othertitle  = &mt('Any users');
 7317:     }
 7318:     my @types;
 7319:     if (ref($order) eq 'ARRAY') {
 7320:         @types = @{$order};
 7321:     }
 7322:     if (@types == 0) {
 7323:         if (ref($usertypes) eq 'HASH') {
 7324:             @types = sort(keys(%{$usertypes}));
 7325:         }
 7326:     }
 7327:     if (keys(%{$usertypes}) > 0) {
 7328:         $othertitle = &mt('Other users');
 7329:     }
 7330:     return ($othertitle,$usertypes,\@types);
 7331: }
 7332: 
 7333: sub get_institutional_codes {
 7334:     my ($settings,$allcourses,$LC_code) = @_;
 7335: # Get complete list of course sections to update
 7336:     my @currsections = ();
 7337:     my @currxlists = ();
 7338:     my $coursecode = $$settings{'internal.coursecode'};
 7339: 
 7340:     if ($$settings{'internal.sectionnums'} ne '') {
 7341:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7342:     }
 7343: 
 7344:     if ($$settings{'internal.crosslistings'} ne '') {
 7345:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7346:     }
 7347: 
 7348:     if (@currxlists > 0) {
 7349:         foreach (@currxlists) {
 7350:             if (m/^([^:]+):(\w*)$/) {
 7351:                 unless (grep/^$1$/,@{$allcourses}) {
 7352:                     push @{$allcourses},$1;
 7353:                     $$LC_code{$1} = $2;
 7354:                 }
 7355:             }
 7356:         }
 7357:     }
 7358:  
 7359:     if (@currsections > 0) {
 7360:         foreach (@currsections) {
 7361:             if (m/^(\w+):(\w*)$/) {
 7362:                 my $sec = $coursecode.$1;
 7363:                 my $lc_sec = $2;
 7364:                 unless (grep/^$sec$/,@{$allcourses}) {
 7365:                     push @{$allcourses},$sec;
 7366:                     $$LC_code{$sec} = $lc_sec;
 7367:                 }
 7368:             }
 7369:         }
 7370:     }
 7371:     return;
 7372: }
 7373: 
 7374: =pod
 7375: 
 7376: =head1 Slot Helpers
 7377: 
 7378: =over 4
 7379: 
 7380: =item * sorted_slots()
 7381: 
 7382: Sorts an array of slot names in order of slot start time (earliest first).
 7383: 
 7384: Inputs:
 7385: 
 7386: =over 4
 7387: 
 7388: slotsarr  - Reference to array of unsorted slot names.
 7389: 
 7390: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7391: 
 7392: =back
 7393: 
 7394: Returns:
 7395: 
 7396: =over 4
 7397: 
 7398: sorted   - An array of slot names sorted by the start time of the slot.
 7399: 
 7400: =back
 7401: 
 7402: =back
 7403: 
 7404: =cut
 7405: 
 7406: 
 7407: sub sorted_slots {
 7408:     my ($slotsarr,$slots) = @_;
 7409:     my @sorted;
 7410:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7411:         @sorted =
 7412:             sort {
 7413:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7414:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7415:                      }
 7416:                      if (ref($slots->{$a})) { return -1;}
 7417:                      if (ref($slots->{$b})) { return 1;}
 7418:                      return 0;
 7419:                  } @{$slotsarr};
 7420:     }
 7421:     return @sorted;
 7422: }
 7423: 
 7424: =pod
 7425: 
 7426: =head1 HTTP Helpers
 7427: 
 7428: =over 4
 7429: 
 7430: =item * &get_unprocessed_cgi($query,$possible_names)
 7431: 
 7432: Modify the %env hash to contain unprocessed CGI form parameters held in
 7433: $query.  The parameters listed in $possible_names (an array reference),
 7434: will be set in $env{'form.name'} if they do not already exist.
 7435: 
 7436: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7437: $possible_names is an ref to an array of form element names.  As an example:
 7438: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7439: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7440: 
 7441: =cut
 7442: 
 7443: sub get_unprocessed_cgi {
 7444:   my ($query,$possible_names)= @_;
 7445:   # $Apache::lonxml::debug=1;
 7446:   foreach my $pair (split(/&/,$query)) {
 7447:     my ($name, $value) = split(/=/,$pair);
 7448:     $name = &unescape($name);
 7449:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7450:       $value =~ tr/+/ /;
 7451:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7452:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7453:     }
 7454:   }
 7455: }
 7456: 
 7457: =pod
 7458: 
 7459: =item * &cacheheader() 
 7460: 
 7461: returns cache-controlling header code
 7462: 
 7463: =cut
 7464: 
 7465: sub cacheheader {
 7466:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7467:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7468:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7469:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7470:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7471:     return $output;
 7472: }
 7473: 
 7474: =pod
 7475: 
 7476: =item * &no_cache($r) 
 7477: 
 7478: specifies header code to not have cache
 7479: 
 7480: =cut
 7481: 
 7482: sub no_cache {
 7483:     my ($r) = @_;
 7484:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7485: 	$env{'request.method'} ne 'GET') { return ''; }
 7486:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7487:     $r->no_cache(1);
 7488:     $r->header_out("Expires" => $date);
 7489:     $r->header_out("Pragma" => "no-cache");
 7490: }
 7491: 
 7492: sub content_type {
 7493:     my ($r,$type,$charset) = @_;
 7494:     if ($r) {
 7495: 	#  Note that printout.pl calls this with undef for $r.
 7496: 	&no_cache($r);
 7497:     }
 7498:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7499:     unless ($charset) {
 7500: 	$charset=&Apache::lonlocal::current_encoding;
 7501:     }
 7502:     if ($charset) { $type.='; charset='.$charset; }
 7503:     if ($r) {
 7504: 	$r->content_type($type);
 7505:     } else {
 7506: 	print("Content-type: $type\n\n");
 7507:     }
 7508: }
 7509: 
 7510: =pod
 7511: 
 7512: =item * &add_to_env($name,$value) 
 7513: 
 7514: adds $name to the %env hash with value
 7515: $value, if $name already exists, the entry is converted to an array
 7516: reference and $value is added to the array.
 7517: 
 7518: =cut
 7519: 
 7520: sub add_to_env {
 7521:   my ($name,$value)=@_;
 7522:   if (defined($env{$name})) {
 7523:     if (ref($env{$name})) {
 7524:       #already have multiple values
 7525:       push(@{ $env{$name} },$value);
 7526:     } else {
 7527:       #first time seeing multiple values, convert hash entry to an arrayref
 7528:       my $first=$env{$name};
 7529:       undef($env{$name});
 7530:       push(@{ $env{$name} },$first,$value);
 7531:     }
 7532:   } else {
 7533:     $env{$name}=$value;
 7534:   }
 7535: }
 7536: 
 7537: =pod
 7538: 
 7539: =item * &get_env_multiple($name) 
 7540: 
 7541: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7542: values may be defined and end up as an array ref.
 7543: 
 7544: returns an array of values
 7545: 
 7546: =cut
 7547: 
 7548: sub get_env_multiple {
 7549:     my ($name) = @_;
 7550:     my @values;
 7551:     if (defined($env{$name})) {
 7552:         # exists is it an array
 7553:         if (ref($env{$name})) {
 7554:             @values=@{ $env{$name} };
 7555:         } else {
 7556:             $values[0]=$env{$name};
 7557:         }
 7558:     }
 7559:     return(@values);
 7560: }
 7561: 
 7562: sub ask_for_embedded_content {
 7563:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7564:     my $upload_output = '
 7565:    <form name="upload_embedded" action="'.$actionurl.'"
 7566:                   method="post" enctype="multipart/form-data">';
 7567:     $upload_output .= $state;
 7568:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7569: 
 7570:     my $num = 0;
 7571:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7572:         $upload_output .= &start_data_table_row().
 7573:             '<td>'.$embed_file.'</td><td>';
 7574:         if ($args->{'ignore_remote_references'}
 7575:             && $embed_file =~ m{^\w+://}) {
 7576:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7577:         } elsif ($args->{'error_on_invalid_names'}
 7578:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7579: 
 7580:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7581: 
 7582:         } else {
 7583:             $upload_output .='
 7584:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7585:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7586:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7587:             $upload_output .=
 7588:                 "\n\t\t".
 7589:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7590:                 $attrib.'" />';
 7591:             if (exists($$codebase{$embed_file})) {
 7592:                 $upload_output .=
 7593:                     "\n\t\t".
 7594:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7595:                     &escape($$codebase{$embed_file}).'" />';
 7596:             }
 7597:         }
 7598:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7599:         $num++;
 7600:     }
 7601:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7602:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7603:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7604:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7605:    </form>';
 7606:     return $upload_output;
 7607: }
 7608: 
 7609: sub upload_embedded {
 7610:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7611:         $current_disk_usage) = @_;
 7612:     my $output;
 7613:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7614:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7615:         my $orig_uploaded_filename =
 7616:             $env{'form.embedded_item_'.$i.'.filename'};
 7617: 
 7618:         $env{'form.embedded_orig_'.$i} =
 7619:             &unescape($env{'form.embedded_orig_'.$i});
 7620:         my ($path,$fname) =
 7621:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7622:         # no path, whole string is fname
 7623:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7624: 
 7625:         $path = $env{'form.currentpath'}.$path;
 7626:         $fname = &Apache::lonnet::clean_filename($fname);
 7627:         # See if there is anything left
 7628:         next if ($fname eq '');
 7629: 
 7630:         # Check if file already exists as a file or directory.
 7631:         my ($state,$msg);
 7632:         if ($context eq 'portfolio') {
 7633:             my $port_path = $dirpath;
 7634:             if ($group ne '') {
 7635:                 $port_path = "groups/$group/$port_path";
 7636:             }
 7637:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7638:                                               $dir_root,$port_path,$disk_quota,
 7639:                                               $current_disk_usage,$uname,$udom);
 7640:             if ($state eq 'will_exceed_quota'
 7641:                 || $state eq 'file_locked'
 7642:                 || $state eq 'file_exists' ) {
 7643:                 $output .= $msg;
 7644:                 next;
 7645:             }
 7646:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7647:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7648:             if ($state eq 'exists') {
 7649:                 $output .= $msg;
 7650:                 next;
 7651:             }
 7652:         }
 7653:         # Check if extension is valid
 7654:         if (($fname =~ /\.(\w+)$/) &&
 7655:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7656:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7657:             next;
 7658:         } elsif (($fname =~ /\.(\w+)$/) &&
 7659:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7660:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7661:             next;
 7662:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7663:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7664:             next;
 7665:         }
 7666: 
 7667:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7668:         if ($context eq 'portfolio') {
 7669:             my $result=
 7670:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7671:                                                 $dirpath.$path);
 7672:             if ($result !~ m|^/uploaded/|) {
 7673:                 $output .= '<span class="LC_error">'
 7674:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7675:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7676:                       .'</span><br />';
 7677:                 next;
 7678:             } else {
 7679:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7680:                            $path.$fname.'</span>').'</p>';     
 7681:             }
 7682:         } else {
 7683: # Save the file
 7684:             my $target = $env{'form.embedded_item_'.$i};
 7685:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7686:             my $dest = $fullpath.$fname;
 7687:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7688:             my @parts=split(/\//,$fullpath);
 7689:             my $count;
 7690:             my $filepath = $dir_root;
 7691:             for ($count=4;$count<=$#parts;$count++) {
 7692:                 $filepath .= "/$parts[$count]";
 7693:                 if ((-e $filepath)!=1) {
 7694:                     mkdir($filepath,0770);
 7695:                 }
 7696:             }
 7697:             my $fh;
 7698:             if (!open($fh,'>'.$dest)) {
 7699:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7700:                 $output .= '<span class="LC_error">'.
 7701:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7702:                            '</span><br />';
 7703:             } else {
 7704:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7705:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7706:                     $output .= '<span class="LC_error">'.
 7707:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7708:                               '</span><br />';
 7709:                 } else {
 7710:                     if ($context eq 'testbank') {
 7711:                         $output .= &mt('Embedded file uploaded successfully:').
 7712:                                    '&nbsp;<a href="'.$url.'">'.
 7713:                                    $orig_uploaded_filename.'</a><br />';
 7714:                     } else {
 7715:                         $output .= '<font size="+2">'.
 7716:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7717:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7718:                     }
 7719:                 }
 7720:                 close($fh);
 7721:             }
 7722:         }
 7723:     }
 7724:     return $output;
 7725: }
 7726: 
 7727: sub check_for_existing {
 7728:     my ($path,$fname,$element) = @_;
 7729:     my ($state,$msg);
 7730:     if (-d $path.'/'.$fname) {
 7731:         $state = 'exists';
 7732:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7733:     } elsif (-e $path.'/'.$fname) {
 7734:         $state = 'exists';
 7735:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7736:     }
 7737:     if ($state eq 'exists') {
 7738:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7739:     }
 7740:     return ($state,$msg);
 7741: }
 7742: 
 7743: sub check_for_upload {
 7744:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7745:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7746:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7747:     my $getpropath = 1;
 7748:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7749:                                             $getpropath);
 7750:     my $found_file = 0;
 7751:     my $locked_file = 0;
 7752:     foreach my $line (@dir_list) {
 7753:         my ($file_name)=split(/\&/,$line,2);
 7754:         if ($file_name eq $fname){
 7755:             $file_name = $path.$file_name;
 7756:             if ($group ne '') {
 7757:                 $file_name = $group.$file_name;
 7758:             }
 7759:             $found_file = 1;
 7760:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7761:                 $locked_file = 1;
 7762:             }
 7763:         }
 7764:     }
 7765:     if (($current_disk_usage + $filesize) > $disk_quota){
 7766:         my $msg = '<span class="LC_error">'.
 7767:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7768:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7769:         return ('will_exceed_quota',$msg);
 7770:     } elsif ($found_file) {
 7771:         if ($locked_file) {
 7772:             my $msg = '<span class="LC_error">';
 7773:             $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>');
 7774:             $msg .= '</span><br />';
 7775:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7776:             return ('file_locked',$msg);
 7777:         } else {
 7778:             my $msg = '<span class="LC_error">';
 7779:             $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'});
 7780:             $msg .= '</span>';
 7781:             $msg .= '<br />';
 7782:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7783:             return ('file_exists',$msg);
 7784:         }
 7785:     }
 7786: }
 7787: 
 7788: 
 7789: =pod
 7790: 
 7791: =back
 7792: 
 7793: =head1 CSV Upload/Handling functions
 7794: 
 7795: =over 4
 7796: 
 7797: =item * &upfile_store($r)
 7798: 
 7799: Store uploaded file, $r should be the HTTP Request object,
 7800: needs $env{'form.upfile'}
 7801: returns $datatoken to be put into hidden field
 7802: 
 7803: =cut
 7804: 
 7805: sub upfile_store {
 7806:     my $r=shift;
 7807:     $env{'form.upfile'}=~s/\r/\n/gs;
 7808:     $env{'form.upfile'}=~s/\f/\n/gs;
 7809:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7810:     $env{'form.upfile'}=~s/\n+$//gs;
 7811: 
 7812:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7813: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7814:     {
 7815:         my $datafile = $r->dir_config('lonDaemons').
 7816:                            '/tmp/'.$datatoken.'.tmp';
 7817:         if ( open(my $fh,">$datafile") ) {
 7818:             print $fh $env{'form.upfile'};
 7819:             close($fh);
 7820:         }
 7821:     }
 7822:     return $datatoken;
 7823: }
 7824: 
 7825: =pod
 7826: 
 7827: =item * &load_tmp_file($r)
 7828: 
 7829: Load uploaded file from tmp, $r should be the HTTP Request object,
 7830: needs $env{'form.datatoken'},
 7831: sets $env{'form.upfile'} to the contents of the file
 7832: 
 7833: =cut
 7834: 
 7835: sub load_tmp_file {
 7836:     my $r=shift;
 7837:     my @studentdata=();
 7838:     {
 7839:         my $studentfile = $r->dir_config('lonDaemons').
 7840:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7841:         if ( open(my $fh,"<$studentfile") ) {
 7842:             @studentdata=<$fh>;
 7843:             close($fh);
 7844:         }
 7845:     }
 7846:     $env{'form.upfile'}=join('',@studentdata);
 7847: }
 7848: 
 7849: =pod
 7850: 
 7851: =item * &upfile_record_sep()
 7852: 
 7853: Separate uploaded file into records
 7854: returns array of records,
 7855: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7856: 
 7857: =cut
 7858: 
 7859: sub upfile_record_sep {
 7860:     if ($env{'form.upfiletype'} eq 'xml') {
 7861:     } else {
 7862: 	my @records;
 7863: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7864: 	    if ($line=~/^\s*$/) { next; }
 7865: 	    push(@records,$line);
 7866: 	}
 7867: 	return @records;
 7868:     }
 7869: }
 7870: 
 7871: =pod
 7872: 
 7873: =item * &record_sep($record)
 7874: 
 7875: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7876: 
 7877: =cut
 7878: 
 7879: sub takeleft {
 7880:     my $index=shift;
 7881:     return substr('0000'.$index,-4,4);
 7882: }
 7883: 
 7884: sub record_sep {
 7885:     my $record=shift;
 7886:     my %components=();
 7887:     if ($env{'form.upfiletype'} eq 'xml') {
 7888:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7889:         my $i=0;
 7890:         foreach my $field (split(/\s+/,$record)) {
 7891:             $field=~s/^(\"|\')//;
 7892:             $field=~s/(\"|\')$//;
 7893:             $components{&takeleft($i)}=$field;
 7894:             $i++;
 7895:         }
 7896:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7897:         my $i=0;
 7898:         foreach my $field (split(/\t/,$record)) {
 7899:             $field=~s/^(\"|\')//;
 7900:             $field=~s/(\"|\')$//;
 7901:             $components{&takeleft($i)}=$field;
 7902:             $i++;
 7903:         }
 7904:     } else {
 7905:         my $separator=',';
 7906:         if ($env{'form.upfiletype'} eq 'semisv') {
 7907:             $separator=';';
 7908:         }
 7909:         my $i=0;
 7910: # the character we are looking for to indicate the end of a quote or a record 
 7911:         my $looking_for=$separator;
 7912: # do not add the characters to the fields
 7913:         my $ignore=0;
 7914: # we just encountered a separator (or the beginning of the record)
 7915:         my $just_found_separator=1;
 7916: # store the field we are working on here
 7917:         my $field='';
 7918: # work our way through all characters in record
 7919:         foreach my $character ($record=~/(.)/g) {
 7920:             if ($character eq $looking_for) {
 7921:                if ($character ne $separator) {
 7922: # Found the end of a quote, again looking for separator
 7923:                   $looking_for=$separator;
 7924:                   $ignore=1;
 7925:                } else {
 7926: # Found a separator, store away what we got
 7927:                   $components{&takeleft($i)}=$field;
 7928: 	          $i++;
 7929:                   $just_found_separator=1;
 7930:                   $ignore=0;
 7931:                   $field='';
 7932:                }
 7933:                next;
 7934:             }
 7935: # single or double quotation marks after a separator indicate beginning of a quote
 7936: # we are now looking for the end of the quote and need to ignore separators
 7937:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7938:                $looking_for=$character;
 7939:                next;
 7940:             }
 7941: # ignore would be true after we reached the end of a quote
 7942:             if ($ignore) { next; }
 7943:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7944:             $field.=$character;
 7945:             $just_found_separator=0; 
 7946:         }
 7947: # catch the very last entry, since we never encountered the separator
 7948:         $components{&takeleft($i)}=$field;
 7949:     }
 7950:     return %components;
 7951: }
 7952: 
 7953: ######################################################
 7954: ######################################################
 7955: 
 7956: =pod
 7957: 
 7958: =item * &upfile_select_html()
 7959: 
 7960: Return HTML code to select a file from the users machine and specify 
 7961: the file type.
 7962: 
 7963: =cut
 7964: 
 7965: ######################################################
 7966: ######################################################
 7967: sub upfile_select_html {
 7968:     my %Types = (
 7969:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7970:                  semisv => &mt('Semicolon separated values'),
 7971:                  space => &mt('Space separated'),
 7972:                  tab   => &mt('Tabulator separated'),
 7973: #                 xml   => &mt('HTML/XML'),
 7974:                  );
 7975:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7976:         '<br />'.&mt('Type').': <select name="upfiletype">';
 7977:     foreach my $type (sort(keys(%Types))) {
 7978:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7979:     }
 7980:     $Str .= "</select>\n";
 7981:     return $Str;
 7982: }
 7983: 
 7984: sub get_samples {
 7985:     my ($records,$toget) = @_;
 7986:     my @samples=({});
 7987:     my $got=0;
 7988:     foreach my $rec (@$records) {
 7989: 	my %temp = &record_sep($rec);
 7990: 	if (! grep(/\S/, values(%temp))) { next; }
 7991: 	if (%temp) {
 7992: 	    $samples[$got]=\%temp;
 7993: 	    $got++;
 7994: 	    if ($got == $toget) { last; }
 7995: 	}
 7996:     }
 7997:     return \@samples;
 7998: }
 7999: 
 8000: ######################################################
 8001: ######################################################
 8002: 
 8003: =pod
 8004: 
 8005: =item * &csv_print_samples($r,$records)
 8006: 
 8007: Prints a table of sample values from each column uploaded $r is an
 8008: Apache Request ref, $records is an arrayref from
 8009: &Apache::loncommon::upfile_record_sep
 8010: 
 8011: =cut
 8012: 
 8013: ######################################################
 8014: ######################################################
 8015: sub csv_print_samples {
 8016:     my ($r,$records) = @_;
 8017:     my $samples = &get_samples($records,5);
 8018: 
 8019:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 8020:               &start_data_table_header_row());
 8021:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 8022:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
 8023:     }
 8024:     $r->print(&end_data_table_header_row());
 8025:     foreach my $hash (@$samples) {
 8026: 	$r->print(&start_data_table_row());
 8027: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8028: 	    $r->print('<td>');
 8029: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 8030: 	    $r->print('</td>');
 8031: 	}
 8032: 	$r->print(&end_data_table_row());
 8033:     }
 8034:     $r->print(&end_data_table().'<br />'."\n");
 8035: }
 8036: 
 8037: ######################################################
 8038: ######################################################
 8039: 
 8040: =pod
 8041: 
 8042: =item * &csv_print_select_table($r,$records,$d)
 8043: 
 8044: Prints a table to create associations between values and table columns.
 8045: 
 8046: $r is an Apache Request ref,
 8047: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8048: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 8049: 
 8050: =cut
 8051: 
 8052: ######################################################
 8053: ######################################################
 8054: sub csv_print_select_table {
 8055:     my ($r,$records,$d) = @_;
 8056:     my $i=0;
 8057:     my $samples = &get_samples($records,1);
 8058:     $r->print(&mt('Associate columns with student attributes.')."\n".
 8059: 	      &start_data_table().&start_data_table_header_row().
 8060:               '<th>'.&mt('Attribute').'</th>'.
 8061:               '<th>'.&mt('Column').'</th>'.
 8062:               &end_data_table_header_row()."\n");
 8063:     foreach my $array_ref (@$d) {
 8064: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 8065: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 8066: 
 8067: 	$r->print('<td><select name"f'.$i.'"'.
 8068: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8069: 	$r->print('<option value="none"></option>');
 8070: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 8071: 	    $r->print('<option value="'.$sample.'"'.
 8072:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 8073:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 8074: 	}
 8075: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 8076: 	$i++;
 8077:     }
 8078:     $r->print(&end_data_table());
 8079:     $i--;
 8080:     return $i;
 8081: }
 8082: 
 8083: ######################################################
 8084: ######################################################
 8085: 
 8086: =pod
 8087: 
 8088: =item * &csv_samples_select_table($r,$records,$d)
 8089: 
 8090: Prints a table of sample values from the upload and can make associate samples to internal names.
 8091: 
 8092: $r is an Apache Request ref,
 8093: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8094: $d is an array of 2 element arrays (internal name, displayed name)
 8095: 
 8096: =cut
 8097: 
 8098: ######################################################
 8099: ######################################################
 8100: sub csv_samples_select_table {
 8101:     my ($r,$records,$d) = @_;
 8102:     my $i=0;
 8103:     #
 8104:     my $max_samples = 5;
 8105:     my $samples = &get_samples($records,$max_samples);
 8106:     $r->print(&start_data_table().
 8107:               &start_data_table_header_row().'<th>'.
 8108:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8109:               &end_data_table_header_row());
 8110: 
 8111:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8112: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8113: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8114: 	foreach my $option (@$d) {
 8115: 	    my ($value,$display,$defaultcol)=@{ $option };
 8116: 	    $r->print('<option value="'.$value.'"'.
 8117:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8118:                       $display.'</option>');
 8119: 	}
 8120: 	$r->print('</select></td><td>');
 8121: 	foreach my $line (0..($max_samples-1)) {
 8122: 	    if (defined($samples->[$line]{$key})) { 
 8123: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8124: 	    }
 8125: 	}
 8126: 	$r->print('</td>'.&end_data_table_row());
 8127: 	$i++;
 8128:     }
 8129:     $r->print(&end_data_table());
 8130:     $i--;
 8131:     return($i);
 8132: }
 8133: 
 8134: ######################################################
 8135: ######################################################
 8136: 
 8137: =pod
 8138: 
 8139: =item * &clean_excel_name($name)
 8140: 
 8141: Returns a replacement for $name which does not contain any illegal characters.
 8142: 
 8143: =cut
 8144: 
 8145: ######################################################
 8146: ######################################################
 8147: sub clean_excel_name {
 8148:     my ($name) = @_;
 8149:     $name =~ s/[:\*\?\/\\]//g;
 8150:     if (length($name) > 31) {
 8151:         $name = substr($name,0,31);
 8152:     }
 8153:     return $name;
 8154: }
 8155: 
 8156: =pod
 8157: 
 8158: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8159: 
 8160: Returns either 1 or undef
 8161: 
 8162: 1 if the part is to be hidden, undef if it is to be shown
 8163: 
 8164: Arguments are:
 8165: 
 8166: $id the id of the part to be checked
 8167: $symb, optional the symb of the resource to check
 8168: $udom, optional the domain of the user to check for
 8169: $uname, optional the username of the user to check for
 8170: 
 8171: =cut
 8172: 
 8173: sub check_if_partid_hidden {
 8174:     my ($id,$symb,$udom,$uname) = @_;
 8175:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8176: 					 $symb,$udom,$uname);
 8177:     my $truth=1;
 8178:     #if the string starts with !, then the list is the list to show not hide
 8179:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8180:     my @hiddenlist=split(/,/,$hiddenparts);
 8181:     foreach my $checkid (@hiddenlist) {
 8182: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8183:     }
 8184:     return !$truth;
 8185: }
 8186: 
 8187: 
 8188: ############################################################
 8189: ############################################################
 8190: 
 8191: =pod
 8192: 
 8193: =back 
 8194: 
 8195: =head1 cgi-bin script and graphing routines
 8196: 
 8197: =over 4
 8198: 
 8199: =item * &get_cgi_id()
 8200: 
 8201: Inputs: none
 8202: 
 8203: Returns an id which can be used to pass environment variables
 8204: to various cgi-bin scripts.  These environment variables will
 8205: be removed from the users environment after a given time by
 8206: the routine &Apache::lonnet::transfer_profile_to_env.
 8207: 
 8208: =cut
 8209: 
 8210: ############################################################
 8211: ############################################################
 8212: my $uniq=0;
 8213: sub get_cgi_id {
 8214:     $uniq=($uniq+1)%100000;
 8215:     return (time.'_'.$$.'_'.$uniq);
 8216: }
 8217: 
 8218: ############################################################
 8219: ############################################################
 8220: 
 8221: =pod
 8222: 
 8223: =item * &DrawBarGraph()
 8224: 
 8225: Facilitates the plotting of data in a (stacked) bar graph.
 8226: Puts plot definition data into the users environment in order for 
 8227: graph.png to plot it.  Returns an <img> tag for the plot.
 8228: The bars on the plot are labeled '1','2',...,'n'.
 8229: 
 8230: Inputs:
 8231: 
 8232: =over 4
 8233: 
 8234: =item $Title: string, the title of the plot
 8235: 
 8236: =item $xlabel: string, text describing the X-axis of the plot
 8237: 
 8238: =item $ylabel: string, text describing the Y-axis of the plot
 8239: 
 8240: =item $Max: scalar, the maximum Y value to use in the plot
 8241: If $Max is < any data point, the graph will not be rendered.
 8242: 
 8243: =item $colors: array ref holding the colors to be used for the data sets when
 8244: they are plotted.  If undefined, default values will be used.
 8245: 
 8246: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8247: 
 8248: =item @Values: An array of array references.  Each array reference holds data
 8249: to be plotted in a stacked bar chart.
 8250: 
 8251: =item If the final element of @Values is a hash reference the key/value
 8252: pairs will be added to the graph definition.
 8253: 
 8254: =back
 8255: 
 8256: Returns:
 8257: 
 8258: An <img> tag which references graph.png and the appropriate identifying
 8259: information for the plot.
 8260: 
 8261: =cut
 8262: 
 8263: ############################################################
 8264: ############################################################
 8265: sub DrawBarGraph {
 8266:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8267:     #
 8268:     if (! defined($colors)) {
 8269:         $colors = ['#33ff00', 
 8270:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8271:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8272:                   ]; 
 8273:     }
 8274:     my $extra_settings = {};
 8275:     if (ref($Values[-1]) eq 'HASH') {
 8276:         $extra_settings = pop(@Values);
 8277:     }
 8278:     #
 8279:     my $identifier = &get_cgi_id();
 8280:     my $id = 'cgi.'.$identifier;        
 8281:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8282:         return '';
 8283:     }
 8284:     #
 8285:     my @Labels;
 8286:     if (defined($labels)) {
 8287:         @Labels = @$labels;
 8288:     } else {
 8289:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8290:             push (@Labels,$i+1);
 8291:         }
 8292:     }
 8293:     #
 8294:     my $NumBars = scalar(@{$Values[0]});
 8295:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8296:     my %ValuesHash;
 8297:     my $NumSets=1;
 8298:     foreach my $array (@Values) {
 8299:         next if (! ref($array));
 8300:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8301:             join(',',@$array);
 8302:     }
 8303:     #
 8304:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8305:     if ($NumBars < 3) {
 8306:         $width = 120+$NumBars*32;
 8307:         $xskip = 1;
 8308:         $bar_width = 30;
 8309:     } elsif ($NumBars < 5) {
 8310:         $width = 120+$NumBars*20;
 8311:         $xskip = 1;
 8312:         $bar_width = 20;
 8313:     } elsif ($NumBars < 10) {
 8314:         $width = 120+$NumBars*15;
 8315:         $xskip = 1;
 8316:         $bar_width = 15;
 8317:     } elsif ($NumBars <= 25) {
 8318:         $width = 120+$NumBars*11;
 8319:         $xskip = 5;
 8320:         $bar_width = 8;
 8321:     } elsif ($NumBars <= 50) {
 8322:         $width = 120+$NumBars*8;
 8323:         $xskip = 5;
 8324:         $bar_width = 4;
 8325:     } else {
 8326:         $width = 120+$NumBars*8;
 8327:         $xskip = 5;
 8328:         $bar_width = 4;
 8329:     }
 8330:     #
 8331:     $Max = 1 if ($Max < 1);
 8332:     if ( int($Max) < $Max ) {
 8333:         $Max++;
 8334:         $Max = int($Max);
 8335:     }
 8336:     $Title  = '' if (! defined($Title));
 8337:     $xlabel = '' if (! defined($xlabel));
 8338:     $ylabel = '' if (! defined($ylabel));
 8339:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8340:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8341:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8342:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8343:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8344:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8345:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8346:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8347:     $ValuesHash{$id.'.height'}   = $height;
 8348:     $ValuesHash{$id.'.width'}    = $width;
 8349:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8350:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8351:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8352:     #
 8353:     # Deal with other parameters
 8354:     while (my ($key,$value) = each(%$extra_settings)) {
 8355:         $ValuesHash{$id.'.'.$key} = $value;
 8356:     }
 8357:     #
 8358:     &Apache::lonnet::appenv(\%ValuesHash);
 8359:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8360: }
 8361: 
 8362: ############################################################
 8363: ############################################################
 8364: 
 8365: =pod
 8366: 
 8367: =item * &DrawXYGraph()
 8368: 
 8369: Facilitates the plotting of data in an XY graph.
 8370: Puts plot definition data into the users environment in order for 
 8371: graph.png to plot it.  Returns an <img> tag for the plot.
 8372: 
 8373: Inputs:
 8374: 
 8375: =over 4
 8376: 
 8377: =item $Title: string, the title of the plot
 8378: 
 8379: =item $xlabel: string, text describing the X-axis of the plot
 8380: 
 8381: =item $ylabel: string, text describing the Y-axis of the plot
 8382: 
 8383: =item $Max: scalar, the maximum Y value to use in the plot
 8384: If $Max is < any data point, the graph will not be rendered.
 8385: 
 8386: =item $colors: Array ref containing the hex color codes for the data to be 
 8387: plotted in.  If undefined, default values will be used.
 8388: 
 8389: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8390: 
 8391: =item $Ydata: Array ref containing Array refs.  
 8392: Each of the contained arrays will be plotted as a separate curve.
 8393: 
 8394: =item %Values: hash indicating or overriding any default values which are 
 8395: passed to graph.png.  
 8396: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8397: 
 8398: =back
 8399: 
 8400: Returns:
 8401: 
 8402: An <img> tag which references graph.png and the appropriate identifying
 8403: information for the plot.
 8404: 
 8405: =cut
 8406: 
 8407: ############################################################
 8408: ############################################################
 8409: sub DrawXYGraph {
 8410:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8411:     #
 8412:     # Create the identifier for the graph
 8413:     my $identifier = &get_cgi_id();
 8414:     my $id = 'cgi.'.$identifier;
 8415:     #
 8416:     $Title  = '' if (! defined($Title));
 8417:     $xlabel = '' if (! defined($xlabel));
 8418:     $ylabel = '' if (! defined($ylabel));
 8419:     my %ValuesHash = 
 8420:         (
 8421:          $id.'.title'  => &escape($Title),
 8422:          $id.'.xlabel' => &escape($xlabel),
 8423:          $id.'.ylabel' => &escape($ylabel),
 8424:          $id.'.y_max_value'=> $Max,
 8425:          $id.'.labels'     => join(',',@$Xlabels),
 8426:          $id.'.PlotType'   => 'XY',
 8427:          );
 8428:     #
 8429:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8430:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8431:     }
 8432:     #
 8433:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8434:         return '';
 8435:     }
 8436:     my $NumSets=1;
 8437:     foreach my $array (@{$Ydata}){
 8438:         next if (! ref($array));
 8439:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8440:     }
 8441:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8442:     #
 8443:     # Deal with other parameters
 8444:     while (my ($key,$value) = each(%Values)) {
 8445:         $ValuesHash{$id.'.'.$key} = $value;
 8446:     }
 8447:     #
 8448:     &Apache::lonnet::appenv(\%ValuesHash);
 8449:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8450: }
 8451: 
 8452: ############################################################
 8453: ############################################################
 8454: 
 8455: =pod
 8456: 
 8457: =item * &DrawXYYGraph()
 8458: 
 8459: Facilitates the plotting of data in an XY graph with two Y axes.
 8460: Puts plot definition data into the users environment in order for 
 8461: graph.png to plot it.  Returns an <img> tag for the plot.
 8462: 
 8463: Inputs:
 8464: 
 8465: =over 4
 8466: 
 8467: =item $Title: string, the title of the plot
 8468: 
 8469: =item $xlabel: string, text describing the X-axis of the plot
 8470: 
 8471: =item $ylabel: string, text describing the Y-axis of the plot
 8472: 
 8473: =item $colors: Array ref containing the hex color codes for the data to be 
 8474: plotted in.  If undefined, default values will be used.
 8475: 
 8476: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8477: 
 8478: =item $Ydata1: The first data set
 8479: 
 8480: =item $Min1: The minimum value of the left Y-axis
 8481: 
 8482: =item $Max1: The maximum value of the left Y-axis
 8483: 
 8484: =item $Ydata2: The second data set
 8485: 
 8486: =item $Min2: The minimum value of the right Y-axis
 8487: 
 8488: =item $Max2: The maximum value of the left Y-axis
 8489: 
 8490: =item %Values: hash indicating or overriding any default values which are 
 8491: passed to graph.png.  
 8492: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8493: 
 8494: =back
 8495: 
 8496: Returns:
 8497: 
 8498: An <img> tag which references graph.png and the appropriate identifying
 8499: information for the plot.
 8500: 
 8501: =cut
 8502: 
 8503: ############################################################
 8504: ############################################################
 8505: sub DrawXYYGraph {
 8506:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8507:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8508:     #
 8509:     # Create the identifier for the graph
 8510:     my $identifier = &get_cgi_id();
 8511:     my $id = 'cgi.'.$identifier;
 8512:     #
 8513:     $Title  = '' if (! defined($Title));
 8514:     $xlabel = '' if (! defined($xlabel));
 8515:     $ylabel = '' if (! defined($ylabel));
 8516:     my %ValuesHash = 
 8517:         (
 8518:          $id.'.title'  => &escape($Title),
 8519:          $id.'.xlabel' => &escape($xlabel),
 8520:          $id.'.ylabel' => &escape($ylabel),
 8521:          $id.'.labels' => join(',',@$Xlabels),
 8522:          $id.'.PlotType' => 'XY',
 8523:          $id.'.NumSets' => 2,
 8524:          $id.'.two_axes' => 1,
 8525:          $id.'.y1_max_value' => $Max1,
 8526:          $id.'.y1_min_value' => $Min1,
 8527:          $id.'.y2_max_value' => $Max2,
 8528:          $id.'.y2_min_value' => $Min2,
 8529:          );
 8530:     #
 8531:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8532:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8533:     }
 8534:     #
 8535:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8536:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8537:         return '';
 8538:     }
 8539:     my $NumSets=1;
 8540:     foreach my $array ($Ydata1,$Ydata2){
 8541:         next if (! ref($array));
 8542:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8543:     }
 8544:     #
 8545:     # Deal with other parameters
 8546:     while (my ($key,$value) = each(%Values)) {
 8547:         $ValuesHash{$id.'.'.$key} = $value;
 8548:     }
 8549:     #
 8550:     &Apache::lonnet::appenv(\%ValuesHash);
 8551:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8552: }
 8553: 
 8554: ############################################################
 8555: ############################################################
 8556: 
 8557: =pod
 8558: 
 8559: =back 
 8560: 
 8561: =head1 Statistics helper routines?  
 8562: 
 8563: Bad place for them but what the hell.
 8564: 
 8565: =over 4
 8566: 
 8567: =item * &chartlink()
 8568: 
 8569: Returns a link to the chart for a specific student.  
 8570: 
 8571: Inputs:
 8572: 
 8573: =over 4
 8574: 
 8575: =item $linktext: The text of the link
 8576: 
 8577: =item $sname: The students username
 8578: 
 8579: =item $sdomain: The students domain
 8580: 
 8581: =back
 8582: 
 8583: =back
 8584: 
 8585: =cut
 8586: 
 8587: ############################################################
 8588: ############################################################
 8589: sub chartlink {
 8590:     my ($linktext, $sname, $sdomain) = @_;
 8591:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8592:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8593:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8594:        '">'.$linktext.'</a>';
 8595: }
 8596: 
 8597: #######################################################
 8598: #######################################################
 8599: 
 8600: =pod
 8601: 
 8602: =head1 Course Environment Routines
 8603: 
 8604: =over 4
 8605: 
 8606: =item * &restore_course_settings()
 8607: 
 8608: =item * &store_course_settings()
 8609: 
 8610: Restores/Store indicated form parameters from the course environment.
 8611: Will not overwrite existing values of the form parameters.
 8612: 
 8613: Inputs: 
 8614: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8615: 
 8616: a hash ref describing the data to be stored.  For example:
 8617:    
 8618: %Save_Parameters = ('Status' => 'scalar',
 8619:     'chartoutputmode' => 'scalar',
 8620:     'chartoutputdata' => 'scalar',
 8621:     'Section' => 'array',
 8622:     'Group' => 'array',
 8623:     'StudentData' => 'array',
 8624:     'Maps' => 'array');
 8625: 
 8626: Returns: both routines return nothing
 8627: 
 8628: =back
 8629: 
 8630: =cut
 8631: 
 8632: #######################################################
 8633: #######################################################
 8634: sub store_course_settings {
 8635:     return &store_settings($env{'request.course.id'},@_);
 8636: }
 8637: 
 8638: sub store_settings {
 8639:     # save to the environment
 8640:     # appenv the same items, just to be safe
 8641:     my $udom  = $env{'user.domain'};
 8642:     my $uname = $env{'user.name'};
 8643:     my ($context,$prefix,$Settings) = @_;
 8644:     my %SaveHash;
 8645:     my %AppHash;
 8646:     while (my ($setting,$type) = each(%$Settings)) {
 8647:         my $basename = join('.','internal',$context,$prefix,$setting);
 8648:         my $envname = 'environment.'.$basename;
 8649:         if (exists($env{'form.'.$setting})) {
 8650:             # Save this value away
 8651:             if ($type eq 'scalar' &&
 8652:                 (! exists($env{$envname}) || 
 8653:                  $env{$envname} ne $env{'form.'.$setting})) {
 8654:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8655:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8656:             } elsif ($type eq 'array') {
 8657:                 my $stored_form;
 8658:                 if (ref($env{'form.'.$setting})) {
 8659:                     $stored_form = join(',',
 8660:                                         map {
 8661:                                             &escape($_);
 8662:                                         } sort(@{$env{'form.'.$setting}}));
 8663:                 } else {
 8664:                     $stored_form = 
 8665:                         &escape($env{'form.'.$setting});
 8666:                 }
 8667:                 # Determine if the array contents are the same.
 8668:                 if ($stored_form ne $env{$envname}) {
 8669:                     $SaveHash{$basename} = $stored_form;
 8670:                     $AppHash{$envname}   = $stored_form;
 8671:                 }
 8672:             }
 8673:         }
 8674:     }
 8675:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8676:                                           $udom,$uname);
 8677:     if ($put_result !~ /^(ok|delayed)/) {
 8678:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8679:                                  'got error:'.$put_result);
 8680:     }
 8681:     # Make sure these settings stick around in this session, too
 8682:     &Apache::lonnet::appenv(\%AppHash);
 8683:     return;
 8684: }
 8685: 
 8686: sub restore_course_settings {
 8687:     return &restore_settings($env{'request.course.id'},@_);
 8688: }
 8689: 
 8690: sub restore_settings {
 8691:     my ($context,$prefix,$Settings) = @_;
 8692:     while (my ($setting,$type) = each(%$Settings)) {
 8693:         next if (exists($env{'form.'.$setting}));
 8694:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8695:             '.'.$setting;
 8696:         if (exists($env{$envname})) {
 8697:             if ($type eq 'scalar') {
 8698:                 $env{'form.'.$setting} = $env{$envname};
 8699:             } elsif ($type eq 'array') {
 8700:                 $env{'form.'.$setting} = [ 
 8701:                                            map { 
 8702:                                                &unescape($_); 
 8703:                                            } split(',',$env{$envname})
 8704:                                            ];
 8705:             }
 8706:         }
 8707:     }
 8708: }
 8709: 
 8710: #######################################################
 8711: #######################################################
 8712: 
 8713: =pod
 8714: 
 8715: =head1 Domain E-mail Routines  
 8716: 
 8717: =over 4
 8718: 
 8719: =item * &build_recipient_list()
 8720: 
 8721: Build recipient lists for five types of e-mail:
 8722: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8723: (d) Help requests, (e) Course requests needing approval,  generated by
 8724: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
 8725: loncoursequeueadmin.pm respectively.
 8726: 
 8727: Inputs:
 8728: defmail (scalar - email address of default recipient), 
 8729: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8730: defdom (domain for which to retrieve configuration settings),
 8731: origmail (scalar - email address of recipient from loncapa.conf, 
 8732: i.e., predates configuration by DC via domainprefs.pm 
 8733: 
 8734: Returns: comma separated list of addresses to which to send e-mail.
 8735: 
 8736: =back
 8737: 
 8738: =cut
 8739: 
 8740: ############################################################
 8741: ############################################################
 8742: sub build_recipient_list {
 8743:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8744:     my @recipients;
 8745:     my $otheremails;
 8746:     my %domconfig =
 8747:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8748:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8749:         if (exists($domconfig{'contacts'}{$mailing})) {
 8750:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8751:                 my @contacts = ('adminemail','supportemail');
 8752:                 foreach my $item (@contacts) {
 8753:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8754:                         my $addr = $domconfig{'contacts'}{$item};
 8755:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8756:                             push(@recipients,$addr);
 8757:                         }
 8758:                     }
 8759:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8760:                 }
 8761:             }
 8762:         } elsif ($origmail ne '') {
 8763:             push(@recipients,$origmail);
 8764:         }
 8765:     } elsif ($origmail ne '') {
 8766:         push(@recipients,$origmail);
 8767:     }
 8768:     if (defined($defmail)) {
 8769:         if ($defmail ne '') {
 8770:             push(@recipients,$defmail);
 8771:         }
 8772:     }
 8773:     if ($otheremails) {
 8774:         my @others;
 8775:         if ($otheremails =~ /,/) {
 8776:             @others = split(/,/,$otheremails);
 8777:         } else {
 8778:             push(@others,$otheremails);
 8779:         }
 8780:         foreach my $addr (@others) {
 8781:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8782:                 push(@recipients,$addr);
 8783:             }
 8784:         }
 8785:     }
 8786:     my $recipientlist = join(',',@recipients); 
 8787:     return $recipientlist;
 8788: }
 8789: 
 8790: ############################################################
 8791: ############################################################
 8792: 
 8793: =pod
 8794: 
 8795: =head1 Course Catalog Routines
 8796: 
 8797: =over 4
 8798: 
 8799: =item * &gather_categories()
 8800: 
 8801: Converts category definitions - keys of categories hash stored in  
 8802: coursecategories in configuration.db on the primary library server in a 
 8803: domain - to an array.  Also generates javascript and idx hash used to 
 8804: generate Domain Coordinator interface for editing Course Categories.
 8805: 
 8806: Inputs:
 8807: 
 8808: categories (reference to hash of category definitions).
 8809: 
 8810: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8811:       categories and subcategories).
 8812: 
 8813: idx (reference to hash of counters used in Domain Coordinator interface for 
 8814:       editing Course Categories).
 8815: 
 8816: jsarray (reference to array of categories used to create Javascript arrays for
 8817:          Domain Coordinator interface for editing Course Categories).
 8818: 
 8819: Returns: nothing
 8820: 
 8821: Side effects: populates cats, idx and jsarray. 
 8822: 
 8823: =cut
 8824: 
 8825: sub gather_categories {
 8826:     my ($categories,$cats,$idx,$jsarray) = @_;
 8827:     my %counters;
 8828:     my $num = 0;
 8829:     foreach my $item (keys(%{$categories})) {
 8830:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8831:         if ($container eq '' && $depth == 0) {
 8832:             $cats->[$depth][$categories->{$item}] = $cat;
 8833:         } else {
 8834:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8835:         }
 8836:         my ($escitem,$tail) = split(/:/,$item,2);
 8837:         if ($counters{$tail} eq '') {
 8838:             $counters{$tail} = $num;
 8839:             $num ++;
 8840:         }
 8841:         if (ref($idx) eq 'HASH') {
 8842:             $idx->{$item} = $counters{$tail};
 8843:         }
 8844:         if (ref($jsarray) eq 'ARRAY') {
 8845:             push(@{$jsarray->[$counters{$tail}]},$item);
 8846:         }
 8847:     }
 8848:     return;
 8849: }
 8850: 
 8851: =pod
 8852: 
 8853: =item * &extract_categories()
 8854: 
 8855: Used to generate breadcrumb trails for course categories.
 8856: 
 8857: Inputs:
 8858: 
 8859: categories (reference to hash of category definitions).
 8860: 
 8861: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8862:       categories and subcategories).
 8863: 
 8864: trails (reference to array of breacrumb trails for each category).
 8865: 
 8866: allitems (reference to hash - key is category key 
 8867:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8868: 
 8869: idx (reference to hash of counters used in Domain Coordinator interface for
 8870:       editing Course Categories).
 8871: 
 8872: jsarray (reference to array of categories used to create Javascript arrays for
 8873:          Domain Coordinator interface for editing Course Categories).
 8874: 
 8875: subcats (reference to hash of arrays containing all subcategories within each 
 8876:          category, -recursive)
 8877: 
 8878: Returns: nothing
 8879: 
 8880: Side effects: populates trails and allitems hash references.
 8881: 
 8882: =cut
 8883: 
 8884: sub extract_categories {
 8885:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8886:     if (ref($categories) eq 'HASH') {
 8887:         &gather_categories($categories,$cats,$idx,$jsarray);
 8888:         if (ref($cats->[0]) eq 'ARRAY') {
 8889:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8890:                 my $name = $cats->[0][$i];
 8891:                 my $item = &escape($name).'::0';
 8892:                 my $trailstr;
 8893:                 if ($name eq 'instcode') {
 8894:                     $trailstr = &mt('Official courses (with institutional codes)');
 8895:                 } else {
 8896:                     $trailstr = $name;
 8897:                 }
 8898:                 if ($allitems->{$item} eq '') {
 8899:                     push(@{$trails},$trailstr);
 8900:                     $allitems->{$item} = scalar(@{$trails})-1;
 8901:                 }
 8902:                 my @parents = ($name);
 8903:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8904:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8905:                         my $category = $cats->[1]{$name}[$j];
 8906:                         if (ref($subcats) eq 'HASH') {
 8907:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8908:                         }
 8909:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8910:                     }
 8911:                 } else {
 8912:                     if (ref($subcats) eq 'HASH') {
 8913:                         $subcats->{$item} = [];
 8914:                     }
 8915:                 }
 8916:             }
 8917:         }
 8918:     }
 8919:     return;
 8920: }
 8921: 
 8922: =pod
 8923: 
 8924: =item *&recurse_categories()
 8925: 
 8926: Recursively used to generate breadcrumb trails for course categories.
 8927: 
 8928: Inputs:
 8929: 
 8930: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8931:       categories and subcategories).
 8932: 
 8933: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8934: 
 8935: category (current course category, for which breadcrumb trail is being generated).
 8936: 
 8937: trails (reference to array of breadcrumb trails for each category).
 8938: 
 8939: allitems (reference to hash - key is category key
 8940:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8941: 
 8942: parents (array containing containers directories for current category, 
 8943:          back to top level). 
 8944: 
 8945: Returns: nothing
 8946: 
 8947: Side effects: populates trails and allitems hash references
 8948: 
 8949: =cut
 8950: 
 8951: sub recurse_categories {
 8952:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8953:     my $shallower = $depth - 1;
 8954:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8955:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8956:             my $name = $cats->[$depth]{$category}[$k];
 8957:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8958:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8959:             if ($allitems->{$item} eq '') {
 8960:                 push(@{$trails},$trailstr);
 8961:                 $allitems->{$item} = scalar(@{$trails})-1;
 8962:             }
 8963:             my $deeper = $depth+1;
 8964:             push(@{$parents},$category);
 8965:             if (ref($subcats) eq 'HASH') {
 8966:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8967:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8968:                     my $higher;
 8969:                     if ($j > 0) {
 8970:                         $higher = &escape($parents->[$j]).':'.
 8971:                                   &escape($parents->[$j-1]).':'.$j;
 8972:                     } else {
 8973:                         $higher = &escape($parents->[$j]).'::'.$j;
 8974:                     }
 8975:                     push(@{$subcats->{$higher}},$subcat);
 8976:                 }
 8977:             }
 8978:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8979:                                 $subcats);
 8980:             pop(@{$parents});
 8981:         }
 8982:     } else {
 8983:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8984:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8985:         if ($allitems->{$item} eq '') {
 8986:             push(@{$trails},$trailstr);
 8987:             $allitems->{$item} = scalar(@{$trails})-1;
 8988:         }
 8989:     }
 8990:     return;
 8991: }
 8992: 
 8993: =pod
 8994: 
 8995: =item *&assign_categories_table()
 8996: 
 8997: Create a datatable for display of hierarchical categories in a domain,
 8998: with checkboxes to allow a course to be categorized. 
 8999: 
 9000: Inputs:
 9001: 
 9002: cathash - reference to hash of categories defined for the domain (from
 9003:           configuration.db)
 9004: 
 9005: currcat - scalar with an & separated list of categories assigned to a course. 
 9006: 
 9007: Returns: $output (markup to be displayed) 
 9008: 
 9009: =cut
 9010: 
 9011: sub assign_categories_table {
 9012:     my ($cathash,$currcat) = @_;
 9013:     my $output;
 9014:     if (ref($cathash) eq 'HASH') {
 9015:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 9016:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 9017:         $maxdepth = scalar(@cats);
 9018:         if (@cats > 0) {
 9019:             my $itemcount = 0;
 9020:             if (ref($cats[0]) eq 'ARRAY') {
 9021:                 $output = &Apache::loncommon::start_data_table();
 9022:                 my @currcategories;
 9023:                 if ($currcat ne '') {
 9024:                     @currcategories = split('&',$currcat);
 9025:                 }
 9026:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 9027:                     my $parent = $cats[0][$i];
 9028:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9029:                     next if ($parent eq 'instcode');
 9030:                     my $item = &escape($parent).'::0';
 9031:                     my $checked = '';
 9032:                     if (@currcategories > 0) {
 9033:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 9034:                             $checked = ' checked="checked" ';
 9035:                         }
 9036:                     }
 9037:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 9038:                                '<input type="checkbox" name="usecategory" value="'.
 9039:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 9040:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 9041:                     my $depth = 1;
 9042:                     push(@path,$parent);
 9043:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 9044:                     pop(@path);
 9045:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9046:                     $itemcount ++;
 9047:                 }
 9048:                 $output .= &Apache::loncommon::end_data_table();
 9049:             }
 9050:         }
 9051:     }
 9052:     return $output;
 9053: }
 9054: 
 9055: =pod
 9056: 
 9057: =item *&assign_category_rows()
 9058: 
 9059: Create a datatable row for display of nested categories in a domain,
 9060: with checkboxes to allow a course to be categorized,called recursively.
 9061: 
 9062: Inputs:
 9063: 
 9064: itemcount - track row number for alternating colors
 9065: 
 9066: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 9067:       categories and subcategories.
 9068: 
 9069: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 9070: 
 9071: parent - parent of current category item
 9072: 
 9073: path - Array containing all categories back up through the hierarchy from the
 9074:        current category to the top level.
 9075: 
 9076: currcategories - reference to array of current categories assigned to the course
 9077: 
 9078: Returns: $output (markup to be displayed).
 9079: 
 9080: =cut
 9081: 
 9082: sub assign_category_rows {
 9083:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 9084:     my ($text,$name,$item,$chgstr);
 9085:     if (ref($cats) eq 'ARRAY') {
 9086:         my $maxdepth = scalar(@{$cats});
 9087:         if (ref($cats->[$depth]) eq 'HASH') {
 9088:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9089:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9090:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9091:                 $text .= '<td><table class="LC_datatable">';
 9092:                 for (my $j=0; $j<$numchildren; $j++) {
 9093:                     $name = $cats->[$depth]{$parent}[$j];
 9094:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9095:                     my $deeper = $depth+1;
 9096:                     my $checked = '';
 9097:                     if (ref($currcategories) eq 'ARRAY') {
 9098:                         if (@{$currcategories} > 0) {
 9099:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9100:                                 $checked = ' checked="checked" ';
 9101:                             }
 9102:                         }
 9103:                     }
 9104:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9105:                              '<input type="checkbox" name="usecategory" value="'.
 9106:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9107:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9108:                              '</td><td>';
 9109:                     if (ref($path) eq 'ARRAY') {
 9110:                         push(@{$path},$name);
 9111:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9112:                         pop(@{$path});
 9113:                     }
 9114:                     $text .= '</td></tr>';
 9115:                 }
 9116:                 $text .= '</table></td>';
 9117:             }
 9118:         }
 9119:     }
 9120:     return $text;
 9121: }
 9122: 
 9123: ############################################################
 9124: ############################################################
 9125: 
 9126: 
 9127: sub commit_customrole {
 9128:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9129:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9130:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9131:                          ($end?', ending '.localtime($end):'').': <b>'.
 9132:               &Apache::lonnet::assigncustomrole(
 9133:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9134:                  '</b><br />';
 9135:     return $output;
 9136: }
 9137: 
 9138: sub commit_standardrole {
 9139:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9140:     my ($output,$logmsg,$linefeed);
 9141:     if ($context eq 'auto') {
 9142:         $linefeed = "\n";
 9143:     } else {
 9144:         $linefeed = "<br />\n";
 9145:     }  
 9146:     if ($three eq 'st') {
 9147:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9148:                                          $one,$two,$sec,$context);
 9149:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9150:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9151:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9152:         } else {
 9153:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9154:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9155:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9156:             if ($context eq 'auto') {
 9157:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9158:             } else {
 9159:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9160:                &mt('Add to classlist').': <b>ok</b>';
 9161:             }
 9162:             $output .= $linefeed;
 9163:         }
 9164:     } else {
 9165:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9166:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9167:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9168:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9169:         if ($context eq 'auto') {
 9170:             $output .= $result.$linefeed;
 9171:         } else {
 9172:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9173:         }
 9174:     }
 9175:     return $output;
 9176: }
 9177: 
 9178: sub commit_studentrole {
 9179:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9180:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9181:     if ($context eq 'auto') {
 9182:         $linefeed = "\n";
 9183:     } else {
 9184:         $linefeed = '<br />'."\n";
 9185:     }
 9186:     if (defined($one) && defined($two)) {
 9187:         my $cid=$one.'_'.$two;
 9188:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9189:         my $secchange = 0;
 9190:         my $expire_role_result;
 9191:         my $modify_section_result;
 9192:         if ($oldsec ne '-1') { 
 9193:             if ($oldsec ne $sec) {
 9194:                 $secchange = 1;
 9195:                 my $now = time;
 9196:                 my $uurl='/'.$cid;
 9197:                 $uurl=~s/\_/\//g;
 9198:                 if ($oldsec) {
 9199:                     $uurl.='/'.$oldsec;
 9200:                 }
 9201:                 $oldsecurl = $uurl;
 9202:                 $expire_role_result = 
 9203:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9204:                 if ($env{'request.course.sec'} ne '') { 
 9205:                     if ($expire_role_result eq 'refused') {
 9206:                         my @roles = ('st');
 9207:                         my @statuses = ('previous');
 9208:                         my @roledoms = ($one);
 9209:                         my $withsec = 1;
 9210:                         my %roleshash = 
 9211:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9212:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9213:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9214:                             my ($oldstart,$oldend) = 
 9215:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9216:                             if ($oldend > 0 && $oldend <= $now) {
 9217:                                 $expire_role_result = 'ok';
 9218:                             }
 9219:                         }
 9220:                     }
 9221:                 }
 9222:                 $result = $expire_role_result;
 9223:             }
 9224:         }
 9225:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9226:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9227:             if ($modify_section_result =~ /^ok/) {
 9228:                 if ($secchange == 1) {
 9229:                     if ($sec eq '') {
 9230:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9231:                     } else {
 9232:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9233:                     }
 9234:                 } elsif ($oldsec eq '-1') {
 9235:                     if ($sec eq '') {
 9236:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9237:                     } else {
 9238:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9239:                     }
 9240:                 } else {
 9241:                     if ($sec eq '') {
 9242:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9243:                     } else {
 9244:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9245:                     }
 9246:                 }
 9247:             } else {
 9248:                 if ($secchange) {       
 9249:                     $$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;
 9250:                 } else {
 9251:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9252:                 }
 9253:             }
 9254:             $result = $modify_section_result;
 9255:         } elsif ($secchange == 1) {
 9256:             if ($oldsec eq '') {
 9257:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9258:             } else {
 9259:                 $$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;
 9260:             }
 9261:             if ($expire_role_result eq 'refused') {
 9262:                 my $newsecurl = '/'.$cid;
 9263:                 $newsecurl =~ s/\_/\//g;
 9264:                 if ($sec ne '') {
 9265:                     $newsecurl.='/'.$sec;
 9266:                 }
 9267:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9268:                     if ($sec eq '') {
 9269:                         $$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;
 9270:                     } else {
 9271:                         $$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;
 9272:                     }
 9273:                 }
 9274:             }
 9275:         }
 9276:     } else {
 9277:         $$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;
 9278:         $result = "error: incomplete course id\n";
 9279:     }
 9280:     return $result;
 9281: }
 9282: 
 9283: ############################################################
 9284: ############################################################
 9285: 
 9286: sub check_clone {
 9287:     my ($args,$linefeed) = @_;
 9288:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9289:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9290:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9291:     my $clonemsg;
 9292:     my $can_clone = 0;
 9293: 
 9294:     if ($clonehome eq 'no_host') {
 9295:         $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'});     
 9296:     } else {
 9297: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9298:         if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
 9299:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
 9300:  	    $can_clone = 1;
 9301: 	} else {
 9302: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9303: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9304: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9305:             if (grep(/^\*$/,@cloners)) {
 9306:                 $can_clone = 1;
 9307:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9308:                 $can_clone = 1;
 9309:             } else {
 9310: 	        my %roleshash =
 9311: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9312: 					 $args->{'ccdomain'},
 9313:                                          'userroles',['active'],['cc'],
 9314: 					 [$args->{'clonedomain'}]);
 9315: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9316: 		    $can_clone = 1;
 9317: 	        } else {
 9318:                     $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'});
 9319: 	        }
 9320: 	    }
 9321:         }
 9322:     }
 9323:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9324: }
 9325: 
 9326: sub construct_course {
 9327:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
 9328:     my $outcome;
 9329:     my $linefeed =  '<br />'."\n";
 9330:     if ($context eq 'auto') {
 9331:         $linefeed = "\n";
 9332:     }
 9333: 
 9334: #
 9335: # Are we cloning?
 9336: #
 9337:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9338:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9339: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9340: 	if ($context ne 'auto') {
 9341:             if ($clonemsg ne '') {
 9342: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9343:             }
 9344: 	}
 9345: 	$outcome .= $clonemsg.$linefeed;
 9346: 
 9347:         if (!$can_clone) {
 9348: 	    return (0,$outcome);
 9349: 	}
 9350:     }
 9351: 
 9352: #
 9353: # Open course
 9354: #
 9355:     my $crstype = lc($args->{'crstype'});
 9356:     my %cenv=();
 9357:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9358:                                              $args->{'cdescr'},
 9359:                                              $args->{'curl'},
 9360:                                              $args->{'course_home'},
 9361:                                              $args->{'nonstandard'},
 9362:                                              $args->{'crscode'},
 9363:                                              $args->{'ccuname'}.':'.
 9364:                                              $args->{'ccdomain'},
 9365:                                              $args->{'crstype'},
 9366:                                              $cnum,$context,$category);
 9367: 
 9368: 
 9369:     # Note: The testing routines depend on this being output; see 
 9370:     # Utils::Course. This needs to at least be output as a comment
 9371:     # if anyone ever decides to not show this, and Utils::Course::new
 9372:     # will need to be suitably modified.
 9373:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9374: #
 9375: # Check if created correctly
 9376: #
 9377:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9378:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9379:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9380: 
 9381: #
 9382: # Do the cloning
 9383: #   
 9384:     if ($can_clone && $cloneid) {
 9385: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9386: 	if ($context ne 'auto') {
 9387: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9388: 	}
 9389: 	$outcome .= $clonemsg.$linefeed;
 9390: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9391: # Copy all files
 9392: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9393: # Restore URL
 9394: 	$cenv{'url'}=$oldcenv{'url'};
 9395: # Restore title
 9396: 	$cenv{'description'}=$oldcenv{'description'};
 9397: # Mark as cloned
 9398: 	$cenv{'clonedfrom'}=$cloneid;
 9399: # Need to clone grading mode
 9400:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9401:         $cenv{'grading'}=$newenv{'grading'};
 9402: # Do not clone these environment entries
 9403:         &Apache::lonnet::del('environment',
 9404:                   ['default_enrollment_start_date',
 9405:                    'default_enrollment_end_date',
 9406:                    'question.email',
 9407:                    'policy.email',
 9408:                    'comment.email',
 9409:                    'pch.users.denied',
 9410:                    'plc.users.denied',
 9411:                    'hidefromcat',
 9412:                    'categories'],
 9413:                    $$crsudom,$$crsunum);
 9414:     }
 9415: 
 9416: #
 9417: # Set environment (will override cloned, if existing)
 9418: #
 9419:     my @sections = ();
 9420:     my @xlists = ();
 9421:     if ($args->{'crstype'}) {
 9422:         $cenv{'type'}=$args->{'crstype'};
 9423:     }
 9424:     if ($args->{'crsid'}) {
 9425:         $cenv{'courseid'}=$args->{'crsid'};
 9426:     }
 9427:     if ($args->{'crscode'}) {
 9428:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9429:     }
 9430:     if ($args->{'crsquota'} ne '') {
 9431:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9432:     } else {
 9433:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9434:     }
 9435:     if ($args->{'ccuname'}) {
 9436:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9437:                                         ':'.$args->{'ccdomain'};
 9438:     } else {
 9439:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9440:     }
 9441:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9442:     if ($args->{'crssections'}) {
 9443:         $cenv{'internal.sectionnums'} = '';
 9444:         if ($args->{'crssections'} =~ m/,/) {
 9445:             @sections = split/,/,$args->{'crssections'};
 9446:         } else {
 9447:             $sections[0] = $args->{'crssections'};
 9448:         }
 9449:         if (@sections > 0) {
 9450:             foreach my $item (@sections) {
 9451:                 my ($sec,$gp) = split/:/,$item;
 9452:                 my $class = $args->{'crscode'}.$sec;
 9453:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9454:                 $cenv{'internal.sectionnums'} .= $item.',';
 9455:                 unless ($addcheck eq 'ok') {
 9456:                     push @badclasses, $class;
 9457:                 }
 9458:             }
 9459:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9460:         }
 9461:     }
 9462: # do not hide course coordinator from staff listing, 
 9463: # even if privileged
 9464:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9465: # add crosslistings
 9466:     if ($args->{'crsxlist'}) {
 9467:         $cenv{'internal.crosslistings'}='';
 9468:         if ($args->{'crsxlist'} =~ m/,/) {
 9469:             @xlists = split/,/,$args->{'crsxlist'};
 9470:         } else {
 9471:             $xlists[0] = $args->{'crsxlist'};
 9472:         }
 9473:         if (@xlists > 0) {
 9474:             foreach my $item (@xlists) {
 9475:                 my ($xl,$gp) = split/:/,$item;
 9476:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9477:                 $cenv{'internal.crosslistings'} .= $item.',';
 9478:                 unless ($addcheck eq 'ok') {
 9479:                     push @badclasses, $xl;
 9480:                 }
 9481:             }
 9482:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9483:         }
 9484:     }
 9485:     if ($args->{'autoadds'}) {
 9486:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9487:     }
 9488:     if ($args->{'autodrops'}) {
 9489:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9490:     }
 9491: # check for notification of enrollment changes
 9492:     my @notified = ();
 9493:     if ($args->{'notify_owner'}) {
 9494:         if ($args->{'ccuname'} ne '') {
 9495:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9496:         }
 9497:     }
 9498:     if ($args->{'notify_dc'}) {
 9499:         if ($uname ne '') { 
 9500:             push(@notified,$uname.':'.$udom);
 9501:         }
 9502:     }
 9503:     if (@notified > 0) {
 9504:         my $notifylist;
 9505:         if (@notified > 1) {
 9506:             $notifylist = join(',',@notified);
 9507:         } else {
 9508:             $notifylist = $notified[0];
 9509:         }
 9510:         $cenv{'internal.notifylist'} = $notifylist;
 9511:     }
 9512:     if (@badclasses > 0) {
 9513:         my %lt=&Apache::lonlocal::texthash(
 9514:                 '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',
 9515:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9516:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9517:         );
 9518:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9519:                            ' ('.$lt{'adby'}.')';
 9520:         if ($context eq 'auto') {
 9521:             $outcome .= $badclass_msg.$linefeed;
 9522:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9523:             foreach my $item (@badclasses) {
 9524:                 if ($context eq 'auto') {
 9525:                     $outcome .= " - $item\n";
 9526:                 } else {
 9527:                     $outcome .= "<li>$item</li>\n";
 9528:                 }
 9529:             }
 9530:             if ($context eq 'auto') {
 9531:                 $outcome .= $linefeed;
 9532:             } else {
 9533:                 $outcome .= "</ul><br /><br /></div>\n";
 9534:             }
 9535:         } 
 9536:     }
 9537:     if ($args->{'no_end_date'}) {
 9538:         $args->{'endaccess'} = 0;
 9539:     }
 9540:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9541:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9542:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9543:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9544:     if ($args->{'showphotos'}) {
 9545:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9546:     }
 9547:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9548:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9549:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9550:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9551:             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'); 
 9552:             if ($context eq 'auto') {
 9553:                 $outcome .= $krb_msg;
 9554:             } else {
 9555:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9556:             }
 9557:             $outcome .= $linefeed;
 9558:         }
 9559:     }
 9560:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9561:        if ($args->{'setpolicy'}) {
 9562:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9563:        }
 9564:        if ($args->{'setcontent'}) {
 9565:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9566:        }
 9567:     }
 9568:     if ($args->{'reshome'}) {
 9569: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9570: 	$cenv{'reshome'}=~s/\/+$/\//;
 9571:     }
 9572: #
 9573: # course has keyed access
 9574: #
 9575:     if ($args->{'setkeys'}) {
 9576:        $cenv{'keyaccess'}='yes';
 9577:     }
 9578: # if specified, key authority is not course, but user
 9579: # only active if keyaccess is yes
 9580:     if ($args->{'keyauth'}) {
 9581: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9582: 	$user = &LONCAPA::clean_username($user);
 9583: 	$domain = &LONCAPA::clean_username($domain);
 9584: 	if ($user ne '' && $domain ne '') {
 9585: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9586: 	}
 9587:     }
 9588: 
 9589:     if ($args->{'disresdis'}) {
 9590:         $cenv{'pch.roles.denied'}='st';
 9591:     }
 9592:     if ($args->{'disablechat'}) {
 9593:         $cenv{'plc.roles.denied'}='st';
 9594:     }
 9595: 
 9596:     # Record we've not yet viewed the Course Initialization Helper for this 
 9597:     # course
 9598:     $cenv{'course.helper.not.run'} = 1;
 9599:     #
 9600:     # Use new Randomseed
 9601:     #
 9602:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9603:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9604:     #
 9605:     # The encryption code and receipt prefix for this course
 9606:     #
 9607:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9608:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9609:     #
 9610:     # By default, use standard grading
 9611:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9612: 
 9613:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9614:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9615: #
 9616: # Open all assignments
 9617: #
 9618:     if ($args->{'openall'}) {
 9619:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9620:        my %storecontent = ($storeunder         => time,
 9621:                            $storeunder.'.type' => 'date_start');
 9622:        
 9623:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9624:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9625:    }
 9626: #
 9627: # Set first page
 9628: #
 9629:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9630: 	    || ($cloneid)) {
 9631: 	use LONCAPA::map;
 9632: 	$outcome .= &mt('Setting first resource').': ';
 9633: 
 9634: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9635:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9636: 
 9637:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9638:         my $title; my $url;
 9639:         if ($args->{'firstres'} eq 'syl') {
 9640: 	    $title=&mt('Syllabus');
 9641:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9642:         } else {
 9643:             $title=&mt('Navigate Contents');
 9644:             $url='/adm/navmaps';
 9645:         }
 9646: 
 9647:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9648: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9649: 
 9650: 	if ($errtext) { $fatal=2; }
 9651:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9652:     }
 9653: 
 9654:     return (1,$outcome);
 9655: }
 9656: 
 9657: ############################################################
 9658: ############################################################
 9659: 
 9660: sub course_type {
 9661:     my ($cid) = @_;
 9662:     if (!defined($cid)) {
 9663:         $cid = $env{'request.course.id'};
 9664:     }
 9665:     if (defined($env{'course.'.$cid.'.type'})) {
 9666:         return $env{'course.'.$cid.'.type'};
 9667:     } else {
 9668:         return 'Course';
 9669:     }
 9670: }
 9671: 
 9672: sub group_term {
 9673:     my $crstype = &course_type();
 9674:     my %names = (
 9675:                   'Course'    => 'group',
 9676:                   'Community' => 'group',
 9677:                 );
 9678:     return $names{$crstype};
 9679: }
 9680: 
 9681: sub icon {
 9682:     my ($file)=@_;
 9683:     my $curfext = lc((split(/\./,$file))[-1]);
 9684:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9685:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9686:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9687: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9688: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9689: 	            $curfext.".gif") {
 9690: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9691: 		$curfext.".gif";
 9692: 	}
 9693:     }
 9694:     return &lonhttpdurl($iconname);
 9695: } 
 9696: 
 9697: sub lonhttpdurl {
 9698: #
 9699: # Had been used for "small fry" static images on separate port 8080.
 9700: # Modify here if lightweight http functionality desired again.
 9701: # Currently eliminated due to increasing firewall issues.
 9702: #
 9703:     my ($url)=@_;
 9704:     return $url;
 9705: }
 9706: 
 9707: sub connection_aborted {
 9708:     my ($r)=@_;
 9709:     $r->print(" ");$r->rflush();
 9710:     my $c = $r->connection;
 9711:     return $c->aborted();
 9712: }
 9713: 
 9714: #    Escapes strings that may have embedded 's that will be put into
 9715: #    strings as 'strings'.
 9716: sub escape_single {
 9717:     my ($input) = @_;
 9718:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9719:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9720:     return $input;
 9721: }
 9722: 
 9723: #  Same as escape_single, but escape's "'s  This 
 9724: #  can be used for  "strings"
 9725: sub escape_double {
 9726:     my ($input) = @_;
 9727:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9728:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9729:     return $input;
 9730: }
 9731:  
 9732: #   Escapes the last element of a full URL.
 9733: sub escape_url {
 9734:     my ($url)   = @_;
 9735:     my @urlslices = split(/\//, $url,-1);
 9736:     my $lastitem = &escape(pop(@urlslices));
 9737:     return join('/',@urlslices).'/'.$lastitem;
 9738: }
 9739: 
 9740: sub compare_arrays {
 9741:     my ($arrayref1,$arrayref2) = @_;
 9742:     my (@difference,%count);
 9743:     @difference = ();
 9744:     %count = ();
 9745:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
 9746:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
 9747:         foreach my $element (keys(%count)) {
 9748:             if ($count{$element} == 1) {
 9749:                 push(@difference,$element);
 9750:             }
 9751:         }
 9752:     }
 9753:     return @difference;
 9754: }
 9755: 
 9756: # -------------------------------------------------------- Initliaze user login
 9757: sub init_user_environment {
 9758:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9759:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9760: 
 9761:     my $public=($username eq 'public' && $domain eq 'public');
 9762: 
 9763: # See if old ID present, if so, remove
 9764: 
 9765:     my ($filename,$cookie,$userroles);
 9766:     my $now=time;
 9767: 
 9768:     if ($public) {
 9769: 	my $max_public=100;
 9770: 	my $oldest;
 9771: 	my $oldest_time=0;
 9772: 	for(my $next=1;$next<=$max_public;$next++) {
 9773: 	    if (-e $lonids."/publicuser_$next.id") {
 9774: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9775: 		if ($mtime<$oldest_time || !$oldest_time) {
 9776: 		    $oldest_time=$mtime;
 9777: 		    $oldest=$next;
 9778: 		}
 9779: 	    } else {
 9780: 		$cookie="publicuser_$next";
 9781: 		last;
 9782: 	    }
 9783: 	}
 9784: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9785:     } else {
 9786: 	# if this isn't a robot, kill any existing non-robot sessions
 9787: 	if (!$args->{'robot'}) {
 9788: 	    opendir(DIR,$lonids);
 9789: 	    while ($filename=readdir(DIR)) {
 9790: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9791: 		    unlink($lonids.'/'.$filename);
 9792: 		}
 9793: 	    }
 9794: 	    closedir(DIR);
 9795: 	}
 9796: # Give them a new cookie
 9797: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9798: 		                   : $now.$$.int(rand(10000)));
 9799: 	$cookie="$username\_$id\_$domain\_$authhost";
 9800:     
 9801: # Initialize roles
 9802: 
 9803: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9804:     }
 9805: # ------------------------------------ Check browser type and MathML capability
 9806: 
 9807:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9808:         $clientunicode,$clientos) = &decode_user_agent($r);
 9809: 
 9810: # -------------------------------------- Any accessibility options to remember?
 9811:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9812: 	foreach my $option ('imagesuppress','appletsuppress',
 9813: 			    'embedsuppress','fontenhance','blackwhite') {
 9814: 	    if ($form->{$option} eq 'true') {
 9815: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9816: 				     $domain,$username);
 9817: 	    } else {
 9818: 		&Apache::lonnet::del('environment',[$option],
 9819: 				     $domain,$username);
 9820: 	    }
 9821: 	}
 9822:     }
 9823: # ------------------------------------------------------------- Get environment
 9824: 
 9825:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9826:     my ($tmp) = keys(%userenv);
 9827:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9828: 	# default remote control to off
 9829: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9830:     } else {
 9831: 	undef(%userenv);
 9832:     }
 9833:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9834: 	$form->{'interface'}=$userenv{'interface'};
 9835:     }
 9836:     $env{'environment.remote'}=$userenv{'remote'};
 9837:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9838: 
 9839: # --------------- Do not trust query string to be put directly into environment
 9840:     foreach my $option ('imagesuppress','appletsuppress',
 9841: 			'embedsuppress','fontenhance','blackwhite',
 9842: 			'interface','localpath','localres') {
 9843: 	$form->{$option}=~s/[\n\r\=]//gs;
 9844:     }
 9845: # --------------------------------------------------------- Write first profile
 9846: 
 9847:     {
 9848: 	my %initial_env = 
 9849: 	    ("user.name"          => $username,
 9850: 	     "user.domain"        => $domain,
 9851: 	     "user.home"          => $authhost,
 9852: 	     "browser.type"       => $clientbrowser,
 9853: 	     "browser.version"    => $clientversion,
 9854: 	     "browser.mathml"     => $clientmathml,
 9855: 	     "browser.unicode"    => $clientunicode,
 9856: 	     "browser.os"         => $clientos,
 9857: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9858: 	     "request.course.fn"  => '',
 9859: 	     "request.course.uri" => '',
 9860: 	     "request.course.sec" => '',
 9861: 	     "request.role"       => 'cm',
 9862: 	     "request.role.adv"   => $env{'user.adv'},
 9863: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9864: 
 9865:         if ($form->{'localpath'}) {
 9866: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9867: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9868:         }
 9869: 	
 9870: 	if ($public) {
 9871: 	    $initial_env{"environment.remote"} = "off";
 9872: 	}
 9873: 	if ($form->{'interface'}) {
 9874: 	    $form->{'interface'}=~s/\W//gs;
 9875: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9876: 	    $env{'browser.interface'}=$form->{'interface'};
 9877: 	    foreach my $option ('imagesuppress','appletsuppress',
 9878: 				'embedsuppress','fontenhance','blackwhite') {
 9879: 		if (($form->{$option} eq 'true') ||
 9880: 		    ($userenv{$option} eq 'on')) {
 9881: 		    $initial_env{"browser.$option"} = "on";
 9882: 		}
 9883: 	    }
 9884: 	}
 9885: 
 9886:         foreach my $tool ('aboutme','blog','portfolio') {
 9887:             $userenv{'availabletools.'.$tool} =
 9888:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9889:         }
 9890: 
 9891:         foreach my $crstype ('official','unofficial','community') {
 9892:             $userenv{'canrequest.'.$crstype} =
 9893:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
 9894:                                                   'reload','requestcourses');
 9895:         }
 9896: 
 9897: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9898: 	
 9899: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9900: 		 &GDBM_WRCREAT(),0640)) {
 9901: 	    &_add_to_env(\%disk_env,\%initial_env);
 9902: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9903: 	    &_add_to_env(\%disk_env,$userroles);
 9904: 	    if (ref($args->{'extra_env'})) {
 9905: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9906: 	    }
 9907: 	    untie(%disk_env);
 9908: 	} else {
 9909: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9910: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9911: 	    return 'error: '.$!;
 9912: 	}
 9913:     }
 9914:     $env{'request.role'}='cm';
 9915:     $env{'request.role.adv'}=$env{'user.adv'};
 9916:     $env{'browser.type'}=$clientbrowser;
 9917: 
 9918:     return $cookie;
 9919: 
 9920: }
 9921: 
 9922: sub _add_to_env {
 9923:     my ($idf,$env_data,$prefix) = @_;
 9924:     if (ref($env_data) eq 'HASH') {
 9925:         while (my ($key,$value) = each(%$env_data)) {
 9926: 	    $idf->{$prefix.$key} = $value;
 9927: 	    $env{$prefix.$key}   = $value;
 9928:         }
 9929:     }
 9930: }
 9931: 
 9932: # --- Get the symbolic name of a problem and the url
 9933: sub get_symb {
 9934:     my ($request,$silent) = @_;
 9935:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9936:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9937:     if ($symb eq '') {
 9938:         if (!$silent) {
 9939:             $request->print("Unable to handle ambiguous references:$url:.");
 9940:             return ();
 9941:         }
 9942:     }
 9943:     &Apache::lonenc::check_decrypt(\$symb);
 9944:     return ($symb);
 9945: }
 9946: 
 9947: # --------------------------------------------------------------Get annotation
 9948: 
 9949: sub get_annotation {
 9950:     my ($symb,$enc) = @_;
 9951: 
 9952:     my $key = $symb;
 9953:     if (!$enc) {
 9954:         $key =
 9955:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9956:     }
 9957:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9958:     return $annotation{$key};
 9959: }
 9960: 
 9961: sub clean_symb {
 9962:     my ($symb,$delete_enc) = @_;
 9963: 
 9964:     &Apache::lonenc::check_decrypt(\$symb);
 9965:     my $enc = $env{'request.enc'};
 9966:     if ($delete_enc) {
 9967:         delete($env{'request.enc'});
 9968:     }
 9969: 
 9970:     return ($symb,$enc);
 9971: }
 9972: 
 9973: =pod
 9974: 
 9975: =back
 9976: 
 9977: =cut
 9978: 
 9979: 1;
 9980: __END__;
 9981: 

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