File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.692.4.6: download - view: text, annotated - select for diffs
Fri Aug 14 07:40:50 2009 UTC (14 years, 10 months ago) by raeburn
Branches: version_2_9_X
Diff to branchpoint 1.692: preferred, unified
- Backport 1.845, part of 1.846, 1.849, 1.850, 1.864, 1.865, 1.871.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.692.4.6 2009/08/14 07:40:50 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 $output = '
  487: <script type="text/javascript" language="JavaScript">
  488: // <![CDATA[
  489:     var stdeditbrowser;'."\n";
  490:    $output .= <<"ENDSTDBRW";
  491:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  492:         var url = '/adm/pickcourse?';
  493:         var domainfilter = '';
  494:         var formid = getFormIdByName(formname);
  495:         if (formid > -1) {
  496:             var domid = getIndexByName(formid,udom);
  497:             if (domid > -1) {
  498:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  499:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  500:                 }
  501:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  502:                     domainfilter=document.forms[formid].elements[domid].value;
  503:                 }
  504:             }
  505:         }
  506:         if (domainfilter != null) {
  507:            if (domainfilter != '') {
  508:                url += 'domainfilter='+domainfilter+'&';
  509: 	   }
  510:         }
  511:         url += 'form=' + formname + '&cnumelement='+uname+
  512: 	                            '&cdomelement='+udom+
  513:                                     '&cnameelement='+desc;
  514:         if (extra_element !=null && extra_element != '') {
  515:             if (formname == 'rolechoice' || formname == 'studentform') {
  516:                 url += '&roleelement='+extra_element;
  517:                 if (domainfilter == null || domainfilter == '') {
  518:                     url += '&domainfilter='+extra_element;
  519:                 }
  520:             }
  521:             else {
  522:                 if (formname == 'portform') {
  523:                     url += '&setroles='+extra_element;
  524:                 }
  525:             }     
  526:         }
  527:         if (multflag !=null && multflag != '') {
  528:             url += '&multiple='+multflag;
  529:         }
  530:         if (crstype == 'Course/Community') {
  531:             if (formname == 'cu') {
  532:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  533:                 if (crstype == "") {
  534:                     alert("$crs_or_grp_alert");
  535:                     return;
  536:                 }
  537:             }
  538:         }
  539:         if (crstype !=null && crstype != '') {
  540:             url += '&type='+crstype;
  541:         }
  542:         var title = 'Course_Browser';
  543:         var options = 'scrollbars=1,resizable=1,menubar=0';
  544:         options += ',width=700,height=600';
  545:         stdeditbrowser = open(url,title,options,'1');
  546:         stdeditbrowser.focus();
  547:     }
  548: 
  549:     function getFormIdByName(formname) {
  550:         for (var i=0;i<document.forms.length;i++) {
  551:             if (document.forms[i].name == formname) {
  552:                 return i;
  553:             }
  554:         }
  555:         return -1; 
  556:     }
  557: 
  558:     function getIndexByName(formid,item) {
  559:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  560:             if (document.forms[formid].elements[i].name == item) {
  561:                 return i;
  562:             }
  563:         }
  564:         return -1;
  565:     }
  566: ENDSTDBRW
  567:     if ($sec_element ne '') {
  568:         $output .= &setsec_javascript($sec_element,$formname);
  569:     }
  570:     $output .= '
  571: // ]]>
  572: </script>';
  573:     return $output;
  574: }
  575: 
  576: sub setsec_javascript {
  577:     my ($sec_element,$formname) = @_;
  578:     my $setsections = qq|
  579: function setSect(sectionlist) {
  580:     var sectionsArray = new Array();
  581:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  582:         sectionsArray = sectionlist.split(",");
  583:     }
  584:     var numSections = sectionsArray.length;
  585:     document.$formname.$sec_element.length = 0;
  586:     if (numSections == 0) {
  587:         document.$formname.$sec_element.multiple=false;
  588:         document.$formname.$sec_element.size=1;
  589:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  590:     } else {
  591:         if (numSections == 1) {
  592:             document.$formname.$sec_element.multiple=false;
  593:             document.$formname.$sec_element.size=1;
  594:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  595:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  596:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  597:         } else {
  598:             for (var i=0; i<numSections; i++) {
  599:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  600:             }
  601:             document.$formname.$sec_element.multiple=true
  602:             if (numSections < 3) {
  603:                 document.$formname.$sec_element.size=numSections;
  604:             } else {
  605:                 document.$formname.$sec_element.size=3;
  606:             }
  607:             document.$formname.$sec_element.options[0].selected = false
  608:         }
  609:     }
  610: }
  611: |;
  612:     return $setsections;
  613: }
  614: 
  615: 
  616: sub selectcourse_link {
  617:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  618:    my $linktext = &mt('Select Course');
  619:    if ($selecttype eq 'Community') {
  620:        $linktext = &mt('Select Community');
  621:    }
  622:    return '<span class="LC_nobreak">'
  623:          ."<a href='"
  624:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  625:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  626:          .'","'.$multflag.'","'.$selecttype.'");'
  627:          ."'>".$linktext.'</a>'
  628:          .'</span>';
  629: }
  630: 
  631: sub selectauthor_link {
  632:    my ($form,$udom)=@_;
  633:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  634:           &mt('Select Author').'</a>';
  635: }
  636: 
  637: sub check_uncheck_jscript {
  638:     my $jscript = <<"ENDSCRT";
  639: function checkAll(field) {
  640:     if (field.length > 0) {
  641:         for (i = 0; i < field.length; i++) {
  642:             field[i].checked = true ;
  643:         }
  644:     } else {
  645:         field.checked = true
  646:     }
  647: }
  648:  
  649: function uncheckAll(field) {
  650:     if (field.length > 0) {
  651:         for (i = 0; i < field.length; i++) {
  652:             field[i].checked = false ;
  653:         }
  654:     } else {
  655:         field.checked = false ;
  656:     }
  657: }
  658: ENDSCRT
  659:     return $jscript;
  660: }
  661: 
  662: sub select_timezone {
  663:    my ($name,$selected,$onchange,$includeempty)=@_;
  664:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  665:    if ($includeempty) {
  666:        $output .= '<option value=""';
  667:        if (($selected eq '') || ($selected eq 'local')) {
  668:            $output .= ' selected="selected" ';
  669:        }
  670:        $output .= '> </option>';
  671:    }
  672:    my @timezones = DateTime::TimeZone->all_names;
  673:    foreach my $tzone (@timezones) {
  674:        $output.= '<option value="'.$tzone.'"';
  675:        if ($tzone eq $selected) {
  676:            $output.=' selected="selected"';
  677:        }
  678:        $output.=">$tzone</option>\n";
  679:    }
  680:    $output.="</select>";
  681:    return $output;
  682: }
  683: 
  684: sub select_datelocale {
  685:     my ($name,$selected,$onchange,$includeempty)=@_;
  686:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  687:     if ($includeempty) {
  688:         $output .= '<option value=""';
  689:         if ($selected eq '') {
  690:             $output .= ' selected="selected" ';
  691:         }
  692:         $output .= '> </option>';
  693:     }
  694:     my (@possibles,%locale_names);
  695:     my @locales = DateTime::Locale::Catalog::Locales;
  696:     foreach my $locale (@locales) {
  697:         if (ref($locale) eq 'HASH') {
  698:             my $id = $locale->{'id'};
  699:             if ($id ne '') {
  700:                 my $en_terr = $locale->{'en_territory'};
  701:                 my $native_terr = $locale->{'native_territory'};
  702:                 my @languages = &Apache::lonlocal::preferred_languages();
  703:                 if (grep(/^en$/,@languages) || !@languages) {
  704:                     if ($en_terr ne '') {
  705:                         $locale_names{$id} = '('.$en_terr.')';
  706:                     } elsif ($native_terr ne '') {
  707:                         $locale_names{$id} = $native_terr;
  708:                     }
  709:                 } else {
  710:                     if ($native_terr ne '') {
  711:                         $locale_names{$id} = $native_terr.' ';
  712:                     } elsif ($en_terr ne '') {
  713:                         $locale_names{$id} = '('.$en_terr.')';
  714:                     }
  715:                 }
  716:                 push (@possibles,$id);
  717:             }
  718:         }
  719:     }
  720:     foreach my $item (sort(@possibles)) {
  721:         $output.= '<option value="'.$item.'"';
  722:         if ($item eq $selected) {
  723:             $output.=' selected="selected"';
  724:         }
  725:         $output.=">$item";
  726:         if ($locale_names{$item} ne '') {
  727:             $output.="  $locale_names{$item}</option>\n";
  728:         }
  729:         $output.="</option>\n";
  730:     }
  731:     $output.="</select>";
  732:     return $output;
  733: }
  734: 
  735: sub select_language {
  736:     my ($name,$selected,$includeempty) = @_;
  737:     my %langchoices;
  738:     if ($includeempty) {
  739:         %langchoices = ('' => 'No language preference');
  740:     }
  741:     foreach my $id (&languageids()) {
  742:         my $code = &supportedlanguagecode($id);
  743:         if ($code) {
  744:             $langchoices{$code} = &plainlanguagedescription($id);
  745:         }
  746:     }
  747:     return &select_form($selected,$name,%langchoices);
  748: }
  749: 
  750: =pod
  751: 
  752: =item * &linked_select_forms(...)
  753: 
  754: linked_select_forms returns a string containing a <script></script> block
  755: and html for two <select> menus.  The select menus will be linked in that
  756: changing the value of the first menu will result in new values being placed
  757: in the second menu.  The values in the select menu will appear in alphabetical
  758: order unless a defined order is provided.
  759: 
  760: linked_select_forms takes the following ordered inputs:
  761: 
  762: =over 4
  763: 
  764: =item * $formname, the name of the <form> tag
  765: 
  766: =item * $middletext, the text which appears between the <select> tags
  767: 
  768: =item * $firstdefault, the default value for the first menu
  769: 
  770: =item * $firstselectname, the name of the first <select> tag
  771: 
  772: =item * $secondselectname, the name of the second <select> tag
  773: 
  774: =item * $hashref, a reference to a hash containing the data for the menus.
  775: 
  776: =item * $menuorder, the order of values in the first menu
  777: 
  778: =back 
  779: 
  780: Below is an example of such a hash.  Only the 'text', 'default', and 
  781: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  782: values for the first select menu.  The text that coincides with the 
  783: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  784: and text for the second menu are given in the hash pointed to by 
  785: $menu{$choice1}->{'select2'}.  
  786: 
  787:  my %menu = ( A1 => { text =>"Choice A1" ,
  788:                        default => "B3",
  789:                        select2 => { 
  790:                            B1 => "Choice B1",
  791:                            B2 => "Choice B2",
  792:                            B3 => "Choice B3",
  793:                            B4 => "Choice B4"
  794:                            },
  795:                        order => ['B4','B3','B1','B2'],
  796:                    },
  797:                A2 => { text =>"Choice A2" ,
  798:                        default => "C2",
  799:                        select2 => { 
  800:                            C1 => "Choice C1",
  801:                            C2 => "Choice C2",
  802:                            C3 => "Choice C3"
  803:                            },
  804:                        order => ['C2','C1','C3'],
  805:                    },
  806:                A3 => { text =>"Choice A3" ,
  807:                        default => "D6",
  808:                        select2 => { 
  809:                            D1 => "Choice D1",
  810:                            D2 => "Choice D2",
  811:                            D3 => "Choice D3",
  812:                            D4 => "Choice D4",
  813:                            D5 => "Choice D5",
  814:                            D6 => "Choice D6",
  815:                            D7 => "Choice D7"
  816:                            },
  817:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
  818:                    }
  819:                );
  820: 
  821: =cut
  822: 
  823: sub linked_select_forms {
  824:     my ($formname,
  825:         $middletext,
  826:         $firstdefault,
  827:         $firstselectname,
  828:         $secondselectname, 
  829:         $hashref,
  830:         $menuorder,
  831:         ) = @_;
  832:     my $second = "document.$formname.$secondselectname";
  833:     my $first = "document.$formname.$firstselectname";
  834:     # output the javascript to do the changing
  835:     my $result = '';
  836:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
  837:     $result.="// <![CDATA[\n";
  838:     $result.="var select2data = new Object();\n";
  839:     $" = '","';
  840:     my $debug = '';
  841:     foreach my $s1 (sort(keys(%$hashref))) {
  842:         $result.="select2data.d_$s1 = new Object();\n";        
  843:         $result.="select2data.d_$s1.def = new String('".
  844:             $hashref->{$s1}->{'default'}."');\n";
  845:         $result.="select2data.d_$s1.values = new Array(";
  846:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  847:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
  848:             @s2values = @{$hashref->{$s1}->{'order'}};
  849:         }
  850:         $result.="\"@s2values\");\n";
  851:         $result.="select2data.d_$s1.texts = new Array(";        
  852:         my @s2texts;
  853:         foreach my $value (@s2values) {
  854:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  855:         }
  856:         $result.="\"@s2texts\");\n";
  857:     }
  858:     $"=' ';
  859:     $result.= <<"END";
  860: 
  861: function select1_changed() {
  862:     // Determine new choice
  863:     var newvalue = "d_" + $first.value;
  864:     // update select2
  865:     var values     = select2data[newvalue].values;
  866:     var texts      = select2data[newvalue].texts;
  867:     var select2def = select2data[newvalue].def;
  868:     var i;
  869:     // out with the old
  870:     for (i = 0; i < $second.options.length; i++) {
  871:         $second.options[i] = null;
  872:     }
  873:     // in with the nuclear
  874:     for (i=0;i<values.length; i++) {
  875:         $second.options[i] = new Option(values[i]);
  876:         $second.options[i].value = values[i];
  877:         $second.options[i].text = texts[i];
  878:         if (values[i] == select2def) {
  879:             $second.options[i].selected = true;
  880:         }
  881:     }
  882: }
  883: // ]]>
  884: </script>
  885: END
  886:     # output the initial values for the selection lists
  887:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  888:     my @order = sort(keys(%{$hashref}));
  889:     if (ref($menuorder) eq 'ARRAY') {
  890:         @order = @{$menuorder};
  891:     }
  892:     foreach my $value (@order) {
  893:         $result.="    <option value=\"$value\" ";
  894:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  895:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  896:     }
  897:     $result .= "</select>\n";
  898:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  899:     $result .= $middletext;
  900:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  901:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  902:     
  903:     my @secondorder = sort(keys(%select2));
  904:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
  905:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
  906:     }
  907:     foreach my $value (@secondorder) {
  908:         $result.="    <option value=\"$value\" ";        
  909:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  910:         $result.=">".&mt($select2{$value})."</option>\n";
  911:     }
  912:     $result .= "</select>\n";
  913:     #    return $debug;
  914:     return $result;
  915: }   #  end of sub linked_select_forms {
  916: 
  917: =pod
  918: 
  919: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
  920: 
  921: Returns a string corresponding to an HTML link to the given help
  922: $topic, where $topic corresponds to the name of a .tex file in
  923: /home/httpd/html/adm/help/tex, with underscores replaced by
  924: spaces. 
  925: 
  926: $text will optionally be linked to the same topic, allowing you to
  927: link text in addition to the graphic. If you do not want to link
  928: text, but wish to specify one of the later parameters, pass an
  929: empty string. 
  930: 
  931: $stayOnPage is a value that will be interpreted as a boolean. If true,
  932: the link will not open a new window. If false, the link will open
  933: a new window using Javascript. (Default is false.) 
  934: 
  935: $width and $height are optional numerical parameters that will
  936: override the width and height of the popped up window, which may
  937: be useful for certain help topics with big pictures included. 
  938: 
  939: =cut
  940: 
  941: sub help_open_topic {
  942:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  943:     $text = "" if (not defined $text);
  944:     $stayOnPage = 0 if (not defined $stayOnPage);
  945:     if ($env{'browser.interface'} eq 'textual') {
  946: 	$stayOnPage=1;
  947:     }
  948:     $width = 350 if (not defined $width);
  949:     $height = 400 if (not defined $height);
  950:     my $filename = $topic;
  951:     $filename =~ s/ /_/g;
  952: 
  953:     my $template = "";
  954:     my $link;
  955:     
  956:     $topic=~s/\W/\_/g;
  957: 
  958:     if (!$stayOnPage) {
  959: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  960:     } else {
  961: 	$link = "/adm/help/${filename}.hlp";
  962:     }
  963: 
  964:     # Add the text
  965:     if ($text ne "") {
  966: 	$template .= 
  967:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  968:             "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  969:     }
  970: 
  971:     # Add the graphic
  972:     my $title = &mt('Online Help');
  973:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
  974:     $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
  975:                  '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
  976:                  '" title="'.$title.'" /></a>';
  977:     if ($text ne '') {
  978:         $template.='</span></td></tr></table>';
  979:     }
  980:     return $template;
  981: 
  982: }
  983: 
  984: # This is a quicky function for Latex cheatsheet editing, since it 
  985: # appears in at least four places
  986: sub helpLatexCheatsheet {
  987:     my ($topic,$text,$not_author) = @_;
  988:     my $out;
  989:     my $addOther = '';
  990:     if ($topic) {
  991: 	$addOther = &Apache::loncommon::help_open_topic($topic,$text,
  992: 						       undef, undef, 600) .
  993: 							   '</td><td>';
  994:     }
  995:     $out = '<table><tr><td>'.
  996:            $addOther .
  997:            &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
  998:                                                undef,undef,600).
  999:            '</td><td>'.
 1000:            &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
 1001:                                                undef,undef,600).
 1002:            '</td>';
 1003:     unless ($not_author) {
 1004:         $out .= '<td>'.
 1005:                 &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
 1006:                                                     undef,undef,600).
 1007:                 '</td>';
 1008:     }
 1009:     $out .= '</tr></table>';
 1010:     return $out;
 1011: }
 1012: 
 1013: sub general_help {
 1014:     my $helptopic='Student_Intro';
 1015:     if ($env{'request.role'}=~/^(ca|au)/) {
 1016: 	$helptopic='Authoring_Intro';
 1017:     } elsif ($env{'request.role'}=~/^cc/) {
 1018: 	$helptopic='Course_Coordination_Intro';
 1019:     } elsif ($env{'request.role'}=~/^dc/) {
 1020:         $helptopic='Domain_Coordination_Intro';
 1021:     }
 1022:     return $helptopic;
 1023: }
 1024: 
 1025: sub update_help_link {
 1026:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1027:     my $origurl = $ENV{'REQUEST_URI'};
 1028:     $origurl=~s|^/~|/priv/|;
 1029:     my $timestamp = time;
 1030:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1031:         $$datum = &escape($$datum);
 1032:     }
 1033: 
 1034:     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";
 1035:     my $output .= <<"ENDOUTPUT";
 1036: <script type="text/javascript">
 1037: // <![CDATA[
 1038: banner_link = '$banner_link';
 1039: // ]]>
 1040: </script>
 1041: ENDOUTPUT
 1042:     return $output;
 1043: }
 1044: 
 1045: # now just updates the help link and generates a blue icon
 1046: sub help_open_menu {
 1047:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1048: 	= @_;    
 1049:     $stayOnPage = 0 if (not defined $stayOnPage);
 1050:     # only use pop-up help (stayOnPage == 0)
 1051:     # if environment.remote is on (using remote control UI)
 1052:     if ($env{'browser.interface'} eq 'textual' ||
 1053:     	$env{'environment.remote'} eq 'off' ) {
 1054:         $stayOnPage=1;
 1055:     }
 1056:     my $output;
 1057:     if ($component_help) {
 1058: 	if (!$text) {
 1059: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1060: 				       $width,$height);
 1061: 	} else {
 1062: 	    my $help_text;
 1063: 	    $help_text=&unescape($topic);
 1064: 	    $output='<table><tr><td>'.
 1065: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1066: 				 $width,$height).'</td></tr></table>';
 1067: 	}
 1068:     }
 1069:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1070:     return $output.$banner_link;
 1071: }
 1072: 
 1073: sub top_nav_help {
 1074:     my ($text) = @_;
 1075:     $text = &mt($text);
 1076:     my $stay_on_page = 
 1077: 	($env{'browser.interface'}  eq 'textual' ||
 1078: 	 $env{'environment.remote'} eq 'off' );
 1079:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1080: 	                     : "javascript:helpMenu('open')";
 1081:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1082: 
 1083:     my $title = &mt('Get help');
 1084: 
 1085:     return <<"END";
 1086: $banner_link
 1087:  <a href="$link" title="$title">$text</a>
 1088: END
 1089: }
 1090: 
 1091: sub help_menu_js {
 1092:     my ($text) = @_;
 1093: 
 1094:     my $stayOnPage = 
 1095: 	($env{'browser.interface'}  eq 'textual' ||
 1096: 	 $env{'environment.remote'} eq 'off' );
 1097: 
 1098:     my $width = 620;
 1099:     my $height = 600;
 1100:     my $helptopic=&general_help();
 1101:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1102:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1103:     my $start_page =
 1104:         &Apache::loncommon::start_page('Help Menu', undef,
 1105: 				       {'frameset'    => 1,
 1106: 					'js_ready'    => 1,
 1107: 					'add_entries' => {
 1108: 					    'border' => '0',
 1109: 					    'rows'   => "110,*",},});
 1110:     my $end_page =
 1111:         &Apache::loncommon::end_page({'frameset' => 1,
 1112: 				      'js_ready' => 1,});
 1113: 
 1114:     my $template .= <<"ENDTEMPLATE";
 1115: <script type="text/javascript">
 1116: // <!-- BEGIN LON-CAPA Internal
 1117: // <![CDATA[
 1118: var banner_link = '';
 1119: function helpMenu(target) {
 1120:     var caller = this;
 1121:     if (target == 'open') {
 1122:         var newWindow = null;
 1123:         try {
 1124:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1125:         }
 1126:         catch(error) {
 1127:             writeHelp(caller);
 1128:             return;
 1129:         }
 1130:         if (newWindow) {
 1131:             caller = newWindow;
 1132:         }
 1133:     }
 1134:     writeHelp(caller);
 1135:     return;
 1136: }
 1137: function writeHelp(caller) {
 1138:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
 1139:     caller.document.close()
 1140:     caller.focus()
 1141: }
 1142: // ]]>
 1143: // END LON-CAPA Internal -->
 1144: </script>
 1145: ENDTEMPLATE
 1146:     return $template;
 1147: }
 1148: 
 1149: sub help_open_bug {
 1150:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1151:     unless ($env{'user.adv'}) { return ''; }
 1152:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1153:     $text = "" if (not defined $text);
 1154:     $stayOnPage = 0 if (not defined $stayOnPage);
 1155:     if ($env{'browser.interface'} eq 'textual' ||
 1156: 	$env{'environment.remote'} eq 'off' ) {
 1157: 	$stayOnPage=1;
 1158:     }
 1159:     $width = 600 if (not defined $width);
 1160:     $height = 600 if (not defined $height);
 1161: 
 1162:     $topic=~s/\W+/\+/g;
 1163:     my $link='';
 1164:     my $template='';
 1165:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1166: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1167:     if (!$stayOnPage)
 1168:     {
 1169: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1170:     }
 1171:     else
 1172:     {
 1173: 	$link = $url;
 1174:     }
 1175:     # Add the text
 1176:     if ($text ne "")
 1177:     {
 1178: 	$template .= 
 1179:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1180:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1181:     }
 1182: 
 1183:     # Add the graphic
 1184:     my $title = &mt('Report a Bug');
 1185:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1186:     $template .= <<"ENDTEMPLATE";
 1187:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1188: ENDTEMPLATE
 1189:     if ($text ne '') { $template.='</td></tr></table>' };
 1190:     return $template;
 1191: 
 1192: }
 1193: 
 1194: sub help_open_faq {
 1195:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1196:     unless ($env{'user.adv'}) { return ''; }
 1197:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1198:     $text = "" if (not defined $text);
 1199:     $stayOnPage = 0 if (not defined $stayOnPage);
 1200:     if ($env{'browser.interface'} eq 'textual' ||
 1201: 	$env{'environment.remote'} eq 'off' ) {
 1202: 	$stayOnPage=1;
 1203:     }
 1204:     $width = 350 if (not defined $width);
 1205:     $height = 400 if (not defined $height);
 1206: 
 1207:     $topic=~s/\W+/\+/g;
 1208:     my $link='';
 1209:     my $template='';
 1210:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1211:     if (!$stayOnPage)
 1212:     {
 1213: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1214:     }
 1215:     else
 1216:     {
 1217: 	$link = $url;
 1218:     }
 1219: 
 1220:     # Add the text
 1221:     if ($text ne "")
 1222:     {
 1223: 	$template .= 
 1224:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1225:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
 1226:     }
 1227: 
 1228:     # Add the graphic
 1229:     my $title = &mt('View the FAQ');
 1230:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1231:     $template .= <<"ENDTEMPLATE";
 1232:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1233: ENDTEMPLATE
 1234:     if ($text ne '') { $template.='</td></tr></table>' };
 1235:     return $template;
 1236: 
 1237: }
 1238: 
 1239: ###############################################################
 1240: ###############################################################
 1241: 
 1242: =pod
 1243: 
 1244: =item * &change_content_javascript():
 1245: 
 1246: This and the next function allow you to create small sections of an
 1247: otherwise static HTML page that you can update on the fly with
 1248: Javascript, even in Netscape 4.
 1249: 
 1250: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1251: must be written to the HTML page once. It will prove the Javascript
 1252: function "change(name, content)". Calling the change function with the
 1253: name of the section 
 1254: you want to update, matching the name passed to C<changable_area>, and
 1255: the new content you want to put in there, will put the content into
 1256: that area.
 1257: 
 1258: B<Note>: Netscape 4 only reserves enough space for the changable area
 1259: to contain room for the original contents. You need to "make space"
 1260: for whatever changes you wish to make, and be B<sure> to check your
 1261: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1262: it's adequate for updating a one-line status display, but little more.
 1263: This script will set the space to 100% width, so you only need to
 1264: worry about height in Netscape 4.
 1265: 
 1266: Modern browsers are much less limiting, and if you can commit to the
 1267: user not using Netscape 4, this feature may be used freely with
 1268: pretty much any HTML.
 1269: 
 1270: =cut
 1271: 
 1272: sub change_content_javascript {
 1273:     # If we're on Netscape 4, we need to use Layer-based code
 1274:     if ($env{'browser.type'} eq 'netscape' &&
 1275: 	$env{'browser.version'} =~ /^4\./) {
 1276: 	return (<<NETSCAPE4);
 1277: 	function change(name, content) {
 1278: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1279: 	    doc.open();
 1280: 	    doc.write(content);
 1281: 	    doc.close();
 1282: 	}
 1283: NETSCAPE4
 1284:     } else {
 1285: 	# Otherwise, we need to use semi-standards-compliant code
 1286: 	# (technically, "innerHTML" isn't standard but the equivalent
 1287: 	# is really scary, and every useful browser supports it
 1288: 	return (<<DOMBASED);
 1289: 	function change(name, content) {
 1290: 	    element = document.getElementById(name);
 1291: 	    element.innerHTML = content;
 1292: 	}
 1293: DOMBASED
 1294:     }
 1295: }
 1296: 
 1297: =pod
 1298: 
 1299: =item * &changable_area($name,$origContent):
 1300: 
 1301: This provides a "changable area" that can be modified on the fly via
 1302: the Javascript code provided in C<change_content_javascript>. $name is
 1303: the name you will use to reference the area later; do not repeat the
 1304: same name on a given HTML page more then once. $origContent is what
 1305: the area will originally contain, which can be left blank.
 1306: 
 1307: =cut
 1308: 
 1309: sub changable_area {
 1310:     my ($name, $origContent) = @_;
 1311: 
 1312:     if ($env{'browser.type'} eq 'netscape' &&
 1313: 	$env{'browser.version'} =~ /^4\./) {
 1314: 	# If this is netscape 4, we need to use the Layer tag
 1315: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1316:     } else {
 1317: 	return "<span id='$name'>$origContent</span>";
 1318:     }
 1319: }
 1320: 
 1321: =pod
 1322: 
 1323: =item * &viewport_geometry_js 
 1324: 
 1325: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1326: 
 1327: =cut
 1328: 
 1329: 
 1330: sub viewport_geometry_js { 
 1331:     return <<"GEOMETRY";
 1332: var Geometry = {};
 1333: function init_geometry() {
 1334:     if (Geometry.init) { return };
 1335:     Geometry.init=1;
 1336:     if (window.innerHeight) {
 1337:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1338:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1339:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1340:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1341:     }
 1342:     else if (document.documentElement && document.documentElement.clientHeight) {
 1343:         Geometry.getViewportHeight =
 1344:             function() { return document.documentElement.clientHeight; };
 1345:         Geometry.getViewportWidth =
 1346:             function() { return document.documentElement.clientWidth; };
 1347: 
 1348:         Geometry.getHorizontalScroll =
 1349:             function() { return document.documentElement.scrollLeft; };
 1350:         Geometry.getVerticalScroll =
 1351:             function() { return document.documentElement.scrollTop; };
 1352:     }
 1353:     else if (document.body.clientHeight) {
 1354:         Geometry.getViewportHeight =
 1355:             function() { return document.body.clientHeight; };
 1356:         Geometry.getViewportWidth =
 1357:             function() { return document.body.clientWidth; };
 1358:         Geometry.getHorizontalScroll =
 1359:             function() { return document.body.scrollLeft; };
 1360:         Geometry.getVerticalScroll =
 1361:             function() { return document.body.scrollTop; };
 1362:     }
 1363: }
 1364: 
 1365: GEOMETRY
 1366: }
 1367: 
 1368: =pod
 1369: 
 1370: =item * &viewport_size_js()
 1371: 
 1372: 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. 
 1373: 
 1374: =cut
 1375: 
 1376: sub viewport_size_js {
 1377:     my $geometry = &viewport_geometry_js();
 1378:     return <<"DIMS";
 1379: 
 1380: $geometry
 1381: 
 1382: function getViewportDims(width,height) {
 1383:     init_geometry();
 1384:     width.value = Geometry.getViewportWidth();
 1385:     height.value = Geometry.getViewportHeight();
 1386:     return;
 1387: }
 1388: 
 1389: DIMS
 1390: }
 1391: 
 1392: =pod
 1393: 
 1394: =item * &resize_textarea_js()
 1395: 
 1396: emits the needed javascript to resize a textarea to be as big as possible
 1397: 
 1398: creates a function resize_textrea that takes two IDs first should be
 1399: the id of the element to resize, second should be the id of a div that
 1400: surrounds everything that comes after the textarea, this routine needs
 1401: to be attached to the <body> for the onload and onresize events.
 1402: 
 1403: =back
 1404: 
 1405: =cut
 1406: 
 1407: sub resize_textarea_js {
 1408:     my $geometry = &viewport_geometry_js();
 1409:     return <<"RESIZE";
 1410:     <script type="text/javascript">
 1411: // <![CDATA[
 1412: $geometry
 1413: 
 1414: function getX(element) {
 1415:     var x = 0;
 1416:     while (element) {
 1417: 	x += element.offsetLeft;
 1418: 	element = element.offsetParent;
 1419:     }
 1420:     return x;
 1421: }
 1422: function getY(element) {
 1423:     var y = 0;
 1424:     while (element) {
 1425: 	y += element.offsetTop;
 1426: 	element = element.offsetParent;
 1427:     }
 1428:     return y;
 1429: }
 1430: 
 1431: 
 1432: function resize_textarea(textarea_id,bottom_id) {
 1433:     init_geometry();
 1434:     var textarea        = document.getElementById(textarea_id);
 1435:     //alert(textarea);
 1436: 
 1437:     var textarea_top    = getY(textarea);
 1438:     var textarea_height = textarea.offsetHeight;
 1439:     var bottom          = document.getElementById(bottom_id);
 1440:     var bottom_top      = getY(bottom);
 1441:     var bottom_height   = bottom.offsetHeight;
 1442:     var window_height   = Geometry.getViewportHeight();
 1443:     var fudge           = 23;
 1444:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1445:     if (new_height < 300) {
 1446: 	new_height = 300;
 1447:     }
 1448:     textarea.style.height=new_height+'px';
 1449: }
 1450: // ]]>
 1451: </script>
 1452: RESIZE
 1453: 
 1454: }
 1455: 
 1456: =pod
 1457: 
 1458: =head1 Excel and CSV file utility routines
 1459: 
 1460: =over 4
 1461: 
 1462: =cut
 1463: 
 1464: ###############################################################
 1465: ###############################################################
 1466: 
 1467: =pod
 1468: 
 1469: =item * &csv_translate($text) 
 1470: 
 1471: Translate $text to allow it to be output as a 'comma separated values' 
 1472: format.
 1473: 
 1474: =cut
 1475: 
 1476: ###############################################################
 1477: ###############################################################
 1478: sub csv_translate {
 1479:     my $text = shift;
 1480:     $text =~ s/\"/\"\"/g;
 1481:     $text =~ s/\n/ /g;
 1482:     return $text;
 1483: }
 1484: 
 1485: ###############################################################
 1486: ###############################################################
 1487: 
 1488: =pod
 1489: 
 1490: =item * &define_excel_formats()
 1491: 
 1492: Define some commonly used Excel cell formats.
 1493: 
 1494: Currently supported formats:
 1495: 
 1496: =over 4
 1497: 
 1498: =item header
 1499: 
 1500: =item bold
 1501: 
 1502: =item h1
 1503: 
 1504: =item h2
 1505: 
 1506: =item h3
 1507: 
 1508: =item h4
 1509: 
 1510: =item i
 1511: 
 1512: =item date
 1513: 
 1514: =back
 1515: 
 1516: Inputs: $workbook
 1517: 
 1518: Returns: $format, a hash reference.
 1519: 
 1520: =cut
 1521: 
 1522: ###############################################################
 1523: ###############################################################
 1524: sub define_excel_formats {
 1525:     my ($workbook) = @_;
 1526:     my $format;
 1527:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1528:                                                 bottom    => 1,
 1529:                                                 align     => 'center');
 1530:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1531:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1532:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1533:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1534:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1535:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1536:     $format->{'date'} = $workbook->add_format(num_format=>
 1537:                                             'mm/dd/yyyy hh:mm:ss');
 1538:     return $format;
 1539: }
 1540: 
 1541: ###############################################################
 1542: ###############################################################
 1543: 
 1544: =pod
 1545: 
 1546: =item * &create_workbook()
 1547: 
 1548: Create an Excel worksheet.  If it fails, output message on the
 1549: request object and return undefs.
 1550: 
 1551: Inputs: Apache request object
 1552: 
 1553: Returns (undef) on failure, 
 1554:     Excel worksheet object, scalar with filename, and formats 
 1555:     from &Apache::loncommon::define_excel_formats on success
 1556: 
 1557: =cut
 1558: 
 1559: ###############################################################
 1560: ###############################################################
 1561: sub create_workbook {
 1562:     my ($r) = @_;
 1563:         #
 1564:     # Create the excel spreadsheet
 1565:     my $filename = '/prtspool/'.
 1566:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1567:         time.'_'.rand(1000000000).'.xls';
 1568:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1569:     if (! defined($workbook)) {
 1570:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1571:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1572:                             "This error has been logged.  ".
 1573:                             "Please alert your LON-CAPA administrator").
 1574:                   '</p>');
 1575:         return (undef);
 1576:     }
 1577:     #
 1578:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1579:     #
 1580:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1581:     return ($workbook,$filename,$format);
 1582: }
 1583: 
 1584: ###############################################################
 1585: ###############################################################
 1586: 
 1587: =pod
 1588: 
 1589: =item * &create_text_file()
 1590: 
 1591: Create a file to write to and eventually make available to the user.
 1592: If file creation fails, outputs an error message on the request object and 
 1593: return undefs.
 1594: 
 1595: Inputs: Apache request object, and file suffix
 1596: 
 1597: Returns (undef) on failure, 
 1598:     Filehandle and filename on success.
 1599: 
 1600: =cut
 1601: 
 1602: ###############################################################
 1603: ###############################################################
 1604: sub create_text_file {
 1605:     my ($r,$suffix) = @_;
 1606:     if (! defined($suffix)) { $suffix = 'txt'; };
 1607:     my $fh;
 1608:     my $filename = '/prtspool/'.
 1609:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1610:         time.'_'.rand(1000000000).'.'.$suffix;
 1611:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1612:     if (! defined($fh)) {
 1613:         $r->log_error("Couldn't open $filename for output $!");
 1614:         $r->print(&mt('Problems occurred in creating the output file. '
 1615:                      .'This error has been logged. '
 1616:                      .'Please alert your LON-CAPA administrator.'));
 1617:     }
 1618:     return ($fh,$filename)
 1619: }
 1620: 
 1621: 
 1622: =pod 
 1623: 
 1624: =back
 1625: 
 1626: =cut
 1627: 
 1628: ###############################################################
 1629: ##        Home server <option> list generating code          ##
 1630: ###############################################################
 1631: 
 1632: # ------------------------------------------
 1633: 
 1634: sub domain_select {
 1635:     my ($name,$value,$multiple)=@_;
 1636:     my %domains=map { 
 1637: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1638:     } &Apache::lonnet::all_domains();
 1639:     if ($multiple) {
 1640: 	$domains{''}=&mt('Any domain');
 1641: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1642: 	return &multiple_select_form($name,$value,4,\%domains);
 1643:     } else {
 1644: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1645: 	return &select_form($name,$value,%domains);
 1646:     }
 1647: }
 1648: 
 1649: #-------------------------------------------
 1650: 
 1651: =pod
 1652: 
 1653: =head1 Routines for form select boxes
 1654: 
 1655: =over 4
 1656: 
 1657: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1658: 
 1659: Returns a string containing a <select> element int multiple mode
 1660: 
 1661: 
 1662: Args:
 1663:   $name - name of the <select> element
 1664:   $value - scalar or array ref of values that should already be selected
 1665:   $size - number of rows long the select element is
 1666:   $hash - the elements should be 'option' => 'shown text'
 1667:           (shown text should already have been &mt())
 1668:   $order - (optional) array ref of the order to show the elements in
 1669: 
 1670: =cut
 1671: 
 1672: #-------------------------------------------
 1673: sub multiple_select_form {
 1674:     my ($name,$value,$size,$hash,$order)=@_;
 1675:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1676:     my $output='';
 1677:     if (! defined($size)) {
 1678:         $size = 4;
 1679:         if (scalar(keys(%$hash))<4) {
 1680:             $size = scalar(keys(%$hash));
 1681:         }
 1682:     }
 1683:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1684:     my @order;
 1685:     if (ref($order) eq 'ARRAY')  {
 1686:         @order = @{$order};
 1687:     } else {
 1688:         @order = sort(keys(%$hash));
 1689:     }
 1690:     if (exists($$hash{'select_form_order'})) {
 1691:         @order = @{$$hash{'select_form_order'}};
 1692:     }
 1693:         
 1694:     foreach my $key (@order) {
 1695:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1696:         $output.='selected="selected" ' if ($selected{$key});
 1697:         $output.='>'.$hash->{$key}."</option>\n";
 1698:     }
 1699:     $output.="</select>\n";
 1700:     return $output;
 1701: }
 1702: 
 1703: #-------------------------------------------
 1704: 
 1705: =pod
 1706: 
 1707: =item * &select_form($defdom,$name,%hash)
 1708: 
 1709: Returns a string containing a <select name='$name' size='1'> form to 
 1710: allow a user to select options from a hash option_name => displayed text.  
 1711: See lonrights.pm for an example invocation and use.
 1712: 
 1713: =cut
 1714: 
 1715: #-------------------------------------------
 1716: sub select_form {
 1717:     my ($def,$name,%hash) = @_;
 1718:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1719:     my @keys;
 1720:     if (exists($hash{'select_form_order'})) {
 1721: 	@keys=@{$hash{'select_form_order'}};
 1722:     } else {
 1723: 	@keys=sort(keys(%hash));
 1724:     }
 1725:     foreach my $key (@keys) {
 1726:         $selectform.=
 1727: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1728:             ($key eq $def ? 'selected="selected" ' : '').
 1729:                 ">".&mt($hash{$key})."</option>\n";
 1730:     }
 1731:     $selectform.="</select>";
 1732:     return $selectform;
 1733: }
 1734: 
 1735: # For display filters
 1736: 
 1737: sub display_filter {
 1738:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1739:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1740:     return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
 1741: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1742: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1743: 	   '</label></span> <span class="LC_nobreak">'.
 1744:            &mt('Filter [_1]',
 1745: 	   &select_form($env{'form.displayfilter'},
 1746: 			'displayfilter',
 1747: 			('currentfolder' => 'Current folder/page',
 1748: 			 'containing' => 'Containing phrase',
 1749: 			 'none' => 'None'))).
 1750: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
 1751: }
 1752: 
 1753: sub gradeleveldescription {
 1754:     my $gradelevel=shift;
 1755:     my %gradelevels=(0 => 'Not specified',
 1756: 		     1 => 'Grade 1',
 1757: 		     2 => 'Grade 2',
 1758: 		     3 => 'Grade 3',
 1759: 		     4 => 'Grade 4',
 1760: 		     5 => 'Grade 5',
 1761: 		     6 => 'Grade 6',
 1762: 		     7 => 'Grade 7',
 1763: 		     8 => 'Grade 8',
 1764: 		     9 => 'Grade 9',
 1765: 		     10 => 'Grade 10',
 1766: 		     11 => 'Grade 11',
 1767: 		     12 => 'Grade 12',
 1768: 		     13 => 'Grade 13',
 1769: 		     14 => '100 Level',
 1770: 		     15 => '200 Level',
 1771: 		     16 => '300 Level',
 1772: 		     17 => '400 Level',
 1773: 		     18 => 'Graduate Level');
 1774:     return &mt($gradelevels{$gradelevel});
 1775: }
 1776: 
 1777: sub select_level_form {
 1778:     my ($deflevel,$name)=@_;
 1779:     unless ($deflevel) { $deflevel=0; }
 1780:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1781:     for (my $i=0; $i<=18; $i++) {
 1782:         $selectform.="<option value=\"$i\" ".
 1783:             ($i==$deflevel ? 'selected="selected" ' : '').
 1784:                 ">".&gradeleveldescription($i)."</option>\n";
 1785:     }
 1786:     $selectform.="</select>";
 1787:     return $selectform;
 1788: }
 1789: 
 1790: #-------------------------------------------
 1791: 
 1792: =pod
 1793: 
 1794: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$autosubmit)
 1795: 
 1796: Returns a string containing a <select name='$name' size='1'> form to 
 1797: allow a user to select the domain to preform an operation in.  
 1798: See loncreateuser.pm for an example invocation and use.
 1799: 
 1800: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1801: selected");
 1802: 
 1803: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 1804: 
 1805: If the $autosubmit flag is set, the form containing the domain selector will be auto-submitted by an onchange action.
 1806: 
 1807: =cut
 1808: 
 1809: #-------------------------------------------
 1810: sub select_dom_form {
 1811:     my ($defdom,$name,$includeempty,$showdomdesc,$autosubmit) = @_;
 1812:     my $onchange;
 1813:     if ($autosubmit) {
 1814:         $onchange = ' onchange="this.form.submit()"';
 1815:     }
 1816:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1817:     if ($includeempty) { @domains=('',@domains); }
 1818:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 1819:     foreach my $dom (@domains) {
 1820:         $selectdomain.="<option value=\"$dom\" ".
 1821:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1822:         if ($showdomdesc) {
 1823:             if ($dom ne '') {
 1824:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1825:                 if ($domdesc ne '') {
 1826:                     $selectdomain .= ' ('.$domdesc.')';
 1827:                 }
 1828:             } 
 1829:         }
 1830:         $selectdomain .= "</option>\n";
 1831:     }
 1832:     $selectdomain.="</select>";
 1833:     return $selectdomain;
 1834: }
 1835: 
 1836: #-------------------------------------------
 1837: 
 1838: =pod
 1839: 
 1840: =item * &home_server_form_item($domain,$name,$defaultflag)
 1841: 
 1842: input: 4 arguments (two required, two optional) - 
 1843:     $domain - domain of new user
 1844:     $name - name of form element
 1845:     $default - Value of 'default' causes a default item to be first 
 1846:                             option, and selected by default. 
 1847:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1848:                             if 1 server found, or default, if 0 found.
 1849: output: returns 2 items: 
 1850: (a) form element which contains either:
 1851:    (i) <select name="$name">
 1852:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1853:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1854:        </select>
 1855:        form item if there are multiple library servers in $domain, or
 1856:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1857:        if there is only one library server in $domain.
 1858: 
 1859: (b) number of library servers found.
 1860: 
 1861: See loncreateuser.pm for example of use.
 1862: 
 1863: =cut
 1864: 
 1865: #-------------------------------------------
 1866: sub home_server_form_item {
 1867:     my ($domain,$name,$default,$hide) = @_;
 1868:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1869:     my $result;
 1870:     my $numlib = keys(%servers);
 1871:     if ($numlib > 1) {
 1872:         $result .= '<select name="'.$name.'" />'."\n";
 1873:         if ($default) {
 1874:             $result .= '<option value="default" selected="selected">'.&mt('default').
 1875:                        '</option>'."\n";
 1876:         }
 1877:         foreach my $hostid (sort(keys(%servers))) {
 1878:             $result.= '<option value="'.$hostid.'">'.
 1879: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1880:         }
 1881:         $result .= '</select>'."\n";
 1882:     } elsif ($numlib == 1) {
 1883:         my $hostid;
 1884:         foreach my $item (keys(%servers)) {
 1885:             $hostid = $item;
 1886:         }
 1887:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1888:                    $hostid.'" />';
 1889:                    if (!$hide) {
 1890:                        $result .= $hostid.' '.$servers{$hostid};
 1891:                    }
 1892:                    $result .= "\n";
 1893:     } elsif ($default) {
 1894:         $result .= '<input type="hidden" name="'.$name.
 1895:                    '" value="default" />';
 1896:                    if (!$hide) {
 1897:                        $result .= &mt('default');
 1898:                    }
 1899:                    $result .= "\n";
 1900:     }
 1901:     return ($result,$numlib);
 1902: }
 1903: 
 1904: =pod
 1905: 
 1906: =back 
 1907: 
 1908: =cut
 1909: 
 1910: ###############################################################
 1911: ##                  Decoding User Agent                      ##
 1912: ###############################################################
 1913: 
 1914: =pod
 1915: 
 1916: =head1 Decoding the User Agent
 1917: 
 1918: =over 4
 1919: 
 1920: =item * &decode_user_agent()
 1921: 
 1922: Inputs: $r
 1923: 
 1924: Outputs:
 1925: 
 1926: =over 4
 1927: 
 1928: =item * $httpbrowser
 1929: 
 1930: =item * $clientbrowser
 1931: 
 1932: =item * $clientversion
 1933: 
 1934: =item * $clientmathml
 1935: 
 1936: =item * $clientunicode
 1937: 
 1938: =item * $clientos
 1939: 
 1940: =back
 1941: 
 1942: =back 
 1943: 
 1944: =cut
 1945: 
 1946: ###############################################################
 1947: ###############################################################
 1948: sub decode_user_agent {
 1949:     my ($r)=@_;
 1950:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1951:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1952:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1953:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1954:     my $clientbrowser='unknown';
 1955:     my $clientversion='0';
 1956:     my $clientmathml='';
 1957:     my $clientunicode='0';
 1958:     for (my $i=0;$i<=$#browsertype;$i++) {
 1959:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1960: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1961: 	    $clientbrowser=$bname;
 1962:             $httpbrowser=~/$vreg/i;
 1963: 	    $clientversion=$1;
 1964:             $clientmathml=($clientversion>=$minv);
 1965:             $clientunicode=($clientversion>=$univ);
 1966: 	}
 1967:     }
 1968:     my $clientos='unknown';
 1969:     if (($httpbrowser=~/linux/i) ||
 1970:         ($httpbrowser=~/unix/i) ||
 1971:         ($httpbrowser=~/ux/i) ||
 1972:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1973:     if (($httpbrowser=~/vax/i) ||
 1974:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1975:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1976:     if (($httpbrowser=~/mac/i) ||
 1977:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1978:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1979:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1980:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1981:             $clientunicode,$clientos,);
 1982: }
 1983: 
 1984: ###############################################################
 1985: ##    Authentication changing form generation subroutines    ##
 1986: ###############################################################
 1987: ##
 1988: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1989: ## hash, and have reasonable default values.
 1990: ##
 1991: ##    formname = the name given in the <form> tag.
 1992: #-------------------------------------------
 1993: 
 1994: =pod
 1995: 
 1996: =head1 Authentication Routines
 1997: 
 1998: =over 4
 1999: 
 2000: =item * &authform_xxxxxx()
 2001: 
 2002: The authform_xxxxxx subroutines provide javascript and html forms which 
 2003: handle some of the conveniences required for authentication forms.  
 2004: This is not an optimal method, but it works.  
 2005: 
 2006: =over 4
 2007: 
 2008: =item * authform_header
 2009: 
 2010: =item * authform_authorwarning
 2011: 
 2012: =item * authform_nochange
 2013: 
 2014: =item * authform_kerberos
 2015: 
 2016: =item * authform_internal
 2017: 
 2018: =item * authform_filesystem
 2019: 
 2020: =back
 2021: 
 2022: See loncreateuser.pm for invocation and use examples.
 2023: 
 2024: =cut
 2025: 
 2026: #-------------------------------------------
 2027: sub authform_header{  
 2028:     my %in = (
 2029:         formname => 'cu',
 2030:         kerb_def_dom => '',
 2031:         @_,
 2032:     );
 2033:     $in{'formname'} = 'document.' . $in{'formname'};
 2034:     my $result='';
 2035: 
 2036: #---------------------------------------------- Code for upper case translation
 2037:     my $Javascript_toUpperCase;
 2038:     unless ($in{kerb_def_dom}) {
 2039:         $Javascript_toUpperCase =<<"END";
 2040:         switch (choice) {
 2041:            case 'krb': currentform.elements[choicearg].value =
 2042:                currentform.elements[choicearg].value.toUpperCase();
 2043:                break;
 2044:            default:
 2045:         }
 2046: END
 2047:     } else {
 2048:         $Javascript_toUpperCase = "";
 2049:     }
 2050: 
 2051:     my $radioval = "'nochange'";
 2052:     if (defined($in{'curr_authtype'})) {
 2053:         if ($in{'curr_authtype'} ne '') {
 2054:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2055:         }
 2056:     }
 2057:     my $argfield = 'null';
 2058:     if (defined($in{'mode'})) {
 2059:         if ($in{'mode'} eq 'modifycourse')  {
 2060:             if (defined($in{'curr_autharg'})) {
 2061:                 if ($in{'curr_autharg'} ne '') {
 2062:                     $argfield = "'$in{'curr_autharg'}'";
 2063:                 }
 2064:             }
 2065:         }
 2066:     }
 2067: 
 2068:     $result.=<<"END";
 2069: var current = new Object();
 2070: current.radiovalue = $radioval;
 2071: current.argfield = $argfield;
 2072: 
 2073: function changed_radio(choice,currentform) {
 2074:     var choicearg = choice + 'arg';
 2075:     // If a radio button in changed, we need to change the argfield
 2076:     if (current.radiovalue != choice) {
 2077:         current.radiovalue = choice;
 2078:         if (current.argfield != null) {
 2079:             currentform.elements[current.argfield].value = '';
 2080:         }
 2081:         if (choice == 'nochange') {
 2082:             current.argfield = null;
 2083:         } else {
 2084:             current.argfield = choicearg;
 2085:             switch(choice) {
 2086:                 case 'krb': 
 2087:                     currentform.elements[current.argfield].value = 
 2088:                         "$in{'kerb_def_dom'}";
 2089:                 break;
 2090:               default:
 2091:                 break;
 2092:             }
 2093:         }
 2094:     }
 2095:     return;
 2096: }
 2097: 
 2098: function changed_text(choice,currentform) {
 2099:     var choicearg = choice + 'arg';
 2100:     if (currentform.elements[choicearg].value !='') {
 2101:         $Javascript_toUpperCase
 2102:         // clear old field
 2103:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2104:             currentform.elements[current.argfield].value = '';
 2105:         }
 2106:         current.argfield = choicearg;
 2107:     }
 2108:     set_auth_radio_buttons(choice,currentform);
 2109:     return;
 2110: }
 2111: 
 2112: function set_auth_radio_buttons(newvalue,currentform) {
 2113:     var i=0;
 2114:     while (i < currentform.login.length) {
 2115:         if (currentform.login[i].value == newvalue) { break; }
 2116:         i++;
 2117:     }
 2118:     if (i == currentform.login.length) {
 2119:         return;
 2120:     }
 2121:     current.radiovalue = newvalue;
 2122:     currentform.login[i].checked = true;
 2123:     return;
 2124: }
 2125: END
 2126:     return $result;
 2127: }
 2128: 
 2129: sub authform_authorwarning{
 2130:     my $result='';
 2131:     $result='<i>'.
 2132:         &mt('As a general rule, only authors or co-authors should be '.
 2133:             'filesystem authenticated '.
 2134:             '(which allows access to the server filesystem).')."</i>\n";
 2135:     return $result;
 2136: }
 2137: 
 2138: sub authform_nochange{  
 2139:     my %in = (
 2140:               formname => 'document.cu',
 2141:               kerb_def_dom => 'MSU.EDU',
 2142:               @_,
 2143:           );
 2144:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 2145:     my $result;
 2146:     if (keys(%can_assign) == 0) {
 2147:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 2148:     } else {
 2149:         $result = '<label>'.&mt('[_1] Do not change login data',
 2150:                   '<input type="radio" name="login" value="nochange" '.
 2151:                   'checked="checked" onclick="'.
 2152:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2153: 	    '</label>';
 2154:     }
 2155:     return $result;
 2156: }
 2157: 
 2158: sub authform_kerberos {
 2159:     my %in = (
 2160:               formname => 'document.cu',
 2161:               kerb_def_dom => 'MSU.EDU',
 2162:               kerb_def_auth => 'krb4',
 2163:               @_,
 2164:               );
 2165:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2166:         $autharg,$jscall);
 2167:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2168:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2169:        $check5 = ' checked="checked"';
 2170:     } else {
 2171:        $check4 = ' checked="checked"';
 2172:     }
 2173:     $krbarg = $in{'kerb_def_dom'};
 2174:     if (defined($in{'curr_authtype'})) {
 2175:         if ($in{'curr_authtype'} eq 'krb') {
 2176:             $krbcheck = ' checked="checked"';
 2177:             if (defined($in{'mode'})) {
 2178:                 if ($in{'mode'} eq 'modifyuser') {
 2179:                     $krbcheck = '';
 2180:                 }
 2181:             }
 2182:             if (defined($in{'curr_kerb_ver'})) {
 2183:                 if ($in{'curr_krb_ver'} eq '5') {
 2184:                     $check5 = ' checked="checked"';
 2185:                     $check4 = '';
 2186:                 } else {
 2187:                     $check4 = ' checked="checked"';
 2188:                     $check5 = '';
 2189:                 }
 2190:             }
 2191:             if (defined($in{'curr_autharg'})) {
 2192:                 $krbarg = $in{'curr_autharg'};
 2193:             }
 2194:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2195:                 if (defined($in{'curr_autharg'})) {
 2196:                     $result = 
 2197:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2198:         $in{'curr_autharg'},$krbver);
 2199:                 } else {
 2200:                     $result =
 2201:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2202:                 }
 2203:                 return $result; 
 2204:             }
 2205:         }
 2206:     } else {
 2207:         if ($authnum == 1) {
 2208:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2209:         }
 2210:     }
 2211:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2212:         return;
 2213:     } elsif ($authtype eq '') {
 2214:         if (defined($in{'mode'})) {
 2215:             if ($in{'mode'} eq 'modifycourse') {
 2216:                 if ($authnum == 1) {
 2217:                     $authtype = '<input type="hidden" name="login" value="krb" />';
 2218:                 }
 2219:             }
 2220:         }
 2221:     }
 2222:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2223:     if ($authtype eq '') {
 2224:         $authtype = '<input type="radio" name="login" value="krb" '.
 2225:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2226:                     $krbcheck.' />';
 2227:     }
 2228:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2229:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 2230:          $in{'curr_authtype'} eq 'krb5') ||
 2231:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 2232:          $in{'curr_authtype'} eq 'krb4')) {
 2233:         $result .= &mt
 2234:         ('[_1] Kerberos authenticated with domain [_2] '.
 2235:          '[_3] Version 4 [_4] Version 5 [_5]',
 2236:          '<label>'.$authtype,
 2237:          '</label><input type="text" size="10" name="krbarg" '.
 2238:              'value="'.$krbarg.'" '.
 2239:              'onchange="'.$jscall.'" />',
 2240:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2241:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2242: 	 '</label>');
 2243:     } elsif ($can_assign{'krb4'}) {
 2244:         $result .= &mt
 2245:         ('[_1] Kerberos authenticated with domain [_2] '.
 2246:          '[_3] Version 4 [_4]',
 2247:          '<label>'.$authtype,
 2248:          '</label><input type="text" size="10" name="krbarg" '.
 2249:              'value="'.$krbarg.'" '.
 2250:              'onchange="'.$jscall.'" />',
 2251:          '<label><input type="hidden" name="krbver" value="4" />',
 2252:          '</label>');
 2253:     } elsif ($can_assign{'krb5'}) {
 2254:         $result .= &mt
 2255:         ('[_1] Kerberos authenticated with domain [_2] '.
 2256:          '[_3] Version 5 [_4]',
 2257:          '<label>'.$authtype,
 2258:          '</label><input type="text" size="10" name="krbarg" '.
 2259:              'value="'.$krbarg.'" '.
 2260:              'onchange="'.$jscall.'" />',
 2261:          '<label><input type="hidden" name="krbver" value="5" />',
 2262:          '</label>');
 2263:     }
 2264:     return $result;
 2265: }
 2266: 
 2267: sub authform_internal{  
 2268:     my %in = (
 2269:                 formname => 'document.cu',
 2270:                 kerb_def_dom => 'MSU.EDU',
 2271:                 @_,
 2272:                 );
 2273:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2274:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2275:     if (defined($in{'curr_authtype'})) {
 2276:         if ($in{'curr_authtype'} eq 'int') {
 2277:             if ($can_assign{'int'}) {
 2278:                 $intcheck = 'checked="checked" ';
 2279:                 if (defined($in{'mode'})) {
 2280:                     if ($in{'mode'} eq 'modifyuser') {
 2281:                         $intcheck = '';
 2282:                     }
 2283:                 }
 2284:                 if (defined($in{'curr_autharg'})) {
 2285:                     $intarg = $in{'curr_autharg'};
 2286:                 }
 2287:             } else {
 2288:                 $result = &mt('Currently internally authenticated.');
 2289:                 return $result;
 2290:             }
 2291:         }
 2292:     } else {
 2293:         if ($authnum == 1) {
 2294:             $authtype = '<input type="hidden" name="login" value="int" />';
 2295:         }
 2296:     }
 2297:     if (!$can_assign{'int'}) {
 2298:         return;
 2299:     } elsif ($authtype eq '') {
 2300:         if (defined($in{'mode'})) {
 2301:             if ($in{'mode'} eq 'modifycourse') {
 2302:                 if ($authnum == 1) {
 2303:                     $authtype = '<input type="hidden" name="login" value="int" />';
 2304:                 }
 2305:             }
 2306:         }
 2307:     }
 2308:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2309:     if ($authtype eq '') {
 2310:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2311:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2312:     }
 2313:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2314:                $intarg.'" onchange="'.$jscall.'" />';
 2315:     $result = &mt
 2316:         ('[_1] Internally authenticated (with initial password [_2])',
 2317:          '<label>'.$authtype,'</label>'.$autharg);
 2318:     $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>';
 2319:     return $result;
 2320: }
 2321: 
 2322: sub authform_local{  
 2323:     my %in = (
 2324:               formname => 'document.cu',
 2325:               kerb_def_dom => 'MSU.EDU',
 2326:               @_,
 2327:               );
 2328:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2329:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2330:     if (defined($in{'curr_authtype'})) {
 2331:         if ($in{'curr_authtype'} eq 'loc') {
 2332:             if ($can_assign{'loc'}) {
 2333:                 $loccheck = 'checked="checked" ';
 2334:                 if (defined($in{'mode'})) {
 2335:                     if ($in{'mode'} eq 'modifyuser') {
 2336:                         $loccheck = '';
 2337:                     }
 2338:                 }
 2339:                 if (defined($in{'curr_autharg'})) {
 2340:                     $locarg = $in{'curr_autharg'};
 2341:                 }
 2342:             } else {
 2343:                 $result = &mt('Currently using local (institutional) authentication.');
 2344:                 return $result;
 2345:             }
 2346:         }
 2347:     } else {
 2348:         if ($authnum == 1) {
 2349:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2350:         }
 2351:     }
 2352:     if (!$can_assign{'loc'}) {
 2353:         return;
 2354:     } elsif ($authtype eq '') {
 2355:         if (defined($in{'mode'})) {
 2356:             if ($in{'mode'} eq 'modifycourse') {
 2357:                 if ($authnum == 1) {
 2358:                     $authtype = '<input type="hidden" name="login" value="loc" />';
 2359:                 }
 2360:             }
 2361:         }
 2362:     }
 2363:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2364:     if ($authtype eq '') {
 2365:         $authtype = '<input type="radio" name="login" value="loc" '.
 2366:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2367:                     $jscall.'" />';
 2368:     }
 2369:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2370:                $locarg.'" onchange="'.$jscall.'" />';
 2371:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2372:                   '<label>'.$authtype,'</label>'.$autharg);
 2373:     return $result;
 2374: }
 2375: 
 2376: sub authform_filesystem{  
 2377:     my %in = (
 2378:               formname => 'document.cu',
 2379:               kerb_def_dom => 'MSU.EDU',
 2380:               @_,
 2381:               );
 2382:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2383:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2384:     if (defined($in{'curr_authtype'})) {
 2385:         if ($in{'curr_authtype'} eq 'fsys') {
 2386:             if ($can_assign{'fsys'}) {
 2387:                 $fsyscheck = 'checked="checked" ';
 2388:                 if (defined($in{'mode'})) {
 2389:                     if ($in{'mode'} eq 'modifyuser') {
 2390:                         $fsyscheck = '';
 2391:                     }
 2392:                 }
 2393:             } else {
 2394:                 $result = &mt('Currently Filesystem Authenticated.');
 2395:                 return $result;
 2396:             }           
 2397:         }
 2398:     } else {
 2399:         if ($authnum == 1) {
 2400:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2401:         }
 2402:     }
 2403:     if (!$can_assign{'fsys'}) {
 2404:         return;
 2405:     } elsif ($authtype eq '') {
 2406:         if (defined($in{'mode'})) {
 2407:             if ($in{'mode'} eq 'modifycourse') {
 2408:                 if ($authnum == 1) {
 2409:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
 2410:                 }
 2411:             }
 2412:         }
 2413:     }
 2414:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2415:     if ($authtype eq '') {
 2416:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2417:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2418:                     $jscall.'" />';
 2419:     }
 2420:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2421:                ' onchange="'.$jscall.'" />';
 2422:     $result = &mt
 2423:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2424:          '<label><input type="radio" name="login" value="fsys" '.
 2425:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2426:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2427:                   'onchange="'.$jscall.'" />');
 2428:     return $result;
 2429: }
 2430: 
 2431: sub get_assignable_auth {
 2432:     my ($dom) = @_;
 2433:     if ($dom eq '') {
 2434:         $dom = $env{'request.role.domain'};
 2435:     }
 2436:     my %can_assign = (
 2437:                           krb4 => 1,
 2438:                           krb5 => 1,
 2439:                           int  => 1,
 2440:                           loc  => 1,
 2441:                      );
 2442:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2443:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2444:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2445:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2446:             my $context;
 2447:             if ($env{'request.role'} =~ /^au/) {
 2448:                 $context = 'author';
 2449:             } elsif ($env{'request.role'} =~ /^dc/) {
 2450:                 $context = 'domain';
 2451:             } elsif ($env{'request.course.id'}) {
 2452:                 $context = 'course';
 2453:             }
 2454:             if ($context) {
 2455:                 if (ref($authhash->{$context}) eq 'HASH') {
 2456:                    %can_assign = %{$authhash->{$context}}; 
 2457:                 }
 2458:             }
 2459:         }
 2460:     }
 2461:     my $authnum = 0;
 2462:     foreach my $key (keys(%can_assign)) {
 2463:         if ($can_assign{$key}) {
 2464:             $authnum ++;
 2465:         }
 2466:     }
 2467:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2468:         $authnum --;
 2469:     }
 2470:     return ($authnum,%can_assign);
 2471: }
 2472: 
 2473: ###############################################################
 2474: ##    Get Kerberos Defaults for Domain                 ##
 2475: ###############################################################
 2476: ##
 2477: ## Returns default kerberos version and an associated argument
 2478: ## as listed in file domain.tab. If not listed, provides
 2479: ## appropriate default domain and kerberos version.
 2480: ##
 2481: #-------------------------------------------
 2482: 
 2483: =pod
 2484: 
 2485: =item * &get_kerberos_defaults()
 2486: 
 2487: get_kerberos_defaults($target_domain) returns the default kerberos
 2488: version and domain. If not found, it defaults to version 4 and the 
 2489: domain of the server.
 2490: 
 2491: =over 4
 2492: 
 2493: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2494: 
 2495: =back
 2496: 
 2497: =back
 2498: 
 2499: =cut
 2500: 
 2501: #-------------------------------------------
 2502: sub get_kerberos_defaults {
 2503:     my $domain=shift;
 2504:     my ($krbdef,$krbdefdom);
 2505:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2506:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2507:         $krbdef = $domdefaults{'auth_def'};
 2508:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2509:     } else {
 2510:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2511:         my $krbdefdom=$1;
 2512:         $krbdefdom=~tr/a-z/A-Z/;
 2513:         $krbdef = "krb4";
 2514:     }
 2515:     return ($krbdef,$krbdefdom);
 2516: }
 2517: 
 2518: 
 2519: ###############################################################
 2520: ##                Thesaurus Functions                        ##
 2521: ###############################################################
 2522: 
 2523: =pod
 2524: 
 2525: =head1 Thesaurus Functions
 2526: 
 2527: =over 4
 2528: 
 2529: =item * &initialize_keywords()
 2530: 
 2531: Initializes the package variable %Keywords if it is empty.  Uses the
 2532: package variable $thesaurus_db_file.
 2533: 
 2534: =cut
 2535: 
 2536: ###################################################
 2537: 
 2538: sub initialize_keywords {
 2539:     return 1 if (scalar keys(%Keywords));
 2540:     # If we are here, %Keywords is empty, so fill it up
 2541:     #   Make sure the file we need exists...
 2542:     if (! -e $thesaurus_db_file) {
 2543:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2544:                                  " failed because it does not exist");
 2545:         return 0;
 2546:     }
 2547:     #   Set up the hash as a database
 2548:     my %thesaurus_db;
 2549:     if (! tie(%thesaurus_db,'GDBM_File',
 2550:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2551:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2552:                                  $thesaurus_db_file);
 2553:         return 0;
 2554:     } 
 2555:     #  Get the average number of appearances of a word.
 2556:     my $avecount = $thesaurus_db{'average.count'};
 2557:     #  Put keywords (those that appear > average) into %Keywords
 2558:     while (my ($word,$data)=each (%thesaurus_db)) {
 2559:         my ($count,undef) = split /:/,$data;
 2560:         $Keywords{$word}++ if ($count > $avecount);
 2561:     }
 2562:     untie %thesaurus_db;
 2563:     # Remove special values from %Keywords.
 2564:     foreach my $value ('total.count','average.count') {
 2565:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2566:   }
 2567:     return 1;
 2568: }
 2569: 
 2570: ###################################################
 2571: 
 2572: =pod
 2573: 
 2574: =item * &keyword($word)
 2575: 
 2576: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2577: than the average number of times in the thesaurus database.  Calls 
 2578: &initialize_keywords
 2579: 
 2580: =cut
 2581: 
 2582: ###################################################
 2583: 
 2584: sub keyword {
 2585:     return if (!&initialize_keywords());
 2586:     my $word=lc(shift());
 2587:     $word=~s/\W//g;
 2588:     return exists($Keywords{$word});
 2589: }
 2590: 
 2591: ###############################################################
 2592: 
 2593: =pod 
 2594: 
 2595: =item * &get_related_words()
 2596: 
 2597: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2598: an array of words.  If the keyword is not in the thesaurus, an empty array
 2599: will be returned.  The order of the words returned is determined by the
 2600: database which holds them.
 2601: 
 2602: Uses global $thesaurus_db_file.
 2603: 
 2604: =cut
 2605: 
 2606: ###############################################################
 2607: sub get_related_words {
 2608:     my $keyword = shift;
 2609:     my %thesaurus_db;
 2610:     if (! -e $thesaurus_db_file) {
 2611:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2612:                                  "failed because the file does not exist");
 2613:         return ();
 2614:     }
 2615:     if (! tie(%thesaurus_db,'GDBM_File',
 2616:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2617:         return ();
 2618:     } 
 2619:     my @Words=();
 2620:     my $count=0;
 2621:     if (exists($thesaurus_db{$keyword})) {
 2622: 	# The first element is the number of times
 2623: 	# the word appears.  We do not need it now.
 2624: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2625: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2626: 	my $threshold=$mostfrequentcount/10;
 2627:         foreach my $possibleword (@RelatedWords) {
 2628:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2629:             if ($wordcount>$threshold) {
 2630: 		push(@Words,$word);
 2631:                 $count++;
 2632:                 if ($count>10) { last; }
 2633: 	    }
 2634:         }
 2635:     }
 2636:     untie %thesaurus_db;
 2637:     return @Words;
 2638: }
 2639: 
 2640: =pod
 2641: 
 2642: =back
 2643: 
 2644: =cut
 2645: 
 2646: # -------------------------------------------------------------- Plaintext name
 2647: =pod
 2648: 
 2649: =head1 User Name Functions
 2650: 
 2651: =over 4
 2652: 
 2653: =item * &plainname($uname,$udom,$first)
 2654: 
 2655: Takes a users logon name and returns it as a string in
 2656: "first middle last generation" form 
 2657: if $first is set to 'lastname' then it returns it as
 2658: 'lastname generation, firstname middlename' if their is a lastname
 2659: 
 2660: =cut
 2661: 
 2662: 
 2663: ###############################################################
 2664: sub plainname {
 2665:     my ($uname,$udom,$first)=@_;
 2666:     return if (!defined($uname) || !defined($udom));
 2667:     my %names=&getnames($uname,$udom);
 2668:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2669: 					  $names{'middlename'},
 2670: 					  $names{'lastname'},
 2671: 					  $names{'generation'},$first);
 2672:     $name=~s/^\s+//;
 2673:     $name=~s/\s+$//;
 2674:     $name=~s/\s+/ /g;
 2675:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2676:     return $name;
 2677: }
 2678: 
 2679: # -------------------------------------------------------------------- Nickname
 2680: =pod
 2681: 
 2682: =item * &nickname($uname,$udom)
 2683: 
 2684: Gets a users name and returns it as a string as
 2685: 
 2686: "&quot;nickname&quot;"
 2687: 
 2688: if the user has a nickname or
 2689: 
 2690: "first middle last generation"
 2691: 
 2692: if the user does not
 2693: 
 2694: =cut
 2695: 
 2696: sub nickname {
 2697:     my ($uname,$udom)=@_;
 2698:     return if (!defined($uname) || !defined($udom));
 2699:     my %names=&getnames($uname,$udom);
 2700:     my $name=$names{'nickname'};
 2701:     if ($name) {
 2702:        $name='&quot;'.$name.'&quot;'; 
 2703:     } else {
 2704:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2705: 	     $names{'lastname'}.' '.$names{'generation'};
 2706:        $name=~s/\s+$//;
 2707:        $name=~s/\s+/ /g;
 2708:     }
 2709:     return $name;
 2710: }
 2711: 
 2712: sub getnames {
 2713:     my ($uname,$udom)=@_;
 2714:     return if (!defined($uname) || !defined($udom));
 2715:     if ($udom eq 'public' && $uname eq 'public') {
 2716: 	return ('lastname' => &mt('Public'));
 2717:     }
 2718:     my $id=$uname.':'.$udom;
 2719:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2720:     if ($cached) {
 2721: 	return %{$names};
 2722:     } else {
 2723: 	my %loadnames=&Apache::lonnet::get('environment',
 2724:                     ['firstname','middlename','lastname','generation','nickname'],
 2725: 					 $udom,$uname);
 2726: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2727: 	return %loadnames;
 2728:     }
 2729: }
 2730: 
 2731: # -------------------------------------------------------------------- getemails
 2732: 
 2733: =pod
 2734: 
 2735: =item * &getemails($uname,$udom)
 2736: 
 2737: Gets a user's email information and returns it as a hash with keys:
 2738: notification, critnotification, permanentemail
 2739: 
 2740: For notification and critnotification, values are comma-separated lists 
 2741: of e-mail addresses; for permanentemail, value is a single e-mail address.
 2742:  
 2743: 
 2744: =cut
 2745: 
 2746: 
 2747: sub getemails {
 2748:     my ($uname,$udom)=@_;
 2749:     if ($udom eq 'public' && $uname eq 'public') {
 2750: 	return;
 2751:     }
 2752:     if (!$udom) { $udom=$env{'user.domain'}; }
 2753:     if (!$uname) { $uname=$env{'user.name'}; }
 2754:     my $id=$uname.':'.$udom;
 2755:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2756:     if ($cached) {
 2757: 	return %{$names};
 2758:     } else {
 2759: 	my %loadnames=&Apache::lonnet::get('environment',
 2760:                     			   ['notification','critnotification',
 2761: 					    'permanentemail'],
 2762: 					   $udom,$uname);
 2763: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2764: 	return %loadnames;
 2765:     }
 2766: }
 2767: 
 2768: sub flush_email_cache {
 2769:     my ($uname,$udom)=@_;
 2770:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2771:     if (!$uname) { $uname=$env{'user.name'};   }
 2772:     return if ($udom eq 'public' && $uname eq 'public');
 2773:     my $id=$uname.':'.$udom;
 2774:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2775: }
 2776: 
 2777: # -------------------------------------------------------------------- getlangs
 2778: 
 2779: =pod
 2780: 
 2781: =item * &getlangs($uname,$udom)
 2782: 
 2783: Gets a user's language preference and returns it as a hash with key:
 2784: language.
 2785: 
 2786: =cut
 2787: 
 2788: 
 2789: sub getlangs {
 2790:     my ($uname,$udom) = @_;
 2791:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2792:     if (!$uname) { $uname=$env{'user.name'};   }
 2793:     my $id=$uname.':'.$udom;
 2794:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 2795:     if ($cached) {
 2796:         return %{$langs};
 2797:     } else {
 2798:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 2799:                                            $udom,$uname);
 2800:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 2801:         return %loadlangs;
 2802:     }
 2803: }
 2804: 
 2805: sub flush_langs_cache {
 2806:     my ($uname,$udom)=@_;
 2807:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2808:     if (!$uname) { $uname=$env{'user.name'};   }
 2809:     return if ($udom eq 'public' && $uname eq 'public');
 2810:     my $id=$uname.':'.$udom;
 2811:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 2812: }
 2813: 
 2814: # ------------------------------------------------------------------ Screenname
 2815: 
 2816: =pod
 2817: 
 2818: =item * &screenname($uname,$udom)
 2819: 
 2820: Gets a users screenname and returns it as a string
 2821: 
 2822: =cut
 2823: 
 2824: sub screenname {
 2825:     my ($uname,$udom)=@_;
 2826:     if ($uname eq $env{'user.name'} &&
 2827: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2828:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2829:     return $names{'screenname'};
 2830: }
 2831: 
 2832: # ------------------------------------------------------------- Confirm Wrapper
 2833: =pod
 2834: 
 2835: =item confirmwrapper
 2836: 
 2837: Wrap messages about completion of operation in box
 2838: 
 2839: =cut
 2840: 
 2841: sub confirmwrapper {
 2842:     my ($message)=@_;
 2843:     if ($message) {
 2844:         return "\n".'<div class="LC_confirm_box">'."\n"
 2845:                .$message."\n"
 2846:                .'</div>'."\n";
 2847:     } else {
 2848:         return $message;
 2849:     }
 2850: }
 2851: 
 2852: # ------------------------------------------------------------- Message Wrapper
 2853: 
 2854: sub messagewrapper {
 2855:     my ($link,$username,$domain,$subject,$text)=@_;
 2856:     return 
 2857:         '<a href="/adm/email?compose=individual&amp;'.
 2858:         'recname='.$username.'&amp;recdom='.$domain.
 2859: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2860:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2861: }
 2862: # --------------------------------------------------------------- Notes Wrapper
 2863: 
 2864: sub noteswrapper {
 2865:     my ($link,$un,$do)=@_;
 2866:     return 
 2867: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2868: }
 2869: # ------------------------------------------------------------- Aboutme Wrapper
 2870: 
 2871: sub aboutmewrapper {
 2872:     my ($link,$username,$domain,$target)=@_;
 2873:     if (!defined($username)  && !defined($domain)) {
 2874:         return;
 2875:     }
 2876:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2877: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 2878: }
 2879: 
 2880: # ------------------------------------------------------------ Syllabus Wrapper
 2881: 
 2882: 
 2883: sub syllabuswrapper {
 2884:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2885:     if ($fontcolor) { 
 2886:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2887:     }
 2888:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2889: }
 2890: 
 2891: sub track_student_link {
 2892:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2893:     my $link ="/adm/trackstudent?";
 2894:     my $title = 'View recent activity';
 2895:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2896:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2897:         $link .= "selected_student=$sname:$sdom";
 2898:         $title .= ' of this student';
 2899:     } 
 2900:     if (defined($target) && $target !~ /^\s*$/) {
 2901:         $target = qq{target="$target"};
 2902:     } else {
 2903:         $target = '';
 2904:     }
 2905:     if ($start) { $link.='&amp;start='.$start; }
 2906:     $title = &mt($title);
 2907:     $linktext = &mt($linktext);
 2908:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2909: 	&help_open_topic('View_recent_activity');
 2910: }
 2911: 
 2912: sub slot_reservations_link {
 2913:     my ($linktext,$sname,$sdom,$target) = @_;
 2914:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 2915:     my $title = 'View slot reservation history';
 2916:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2917:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2918:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 2919:         $title .= ' of this student';
 2920:     }
 2921:     if (defined($target) && $target !~ /^\s*$/) {
 2922:         $target = qq{target="$target"};
 2923:     } else {
 2924:         $target = '';
 2925:     }
 2926:     $title = &mt($title);
 2927:     $linktext = &mt($linktext);
 2928:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2929: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 2930: 
 2931: }
 2932: 
 2933: # ===================================================== Display a student photo
 2934: 
 2935: 
 2936: sub student_image_tag {
 2937:     my ($domain,$user)=@_;
 2938:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2939:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2940: 	return '<img src="'.$imgsrc.'" align="right" />';
 2941:     } else {
 2942: 	return '';
 2943:     }
 2944: }
 2945: 
 2946: =pod
 2947: 
 2948: =back
 2949: 
 2950: =head1 Access .tab File Data
 2951: 
 2952: =over 4
 2953: 
 2954: =item * &languageids() 
 2955: 
 2956: returns list of all language ids
 2957: 
 2958: =cut
 2959: 
 2960: sub languageids {
 2961:     return sort(keys(%language));
 2962: }
 2963: 
 2964: =pod
 2965: 
 2966: =item * &languagedescription() 
 2967: 
 2968: returns description of a specified language id
 2969: 
 2970: =cut
 2971: 
 2972: sub languagedescription {
 2973:     my $code=shift;
 2974:     return  ($supported_language{$code}?'* ':'').
 2975:             $language{$code}.
 2976: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2977: }
 2978: 
 2979: sub plainlanguagedescription {
 2980:     my $code=shift;
 2981:     return $language{$code};
 2982: }
 2983: 
 2984: sub supportedlanguagecode {
 2985:     my $code=shift;
 2986:     return $supported_language{$code};
 2987: }
 2988: 
 2989: =pod
 2990: 
 2991: =item * &copyrightids() 
 2992: 
 2993: returns list of all copyrights
 2994: 
 2995: =cut
 2996: 
 2997: sub copyrightids {
 2998:     return sort(keys(%cprtag));
 2999: }
 3000: 
 3001: =pod
 3002: 
 3003: =item * &copyrightdescription() 
 3004: 
 3005: returns description of a specified copyright id
 3006: 
 3007: =cut
 3008: 
 3009: sub copyrightdescription {
 3010:     return &mt($cprtag{shift(@_)});
 3011: }
 3012: 
 3013: =pod
 3014: 
 3015: =item * &source_copyrightids() 
 3016: 
 3017: returns list of all source copyrights
 3018: 
 3019: =cut
 3020: 
 3021: sub source_copyrightids {
 3022:     return sort(keys(%scprtag));
 3023: }
 3024: 
 3025: =pod
 3026: 
 3027: =item * &source_copyrightdescription() 
 3028: 
 3029: returns description of a specified source copyright id
 3030: 
 3031: =cut
 3032: 
 3033: sub source_copyrightdescription {
 3034:     return &mt($scprtag{shift(@_)});
 3035: }
 3036: 
 3037: =pod
 3038: 
 3039: =item * &filecategories() 
 3040: 
 3041: returns list of all file categories
 3042: 
 3043: =cut
 3044: 
 3045: sub filecategories {
 3046:     return sort(keys(%category_extensions));
 3047: }
 3048: 
 3049: =pod
 3050: 
 3051: =item * &filecategorytypes() 
 3052: 
 3053: returns list of file types belonging to a given file
 3054: category
 3055: 
 3056: =cut
 3057: 
 3058: sub filecategorytypes {
 3059:     my ($cat) = @_;
 3060:     return @{$category_extensions{lc($cat)}};
 3061: }
 3062: 
 3063: =pod
 3064: 
 3065: =item * &fileembstyle() 
 3066: 
 3067: returns embedding style for a specified file type
 3068: 
 3069: =cut
 3070: 
 3071: sub fileembstyle {
 3072:     return $fe{lc(shift(@_))};
 3073: }
 3074: 
 3075: sub filemimetype {
 3076:     return $fm{lc(shift(@_))};
 3077: }
 3078: 
 3079: 
 3080: sub filecategoryselect {
 3081:     my ($name,$value)=@_;
 3082:     return &select_form($value,$name,
 3083: 			'' => &mt('Any category'),
 3084: 			map { $_,$_ } sort(keys(%category_extensions)));
 3085: }
 3086: 
 3087: =pod
 3088: 
 3089: =item * &filedescription() 
 3090: 
 3091: returns description for a specified file type
 3092: 
 3093: =cut
 3094: 
 3095: sub filedescription {
 3096:     my $file_description = $fd{lc(shift())};
 3097:     $file_description =~ s:([\[\]]):~$1:g;
 3098:     return &mt($file_description);
 3099: }
 3100: 
 3101: =pod
 3102: 
 3103: =item * &filedescriptionex() 
 3104: 
 3105: returns description for a specified file type with
 3106: extra formatting
 3107: 
 3108: =cut
 3109: 
 3110: sub filedescriptionex {
 3111:     my $ex=shift;
 3112:     my $file_description = $fd{lc($ex)};
 3113:     $file_description =~ s:([\[\]]):~$1:g;
 3114:     return '.'.$ex.' '.&mt($file_description);
 3115: }
 3116: 
 3117: # End of .tab access
 3118: =pod
 3119: 
 3120: =back
 3121: 
 3122: =cut
 3123: 
 3124: # ------------------------------------------------------------------ File Types
 3125: sub fileextensions {
 3126:     return sort(keys(%fe));
 3127: }
 3128: 
 3129: # ----------------------------------------------------------- Display Languages
 3130: # returns a hash with all desired display languages
 3131: #
 3132: 
 3133: sub display_languages {
 3134:     my %languages=();
 3135:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3136: 	$languages{$lang}=1;
 3137:     }
 3138:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3139:     if ($env{'form.displaylanguage'}) {
 3140: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3141: 	    $languages{$lang}=1;
 3142:         }
 3143:     }
 3144:     return %languages;
 3145: }
 3146: 
 3147: sub languages {
 3148:     my ($possible_langs) = @_;
 3149:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3150:     if (!ref($possible_langs)) {
 3151: 	if( wantarray ) {
 3152: 	    return @preferred_langs;
 3153: 	} else {
 3154: 	    return $preferred_langs[0];
 3155: 	}
 3156:     }
 3157:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3158:     my @preferred_possibilities;
 3159:     foreach my $preferred_lang (@preferred_langs) {
 3160: 	if (exists($possibilities{$preferred_lang})) {
 3161: 	    push(@preferred_possibilities, $preferred_lang);
 3162: 	}
 3163:     }
 3164:     if( wantarray ) {
 3165: 	return @preferred_possibilities;
 3166:     }
 3167:     return $preferred_possibilities[0];
 3168: }
 3169: 
 3170: sub user_lang {
 3171:     my ($touname,$toudom,$fromcid) = @_;
 3172:     my @userlangs;
 3173:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3174:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3175:                     $env{'course.'.$fromcid.'.languages'}));
 3176:     } else {
 3177:         my %langhash = &getlangs($touname,$toudom);
 3178:         if ($langhash{'languages'} ne '') {
 3179:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3180:         } else {
 3181:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3182:             if ($domdefs{'lang_def'} ne '') {
 3183:                 @userlangs = ($domdefs{'lang_def'});
 3184:             }
 3185:         }
 3186:     }
 3187:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3188:     my $user_lh = Apache::localize->get_handle(@languages);
 3189:     return $user_lh;
 3190: }
 3191: 
 3192: ###############################################################
 3193: ##               Student Answer Attempts                     ##
 3194: ###############################################################
 3195: 
 3196: =pod
 3197: 
 3198: =head1 Alternate Problem Views
 3199: 
 3200: =over 4
 3201: 
 3202: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3203:     $getattempt, $regexp, $gradesub)
 3204: 
 3205: Return string with previous attempt on problem. Arguments:
 3206: 
 3207: =over 4
 3208: 
 3209: =item * $symb: Problem, including path
 3210: 
 3211: =item * $username: username of the desired student
 3212: 
 3213: =item * $domain: domain of the desired student
 3214: 
 3215: =item * $course: Course ID
 3216: 
 3217: =item * $getattempt: Leave blank for all attempts, otherwise put
 3218:     something
 3219: 
 3220: =item * $regexp: if string matches this regexp, the string will be
 3221:     sent to $gradesub
 3222: 
 3223: =item * $gradesub: routine that processes the string if it matches $regexp
 3224: 
 3225: =back
 3226: 
 3227: The output string is a table containing all desired attempts, if any.
 3228: 
 3229: =cut
 3230: 
 3231: sub get_previous_attempt {
 3232:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3233:   my $prevattempts='';
 3234:   no strict 'refs';
 3235:   if ($symb) {
 3236:     my (%returnhash)=
 3237:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3238:     if ($returnhash{'version'}) {
 3239:       my %lasthash=();
 3240:       my $version;
 3241:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3242:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3243: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3244:         }
 3245:       }
 3246:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3247:       $prevattempts.='<th>'.&mt('History').'</th>';
 3248:       foreach my $key (sort(keys(%lasthash))) {
 3249: 	my ($ign,@parts) = split(/\./,$key);
 3250: 	if ($#parts > 0) {
 3251: 	  my $data=$parts[-1];
 3252: 	  pop(@parts);
 3253: 	  $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3254: 	} else {
 3255: 	  if ($#parts == 0) {
 3256: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3257: 	  } else {
 3258: 	    $prevattempts.='<th>'.$ign.'</th>';
 3259: 	  }
 3260: 	}
 3261:       }
 3262:       $prevattempts.=&end_data_table_header_row();
 3263:       if ($getattempt eq '') {
 3264: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3265: 	  $prevattempts.=&start_data_table_row().
 3266: 	      '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3267: 	    foreach my $key (sort(keys(%lasthash))) {
 3268: 		my $value = &format_previous_attempt_value($key,
 3269: 							   $returnhash{$version.':'.$key});
 3270: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 3271: 	    }
 3272: 	  $prevattempts.=&end_data_table_row();
 3273: 	 }
 3274:       }
 3275:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3276:       foreach my $key (sort(keys(%lasthash))) {
 3277: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3278: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 3279: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 3280:       }
 3281:       $prevattempts.= &end_data_table_row().&end_data_table();
 3282:     } else {
 3283:       $prevattempts=
 3284: 	  &start_data_table().&start_data_table_row().
 3285: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3286: 	  &end_data_table_row().&end_data_table();
 3287:     }
 3288:   } else {
 3289:     $prevattempts=
 3290: 	  &start_data_table().&start_data_table_row().
 3291: 	  '<td>'.&mt('No data.').'</td>'.
 3292: 	  &end_data_table_row().&end_data_table();
 3293:   }
 3294: }
 3295: 
 3296: sub format_previous_attempt_value {
 3297:     my ($key,$value) = @_;
 3298:     if ($key =~ /timestamp/) {
 3299: 	$value = &Apache::lonlocal::locallocaltime($value);
 3300:     } elsif (ref($value) eq 'ARRAY') {
 3301: 	$value = '('.join(', ', @{ $value }).')';
 3302:     } else {
 3303: 	$value = &unescape($value);
 3304:     }
 3305:     return $value;
 3306: }
 3307: 
 3308: 
 3309: sub relative_to_absolute {
 3310:     my ($url,$output)=@_;
 3311:     my $parser=HTML::TokeParser->new(\$output);
 3312:     my $token;
 3313:     my $thisdir=$url;
 3314:     my @rlinks=();
 3315:     while ($token=$parser->get_token) {
 3316: 	if ($token->[0] eq 'S') {
 3317: 	    if ($token->[1] eq 'a') {
 3318: 		if ($token->[2]->{'href'}) {
 3319: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3320: 		}
 3321: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3322: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3323: 	    } elsif ($token->[1] eq 'base') {
 3324: 		$thisdir=$token->[2]->{'href'};
 3325: 	    }
 3326: 	}
 3327:     }
 3328:     $thisdir=~s-/[^/]*$--;
 3329:     foreach my $link (@rlinks) {
 3330: 	unless (($link=~/^https?\:\/\//i) ||
 3331: 		($link=~/^\//) ||
 3332: 		($link=~/^javascript:/i) ||
 3333: 		($link=~/^mailto:/i) ||
 3334: 		($link=~/^\#/)) {
 3335: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3336: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3337: 	}
 3338:     }
 3339: # -------------------------------------------------- Deal with Applet codebases
 3340:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3341:     return $output;
 3342: }
 3343: 
 3344: =pod
 3345: 
 3346: =item * &get_student_view()
 3347: 
 3348: show a snapshot of what student was looking at
 3349: 
 3350: =cut
 3351: 
 3352: sub get_student_view {
 3353:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3354:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3355:   my (%form);
 3356:   my @elements=('symb','courseid','domain','username');
 3357:   foreach my $element (@elements) {
 3358:       $form{'grade_'.$element}=eval '$'.$element #'
 3359:   }
 3360:   if (defined($moreenv)) {
 3361:       %form=(%form,%{$moreenv});
 3362:   }
 3363:   if (defined($target)) { $form{'grade_target'} = $target; }
 3364:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3365:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3366:   $userview=~s/\<body[^\>]*\>//gi;
 3367:   $userview=~s/\<\/body\>//gi;
 3368:   $userview=~s/\<html\>//gi;
 3369:   $userview=~s/\<\/html\>//gi;
 3370:   $userview=~s/\<head\>//gi;
 3371:   $userview=~s/\<\/head\>//gi;
 3372:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3373:   $userview=&relative_to_absolute($feedurl,$userview);
 3374:   if (wantarray) {
 3375:      return ($userview,$response);
 3376:   } else {
 3377:      return $userview;
 3378:   }
 3379: }
 3380: 
 3381: sub get_student_view_with_retries {
 3382:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3383: 
 3384:     my $ok = 0;                 # True if we got a good response.
 3385:     my $content;
 3386:     my $response;
 3387: 
 3388:     # Try to get the student_view done. within the retries count:
 3389:     
 3390:     do {
 3391:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 3392:          $ok      = $response->is_success;
 3393:          if (!$ok) {
 3394:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 3395:          }
 3396:          $retries--;
 3397:     } while (!$ok && ($retries > 0));
 3398:     
 3399:     if (!$ok) {
 3400:        $content = '';          # On error return an empty content.
 3401:     }
 3402:     if (wantarray) {
 3403:        return ($content, $response);
 3404:     } else {
 3405:        return $content;
 3406:     }
 3407: }
 3408: 
 3409: =pod
 3410: 
 3411: =item * &get_student_answers() 
 3412: 
 3413: show a snapshot of how student was answering problem
 3414: 
 3415: =cut
 3416: 
 3417: sub get_student_answers {
 3418:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3419:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3420:   my (%moreenv);
 3421:   my @elements=('symb','courseid','domain','username');
 3422:   foreach my $element (@elements) {
 3423:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3424:   }
 3425:   $moreenv{'grade_target'}='answer';
 3426:   %moreenv=(%form,%moreenv);
 3427:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3428:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3429:   return $userview;
 3430: }
 3431: 
 3432: =pod
 3433: 
 3434: =item * &submlink()
 3435: 
 3436: Inputs: $text $uname $udom $symb $target
 3437: 
 3438: Returns: A link to grades.pm such as to see the SUBM view of a student
 3439: 
 3440: =cut
 3441: 
 3442: ###############################################
 3443: sub submlink {
 3444:     my ($text,$uname,$udom,$symb,$target)=@_;
 3445:     if (!($uname && $udom)) {
 3446: 	(my $cursymb, my $courseid,$udom,$uname)=
 3447: 	    &Apache::lonnet::whichuser($symb);
 3448: 	if (!$symb) { $symb=$cursymb; }
 3449:     }
 3450:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3451:     $symb=&escape($symb);
 3452:     if ($target) { $target="target=\"$target\""; }
 3453:     return '<a href="/adm/grades?&command=submission&'.
 3454: 	'symb='.$symb.'&student='.$uname.
 3455: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3456: }
 3457: ##############################################
 3458: 
 3459: =pod
 3460: 
 3461: =item * &pgrdlink()
 3462: 
 3463: Inputs: $text $uname $udom $symb $target
 3464: 
 3465: Returns: A link to grades.pm such as to see the PGRD view of a student
 3466: 
 3467: =cut
 3468: 
 3469: ###############################################
 3470: sub pgrdlink {
 3471:     my $link=&submlink(@_);
 3472:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3473:     return $link;
 3474: }
 3475: ##############################################
 3476: 
 3477: =pod
 3478: 
 3479: =item * &pprmlink()
 3480: 
 3481: Inputs: $text $uname $udom $symb $target
 3482: 
 3483: Returns: A link to parmset.pm such as to see the PPRM view of a
 3484: student and a specific resource
 3485: 
 3486: =cut
 3487: 
 3488: ###############################################
 3489: sub pprmlink {
 3490:     my ($text,$uname,$udom,$symb,$target)=@_;
 3491:     if (!($uname && $udom)) {
 3492: 	(my $cursymb, my $courseid,$udom,$uname)=
 3493: 	    &Apache::lonnet::whichuser($symb);
 3494: 	if (!$symb) { $symb=$cursymb; }
 3495:     }
 3496:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3497:     $symb=&escape($symb);
 3498:     if ($target) { $target="target=\"$target\""; }
 3499:     return '<a href="/adm/parmset?command=set&amp;'.
 3500: 	'symb='.$symb.'&amp;uname='.$uname.
 3501: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3502: }
 3503: ##############################################
 3504: 
 3505: =pod
 3506: 
 3507: =back
 3508: 
 3509: =cut
 3510: 
 3511: ###############################################
 3512: 
 3513: 
 3514: sub timehash {
 3515:     my ($thistime) = @_;
 3516:     my $timezone = &Apache::lonlocal::gettimezone();
 3517:     my $dt = DateTime->from_epoch(epoch => $thistime)
 3518:                      ->set_time_zone($timezone);
 3519:     my $wday = $dt->day_of_week();
 3520:     if ($wday == 7) { $wday = 0; }
 3521:     return ( 'second' => $dt->second(),
 3522:              'minute' => $dt->minute(),
 3523:              'hour'   => $dt->hour(),
 3524:              'day'     => $dt->day_of_month(),
 3525:              'month'   => $dt->month(),
 3526:              'year'    => $dt->year(),
 3527:              'weekday' => $wday,
 3528:              'dayyear' => $dt->day_of_year(),
 3529:              'dlsav'   => $dt->is_dst() );
 3530: }
 3531: 
 3532: sub utc_string {
 3533:     my ($date)=@_;
 3534:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3535: }
 3536: 
 3537: sub maketime {
 3538:     my %th=@_;
 3539:     my ($epoch_time,$timezone,$dt);
 3540:     $timezone = &Apache::lonlocal::gettimezone();
 3541:     eval {
 3542:         $dt = DateTime->new( year   => $th{'year'},
 3543:                              month  => $th{'month'},
 3544:                              day    => $th{'day'},
 3545:                              hour   => $th{'hour'},
 3546:                              minute => $th{'minute'},
 3547:                              second => $th{'second'},
 3548:                              time_zone => $timezone,
 3549:                          );
 3550:     };
 3551:     if (!$@) {
 3552:         $epoch_time = $dt->epoch;
 3553:         if ($epoch_time) {
 3554:             return $epoch_time;
 3555:         }
 3556:     }
 3557:     return POSIX::mktime(
 3558:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3559:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3560: }
 3561: 
 3562: #########################################
 3563: 
 3564: sub findallcourses {
 3565:     my ($roles,$uname,$udom) = @_;
 3566:     my %roles;
 3567:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3568:     my %courses;
 3569:     my $now=time;
 3570:     if (!defined($uname)) {
 3571:         $uname = $env{'user.name'};
 3572:     }
 3573:     if (!defined($udom)) {
 3574:         $udom = $env{'user.domain'};
 3575:     }
 3576:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3577:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3578:         if (!%roles) {
 3579:             %roles = (
 3580:                        cc => 1,
 3581:                        in => 1,
 3582:                        ep => 1,
 3583:                        ta => 1,
 3584:                        cr => 1,
 3585:                        st => 1,
 3586:              );
 3587:         }
 3588:         foreach my $entry (keys(%roleshash)) {
 3589:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3590:             if ($trole =~ /^cr/) { 
 3591:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3592:             } else {
 3593:                 next if (!exists($roles{$trole}));
 3594:             }
 3595:             if ($tend) {
 3596:                 next if ($tend < $now);
 3597:             }
 3598:             if ($tstart) {
 3599:                 next if ($tstart > $now);
 3600:             }
 3601:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3602:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3603:             if ($secpart eq '') {
 3604:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3605:                 $sec = 'none';
 3606:                 $realsec = '';
 3607:             } else {
 3608:                 $cnum = $cnumpart;
 3609:                 ($sec,$role) = split(/_/,$secpart);
 3610:                 $realsec = $sec;
 3611:             }
 3612:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3613:         }
 3614:     } else {
 3615:         foreach my $key (keys(%env)) {
 3616: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3617:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3618: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3619: 	        next if ($role eq 'ca' || $role eq 'aa');
 3620: 	        next if (%roles && !exists($roles{$role}));
 3621: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3622:                 my $active=1;
 3623:                 if ($starttime) {
 3624: 		    if ($now<$starttime) { $active=0; }
 3625:                 }
 3626:                 if ($endtime) {
 3627:                     if ($now>$endtime) { $active=0; }
 3628:                 }
 3629:                 if ($active) {
 3630:                     if ($sec eq '') {
 3631:                         $sec = 'none';
 3632:                     }
 3633:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3634:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3635:                 }
 3636:             }
 3637:         }
 3638:     }
 3639:     return %courses;
 3640: }
 3641: 
 3642: ###############################################
 3643: 
 3644: sub blockcheck {
 3645:     my ($setters,$activity,$uname,$udom) = @_;
 3646: 
 3647:     if (!defined($udom)) {
 3648:         $udom = $env{'user.domain'};
 3649:     }
 3650:     if (!defined($uname)) {
 3651:         $uname = $env{'user.name'};
 3652:     }
 3653: 
 3654:     # If uname and udom are for a course, check for blocks in the course.
 3655: 
 3656:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3657:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3658:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3659:         return ($startblock,$endblock);
 3660:     }
 3661: 
 3662:     my $startblock = 0;
 3663:     my $endblock = 0;
 3664:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3665: 
 3666:     # If uname is for a user, and activity is course-specific, i.e.,
 3667:     # boards, chat or groups, check for blocking in current course only.
 3668: 
 3669:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3670:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3671:         foreach my $key (keys(%live_courses)) {
 3672:             if ($key ne $env{'request.course.id'}) {
 3673:                 delete($live_courses{$key});
 3674:             }
 3675:         }
 3676:     }
 3677: 
 3678:     my $otheruser = 0;
 3679:     my %own_courses;
 3680:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3681:         # Resource belongs to user other than current user.
 3682:         $otheruser = 1;
 3683:         # Gather courses for current user
 3684:         %own_courses = 
 3685:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3686:     }
 3687: 
 3688:     # Gather active course roles - course coordinator, instructor, 
 3689:     # exam proctor, ta, student, or custom role.
 3690: 
 3691:     foreach my $course (keys(%live_courses)) {
 3692:         my ($cdom,$cnum);
 3693:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3694:             $cdom = $env{'course.'.$course.'.domain'};
 3695:             $cnum = $env{'course.'.$course.'.num'};
 3696:         } else {
 3697:             ($cdom,$cnum) = split(/_/,$course); 
 3698:         }
 3699:         my $no_ownblock = 0;
 3700:         my $no_userblock = 0;
 3701:         if ($otheruser && $activity ne 'com') {
 3702:             # Check if current user has 'evb' priv for this
 3703:             if (defined($own_courses{$course})) {
 3704:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3705:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3706:                     if ($sec ne 'none') {
 3707:                         $checkrole .= '/'.$sec;
 3708:                     }
 3709:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3710:                         $no_ownblock = 1;
 3711:                         last;
 3712:                     }
 3713:                 }
 3714:             }
 3715:             # if they have 'evb' priv and are currently not playing student
 3716:             next if (($no_ownblock) &&
 3717:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3718:         }
 3719:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3720:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3721:             if ($sec ne 'none') {
 3722:                 $checkrole .= '/'.$sec;
 3723:             }
 3724:             if ($otheruser) {
 3725:                 # Resource belongs to user other than current user.
 3726:                 # Assemble privs for that user, and check for 'evb' priv.
 3727:                 my ($trole,$tdom,$tnum,$tsec);
 3728:                 my $entry = $live_courses{$course}{$sec};
 3729:                 if ($entry =~ /^cr/) {
 3730:                     ($trole,$tdom,$tnum,$tsec) = 
 3731:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3732:                 } else {
 3733:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3734:                 }
 3735:                 my ($spec,$area,$trest,%allroles,%userroles);
 3736:                 $area = '/'.$tdom.'/'.$tnum;
 3737:                 $trest = $tnum;
 3738:                 if ($tsec ne '') {
 3739:                     $area .= '/'.$tsec;
 3740:                     $trest .= '/'.$tsec;
 3741:                 }
 3742:                 $spec = $trole.'.'.$area;
 3743:                 if ($trole =~ /^cr/) {
 3744:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3745:                                                       $tdom,$spec,$trest,$area);
 3746:                 } else {
 3747:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3748:                                                        $tdom,$spec,$trest,$area);
 3749:                 }
 3750:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3751:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3752:                     if ($1) {
 3753:                         $no_userblock = 1;
 3754:                         last;
 3755:                     }
 3756:                 }
 3757:             } else {
 3758:                 # Resource belongs to current user
 3759:                 # Check for 'evb' priv via lonnet::allowed().
 3760:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3761:                     $no_ownblock = 1;
 3762:                     last;
 3763:                 }
 3764:             }
 3765:         }
 3766:         # if they have the evb priv and are currently not playing student
 3767:         next if (($no_ownblock) &&
 3768:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3769:         next if ($no_userblock);
 3770: 
 3771:         # Retrieve blocking times and identity of blocker for course
 3772:         # of specified user, unless user has 'evb' privilege.
 3773:         
 3774:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3775:         if (($start != 0) && 
 3776:             (($startblock == 0) || ($startblock > $start))) {
 3777:             $startblock = $start;
 3778:         }
 3779:         if (($end != 0)  &&
 3780:             (($endblock == 0) || ($endblock < $end))) {
 3781:             $endblock = $end;
 3782:         }
 3783:     }
 3784:     return ($startblock,$endblock);
 3785: }
 3786: 
 3787: sub get_blocks {
 3788:     my ($setters,$activity,$cdom,$cnum) = @_;
 3789:     my $startblock = 0;
 3790:     my $endblock = 0;
 3791:     my $course = $cdom.'_'.$cnum;
 3792:     $setters->{$course} = {};
 3793:     $setters->{$course}{'staff'} = [];
 3794:     $setters->{$course}{'times'} = [];
 3795:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3796:     foreach my $record (keys(%records)) {
 3797:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3798:         if ($start <= time && $end >= time) {
 3799:             my ($staff_name,$staff_dom,$title,$blocks) =
 3800:                 &parse_block_record($records{$record});
 3801:             if ($blocks->{$activity} eq 'on') {
 3802:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3803:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3804:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3805:                     $startblock = $start;
 3806:                 }
 3807:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3808:                     $endblock = $end;
 3809:                 }
 3810:             }
 3811:         }
 3812:     }
 3813:     return ($startblock,$endblock);
 3814: }
 3815: 
 3816: sub parse_block_record {
 3817:     my ($record) = @_;
 3818:     my ($setuname,$setudom,$title,$blocks);
 3819:     if (ref($record) eq 'HASH') {
 3820:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3821:         $title = &unescape($record->{'event'});
 3822:         $blocks = $record->{'blocks'};
 3823:     } else {
 3824:         my @data = split(/:/,$record,3);
 3825:         if (scalar(@data) eq 2) {
 3826:             $title = $data[1];
 3827:             ($setuname,$setudom) = split(/@/,$data[0]);
 3828:         } else {
 3829:             ($setuname,$setudom,$title) = @data;
 3830:         }
 3831:         $blocks = { 'com' => 'on' };
 3832:     }
 3833:     return ($setuname,$setudom,$title,$blocks);
 3834: }
 3835: 
 3836: sub build_block_table {
 3837:     my ($startblock,$endblock,$setters) = @_;
 3838:     my %lt = &Apache::lonlocal::texthash(
 3839:         'cacb' => 'Currently active communication blocks',
 3840:         'cour' => 'Course',
 3841:         'dura' => 'Duration',
 3842:         'blse' => 'Block set by'
 3843:     );
 3844:     my $output;
 3845:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3846:     $output .= &start_data_table();
 3847:     $output .= '
 3848: <tr>
 3849:  <th>'.$lt{'cour'}.'</th>
 3850:  <th>'.$lt{'dura'}.'</th>
 3851:  <th>'.$lt{'blse'}.'</th>
 3852: </tr>
 3853: ';
 3854:     foreach my $course (keys(%{$setters})) {
 3855:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3856:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3857:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3858:             my $fullname = &plainname($uname,$udom);
 3859:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3860:                 && $env{'user.name'} ne 'public' 
 3861:                 && $env{'user.domain'} ne 'public') {
 3862:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3863:             }
 3864:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3865:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3866:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3867:             $output .= &Apache::loncommon::start_data_table_row().
 3868:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3869:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3870:                        '<td>'.$fullname.'</td>'.
 3871:                         &Apache::loncommon::end_data_table_row();
 3872:         }
 3873:     }
 3874:     $output .= &end_data_table();
 3875: }
 3876: 
 3877: sub blocking_status {
 3878:     my ($activity,$uname,$udom) = @_;
 3879:     my %setters;
 3880:     my ($blocked,$output,$ownitem,$is_course);
 3881:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3882:     if ($startblock && $endblock) {
 3883:         $blocked = 1;
 3884:         if (wantarray) {
 3885:             my $category;
 3886:             if ($activity eq 'boards') {
 3887:                 $category = 'Discussion posts in this course';
 3888:             } elsif ($activity eq 'blogs') {
 3889:                 $category = 'Blogs';
 3890:             } elsif ($activity eq 'port') {
 3891:                 if (defined($uname) && defined($udom)) {
 3892:                     if ($uname eq $env{'user.name'} &&
 3893:                         $udom eq $env{'user.domain'}) {
 3894:                         $ownitem = 1;
 3895:                     }
 3896:                 }
 3897:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3898:                 if ($ownitem) { 
 3899:                     $category = 'Your portfolio files';  
 3900:                 } elsif ($is_course) {
 3901:                     my $coursedesc;
 3902:                     foreach my $course (keys(%setters)) {
 3903:                         my %courseinfo =
 3904:                              &Apache::lonnet::coursedescription($course);
 3905:                         $coursedesc = $courseinfo{'description'};
 3906:                     }
 3907:                     $category = "Group portfolio files in the course '$coursedesc'";
 3908:                 } else {
 3909:                     $category = 'Portfolio files belonging to ';
 3910:                     if ($env{'user.name'} eq 'public' && 
 3911:                         $env{'user.domain'} eq 'public') {
 3912:                         $category .= &plainname($uname,$udom);
 3913:                     } else {
 3914:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3915:                     }
 3916:                 }
 3917:             } elsif ($activity eq 'groups') {
 3918:                 $category = 'Groups in this course';
 3919:             }
 3920:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3921:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3922:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3923:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3924:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3925:             }
 3926:         }
 3927:     }
 3928:     if (wantarray) {
 3929:         return ($blocked,$output);
 3930:     } else {
 3931:         return $blocked;
 3932:     }
 3933: }
 3934: 
 3935: ###############################################
 3936: 
 3937: sub check_ip_acc {
 3938:     my ($acc)=@_;
 3939:     &Apache::lonxml::debug("acc is $acc");
 3940:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 3941:         return 1;
 3942:     }
 3943:     my $allowed=0;
 3944:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 3945: 
 3946:     my $name;
 3947:     foreach my $pattern (split(',',$acc)) {
 3948:         $pattern =~ s/^\s*//;
 3949:         $pattern =~ s/\s*$//;
 3950:         if ($pattern =~ /\*$/) {
 3951:             #35.8.*
 3952:             $pattern=~s/\*//;
 3953:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3954:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 3955:             #35.8.3.[34-56]
 3956:             my $low=$2;
 3957:             my $high=$3;
 3958:             $pattern=$1;
 3959:             if ($ip =~ /^\Q$pattern\E/) {
 3960:                 my $last=(split(/\./,$ip))[3];
 3961:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 3962:             }
 3963:         } elsif ($pattern =~ /^\*/) {
 3964:             #*.msu.edu
 3965:             $pattern=~s/\*//;
 3966:             if (!defined($name)) {
 3967:                 use Socket;
 3968:                 my $netaddr=inet_aton($ip);
 3969:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3970:             }
 3971:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3972:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 3973:             #127.0.0.1
 3974:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 3975:         } else {
 3976:             #some.name.com
 3977:             if (!defined($name)) {
 3978:                 use Socket;
 3979:                 my $netaddr=inet_aton($ip);
 3980:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 3981:             }
 3982:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 3983:         }
 3984:         if ($allowed) { last; }
 3985:     }
 3986:     return $allowed;
 3987: }
 3988: 
 3989: ###############################################
 3990: 
 3991: =pod
 3992: 
 3993: =head1 Domain Template Functions
 3994: 
 3995: =over 4
 3996: 
 3997: =item * &determinedomain()
 3998: 
 3999: Inputs: $domain (usually will be undef)
 4000: 
 4001: Returns: Determines which domain should be used for designs
 4002: 
 4003: =cut
 4004: 
 4005: ###############################################
 4006: sub determinedomain {
 4007:     my $domain=shift;
 4008:     if (! $domain) {
 4009:         # Determine domain if we have not been given one
 4010:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 4011:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4012:         if ($env{'request.role.domain'}) { 
 4013:             $domain=$env{'request.role.domain'}; 
 4014:         }
 4015:     }
 4016:     return $domain;
 4017: }
 4018: ###############################################
 4019: 
 4020: sub devalidate_domconfig_cache {
 4021:     my ($udom)=@_;
 4022:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4023: }
 4024: 
 4025: # ---------------------- Get domain configuration for a domain
 4026: sub get_domainconf {
 4027:     my ($udom) = @_;
 4028:     my $cachetime=1800;
 4029:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4030:     if (defined($cached)) { return %{$result}; }
 4031: 
 4032:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4033: 					     ['login','rolecolors'],$udom);
 4034:     my (%designhash,%legacy);
 4035:     if (keys(%domconfig) > 0) {
 4036:         if (ref($domconfig{'login'}) eq 'HASH') {
 4037:             if (keys(%{$domconfig{'login'}})) {
 4038:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4039:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4040:                         foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4041:                             $designhash{$udom.'.login.'.$key.'_'.$img} =
 4042:                                 $domconfig{'login'}{$key}{$img};
 4043:                         }
 4044:                     } else {
 4045:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4046:                     }
 4047:                 }
 4048:             } else {
 4049:                 $legacy{'login'} = 1;
 4050:             }
 4051:         } else {
 4052:             $legacy{'login'} = 1;
 4053:         }
 4054:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4055:             if (keys(%{$domconfig{'rolecolors'}})) {
 4056:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4057:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4058:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4059:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4060:                         }
 4061:                     }
 4062:                 }
 4063:             } else {
 4064:                 $legacy{'rolecolors'} = 1;
 4065:             }
 4066:         } else {
 4067:             $legacy{'rolecolors'} = 1;
 4068:         }
 4069:         if (keys(%legacy) > 0) {
 4070:             my %legacyhash = &get_legacy_domconf($udom);
 4071:             foreach my $item (keys(%legacyhash)) {
 4072:                 if ($item =~ /^\Q$udom\E\.login/) {
 4073:                     if ($legacy{'login'}) { 
 4074:                         $designhash{$item} = $legacyhash{$item};
 4075:                     }
 4076:                 } else {
 4077:                     if ($legacy{'rolecolors'}) {
 4078:                         $designhash{$item} = $legacyhash{$item};
 4079:                     }
 4080:                 }
 4081:             }
 4082:         }
 4083:     } else {
 4084:         %designhash = &get_legacy_domconf($udom); 
 4085:     }
 4086:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4087: 				  $cachetime);
 4088:     return %designhash;
 4089: }
 4090: 
 4091: sub get_legacy_domconf {
 4092:     my ($udom) = @_;
 4093:     my %legacyhash;
 4094:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4095:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4096:     if (-e $designfile) {
 4097:         if ( open (my $fh,"<$designfile") ) {
 4098:             while (my $line = <$fh>) {
 4099:                 next if ($line =~ /^\#/);
 4100:                 chomp($line);
 4101:                 my ($key,$val)=(split(/\=/,$line));
 4102:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4103:             }
 4104:             close($fh);
 4105:         }
 4106:     }
 4107:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 4108:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4109:     }
 4110:     return %legacyhash;
 4111: }
 4112: 
 4113: =pod
 4114: 
 4115: =item * &domainlogo()
 4116: 
 4117: Inputs: $domain (usually will be undef)
 4118: 
 4119: Returns: A link to a domain logo, if the domain logo exists.
 4120: If the domain logo does not exist, a description of the domain.
 4121: 
 4122: =cut
 4123: 
 4124: ###############################################
 4125: sub domainlogo {
 4126:     my $domain = &determinedomain(shift);
 4127:     my %designhash = &get_domainconf($domain);    
 4128:     # See if there is a logo
 4129:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4130:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4131:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4132: 	    if ($imgsrc =~ m{^/res/}) {
 4133: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4134: 		&Apache::lonnet::repcopy($local_name);
 4135: 	    }
 4136: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4137:         } 
 4138:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4139:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4140:         return &Apache::lonnet::domain($domain,'description');
 4141:     } else {
 4142:         return '';
 4143:     }
 4144: }
 4145: ##############################################
 4146: 
 4147: =pod
 4148: 
 4149: =item * &designparm()
 4150: 
 4151: Inputs: $which parameter; $domain (usually will be undef)
 4152: 
 4153: Returns: value of designparamter $which
 4154: 
 4155: =cut
 4156: 
 4157: 
 4158: ##############################################
 4159: sub designparm {
 4160:     my ($which,$domain)=@_;
 4161:     if ($env{'browser.blackwhite'} eq 'on') {
 4162: 	if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
 4163: 	    return '#000000';
 4164: 	}
 4165: 	if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
 4166: 	    return '#FFFFFF';
 4167: 	}
 4168: 	if ($which=~/\.tabbg$/) {
 4169: 	    return '#CCCCCC';
 4170: 	}
 4171:     }
 4172:     if (exists($env{'environment.color.'.$which})) {
 4173: 	return $env{'environment.color.'.$which};
 4174:     }
 4175:     $domain=&determinedomain($domain);
 4176:     my %domdesign = &get_domainconf($domain);
 4177:     my $output;
 4178:     if ($domdesign{$domain.'.'.$which} ne '') {
 4179: 	$output = $domdesign{$domain.'.'.$which};
 4180:     } else {
 4181:         $output = $defaultdesign{$which};
 4182:     }
 4183:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4184:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4185:         if ($output =~ m{^/(adm|res)/}) {
 4186: 	    if ($output =~ m{^/res/}) {
 4187: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 4188: 		&Apache::lonnet::repcopy($local_name);
 4189: 	    }
 4190:             $output = &lonhttpdurl($output);
 4191:         }
 4192:     }
 4193:     return $output;
 4194: }
 4195: 
 4196: ###############################################
 4197: ###############################################
 4198: 
 4199: =pod
 4200: 
 4201: =back
 4202: 
 4203: =head1 HTML Helpers
 4204: 
 4205: =over 4
 4206: 
 4207: =item * &bodytag()
 4208: 
 4209: Returns a uniform header for LON-CAPA web pages.
 4210: 
 4211: Inputs: 
 4212: 
 4213: =over 4
 4214: 
 4215: =item * $title, A title to be displayed on the page.
 4216: 
 4217: =item * $function, the current role (can be undef).
 4218: 
 4219: =item * $addentries, extra parameters for the <body> tag.
 4220: 
 4221: =item * $bodyonly, if defined, only return the <body> tag.
 4222: 
 4223: =item * $domain, if defined, force a given domain.
 4224: 
 4225: =item * $forcereg, if page should register as content page (relevant for 
 4226:             text interface only)
 4227: 
 4228: =item * $customtitle, alternate text to use instead of $title
 4229:                       in the title box that appears, this text
 4230:                       is not auto translated like the $title is
 4231: 
 4232: =item * $notopbar, if true, keep the 'what is this' info but remove the
 4233:                    navigational links
 4234: 
 4235: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 4236: 
 4237: =item * $notitle, if true keep the nav controls, but remove the title bar
 4238: 
 4239: =item * $no_inline_link, if true and in remote mode, don't show the 
 4240:          'Switch To Inline Menu' link
 4241: 
 4242: =item * $args, optional argument valid values are
 4243:             no_auto_mt_title -> prevents &mt()ing the title arg
 4244:             inherit_jsmath -> when creating popup window in a page,
 4245:                               should it have jsmath forced on by the
 4246:                               current page
 4247: 
 4248: =back
 4249: 
 4250: Returns: A uniform header for LON-CAPA web pages.  
 4251: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 4252: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 4253: other decorations will be returned.
 4254: 
 4255: =cut
 4256: 
 4257: sub bodytag {
 4258:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 4259: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 4260: 
 4261:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 4262: 
 4263:     $function = &get_users_function() if (!$function);
 4264:     my $img =    &designparm($function.'.img',$domain);
 4265:     my $font =   &designparm($function.'.font',$domain);
 4266:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 4267: 
 4268:     my %design = ( 'style'   => 'margin-top: 0',
 4269: 		   'bgcolor' => $pgbg,
 4270: 		   'text'    => $font,
 4271:                    'alink'   => &designparm($function.'.alink',$domain),
 4272: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 4273: 		   'link'    => &designparm($function.'.link',$domain),);
 4274:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 4275: 
 4276:  # role and realm
 4277:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 4278:     if ($role  eq 'ca') {
 4279:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 4280:         $realm = &plainname($rname,$rdom);
 4281:     } 
 4282: # realm
 4283:     if ($env{'request.course.id'}) {
 4284:         if ($env{'request.role'} !~ /^cr/) {
 4285:             $role = &Apache::lonnet::plaintext($role,&course_type());
 4286:         }
 4287: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 4288:     } else {
 4289:         $role = &Apache::lonnet::plaintext($role);
 4290:     }
 4291: 
 4292:     if (!$realm) { $realm='&nbsp;'; }
 4293: # Set messages
 4294:     my $messages=&domainlogo($domain);
 4295: 
 4296:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 4297: 
 4298: # construct main body tag
 4299:     my $bodytag = "<body $extra_body_attr>".
 4300: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 4301: 
 4302:     if ($bodyonly) {
 4303:         return $bodytag;
 4304:     } elsif ($env{'browser.interface'} eq 'textual') {
 4305: # Accessibility
 4306:           
 4307: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 4308: 	if (!$notitle) {
 4309: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 4310: 	}
 4311: 	return $bodytag;
 4312:     }
 4313: 
 4314:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 4315:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4316: 	undef($role);
 4317:     } else {
 4318: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 4319:     }
 4320:     
 4321:     my $roleinfo=(<<ENDROLE);
 4322: <td class="LC_title_bar_who">
 4323: <div class="LC_title_bar_name">
 4324:     $name
 4325:     &nbsp;
 4326: </div>
 4327: <div class="LC_title_bar_role">
 4328: $role&nbsp;
 4329: </div>
 4330: <div class="LC_title_bar_realm">
 4331: $realm&nbsp;
 4332: </div>
 4333: </td>
 4334: ENDROLE
 4335: 
 4336:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 4337:     if ($customtitle) {
 4338:         $titleinfo = $customtitle;
 4339:     }
 4340:     #
 4341:     # Extra info if you are the DC
 4342:     my $dc_info = '';
 4343:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 4344:                         $env{'course.'.$env{'request.course.id'}.
 4345:                                  '.domain'}.'/'})) {
 4346:         my $cid = $env{'request.course.id'};
 4347:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 4348:         $dc_info =~ s/\s+$//;
 4349:         $dc_info = '('.$dc_info.')';
 4350:     }
 4351: 
 4352:     if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
 4353:         # No Remote
 4354: 	if ($env{'request.state'} eq 'construct') {
 4355: 	    $forcereg=1;
 4356: 	}
 4357: 
 4358: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 4359: 	    # this is for resources; directories have customtitle, and crumbs
 4360:             # and select recent are created in lonpubdir.pm  
 4361: 	    my ($uname,$thisdisfn)=
 4362: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 4363: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 4364: 	    $formaction=~s/\/+/\//g;
 4365: 
 4366: 	    my $parentpath = '';
 4367: 	    my $lastitem = '';
 4368: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4369: 		$parentpath = $1;
 4370: 		$lastitem = $2;
 4371: 	    } else {
 4372: 		$lastitem = $thisdisfn;
 4373: 	    }
 4374: 	    $titleinfo = 
 4375: 		&Apache::loncommon::help_open_menu('','',3,'Authoring')
 4376: 		.'<b>'.&mt('Construction Space').'</b>:&nbsp;'
 4377: 		.'<form name="dirs" method="post" action="'.$formaction
 4378: 		.'" target="_top"><tt><b>'
 4379: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 4380: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 4381: 		.'</form>'
 4382: 		.&Apache::lonmenu::constspaceform();
 4383:         }
 4384: 
 4385:         my $titletable;
 4386: 	if (!$notitle) {
 4387: 	    $titletable =
 4388: 		'<table id="LC_title_bar">'.
 4389:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 4390: 			 '</tr></table>';
 4391: 	}
 4392: 	if ($notopbar) {
 4393: 	    $bodytag .= $titletable;
 4394: 	} else {
 4395: 	    if ($env{'request.state'} eq 'construct') {
 4396:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 4397: 							  $titletable);
 4398:             } else {
 4399:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 4400: 		    $titletable;
 4401:             }
 4402:         }
 4403:         return $bodytag;
 4404:     }
 4405: 
 4406: #
 4407: # Top frame rendering, Remote is up
 4408: #
 4409: 
 4410:     my $imgsrc = $img;
 4411:     if ($img =~ /^\/adm/) {
 4412:         $imgsrc = &lonhttpdurl($img);
 4413:     }
 4414:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 4415: 
 4416:     # Explicit link to get inline menu
 4417:     my $menu= ($no_inline_link?''
 4418: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 4419:     #
 4420:     if ($notitle) {
 4421: 	return $bodytag;
 4422:     }
 4423:     return(<<ENDBODY);
 4424: $bodytag
 4425: <table id="LC_title_bar" class="LC_with_remote">
 4426: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 4427:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 4428: </tr>
 4429: <tr><td>$titleinfo $dc_info $menu</td>
 4430: $roleinfo
 4431: </tr>
 4432: </table>
 4433: ENDBODY
 4434: }
 4435: 
 4436: sub make_attr_string {
 4437:     my ($register,$attr_ref) = @_;
 4438: 
 4439:     if ($attr_ref && !ref($attr_ref)) {
 4440: 	die("addentries Must be a hash ref ".
 4441: 	    join(':',caller(1))." ".
 4442: 	    join(':',caller(0))." ");
 4443:     }
 4444: 
 4445:     if ($register) {
 4446: 	my ($on_load,$on_unload);
 4447: 	foreach my $key (keys(%{$attr_ref})) {
 4448: 	    if      (lc($key) eq 'onload') {
 4449: 		$on_load.=$attr_ref->{$key}.';';
 4450: 		delete($attr_ref->{$key});
 4451: 
 4452: 	    } elsif (lc($key) eq 'onunload') {
 4453: 		$on_unload.=$attr_ref->{$key}.';';
 4454: 		delete($attr_ref->{$key});
 4455: 	    }
 4456: 	}
 4457: 	$attr_ref->{'onload'}  =
 4458: 	    &Apache::lonmenu::loadevents().  $on_load;
 4459: 	$attr_ref->{'onunload'}=
 4460: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4461:     }
 4462: 
 4463: # Accessibility font enhance
 4464:     if ($env{'browser.fontenhance'} eq 'on') {
 4465: 	my $style;
 4466: 	foreach my $key (keys(%{$attr_ref})) {
 4467: 	    if (lc($key) eq 'style') {
 4468: 		$style.=$attr_ref->{$key}.';';
 4469: 		delete($attr_ref->{$key});
 4470: 	    }
 4471: 	}
 4472: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4473:     }
 4474: 
 4475:     if ($env{'browser.blackwhite'} eq 'on') {
 4476: 	delete($attr_ref->{'font'});
 4477: 	delete($attr_ref->{'link'});
 4478: 	delete($attr_ref->{'alink'});
 4479: 	delete($attr_ref->{'vlink'});
 4480: 	delete($attr_ref->{'bgcolor'});
 4481: 	delete($attr_ref->{'background'});
 4482:     }
 4483: 
 4484:     my $attr_string;
 4485:     foreach my $attr (keys(%$attr_ref)) {
 4486: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4487:     }
 4488:     return $attr_string;
 4489: }
 4490: 
 4491: 
 4492: ###############################################
 4493: ###############################################
 4494: 
 4495: =pod
 4496: 
 4497: =item * &endbodytag()
 4498: 
 4499: Returns a uniform footer for LON-CAPA web pages.
 4500: 
 4501: Inputs: 1 - optional reference to an args hash
 4502: If in the hash, key for noredirectlink has a value which evaluates to true,
 4503: a 'Continue' link is not displayed if the page contains an
 4504: internal redirect in the <head></head> section,
 4505: i.e., $env{'internal.head.redirect'} exists   
 4506: 
 4507: =cut
 4508: 
 4509: sub endbodytag {
 4510:     my ($args) = @_;
 4511:     my $endbodytag='</body>';
 4512:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4513:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4514:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 4515: 	    $endbodytag=
 4516: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4517: 	        &mt('Continue').'</a>'.
 4518: 	        $endbodytag;
 4519:         }
 4520:     }
 4521:     return $endbodytag;
 4522: }
 4523: 
 4524: =pod
 4525: 
 4526: =item * &standard_css()
 4527: 
 4528: Returns a style sheet
 4529: 
 4530: Inputs: (all optional)
 4531:             domain         -> force to color decorate a page for a specific
 4532:                                domain
 4533:             function       -> force usage of a specific rolish color scheme
 4534:             bgcolor        -> override the default page bgcolor
 4535: 
 4536: =cut
 4537: 
 4538: sub standard_css {
 4539:     my ($function,$domain,$bgcolor) = @_;
 4540:     $function  = &get_users_function() if (!$function);
 4541:     my $img    = &designparm($function.'.img',   $domain);
 4542:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4543:     my $font   = &designparm($function.'.font',  $domain);
 4544:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4545:     my $pgbg_or_bgcolor =
 4546: 	         $bgcolor ||
 4547: 	         &designparm($function.'.pgbg',  $domain);
 4548:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4549:     my $alink  = &designparm($function.'.alink', $domain);
 4550:     my $vlink  = &designparm($function.'.vlink', $domain);
 4551:     my $link   = &designparm($function.'.link',  $domain);
 4552: 
 4553:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 4554:     my $mono                 = 'monospace';
 4555:     my $data_table_head      = $sidebg;
 4556:     my $data_table_light     = '#FAFAFA';
 4557:     my $data_table_dark      = '#F0F0F0';
 4558:     my $data_table_darker    = '#CCCCCC';
 4559:     my $data_table_highlight = '#FFFF00';
 4560:     my $mail_new             = '#FFBB77';
 4561:     my $mail_new_hover       = '#DD9955';
 4562:     my $mail_read            = '#BBBB77';
 4563:     my $mail_read_hover      = '#999944';
 4564:     my $mail_replied         = '#AAAA88';
 4565:     my $mail_replied_hover   = '#888855';
 4566:     my $mail_other           = '#99BBBB';
 4567:     my $mail_other_hover     = '#669999';
 4568:     my $table_header         = '#DDDDDD';
 4569:     my $feedback_link_bg     = '#BBBBBB';
 4570:     my $lg_border_color      = '#C8C8C8';
 4571: 
 4572:     my $border = ($env{'browser.type'} eq 'explorer' ||
 4573: 		  $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 4574: 	                                                 : '0 3px 0 4px';
 4575: 
 4576: 
 4577:     return <<END;
 4578: h1, h2, h3, th { font-family: $sans }
 4579: a:focus { color: red; background: yellow } 
 4580: 
 4581: hr {
 4582:   clear: both;
 4583:   color: $tabbg;
 4584:   background-color: $tabbg;
 4585:   height: 3px;
 4586:   border: none;
 4587: }
 4588: 
 4589: table.thinborder,
 4590: 
 4591: table.thinborder tr th {
 4592:   border-style: solid;
 4593:   border-width: 1px;
 4594:   background: $tabbg;
 4595: }
 4596: table.thinborder tr td {
 4597:   border-style: solid;
 4598:   border-width: 1px
 4599: }
 4600: 
 4601: form, .inline { display: inline; }
 4602: .center { text-align: center; }
 4603: .LC_filename {font-family: $mono; white-space:pre;}
 4604: .LC_error {
 4605:   color: red;
 4606:   font-size: larger;
 4607: }
 4608: .LC_warning,
 4609: .LC_diff_removed {
 4610:   color: red;
 4611: }
 4612: 
 4613: .LC_info,
 4614: .LC_success,
 4615: .LC_diff_added {
 4616:   color: green;
 4617: }
 4618: 
 4619: div.LC_confirm_box {
 4620:   background-color: #FAFAFA;
 4621:   border: 1px solid $lg_border_color;
 4622:   margin-right: 0;
 4623:   padding: 5px;
 4624: }
 4625: 
 4626: div.LC_confirm_box .LC_error img,
 4627: div.LC_confirm_box .LC_success img {
 4628:   vertical-align: middle;
 4629: }
 4630: 
 4631: .LC_icon {
 4632:   border: none;
 4633: }
 4634: .LC_indexer_icon {
 4635:   border: 0;
 4636:   height: 22px;
 4637: }
 4638: .LC_docs_spacer {
 4639:   width: 25px;
 4640:   height: 1px;
 4641:   border: none;
 4642: }
 4643: 
 4644: .LC_internal_info {
 4645:   color: #999999;
 4646: }
 4647: 
 4648: table.LC_pastsubmission {
 4649:   border: 1px solid black;
 4650:   margin: 2px;
 4651: }
 4652: 
 4653: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
 4654:   width: 100%;
 4655:   background: $pgbg;
 4656:   border: 2px;
 4657:   border-collapse: separate;
 4658:   padding: 0;
 4659: }
 4660: 
 4661: table#LC_title_bar, table.LC_breadcrumbs, 
 4662: table#LC_title_bar.LC_with_remote {
 4663:   width: 100%;
 4664:   border-color: $pgbg;
 4665:   border-style: solid;
 4666:   border-width: $border;
 4667: 
 4668:   background: $pgbg;
 4669:   font-family: $sans;
 4670:   border-collapse: collapse;
 4671:   padding: 0;
 4672: }
 4673: 
 4674: table.LC_docs_path {
 4675:   width: 100%;
 4676:   border: 0;
 4677:   background: $pgbg;
 4678:   font-family: $sans;
 4679:   border-collapse: collapse;
 4680:   padding: 0;
 4681: }
 4682: 
 4683: table#LC_title_bar td {
 4684:   background: $tabbg;
 4685: }
 4686: table#LC_title_bar td.LC_title_bar_who {
 4687:   background: $tabbg;
 4688:   color: $font;
 4689:   font: small $sans;
 4690:   text-align: right;
 4691: }
 4692: span.LC_metadata {
 4693:     font-family: $sans;
 4694: }
 4695: span.LC_title_bar_title {
 4696:   font: bold x-large $sans;
 4697: }
 4698: table#LC_title_bar td.LC_title_bar_domain_logo {
 4699:   background: $sidebg;
 4700:   text-align: right;
 4701:   padding: 0;
 4702: }
 4703: table#LC_title_bar td.LC_title_bar_role_logo {
 4704:   background: $sidebg;
 4705:   padding: 0;
 4706: }
 4707: 
 4708: table#LC_menubuttons_mainmenu {
 4709:   width: 100%;
 4710:   border: 0;
 4711:   border-spacing: 1px;
 4712:   padding: 0 1px;
 4713:   margin: 0;
 4714:   border-collapse: separate;
 4715: }
 4716: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4717:   border: none;
 4718: }
 4719: table#LC_top_nav td {
 4720:   background: $tabbg;
 4721:   border: none;
 4722:   font-size: small;
 4723: }
 4724: table#LC_top_nav td a, div#LC_top_nav a {
 4725:   color: $font;
 4726:   font-family: $sans;
 4727: }
 4728: table#LC_top_nav td.LC_top_nav_logo {
 4729:   background: $tabbg;
 4730:   text-align: left;
 4731:   white-space: nowrap;
 4732:   width: 31px;
 4733: }
 4734: table#LC_top_nav td.LC_top_nav_logo img {
 4735:   border: none;
 4736:   vertical-align: bottom;
 4737: }
 4738: table#LC_top_nav td.LC_top_nav_exit,
 4739: table#LC_top_nav td.LC_top_nav_help {
 4740:   width: 2.0em;
 4741: }
 4742: table#LC_top_nav td.LC_top_nav_login {
 4743:   width: 4.0em;
 4744:   text-align: center;
 4745: }
 4746: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4747:   background: $tabbg;
 4748:   color: $font;
 4749:   font-family: $sans;
 4750:   font-size: smaller;
 4751: }
 4752: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4753: table.LC_docs_path td.LC_docs_path_component {
 4754:   background: $tabbg;
 4755:   color: $font;
 4756:   font-family: $sans;
 4757:   font-size: larger;
 4758:   text-align: right;
 4759: }
 4760: td.LC_table_cell_checkbox {
 4761:   text-align: center;
 4762: }
 4763: table#LC_mainmenu td.LC_mainmenu_column {
 4764:     vertical-align: top;
 4765: }
 4766: 
 4767: .LC_menubuttons_inline_text {
 4768:   color: $font;
 4769:   font-family: $sans;
 4770:   font-size: smaller;
 4771: }
 4772: 
 4773: .LC_menubuttons_link {
 4774:   text-decoration: none;
 4775: }
 4776: /*2008--9-5: new menu style sheet.Changed category*/
 4777: .LC_menubuttons_category {
 4778:   color: $font;
 4779:   background: $pgbg;
 4780:   font-family: $sans;
 4781:   font-size: larger;
 4782:   font-weight: bold;
 4783: }
 4784: 
 4785: td.LC_menubuttons_text {
 4786:   width: 90%;
 4787:   color: $font;
 4788:   font-family: $sans;
 4789: }
 4790: 
 4791: td.LC_menubuttons_img {
 4792: }
 4793: 
 4794: .LC_current_location {
 4795:   font-family: $sans;
 4796:   background: $tabbg;
 4797: }
 4798: .LC_new_mail {
 4799:   font-family: $sans;
 4800:   background: $tabbg;
 4801:   font-weight: bold;
 4802: }
 4803: 
 4804: .LC_dropadd_labeltext {
 4805:   font-family: $sans;
 4806:   text-align: right;
 4807: }
 4808: 
 4809: .LC_preferences_labeltext {
 4810:   font-family: $sans;
 4811:   text-align: right;
 4812: }
 4813: 
 4814: .LC_roleslog_note {
 4815:   font-size: smaller;
 4816: }
 4817: 
 4818: .LC_mail_functions {
 4819:     font-weight: bold;
 4820: }
 4821: 
 4822: table.LC_aboutme_port {
 4823:   border: none;
 4824:   border-collapse: collapse;
 4825:   border-spacing: 0;
 4826: }
 4827: table.LC_data_table, table.LC_mail_list {
 4828:   border: 1px solid #000000;
 4829:   border-collapse: separate;
 4830:   border-spacing: 1px;
 4831:   background: $pgbg;
 4832: }
 4833: .LC_data_table_dense {
 4834:   font-size: small;
 4835: }
 4836: table.LC_nested_outer {
 4837:   border: 1px solid #000000;
 4838:   border-collapse: collapse;
 4839:   border-spacing: 0;
 4840:   width: 100%;
 4841: }
 4842: table.LC_nested {
 4843:   border: none;
 4844:   border-collapse: collapse;
 4845:   border-spacing: 0;
 4846:   width: 100%;
 4847: }
 4848: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4849: table.LC_prior_tries tr th {
 4850:   font-weight: bold;
 4851:   background-color: $data_table_head;
 4852:   font-size: smaller;
 4853: }
 4854: table.LC_data_table tr.LC_info_row > td {
 4855:   background-color: #CCCCCC;
 4856:   font-weight: bold;
 4857:   text-align: left;
 4858: }
 4859: table.LC_data_table tr.LC_odd_row > td, 
 4860: table.LC_pick_box tr > td.LC_odd_row,
 4861: table.LC_aboutme_port tr td {
 4862:   background-color: $data_table_light;
 4863:   padding: 2px;
 4864: }
 4865: table.LC_data_table tr.LC_even_row > td,
 4866: table.LC_pick_box tr > td.LC_even_row,
 4867: table.LC_aboutme_port tr.LC_even_row td {
 4868:   background-color: $data_table_dark;
 4869:   padding: 2px;
 4870: }
 4871: table.LC_data_table tr.LC_data_table_highlight td {
 4872:   background-color: $data_table_darker;
 4873: }
 4874: table.LC_data_table tr td.LC_leftcol_header {
 4875:   background-color: $data_table_head;
 4876:   font-weight: bold;
 4877: }
 4878: table.LC_data_table tr.LC_empty_row td,
 4879: table.LC_nested tr.LC_empty_row td {
 4880:   background-color: #FFFFFF;
 4881:   font-weight: bold;
 4882:   font-style: italic;
 4883:   text-align: center;
 4884:   padding: 8px;
 4885: }
 4886: table.LC_nested tr.LC_empty_row td {
 4887:   padding: 4ex
 4888: }
 4889: table.LC_nested_outer tr th {
 4890:   font-weight: bold;
 4891:   background-color: $data_table_head;
 4892:   font-size: smaller;
 4893:   border-bottom: 1px solid #000000;
 4894: }
 4895: table.LC_nested_outer tr td.LC_subheader {
 4896:   background-color: $data_table_head;
 4897:   font-weight: bold;
 4898:   font-size: small;
 4899:   border-bottom: 1px solid #000000;
 4900:   text-align: right;
 4901: }
 4902: table.LC_nested tr.LC_info_row td {
 4903:   background-color: #CCCCCC;
 4904:   font-weight: bold;
 4905:   font-size: small;
 4906:   text-align: center;
 4907: }
 4908: table.LC_nested tr.LC_info_row td.LC_left_item,
 4909: table.LC_nested_outer tr th.LC_left_item {
 4910:   text-align: left;
 4911: }
 4912: table.LC_nested td {
 4913:   background-color: #FFFFFF;
 4914:   font-size: small;
 4915: }
 4916: table.LC_nested_outer tr th.LC_right_item,
 4917: table.LC_nested tr.LC_info_row td.LC_right_item,
 4918: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4919: table.LC_nested tr td.LC_right_item {
 4920:   text-align: right;
 4921: }
 4922: 
 4923: table.LC_nested tr.LC_odd_row td {
 4924:   background-color: #EEEEEE;
 4925: }
 4926: 
 4927: table.LC_createuser {
 4928: }
 4929: 
 4930: table.LC_createuser tr.LC_section_row td {
 4931:   font-size: smaller;
 4932: }
 4933: 
 4934: table.LC_createuser tr.LC_info_row td  {
 4935:   background-color: #CCCCCC;
 4936:   font-weight: bold;
 4937:   text-align: center;
 4938: }
 4939: 
 4940: table.LC_calendar {
 4941:   border: 1px solid #000000;
 4942:   border-collapse: collapse;
 4943: }
 4944: table.LC_calendar_pickdate {
 4945:   font-size: xx-small;
 4946: }
 4947: table.LC_calendar tr td {
 4948:   border: 1px solid #000000;
 4949:   vertical-align: top;
 4950: }
 4951: table.LC_calendar tr td.LC_calendar_day_empty {
 4952:   background-color: $data_table_dark;
 4953: }
 4954: table.LC_calendar tr td.LC_calendar_day_current {
 4955:   background-color: $data_table_highlight;
 4956: }
 4957: 
 4958: table.LC_mail_list tr.LC_mail_new {
 4959:   background-color: $mail_new;
 4960: }
 4961: table.LC_mail_list tr.LC_mail_new:hover {
 4962:   background-color: $mail_new_hover;
 4963: }
 4964: table.LC_mail_list tr.LC_mail_read {
 4965:   background-color: $mail_read;
 4966: }
 4967: table.LC_mail_list tr.LC_mail_read:hover {
 4968:   background-color: $mail_read_hover;
 4969: }
 4970: table.LC_mail_list tr.LC_mail_replied {
 4971:   background-color: $mail_replied;
 4972: }
 4973: table.LC_mail_list tr.LC_mail_replied:hover {
 4974:   background-color: $mail_replied_hover;
 4975: }
 4976: table.LC_mail_list tr.LC_mail_other {
 4977:   background-color: $mail_other;
 4978: }
 4979: table.LC_mail_list tr.LC_mail_other:hover {
 4980:   background-color: $mail_other_hover;
 4981: }
 4982: table.LC_mail_list tr.LC_mail_even {
 4983: }
 4984: table.LC_mail_list tr.LC_mail_odd {
 4985: }
 4986: 
 4987: 
 4988: table#LC_portfolio_actions {
 4989:   width: auto;
 4990:   background: $pgbg;
 4991:   border: none;
 4992:   border-spacing: 2px 2px;
 4993:   padding: 0;
 4994:   margin: 0;
 4995:   border-collapse: separate;
 4996: }
 4997: table#LC_portfolio_actions td.LC_label {
 4998:   background: $tabbg;
 4999:   text-align: right;
 5000: }
 5001: table#LC_portfolio_actions td.LC_value {
 5002:   background: $tabbg;
 5003: }
 5004: 
 5005: table#LC_cstr_controls {
 5006:   width: 100%;
 5007:   border-collapse: collapse;
 5008: }
 5009: table#LC_cstr_controls tr td {
 5010:   border: 4px solid $pgbg;
 5011:   padding: 4px;
 5012:   text-align: center;
 5013:   background: $tabbg;
 5014: }
 5015: table#LC_cstr_controls tr th {
 5016:   border: 4px solid $pgbg;
 5017:   background: $table_header;
 5018:   text-align: center;
 5019:   font-family: $sans;
 5020:   font-size: smaller;
 5021: }
 5022: 
 5023: table#LC_browser {
 5024:  
 5025: }
 5026: table#LC_browser tr th {
 5027:   background: $table_header;
 5028: }
 5029: table#LC_browser tr td {
 5030:   padding: 2px;
 5031: }
 5032: table#LC_browser tr.LC_browser_file,
 5033: table#LC_browser tr.LC_browser_file_published {
 5034:   background: #CCFF88;
 5035: }
 5036: table#LC_browser tr.LC_browser_file_locked,
 5037: table#LC_browser tr.LC_browser_file_unpublished {
 5038:   background: #FFAA99;
 5039: }
 5040: table#LC_browser tr.LC_browser_file_obsolete {
 5041:   background: #AAAAAA;
 5042: }
 5043: table#LC_browser tr.LC_browser_file_modified,
 5044: table#LC_browser tr.LC_browser_file_metamodified {
 5045:   background: #FFFF77;
 5046: }
 5047: table#LC_browser tr.LC_browser_folder {
 5048:   background: #CCCCFF;
 5049: }
 5050: 
 5051: table.LC_data_table tr > td.LC_roles_is {
 5052: /*  background: #77FF77; */
 5053: }
 5054: table.LC_data_table tr > td.LC_roles_future {
 5055:   background: #FFFF77;
 5056: }
 5057: table.LC_data_table tr > td.LC_roles_will {
 5058:   background: #FFAA77;
 5059: }
 5060: table.LC_data_table tr > td.LC_roles_expired {
 5061:   background: #FF7777;
 5062: }
 5063: table.LC_data_table tr > td.LC_roles_will_not {
 5064:   background: #AAFF77;
 5065: }
 5066: table.LC_data_table tr > td.LC_roles_selected {
 5067:   background: #11CC55;
 5068: }
 5069: 
 5070: span.LC_current_location {
 5071:   font-size: x-large;
 5072:   background: $pgbg;
 5073: }
 5074: 
 5075: span.LC_parm_menu_item {
 5076:   font-size: larger;
 5077:   font-family: $sans;
 5078: }
 5079: span.LC_parm_scope_all {
 5080:   color: red;
 5081: }
 5082: span.LC_parm_scope_folder {
 5083:   color: green;
 5084: }
 5085: span.LC_parm_scope_resource {
 5086:   color: orange;
 5087: }
 5088: span.LC_parm_part {
 5089:   color: blue;
 5090: }
 5091: span.LC_parm_folder, span.LC_parm_symb {
 5092:   font-size: x-small;
 5093:   font-family: $mono;
 5094:   color: #AAAAAA;
 5095: }
 5096: 
 5097: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 5098: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 5099:   border: 1px solid black;
 5100:   border-collapse: collapse;
 5101: }
 5102: table.LC_parm_overview_restrictions td {
 5103:   border-width: 1px 4px 1px 4px;
 5104:   border-style: solid;
 5105:   border-color: $pgbg;
 5106:   text-align: center;
 5107: }
 5108: table.LC_parm_overview_restrictions th {
 5109:   background: $tabbg;
 5110:   border-width: 1px 4px 1px 4px;
 5111:   border-style: solid;
 5112:   border-color: $pgbg;
 5113: }
 5114: table#LC_helpmenu {
 5115:   border: none;
 5116:   height: 55px;
 5117:   border-spacing: 0;
 5118: }
 5119: 
 5120: table#LC_helpmenu fieldset legend {
 5121:   font-size: larger;
 5122:   font-weight: bold;
 5123: }
 5124: table#LC_helpmenu_links {
 5125:   width: 100%;
 5126:   border: 1px solid black;
 5127:   background: $pgbg;
 5128:   padding: 0;
 5129:   border-spacing: 1px;
 5130: }
 5131: table#LC_helpmenu_links tr td {
 5132:   padding: 1px;
 5133:   background: $tabbg;
 5134:   text-align: center;
 5135:   font-weight: bold;
 5136: }
 5137: 
 5138: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 5139: table#LC_helpmenu_links a:active {
 5140:   text-decoration: none;
 5141:   color: $font;
 5142: }
 5143: table#LC_helpmenu_links a:hover {
 5144:   text-decoration: underline;
 5145:   color: $vlink;
 5146: }
 5147: 
 5148: .LC_chrt_popup_exists {
 5149:   border: 1px solid #339933;
 5150:   margin: -1px;
 5151: }
 5152: .LC_chrt_popup_up {
 5153:   border: 1px solid yellow;
 5154:   margin: -1px;
 5155: }
 5156: .LC_chrt_popup {
 5157:   border: 1px solid #8888FF;
 5158:   background: #CCCCFF;
 5159: }
 5160: table.LC_pick_box {
 5161:   border-collapse: separate;
 5162:   background: white;
 5163:   border: 1px solid black;
 5164:   border-spacing: 1px;
 5165: }
 5166: table.LC_pick_box td.LC_pick_box_title {
 5167:   background: $sidebg;
 5168:   font-weight: bold;
 5169:   text-align: right;
 5170:   vertical-align: top;
 5171:   width: 184px;
 5172:   padding: 8px;
 5173: }
 5174: table.LC_pick_box td.LC_selfenroll_pick_box_title {
 5175:   background: $sidebg;
 5176:   font-weight: bold;
 5177:   text-align: right;
 5178:   width: 350px;
 5179:   padding: 8px;
 5180: }
 5181: 
 5182: table.LC_pick_box td.LC_pick_box_value {
 5183:   text-align: left;
 5184:   padding: 8px;
 5185: }
 5186: table.LC_pick_box td.LC_pick_box_select {
 5187:   text-align: left;
 5188:   padding: 8px;
 5189: }
 5190: table.LC_pick_box td.LC_pick_box_separator {
 5191:   padding: 0;
 5192:   height: 1px;
 5193:   background: black;
 5194: }
 5195: table.LC_pick_box td.LC_pick_box_submit {
 5196:   text-align: right;
 5197: }
 5198: table.LC_pick_box td.LC_evenrow_value {
 5199:   text-align: left;
 5200:   padding: 8px;
 5201:   background-color: $data_table_light;
 5202: }
 5203: table.LC_pick_box td.LC_oddrow_value {
 5204:   text-align: left;
 5205:   padding: 8px;
 5206:   background-color: $data_table_light;
 5207: }
 5208: table.LC_helpform_receipt {
 5209:   width: 620px;
 5210:   border-collapse: separate;
 5211:   background: white;
 5212:   border: 1px solid black;
 5213:   border-spacing: 1px;
 5214: }
 5215: table.LC_helpform_receipt td.LC_pick_box_title {
 5216:   background: $tabbg;
 5217:   font-weight: bold;
 5218:   text-align: right;
 5219:   width: 184px;
 5220:   padding: 8px;
 5221: }
 5222: table.LC_helpform_receipt td.LC_evenrow_value {
 5223:   text-align: left;
 5224:   padding: 8px;
 5225:   background-color: $data_table_light;
 5226: }
 5227: table.LC_helpform_receipt td.LC_oddrow_value {
 5228:   text-align: left;
 5229:   padding: 8px;
 5230:   background-color: $data_table_light;
 5231: }
 5232: table.LC_helpform_receipt td.LC_pick_box_separator {
 5233:   padding: 0;
 5234:   height: 1px;
 5235:   background: black;
 5236: }
 5237: span.LC_helpform_receipt_cat {
 5238:   font-weight: bold;
 5239: }
 5240: table.LC_group_priv_box {
 5241:   background: white;
 5242:   border: 1px solid black;
 5243:   border-spacing: 1px;
 5244: }
 5245: table.LC_group_priv_box td.LC_pick_box_title {
 5246:   background: $tabbg;
 5247:   font-weight: bold;
 5248:   text-align: right;
 5249:   width: 184px;
 5250: }
 5251: table.LC_group_priv_box td.LC_groups_fixed {
 5252:   background: $data_table_light;
 5253:   text-align: center;
 5254: }
 5255: table.LC_group_priv_box td.LC_groups_optional {
 5256:   background: $data_table_dark;
 5257:   text-align: center;
 5258: }
 5259: table.LC_group_priv_box td.LC_groups_functionality {
 5260:   background: $data_table_darker;
 5261:   text-align: center;
 5262:   font-weight: bold;
 5263: }
 5264: table.LC_group_priv td {
 5265:   text-align: left;
 5266:   padding: 0;
 5267: }
 5268: 
 5269: table.LC_notify_front_page {
 5270:   background: white;
 5271:   border: 1px solid black;
 5272:   padding: 8px;
 5273: }
 5274: table.LC_notify_front_page td {
 5275:   padding: 8px;
 5276: }
 5277: .LC_navbuttons {
 5278:   margin: 2ex 0ex 2ex 0ex;
 5279: }
 5280: .LC_topic_bar {
 5281:   font-family: $sans;
 5282:   font-weight: bold;
 5283:   width: 100%;
 5284:   background: $tabbg;
 5285:   vertical-align: middle;
 5286:   margin: 2ex 0ex 2ex 0ex;
 5287:   padding: 3px;
 5288: }
 5289: .LC_topic_bar span {
 5290:   vertical-align: middle;
 5291: }
 5292: .LC_topic_bar img {
 5293:   vertical-align: bottom;
 5294: }
 5295: table.LC_course_group_status {
 5296:   margin: 20px;
 5297: }
 5298: table.LC_status_selector td {
 5299:   vertical-align: top;
 5300:   text-align: center;
 5301:   padding: 4px;
 5302: }
 5303: table.LC_descriptive_input td.LC_description {
 5304:   vertical-align: top;
 5305:   text-align: right;
 5306:   font-weight: bold;
 5307: }
 5308: div.LC_feedback_link {
 5309:   clear: both;
 5310:   background: white;
 5311:   width: 100%;  
 5312: }
 5313: span.LC_feedback_link {
 5314:   background: $feedback_link_bg;
 5315:   font-size: larger;
 5316: }
 5317: span.LC_message_link {
 5318:   background: $feedback_link_bg;
 5319:   font-size: larger;
 5320:   position: absolute;
 5321:   right: 1em;
 5322: }
 5323: 
 5324: table.LC_prior_tries {
 5325:   border: 1px solid #000000;
 5326:   border-collapse: separate;
 5327:   border-spacing: 1px;
 5328: }
 5329: 
 5330: table.LC_prior_tries td {
 5331:   padding: 2px;
 5332: }
 5333: 
 5334: .LC_answer_correct {
 5335:   background: #AAFFAA;
 5336:   color: black;
 5337: }
 5338: .LC_answer_charged_try {
 5339:   background: #FFAAAA ! important;
 5340:   color: black;
 5341: }
 5342: .LC_answer_not_charged_try, 
 5343: .LC_answer_no_grade,
 5344: .LC_answer_late {
 5345:   background: #FFFFAA;
 5346:   color: black;
 5347: }
 5348: .LC_answer_previous {
 5349:   background: #AAAAFF;
 5350:   color: black;
 5351: }
 5352: .LC_answer_no_message {
 5353:   background: #FFFFFF;
 5354:   color: black;
 5355: }
 5356: .LC_answer_unknown {
 5357:   background: orange;
 5358:   color: black;
 5359: }
 5360: 
 5361: 
 5362: span.LC_prior_numerical,
 5363: span.LC_prior_string,
 5364: span.LC_prior_custom,
 5365: span.LC_prior_reaction,
 5366: span.LC_prior_math {
 5367:   font-family: monospace;
 5368:   white-space: pre;
 5369: }
 5370: 
 5371: span.LC_prior_string {
 5372:   font-family: monospace;
 5373:   white-space: pre;
 5374: }
 5375: 
 5376: table.LC_prior_option {
 5377:   width: 100%;
 5378:   border-collapse: collapse;
 5379: }
 5380: table.LC_prior_rank, table.LC_prior_match {
 5381:   border-collapse: collapse;
 5382: }
 5383: table.LC_prior_option tr td,
 5384: table.LC_prior_rank tr td,
 5385: table.LC_prior_match tr td {
 5386:   border: 1px solid #000000;
 5387: }
 5388: 
 5389: span.LC_nobreak {
 5390:   white-space: nowrap;
 5391: }
 5392: 
 5393: span.LC_cusr_emph {
 5394:   font-style: italic;
 5395: }
 5396: 
 5397: span.LC_cusr_subheading {
 5398:   font-weight: normal;
 5399:   font-size: 85%;
 5400: }
 5401: 
 5402: table.LC_docs_documents {
 5403:   background: #BBBBBB;
 5404:   border-width: 0;
 5405:   border-collapse: collapse;
 5406: }
 5407: 
 5408: table.LC_docs_documents td.LC_docs_document {
 5409:   border: 2px solid black;
 5410:   padding: 4px;
 5411: }
 5412: 
 5413: .LC_docs_course_commands div {
 5414:   float: left;
 5415:   border: 4px solid #AAAAAA;
 5416:   padding: 4px;
 5417:   background: #DDDDCC;
 5418: }
 5419: 
 5420: .LC_docs_entry_move {
 5421:   border: none;
 5422:   border-collapse: collapse;
 5423: }
 5424: 
 5425: .LC_docs_entry_move td {
 5426:   border: 2px solid #BBBBBB;
 5427:   background: #DDDDDD;
 5428: }
 5429: 
 5430: .LC_docs_editor td.LC_docs_entry_commands {
 5431:   background: #DDDDDD;
 5432:   font-size: x-small;
 5433: }
 5434: .LC_docs_copy {
 5435:   color: #000099;
 5436: }
 5437: .LC_docs_cut {
 5438:   color: #550044;
 5439: }
 5440: .LC_docs_rename {
 5441:   color: #009900;
 5442: }
 5443: .LC_docs_remove {
 5444:   color: #990000;
 5445: }
 5446: 
 5447: .LC_docs_reinit_warn,
 5448: .LC_docs_ext_edit {
 5449:   font-size: x-small;
 5450: }
 5451: 
 5452: .LC_docs_editor td.LC_docs_entry_title,
 5453: .LC_docs_editor td.LC_docs_entry_icon {
 5454:   background: #FFFFBB;
 5455: }
 5456: .LC_docs_editor td.LC_docs_entry_parameter {
 5457:   background: #BBBBFF;
 5458:   font-size: x-small;
 5459:   white-space: nowrap;
 5460: }
 5461: 
 5462: table.LC_docs_adddocs td,
 5463: table.LC_docs_adddocs th {
 5464:   border: 1px solid #BBBBBB;
 5465:   padding: 4px;
 5466:   background: #DDDDDD;
 5467: }
 5468: 
 5469: table.LC_sty_begin {
 5470:   background: #BBFFBB;
 5471: }
 5472: table.LC_sty_end {
 5473:   background: #FFBBBB;
 5474: }
 5475: 
 5476: table.LC_double_column {
 5477:   border-width: 0;
 5478:   border-collapse: collapse;
 5479:   width: 100%;
 5480:   padding: 2px;
 5481: }
 5482: 
 5483: table.LC_double_column tr td.LC_left_col {
 5484:   top: 2px;
 5485:   left: 2px;
 5486:   width: 47%;
 5487:   vertical-align: top;
 5488: }
 5489: 
 5490: table.LC_double_column tr td.LC_right_col {
 5491:   top: 2px;
 5492:   right: 2px; 
 5493:   width: 47%;
 5494:   vertical-align: top;
 5495: }
 5496: 
 5497: span.LC_role_level {
 5498:   font-weight: bold;
 5499: }
 5500: 
 5501: div.LC_left_float {
 5502:   float: left;
 5503:   padding-right: 5%;
 5504:   padding-bottom: 4px;
 5505: }
 5506: 
 5507: div.LC_clear_float_header {
 5508:   padding-bottom: 2px;
 5509: }
 5510: 
 5511: div.LC_clear_float_footer {
 5512:   padding-top: 10px;
 5513:   clear: both;
 5514: }
 5515: 
 5516: 
 5517: div.LC_grade_select_mode {
 5518:   font-family: $sans;
 5519: }
 5520: div.LC_grade_select_mode div div {
 5521:   margin: 5px;
 5522: }
 5523: div.LC_grade_select_mode_selector {
 5524:   margin: 5px;
 5525:   float: left;
 5526: }
 5527: div.LC_grade_select_mode_selector_header {
 5528:   font: bold medium $sans;
 5529: }
 5530: div.LC_grade_select_mode_type {
 5531:   clear: left;
 5532: }
 5533: 
 5534: div.LC_grade_show_user {
 5535:   margin-top: 20px;
 5536:   border: 1px solid black;
 5537: }
 5538: div.LC_grade_user_name {
 5539:   background: #DDDDEE;
 5540:   border-bottom: 1px solid black;
 5541:   font: bold large $sans;
 5542: }
 5543: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
 5544:   background: #DDEEDD;
 5545: }
 5546: 
 5547: div.LC_grade_show_problem,
 5548: div.LC_grade_submissions,
 5549: div.LC_grade_message_center,
 5550: div.LC_grade_info_links,
 5551: div.LC_grade_assign {
 5552:   margin: 5px;
 5553:   width: 99%;
 5554:   background: #FFFFFF;
 5555: }
 5556: div.LC_grade_show_problem_header,
 5557: div.LC_grade_submissions_header,
 5558: div.LC_grade_message_center_header,
 5559: div.LC_grade_assign_header {
 5560:   font: bold large $sans;
 5561: }
 5562: div.LC_grade_show_problem_problem,
 5563: div.LC_grade_submissions_body,
 5564: div.LC_grade_message_center_body,
 5565: div.LC_grade_assign_body {
 5566:   border: 1px solid black;
 5567:   width: 99%;
 5568:   background: #FFFFFF;
 5569: }
 5570: span.LC_grade_check_note {
 5571:   font: normal medium $sans;
 5572:   display: inline;
 5573:   position: absolute;
 5574:   right: 1em;
 5575: }
 5576: 
 5577: table.LC_scantron_action {
 5578:   width: 100%;
 5579: }
 5580: table.LC_scantron_action tr th {
 5581:   font: normal bold $sans;
 5582: }
 5583: 
 5584: div.LC_edit_problem_header, 
 5585: div.LC_edit_problem_footer {
 5586:   font: normal medium $sans;
 5587:   margin: 2px;
 5588: }
 5589: div.LC_edit_problem_header,
 5590: div.LC_edit_problem_header div,
 5591: div.LC_edit_problem_footer,
 5592: div.LC_edit_problem_footer div,
 5593: div.LC_edit_problem_editxml_header,
 5594: div.LC_edit_problem_editxml_header div {
 5595:   margin-top: 5px;
 5596: }
 5597: div.LC_edit_problem_header_edit_row {
 5598:   background: $tabbg;
 5599:   padding: 3px;
 5600:   margin-bottom: 5px;
 5601: }
 5602: div.LC_edit_problem_header_title {
 5603:   font: larger bold $sans;
 5604:   background: $tabbg;
 5605:   padding: 3px;
 5606: }
 5607: table.LC_edit_problem_header_title {
 5608:   font: larger bold $sans;
 5609:   width: 100%;
 5610:   border-color: $pgbg;
 5611:   border-style: solid;
 5612:   border-width: $border;
 5613: 
 5614:   background: $tabbg;
 5615:   border-collapse: collapse;
 5616:   padding: 0;
 5617: }
 5618: 
 5619: div.LC_edit_problem_discards {
 5620:   float: left;
 5621:   padding-bottom: 5px;
 5622: }
 5623: div.LC_edit_problem_saves {
 5624:   float: right;
 5625:   padding-bottom: 5px;
 5626: }
 5627: hr.LC_edit_problem_divide {
 5628:   clear: both;
 5629:   color: $tabbg;
 5630:   background-color: $tabbg;
 5631:   height: 3px;
 5632:   border: none;
 5633: }
 5634: img.stift{
 5635:   border-width:0;
 5636:   vertical-align:middle;
 5637: }
 5638: 
 5639: table#LC_mainmenu{
 5640:  margin-top:10px;
 5641:  width:80%;
 5642: 
 5643: }
 5644: 
 5645: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
 5646:   vertical-align: top;
 5647:   width: 45%;
 5648: }
 5649: .LC_mainmenu_fieldset_category {
 5650:   color: $font;
 5651:   background: $pgbg;
 5652:   font-family: $sans;
 5653:   font-size: small;
 5654:   font-weight: bold;
 5655: }
 5656: fieldset#LC_mainmenu_fieldset {
 5657:   margin:0 10px 10px 0;
 5658: 
 5659: }
 5660: 
 5661: div.LC_createcourse {
 5662:     margin: 10px 10px 10px 10px;
 5663: }
 5664: 
 5665: END
 5666: }
 5667: 
 5668: =pod
 5669: 
 5670: =item * &headtag()
 5671: 
 5672: Returns a uniform footer for LON-CAPA web pages.
 5673: 
 5674: Inputs: $title - optional title for the head
 5675:         $head_extra - optional extra HTML to put inside the <head>
 5676:         $args - optional arguments
 5677:             force_register - if is true call registerurl so the remote is 
 5678:                              informed
 5679:             redirect       -> array ref of
 5680:                                    1- seconds before redirect occurs
 5681:                                    2- url to redirect to
 5682:                                    3- whether the side effect should occur
 5683:                            (side effect of setting 
 5684:                                $env{'internal.head.redirect'} to the url 
 5685:                                redirected too)
 5686:             domain         -> force to color decorate a page for a specific
 5687:                                domain
 5688:             function       -> force usage of a specific rolish color scheme
 5689:             bgcolor        -> override the default page bgcolor
 5690:             no_auto_mt_title
 5691:                            -> prevent &mt()ing the title arg
 5692: 
 5693: =cut
 5694: 
 5695: sub headtag {
 5696:     my ($title,$head_extra,$args) = @_;
 5697:     
 5698:     my $function = $args->{'function'} || &get_users_function();
 5699:     my $domain   = $args->{'domain'}   || &determinedomain();
 5700:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5701:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5702: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5703: 		   #time(),
 5704: 		   $env{'environment.color.timestamp'},
 5705: 		   $function,$domain,$bgcolor);
 5706: 
 5707:     $url = '/adm/css/'.&escape($url).'.css';
 5708: 
 5709:     my $result =
 5710: 	'<head>'.
 5711: 	&font_settings();
 5712: 
 5713:     if (!$args->{'frameset'}) {
 5714: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5715:     }
 5716:     if ($args->{'force_register'}) {
 5717: 	$result .= &Apache::lonmenu::registerurl(1);
 5718:     }
 5719:     if (!$args->{'no_nav_bar'} 
 5720: 	&& !$args->{'only_body'}
 5721: 	&& !$args->{'frameset'}) {
 5722: 	$result .= &help_menu_js();
 5723:     }
 5724: 
 5725:     if (ref($args->{'redirect'})) {
 5726: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5727: 	$url = &Apache::lonenc::check_encrypt($url);
 5728: 	if (!$inhibit_continue) {
 5729: 	    $env{'internal.head.redirect'} = $url;
 5730: 	}
 5731: 	$result.=<<ADDMETA
 5732: <meta http-equiv="pragma" content="no-cache" />
 5733: <meta http-equiv="Refresh" content="$time; url=$url" />
 5734: ADDMETA
 5735:     }
 5736:     if (!defined($title)) {
 5737: 	$title = 'The LearningOnline Network with CAPA';
 5738:     }
 5739:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5740:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5741: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5742: 	.$head_extra;
 5743:     return $result;
 5744: }
 5745: 
 5746: =pod
 5747: 
 5748: =item * &font_settings()
 5749: 
 5750: Returns neccessary <meta> to set the proper encoding
 5751: 
 5752: Inputs: none
 5753: 
 5754: =cut
 5755: 
 5756: sub font_settings {
 5757:     my $headerstring='';
 5758:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5759: 	$headerstring.=
 5760: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5761:     }
 5762:     return $headerstring;
 5763: }
 5764: 
 5765: =pod
 5766: 
 5767: =item * &xml_begin()
 5768: 
 5769: Returns the needed doctype and <html>
 5770: 
 5771: Inputs: none
 5772: 
 5773: =cut
 5774: 
 5775: sub xml_begin {
 5776:     my $output='';
 5777: 
 5778:     if ($env{'internal.start_page'}==1) {
 5779: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5780:     }
 5781: 
 5782:     if ($env{'browser.mathml'}) {
 5783: 	$output='<?xml version="1.0"?>'
 5784:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5785: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5786:             
 5787: #	    .'<!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">] >'
 5788: 	    .'<!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">'
 5789:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5790: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5791:     } else {
 5792: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
 5793:             '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 5794:     }
 5795:     return $output;
 5796: }
 5797: 
 5798: =pod
 5799: 
 5800: =item * &endheadtag()
 5801: 
 5802: Returns a uniform </head> for LON-CAPA web pages.
 5803: 
 5804: Inputs: none
 5805: 
 5806: =cut
 5807: 
 5808: sub endheadtag {
 5809:     return '</head>';
 5810: }
 5811: 
 5812: =pod
 5813: 
 5814: =item * &head()
 5815: 
 5816: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5817: 
 5818: Inputs:
 5819: 
 5820: =over 4
 5821: 
 5822: $title - optional title for the page
 5823: 
 5824: $head_extra - optional extra HTML to put inside the <head>
 5825: 
 5826: =back
 5827: 
 5828: =cut
 5829: 
 5830: sub head {
 5831:     my ($title,$head_extra,$args) = @_;
 5832:     return &headtag($title,$head_extra,$args).&endheadtag();
 5833: }
 5834: 
 5835: =pod
 5836: 
 5837: =item * &start_page()
 5838: 
 5839: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5840: 
 5841: Inputs:
 5842: 
 5843: =over 4
 5844: 
 5845: $title - optional title for the page
 5846: 
 5847: $head_extra - optional extra HTML to incude inside the <head>
 5848: 
 5849: $args - additional optional args supported are:
 5850: 
 5851: =over 8
 5852: 
 5853:              only_body      -> is true will set &bodytag() onlybodytag
 5854:                                     arg on
 5855:              no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5856:              add_entries    -> additional attributes to add to the  <body>
 5857:              domain         -> force to color decorate a page for a 
 5858:                                     specific domain
 5859:              function       -> force usage of a specific rolish color
 5860:                                     scheme
 5861:              redirect       -> see &headtag()
 5862:              bgcolor        -> override the default page bg color
 5863:              js_ready       -> return a string ready for being used in 
 5864:                                     a javascript writeln
 5865:              html_encode    -> return a string ready for being used in 
 5866:                                     a html attribute
 5867:              force_register -> if is true will turn on the &bodytag()
 5868:                                     $forcereg arg
 5869:              body_title     -> alternate text to use instead of $title
 5870:                                     in the title box that appears, this text
 5871:                                     is not auto translated like the $title is
 5872:              frameset       -> if true will start with a <frameset>
 5873:                                     rather than <body>
 5874:              no_title       -> if true the title bar won't be shown
 5875:              skip_phases    -> hash ref of 
 5876:                                     head -> skip the <html><head> generation
 5877:                                     body -> skip all <body> generation
 5878:              no_inline_link -> if true and in remote mode, don't show the 
 5879:                                     'Switch To Inline Menu' link
 5880:              no_auto_mt_title -> prevent &mt()ing the title arg
 5881:              inherit_jsmath -> when creating popup window in a page,
 5882:                                     should it have jsmath forced on by the
 5883:                                     current page
 5884: 
 5885: =back
 5886: 
 5887: =back
 5888: 
 5889: =cut
 5890: 
 5891: sub start_page {
 5892:     my ($title,$head_extra,$args) = @_;
 5893:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5894:     my %head_args;
 5895:     foreach my $arg ('redirect','force_register','domain','function',
 5896: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5897: 		     'no_auto_mt_title') {
 5898: 	if (defined($args->{$arg})) {
 5899: 	    $head_args{$arg} = $args->{$arg};
 5900: 	}
 5901:     }
 5902: 
 5903:     $env{'internal.start_page'}++;
 5904:     my $result;
 5905:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5906: 	$result.=
 5907: 	    &xml_begin().
 5908: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5909:     }
 5910:     
 5911:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5912: 	if ($args->{'frameset'}) {
 5913: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5914: 						$args->{'add_entries'});
 5915: 	    $result .= "\n<frameset $attr_string>\n";
 5916: 	} else {
 5917: 	    $result .=
 5918: 		&bodytag($title, 
 5919: 			 $args->{'function'},       $args->{'add_entries'},
 5920: 			 $args->{'only_body'},      $args->{'domain'},
 5921: 			 $args->{'force_register'}, $args->{'body_title'},
 5922: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5923: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5924: 			 $args);
 5925: 	}
 5926:     }
 5927: 
 5928:     if ($args->{'js_ready'}) {
 5929: 	$result = &js_ready($result);
 5930:     }
 5931:     if ($args->{'html_encode'}) {
 5932: 	$result = &html_encode($result);
 5933:     }
 5934:     #Breadcrumbs
 5935:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 5936:         &Apache::lonhtmlcommon::clear_breadcrumbs();
 5937:         #if any br links exists, add them to the breadcrumbs
 5938:         if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5939:             foreach my $crumb (@{$args->{'bread_crumbs'}}){
 5940:                 &Apache::lonhtmlcommon::add_breadcrumb($crumb);
 5941:             }
 5942:         }
 5943: 
 5944:         #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 5945:         if (exists($args->{'bread_crumbs_component'})){
 5946:             $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 5947:         } else {
 5948:             $result .= &Apache::lonhtmlcommon::breadcrumbs();
 5949:         }
 5950:     }
 5951:     return $result;
 5952: }
 5953: 
 5954: =pod
 5955: 
 5956: =item * &head()
 5957: 
 5958: Returns a complete </body></html> section for LON-CAPA web pages.
 5959: 
 5960: Inputs:         $args - additional optional args supported are:
 5961:                  js_ready     -> return a string ready for being used in 
 5962:                                  a javascript writeln
 5963:                  html_encode  -> return a string ready for being used in 
 5964:                                  a html attribute
 5965:                  frameset     -> if true will start with a <frameset>
 5966:                                  rather than <body>
 5967:                  dicsussion   -> if true will get discussion from
 5968:                                   lonxml::xmlend
 5969:                                  (you can pass the target and parser arguments
 5970:                                   through optional 'target' and 'parser' args
 5971:                                   to this routine)
 5972: 
 5973: =cut
 5974: 
 5975: sub end_page {
 5976:     my ($args) = @_;
 5977:     $env{'internal.end_page'}++;
 5978:     my $result;
 5979:     if ($args->{'discussion'}) {
 5980: 	my ($target,$parser);
 5981: 	if (ref($args->{'discussion'})) {
 5982: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5983: 				$args->{'discussion'}{'parser'});
 5984: 	}
 5985: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5986:     }
 5987: 
 5988:     if ($args->{'frameset'}) {
 5989: 	$result .= '</frameset>';
 5990:     } else {
 5991: 	$result .= &endbodytag($args);
 5992:     }
 5993:     $result .= "\n</html>";
 5994: 
 5995:     if ($args->{'js_ready'}) {
 5996: 	$result = &js_ready($result);
 5997:     }
 5998: 
 5999:     if ($args->{'html_encode'}) {
 6000: 	$result = &html_encode($result);
 6001:     }
 6002: 
 6003:     return $result;
 6004: }
 6005: 
 6006: sub html_encode {
 6007:     my ($result) = @_;
 6008: 
 6009:     $result = &HTML::Entities::encode($result,'<>&"');
 6010:     
 6011:     return $result;
 6012: }
 6013: sub js_ready {
 6014:     my ($result) = @_;
 6015: 
 6016:     $result =~ s/[\n\r]/ /xmsg;
 6017:     $result =~ s/\\/\\\\/xmsg;
 6018:     $result =~ s/'/\\'/xmsg;
 6019:     $result =~ s{</}{<\\/}xmsg;
 6020:     
 6021:     return $result;
 6022: }
 6023: 
 6024: sub validate_page {
 6025:     if (  exists($env{'internal.start_page'})
 6026: 	  &&     $env{'internal.start_page'} > 1) {
 6027: 	&Apache::lonnet::logthis('start_page called multiple times '.
 6028: 				 $env{'internal.start_page'}.' '.
 6029: 				 $ENV{'request.filename'});
 6030:     }
 6031:     if (  exists($env{'internal.end_page'})
 6032: 	  &&     $env{'internal.end_page'} > 1) {
 6033: 	&Apache::lonnet::logthis('end_page called multiple times '.
 6034: 				 $env{'internal.end_page'}.' '.
 6035: 				 $env{'request.filename'});
 6036:     }
 6037:     if (     exists($env{'internal.start_page'})
 6038: 	&& ! exists($env{'internal.end_page'})) {
 6039: 	&Apache::lonnet::logthis('start_page called without end_page '.
 6040: 				 $env{'request.filename'});
 6041:     }
 6042:     if (   ! exists($env{'internal.start_page'})
 6043: 	&&   exists($env{'internal.end_page'})) {
 6044: 	&Apache::lonnet::logthis('end_page called without start_page'.
 6045: 				 $env{'request.filename'});
 6046:     }
 6047: }
 6048: 
 6049: sub simple_error_page {
 6050:     my ($r,$title,$msg) = @_;
 6051:     my $page =
 6052: 	&Apache::loncommon::start_page($title).
 6053: 	&mt($msg).
 6054: 	&Apache::loncommon::end_page();
 6055:     if (ref($r)) {
 6056: 	$r->print($page);
 6057: 	return;
 6058:     }
 6059:     return $page;
 6060: }
 6061: 
 6062: {
 6063:     my @row_count;
 6064:     sub start_data_table {
 6065: 	my ($add_class) = @_;
 6066: 	my $css_class = (join(' ','LC_data_table',$add_class));
 6067: 	unshift(@row_count,0);
 6068: 	return '<table class="'.$css_class.'">'."\n";
 6069:     }
 6070: 
 6071:     sub end_data_table {
 6072: 	shift(@row_count);
 6073: 	return '</table>'."\n";;
 6074:     }
 6075: 
 6076:     sub start_data_table_row {
 6077: 	my ($add_class) = @_;
 6078: 	$row_count[0]++;
 6079: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6080: 	$css_class = (join(' ',$css_class,$add_class));
 6081: 	return  '<tr class="'.$css_class.'">'."\n";;
 6082:     }
 6083:     
 6084:     sub continue_data_table_row {
 6085: 	my ($add_class) = @_;
 6086: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 6087: 	$css_class = (join(' ',$css_class,$add_class));
 6088: 	return  '<tr class="'.$css_class.'">'."\n";;
 6089:     }
 6090: 
 6091:     sub end_data_table_row {
 6092: 	return '</tr>'."\n";;
 6093:     }
 6094: 
 6095:     sub start_data_table_empty_row {
 6096: 	$row_count[0]++;
 6097: 	return  '<tr class="LC_empty_row" >'."\n";;
 6098:     }
 6099: 
 6100:     sub end_data_table_empty_row {
 6101: 	return '</tr>'."\n";;
 6102:     }
 6103: 
 6104:     sub start_data_table_header_row {
 6105: 	return  '<tr class="LC_header_row">'."\n";;
 6106:     }
 6107: 
 6108:     sub end_data_table_header_row {
 6109: 	return '</tr>'."\n";;
 6110:     }
 6111: }
 6112: 
 6113: =pod
 6114: 
 6115: =item * &inhibit_menu_check($arg)
 6116: 
 6117: Checks for a inhibitmenu state and generates output to preserve it
 6118: 
 6119: Inputs:         $arg - can be any of
 6120:                      - undef - in which case the return value is a string 
 6121:                                to add  into arguments list of a uri
 6122:                      - 'input' - in which case the return value is a HTML
 6123:                                  <form> <input> field of type hidden to
 6124:                                  preserve the value
 6125:                      - a url - in which case the return value is the url with
 6126:                                the neccesary cgi args added to preserve the
 6127:                                inhibitmenu state
 6128:                      - a ref to a url - no return value, but the string is
 6129:                                         updated to include the neccessary cgi
 6130:                                         args to preserve the inhibitmenu state
 6131: 
 6132: =cut
 6133: 
 6134: sub inhibit_menu_check {
 6135:     my ($arg) = @_;
 6136:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6137:     if ($arg eq 'input') {
 6138: 	if ($env{'form.inhibitmenu'}) {
 6139: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 6140: 	} else {
 6141: 	    return
 6142: 	}
 6143:     }
 6144:     if ($env{'form.inhibitmenu'}) {
 6145: 	if (ref($arg)) {
 6146: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6147: 	} elsif ($arg eq '') {
 6148: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 6149: 	} else {
 6150: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 6151: 	}
 6152:     }
 6153:     if (!ref($arg)) {
 6154: 	return $arg;
 6155:     }
 6156: }
 6157: 
 6158: ###############################################
 6159: 
 6160: =pod
 6161: 
 6162: =back
 6163: 
 6164: =head1 User Information Routines
 6165: 
 6166: =over 4
 6167: 
 6168: =item * &get_users_function()
 6169: 
 6170: Used by &bodytag to determine the current users primary role.
 6171: Returns either 'student','coordinator','admin', or 'author'.
 6172: 
 6173: =cut
 6174: 
 6175: ###############################################
 6176: sub get_users_function {
 6177:     my $function = 'student';
 6178:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 6179:         $function='coordinator';
 6180:     }
 6181:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 6182:         $function='admin';
 6183:     }
 6184:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 6185:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 6186:         $function='author';
 6187:     }
 6188:     return $function;
 6189: }
 6190: 
 6191: ###############################################
 6192: 
 6193: =pod
 6194: 
 6195: =item * &show_course()
 6196: 
 6197: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 6198: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 6199: Inputs:
 6200: None
 6201: 
 6202: Outputs:
 6203: Scalar: 1 if 'Course' to be used, 0 otherwise.
 6204: 
 6205: =cut
 6206: 
 6207: ###############################################
 6208: sub show_course {
 6209:     my $course = !$env{'user.adv'};
 6210:     if (!$env{'user.adv'}) {
 6211:         foreach my $env (keys(%env)) {
 6212:             next if ($env !~ m/^user\.priv\./);
 6213:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 6214:                 $course = 0;
 6215:                 last;
 6216:             }
 6217:         }
 6218:     }
 6219:     return $course;
 6220: }
 6221: 
 6222: ###############################################
 6223: 
 6224: =pod
 6225: 
 6226: =item * &check_user_status()
 6227: 
 6228: Determines current status of supplied role for a
 6229: specific user. Roles can be active, previous or future.
 6230: 
 6231: Inputs: 
 6232: user's domain, user's username, course's domain,
 6233: course's number, optional section ID.
 6234: 
 6235: Outputs:
 6236: role status: active, previous or future. 
 6237: 
 6238: =cut
 6239: 
 6240: sub check_user_status {
 6241:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 6242:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 6243:     my @uroles = keys %userinfo;
 6244:     my $srchstr;
 6245:     my $active_chk = 'none';
 6246:     my $now = time;
 6247:     if (@uroles > 0) {
 6248:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 6249:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 6250:         } else {
 6251:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 6252:         }
 6253:         if (grep/^\Q$srchstr\E$/,@uroles) {
 6254:             my $role_end = 0;
 6255:             my $role_start = 0;
 6256:             $active_chk = 'active';
 6257:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 6258:                 $role_end = $1;
 6259:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 6260:                     $role_start = $1;
 6261:                 }
 6262:             }
 6263:             if ($role_start > 0) {
 6264:                 if ($now < $role_start) {
 6265:                     $active_chk = 'future';
 6266:                 }
 6267:             }
 6268:             if ($role_end > 0) {
 6269:                 if ($now > $role_end) {
 6270:                     $active_chk = 'previous';
 6271:                 }
 6272:             }
 6273:         }
 6274:     }
 6275:     return $active_chk;
 6276: }
 6277: 
 6278: ###############################################
 6279: 
 6280: =pod
 6281: 
 6282: =item * &get_sections()
 6283: 
 6284: Determines all the sections for a course including
 6285: sections with students and sections containing other roles.
 6286: Incoming parameters: 
 6287: 
 6288: 1. domain
 6289: 2. course number 
 6290: 3. reference to array containing roles for which sections should 
 6291: be gathered (optional).
 6292: 4. reference to array containing status types for which sections 
 6293: should be gathered (optional).
 6294: 
 6295: If the third argument is undefined, sections are gathered for any role. 
 6296: If the fourth argument is undefined, sections are gathered for any status.
 6297: Permissible values are 'active' or 'future' or 'previous'.
 6298:  
 6299: Returns section hash (keys are section IDs, values are
 6300: number of users in each section), subject to the
 6301: optional roles filter, optional status filter 
 6302: 
 6303: =cut
 6304: 
 6305: ###############################################
 6306: sub get_sections {
 6307:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 6308:     if (!defined($cdom) || !defined($cnum)) {
 6309:         my $cid =  $env{'request.course.id'};
 6310: 
 6311: 	return if (!defined($cid));
 6312: 
 6313:         $cdom = $env{'course.'.$cid.'.domain'};
 6314:         $cnum = $env{'course.'.$cid.'.num'};
 6315:     }
 6316: 
 6317:     my %sectioncount;
 6318:     my $now = time;
 6319: 
 6320:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 6321: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 6322: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 6323: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 6324:         my $start_index = &Apache::loncoursedata::CL_START();
 6325:         my $end_index = &Apache::loncoursedata::CL_END();
 6326:         my $status;
 6327: 	while (my ($student,$data) = each(%$classlist)) {
 6328: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 6329: 				                     $data->[$status_index],
 6330:                                                      $data->[$start_index],
 6331:                                                      $data->[$end_index]);
 6332:             if ($stu_status eq 'Active') {
 6333:                 $status = 'active';
 6334:             } elsif ($end < $now) {
 6335:                 $status = 'previous';
 6336:             } elsif ($start > $now) {
 6337:                 $status = 'future';
 6338:             } 
 6339: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 6340:                 if ((!defined($possible_status)) || (($status ne '') && 
 6341:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 6342: 		    $sectioncount{$section}++;
 6343:                 }
 6344: 	    }
 6345: 	}
 6346:     }
 6347:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6348:     foreach my $user (sort(keys(%courseroles))) {
 6349: 	if ($user !~ /^(\w{2})/) { next; }
 6350: 	my ($role) = ($user =~ /^(\w{2})/);
 6351: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 6352: 	my ($section,$status);
 6353: 	if ($role eq 'cr' &&
 6354: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 6355: 	    $section=$1;
 6356: 	}
 6357: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 6358: 	if (!defined($section) || $section eq '-1') { next; }
 6359:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 6360:         if ($end == -1 && $start == -1) {
 6361:             next; #deleted role
 6362:         }
 6363:         if (!defined($possible_status)) { 
 6364:             $sectioncount{$section}++;
 6365:         } else {
 6366:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 6367:                 $status = 'active';
 6368:             } elsif ($end < $now) {
 6369:                 $status = 'future';
 6370:             } elsif ($start > $now) {
 6371:                 $status = 'previous';
 6372:             }
 6373:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 6374:                 $sectioncount{$section}++;
 6375:             }
 6376:         }
 6377:     }
 6378:     return %sectioncount;
 6379: }
 6380: 
 6381: ###############################################
 6382: 
 6383: =pod
 6384: 
 6385: =item * &get_course_users()
 6386: 
 6387: Retrieves usernames:domains for users in the specified course
 6388: with specific role(s), and access status. 
 6389: 
 6390: Incoming parameters:
 6391: 1. course domain
 6392: 2. course number
 6393: 3. access status: users must have - either active, 
 6394: previous, future, or all.
 6395: 4. reference to array of permissible roles
 6396: 5. reference to array of section restrictions (optional)
 6397: 6. reference to results object (hash of hashes).
 6398: 7. reference to optional userdata hash
 6399: 8. reference to optional statushash
 6400: 9. flag if privileged users (except those set to unhide in
 6401:    course settings) should be excluded    
 6402: Keys of top level results hash are roles.
 6403: Keys of inner hashes are username:domain, with 
 6404: values set to access type.
 6405: Optional userdata hash returns an array with arguments in the 
 6406: same order as loncoursedata::get_classlist() for student data.
 6407: 
 6408: Optional statushash returns
 6409: 
 6410: Entries for end, start, section and status are blank because
 6411: of the possibility of multiple values for non-student roles.
 6412: 
 6413: =cut
 6414: 
 6415: ###############################################
 6416: 
 6417: sub get_course_users {
 6418:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 6419:     my %idx = ();
 6420:     my %seclists;
 6421: 
 6422:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 6423:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 6424:     $idx{end} = &Apache::loncoursedata::CL_END();
 6425:     $idx{start} = &Apache::loncoursedata::CL_START();
 6426:     $idx{id} = &Apache::loncoursedata::CL_ID();
 6427:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 6428:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 6429:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 6430: 
 6431:     if (grep(/^st$/,@{$roles})) {
 6432:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 6433:         my $now = time;
 6434:         foreach my $student (keys(%{$classlist})) {
 6435:             my $match = 0;
 6436:             my $secmatch = 0;
 6437:             my $section = $$classlist{$student}[$idx{section}];
 6438:             my $status = $$classlist{$student}[$idx{status}];
 6439:             if ($section eq '') {
 6440:                 $section = 'none';
 6441:             }
 6442:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6443:                 if (grep(/^all$/,@{$sections})) {
 6444:                     $secmatch = 1;
 6445:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 6446:                     if (grep(/^none$/,@{$sections})) {
 6447:                         $secmatch = 1;
 6448:                     }
 6449:                 } else {  
 6450: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 6451: 		        $secmatch = 1;
 6452:                     }
 6453: 		}
 6454:                 if (!$secmatch) {
 6455:                     next;
 6456:                 }
 6457:             }
 6458:             if (defined($$types{'active'})) {
 6459:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 6460:                     push(@{$$users{st}{$student}},'active');
 6461:                     $match = 1;
 6462:                 }
 6463:             }
 6464:             if (defined($$types{'previous'})) {
 6465:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 6466:                     push(@{$$users{st}{$student}},'previous');
 6467:                     $match = 1;
 6468:                 }
 6469:             }
 6470:             if (defined($$types{'future'})) {
 6471:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 6472:                     push(@{$$users{st}{$student}},'future');
 6473:                     $match = 1;
 6474:                 }
 6475:             }
 6476:             if ($match) {
 6477:                 push(@{$seclists{$student}},$section);
 6478:                 if (ref($userdata) eq 'HASH') {
 6479:                     $$userdata{$student} = $$classlist{$student};
 6480:                 }
 6481:                 if (ref($statushash) eq 'HASH') {
 6482:                     $statushash->{$student}{'st'}{$section} = $status;
 6483:                 }
 6484:             }
 6485:         }
 6486:     }
 6487:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 6488:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6489:         my $now = time;
 6490:         my %displaystatus = ( previous => 'Expired',
 6491:                               active   => 'Active',
 6492:                               future   => 'Future',
 6493:                             );
 6494:         my %nothide;
 6495:         if ($hidepriv) {
 6496:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 6497:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 6498:                 if ($user !~ /:/) {
 6499:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 6500:                 } else {
 6501:                     $nothide{$user} = 1;
 6502:                 }
 6503:             }
 6504:         }
 6505:         foreach my $person (sort(keys(%coursepersonnel))) {
 6506:             my $match = 0;
 6507:             my $secmatch = 0;
 6508:             my $status;
 6509:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 6510:             $user =~ s/:$//;
 6511:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 6512:             if ($end == -1 || $start == -1) {
 6513:                 next;
 6514:             }
 6515:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 6516:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 6517:                 my ($uname,$udom) = split(/:/,$user);
 6518:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 6519:                     if (grep(/^all$/,@{$sections})) {
 6520:                         $secmatch = 1;
 6521:                     } elsif ($usec eq '') {
 6522:                         if (grep(/^none$/,@{$sections})) {
 6523:                             $secmatch = 1;
 6524:                         }
 6525:                     } else {
 6526:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 6527:                             $secmatch = 1;
 6528:                         }
 6529:                     }
 6530:                     if (!$secmatch) {
 6531:                         next;
 6532:                     }
 6533:                 }
 6534:                 if ($usec eq '') {
 6535:                     $usec = 'none';
 6536:                 }
 6537:                 if ($uname ne '' && $udom ne '') {
 6538:                     if ($hidepriv) {
 6539:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 6540:                             (!$nothide{$uname.':'.$udom})) {
 6541:                             next;
 6542:                         }
 6543:                     }
 6544:                     if ($end > 0 && $end < $now) {
 6545:                         $status = 'previous';
 6546:                     } elsif ($start > $now) {
 6547:                         $status = 'future';
 6548:                     } else {
 6549:                         $status = 'active';
 6550:                     }
 6551:                     foreach my $type (keys(%{$types})) { 
 6552:                         if ($status eq $type) {
 6553:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 6554:                                 push(@{$$users{$role}{$user}},$type);
 6555:                             }
 6556:                             $match = 1;
 6557:                         }
 6558:                     }
 6559:                     if (($match) && (ref($userdata) eq 'HASH')) {
 6560:                         if (!exists($$userdata{$uname.':'.$udom})) {
 6561: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 6562:                         }
 6563:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 6564:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 6565:                         }
 6566:                         if (ref($statushash) eq 'HASH') {
 6567:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 6568:                         }
 6569:                     }
 6570:                 }
 6571:             }
 6572:         }
 6573:         if (grep(/^ow$/,@{$roles})) {
 6574:             if ((defined($cdom)) && (defined($cnum))) {
 6575:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 6576:                 if ( defined($csettings{'internal.courseowner'}) ) {
 6577:                     my $owner = $csettings{'internal.courseowner'};
 6578:                     next if ($owner eq '');
 6579:                     my ($ownername,$ownerdom);
 6580:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 6581:                         $ownername = $1;
 6582:                         $ownerdom = $2;
 6583:                     } else {
 6584:                         $ownername = $owner;
 6585:                         $ownerdom = $cdom;
 6586:                         $owner = $ownername.':'.$ownerdom;
 6587:                     }
 6588:                     @{$$users{'ow'}{$owner}} = 'any';
 6589:                     if (defined($userdata) && 
 6590: 			!exists($$userdata{$owner})) {
 6591: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 6592:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 6593:                             push(@{$seclists{$owner}},'none');
 6594:                         }
 6595:                         if (ref($statushash) eq 'HASH') {
 6596:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 6597:                         }
 6598: 		    }
 6599:                 }
 6600:             }
 6601:         }
 6602:         foreach my $user (keys(%seclists)) {
 6603:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 6604:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 6605:         }
 6606:     }
 6607:     return;
 6608: }
 6609: 
 6610: sub get_user_info {
 6611:     my ($udom,$uname,$idx,$userdata) = @_;
 6612:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 6613: 	&plainname($uname,$udom,'lastname');
 6614:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 6615:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 6616:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 6617:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 6618:     return;
 6619: }
 6620: 
 6621: ###############################################
 6622: 
 6623: =pod
 6624: 
 6625: =item * &get_user_quota()
 6626: 
 6627: Retrieves quota assigned for storage of portfolio files for a user  
 6628: 
 6629: Incoming parameters:
 6630: 1. user's username
 6631: 2. user's domain
 6632: 
 6633: Returns:
 6634: 1. Disk quota (in Mb) assigned to student.
 6635: 2. (Optional) Type of setting: custom or default
 6636:    (individually assigned or default for user's 
 6637:    institutional status).
 6638: 3. (Optional) - User's institutional status (e.g., faculty, staff
 6639:    or student - types as defined in localenroll::inst_usertypes 
 6640:    for user's domain, which determines default quota for user.
 6641: 4. (Optional) - Default quota which would apply to the user.
 6642: 
 6643: If a value has been stored in the user's environment, 
 6644: it will return that, otherwise it returns the maximal default
 6645: defined for the user's instituional status(es) in the domain.
 6646: 
 6647: =cut
 6648: 
 6649: ###############################################
 6650: 
 6651: 
 6652: sub get_user_quota {
 6653:     my ($uname,$udom) = @_;
 6654:     my ($quota,$quotatype,$settingstatus,$defquota);
 6655:     if (!defined($udom)) {
 6656:         $udom = $env{'user.domain'};
 6657:     }
 6658:     if (!defined($uname)) {
 6659:         $uname = $env{'user.name'};
 6660:     }
 6661:     if (($udom eq '' || $uname eq '') ||
 6662:         ($udom eq 'public') && ($uname eq 'public')) {
 6663:         $quota = 0;
 6664:         $quotatype = 'default';
 6665:         $defquota = 0; 
 6666:     } else {
 6667:         my $inststatus;
 6668:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 6669:             $quota = $env{'environment.portfolioquota'};
 6670:             $inststatus = $env{'environment.inststatus'};
 6671:         } else {
 6672:             my %userenv = 
 6673:                 &Apache::lonnet::get('environment',['portfolioquota',
 6674:                                      'inststatus'],$udom,$uname);
 6675:             my ($tmp) = keys(%userenv);
 6676:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6677:                 $quota = $userenv{'portfolioquota'};
 6678:                 $inststatus = $userenv{'inststatus'};
 6679:             } else {
 6680:                 undef(%userenv);
 6681:             }
 6682:         }
 6683:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 6684:         if ($quota eq '') {
 6685:             $quota = $defquota;
 6686:             $quotatype = 'default';
 6687:         } else {
 6688:             $quotatype = 'custom';
 6689:         }
 6690:     }
 6691:     if (wantarray) {
 6692:         return ($quota,$quotatype,$settingstatus,$defquota);
 6693:     } else {
 6694:         return $quota;
 6695:     }
 6696: }
 6697: 
 6698: ###############################################
 6699: 
 6700: =pod
 6701: 
 6702: =item * &default_quota()
 6703: 
 6704: Retrieves default quota assigned for storage of user portfolio files,
 6705: given an (optional) user's institutional status.
 6706: 
 6707: Incoming parameters:
 6708: 1. domain
 6709: 2. (Optional) institutional status(es).  This is a : separated list of 
 6710:    status types (e.g., faculty, staff, student etc.)
 6711:    which apply to the user for whom the default is being retrieved.
 6712:    If the institutional status string in undefined, the domain
 6713:    default quota will be returned. 
 6714: 
 6715: Returns:
 6716: 1. Default disk quota (in Mb) for user portfolios in the domain.
 6717: 2. (Optional) institutional type which determined the value of the
 6718:    default quota.
 6719: 
 6720: If a value has been stored in the domain's configuration db,
 6721: it will return that, otherwise it returns 20 (for backwards 
 6722: compatibility with domains which have not set up a configuration
 6723: db file; the original statically defined portfolio quota was 20 Mb). 
 6724: 
 6725: If the user's status includes multiple types (e.g., staff and student),
 6726: the largest default quota which applies to the user determines the
 6727: default quota returned.
 6728: 
 6729: =cut
 6730: 
 6731: ###############################################
 6732: 
 6733: 
 6734: sub default_quota {
 6735:     my ($udom,$inststatus) = @_;
 6736:     my ($defquota,$settingstatus);
 6737:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 6738:                                             ['quotas'],$udom);
 6739:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 6740:         if ($inststatus ne '') {
 6741:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 6742:             foreach my $item (@statuses) {
 6743:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6744:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 6745:                         if ($defquota eq '') {
 6746:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6747:                             $settingstatus = $item;
 6748:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 6749:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 6750:                             $settingstatus = $item;
 6751:                         }
 6752:                     }
 6753:                 } else {
 6754:                     if ($quotahash{'quotas'}{$item} ne '') {
 6755:                         if ($defquota eq '') {
 6756:                             $defquota = $quotahash{'quotas'}{$item};
 6757:                             $settingstatus = $item;
 6758:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 6759:                             $defquota = $quotahash{'quotas'}{$item};
 6760:                             $settingstatus = $item;
 6761:                         }
 6762:                     }
 6763:                 }
 6764:             }
 6765:         }
 6766:         if ($defquota eq '') {
 6767:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 6768:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 6769:             } else {
 6770:                 $defquota = $quotahash{'quotas'}{'default'};
 6771:             }
 6772:             $settingstatus = 'default';
 6773:         }
 6774:     } else {
 6775:         $settingstatus = 'default';
 6776:         $defquota = 20;
 6777:     }
 6778:     if (wantarray) {
 6779:         return ($defquota,$settingstatus);
 6780:     } else {
 6781:         return $defquota;
 6782:     }
 6783: }
 6784: 
 6785: sub get_secgrprole_info {
 6786:     my ($cdom,$cnum,$needroles,$type)  = @_;
 6787:     my %sections_count = &get_sections($cdom,$cnum);
 6788:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6789:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6790:     my @groups = sort(keys(%curr_groups));
 6791:     my $allroles = [];
 6792:     my $rolehash;
 6793:     my $accesshash = {
 6794:                      active => 'Currently has access',
 6795:                      future => 'Will have future access',
 6796:                      previous => 'Previously had access',
 6797:                   };
 6798:     if ($needroles) {
 6799:         $rolehash = {'all' => 'all'};
 6800:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6801: 	if (&Apache::lonnet::error(%user_roles)) {
 6802: 	    undef(%user_roles);
 6803: 	}
 6804:         foreach my $item (keys(%user_roles)) {
 6805:             my ($role)=split(/\:/,$item,2);
 6806:             if ($role eq 'cr') { next; }
 6807:             if ($role =~ /^cr/) {
 6808:                 $$rolehash{$role} = (split('/',$role))[3];
 6809:             } else {
 6810:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6811:             }
 6812:         }
 6813:         foreach my $key (sort(keys(%{$rolehash}))) {
 6814:             push(@{$allroles},$key);
 6815:         }
 6816:         push (@{$allroles},'st');
 6817:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6818:     }
 6819:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6820: }
 6821: 
 6822: sub user_picker {
 6823:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
 6824:     my $currdom = $dom;
 6825:     my %curr_selected = (
 6826:                         srchin => 'dom',
 6827:                         srchby => 'lastname',
 6828:                       );
 6829:     my $srchterm;
 6830:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 6831:         if ($srch->{'srchby'} ne '') {
 6832:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6833:         }
 6834:         if ($srch->{'srchin'} ne '') {
 6835:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6836:         }
 6837:         if ($srch->{'srchtype'} ne '') {
 6838:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6839:         }
 6840:         if ($srch->{'srchdomain'} ne '') {
 6841:             $currdom = $srch->{'srchdomain'};
 6842:         }
 6843:         $srchterm = $srch->{'srchterm'};
 6844:     }
 6845:     my %lt=&Apache::lonlocal::texthash(
 6846:                     'usr'       => 'Search criteria',
 6847:                     'doma'      => 'Domain/institution to search',
 6848:                     'uname'     => 'username',
 6849:                     'lastname'  => 'last name',
 6850:                     'lastfirst' => 'last name, first name',
 6851:                     'crs'       => 'in this course',
 6852:                     'dom'       => 'in selected LON-CAPA domain', 
 6853:                     'alc'       => 'all LON-CAPA',
 6854:                     'instd'     => 'in institutional directory for selected domain',
 6855:                     'exact'     => 'is',
 6856:                     'contains'  => 'contains',
 6857:                     'begins'    => 'begins with',
 6858:                     'youm'      => "You must include some text to search for.",
 6859:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6860:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6861:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6862:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6863:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6864:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6865:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6866:                                        );
 6867:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6868:     my $srchinsel = ' <select name="srchin">';
 6869: 
 6870:     my @srchins = ('crs','dom','alc','instd');
 6871: 
 6872:     foreach my $option (@srchins) {
 6873:         # FIXME 'alc' option unavailable until 
 6874:         #       loncreateuser::print_user_query_page()
 6875:         #       has been completed.
 6876:         next if ($option eq 'alc');
 6877:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6878:         if ($curr_selected{'srchin'} eq $option) {
 6879:             $srchinsel .= ' 
 6880:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6881:         } else {
 6882:             $srchinsel .= '
 6883:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6884:         }
 6885:     }
 6886:     $srchinsel .= "\n  </select>\n";
 6887: 
 6888:     my $srchbysel =  ' <select name="srchby">';
 6889:     foreach my $option ('lastname','lastfirst','uname') {
 6890:         if ($curr_selected{'srchby'} eq $option) {
 6891:             $srchbysel .= '
 6892:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6893:         } else {
 6894:             $srchbysel .= '
 6895:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6896:          }
 6897:     }
 6898:     $srchbysel .= "\n  </select>\n";
 6899: 
 6900:     my $srchtypesel = ' <select name="srchtype">';
 6901:     foreach my $option ('begins','contains','exact') {
 6902:         if ($curr_selected{'srchtype'} eq $option) {
 6903:             $srchtypesel .= '
 6904:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6905:         } else {
 6906:             $srchtypesel .= '
 6907:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6908:         }
 6909:     }
 6910:     $srchtypesel .= "\n  </select>\n";
 6911: 
 6912:     my ($newuserscript,$new_user_create);
 6913: 
 6914:     if ($forcenewuser) {
 6915:         if (ref($srch) eq 'HASH') {
 6916:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6917:                 if ($cancreate) {
 6918:                     $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>';
 6919:                 } else {
 6920:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 6921:                     my %usertypetext = (
 6922:                         official   => 'institutional',
 6923:                         unofficial => 'non-institutional',
 6924:                     );
 6925:                     $new_user_create = '<p class="LC_warning">'.
 6926:                                        &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
 6927:                                        &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
 6928:                 }
 6929:             }
 6930:         }
 6931: 
 6932:         $newuserscript = <<"ENDSCRIPT";
 6933: 
 6934: function setSearch(createnew,callingForm) {
 6935:     if (createnew == 1) {
 6936:         for (var i=0; i<callingForm.srchby.length; i++) {
 6937:             if (callingForm.srchby.options[i].value == 'uname') {
 6938:                 callingForm.srchby.selectedIndex = i;
 6939:             }
 6940:         }
 6941:         for (var i=0; i<callingForm.srchin.length; i++) {
 6942:             if ( callingForm.srchin.options[i].value == 'dom') {
 6943: 		callingForm.srchin.selectedIndex = i;
 6944:             }
 6945:         }
 6946:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6947:             if (callingForm.srchtype.options[i].value == 'exact') {
 6948:                 callingForm.srchtype.selectedIndex = i;
 6949:             }
 6950:         }
 6951:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6952:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6953:                 callingForm.srchdomain.selectedIndex = i;
 6954:             }
 6955:         }
 6956:     }
 6957: }
 6958: ENDSCRIPT
 6959: 
 6960:     }
 6961: 
 6962:     my $output = <<"END_BLOCK";
 6963: <script type="text/javascript">
 6964: // <![CDATA[
 6965: function validateEntry(callingForm) {
 6966: 
 6967:     var checkok = 1;
 6968:     var srchin;
 6969:     for (var i=0; i<callingForm.srchin.length; i++) {
 6970: 	if ( callingForm.srchin[i].checked ) {
 6971: 	    srchin = callingForm.srchin[i].value;
 6972: 	}
 6973:     }
 6974: 
 6975:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6976:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6977:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6978:     var srchterm =  callingForm.srchterm.value;
 6979:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6980:     var msg = "";
 6981: 
 6982:     if (srchterm == "") {
 6983:         checkok = 0;
 6984:         msg += "$lt{'youm'}\\n";
 6985:     }
 6986: 
 6987:     if (srchtype== 'begins') {
 6988:         if (srchterm.length < 2) {
 6989:             checkok = 0;
 6990:             msg += "$lt{'thte'}\\n";
 6991:         }
 6992:     }
 6993: 
 6994:     if (srchtype== 'contains') {
 6995:         if (srchterm.length < 3) {
 6996:             checkok = 0;
 6997:             msg += "$lt{'thet'}\\n";
 6998:         }
 6999:     }
 7000:     if (srchin == 'instd') {
 7001:         if (srchdomain == '') {
 7002:             checkok = 0;
 7003:             msg += "$lt{'yomc'}\\n";
 7004:         }
 7005:     }
 7006:     if (srchin == 'dom') {
 7007:         if (srchdomain == '') {
 7008:             checkok = 0;
 7009:             msg += "$lt{'ymcd'}\\n";
 7010:         }
 7011:     }
 7012:     if (srchby == 'lastfirst') {
 7013:         if (srchterm.indexOf(",") == -1) {
 7014:             checkok = 0;
 7015:             msg += "$lt{'whus'}\\n";
 7016:         }
 7017:         if (srchterm.indexOf(",") == srchterm.length -1) {
 7018:             checkok = 0;
 7019:             msg += "$lt{'whse'}\\n";
 7020:         }
 7021:     }
 7022:     if (checkok == 0) {
 7023:         alert("$lt{'thfo'}\\n"+msg);
 7024:         return;
 7025:     }
 7026:     if (checkok == 1) {
 7027:         callingForm.submit();
 7028:     }
 7029: }
 7030: 
 7031: $newuserscript
 7032: 
 7033: // ]]>
 7034: </script>
 7035: 
 7036: $new_user_create
 7037: 
 7038: <table>
 7039:  <tr>
 7040:   <td>$lt{'doma'}:</td>
 7041:   <td>$domform</td>
 7042:   </td>
 7043:  </tr>
 7044:  <tr>
 7045:   <td>$lt{'usr'}:</td>
 7046:   <td>$srchbysel
 7047:       $srchtypesel 
 7048:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 7049:       $srchinsel 
 7050:   </td>
 7051:  </tr>
 7052: </table>
 7053: <br />
 7054: END_BLOCK
 7055: 
 7056:     return $output;
 7057: }
 7058: 
 7059: sub user_rule_check {
 7060:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 7061:     my $response;
 7062:     if (ref($usershash) eq 'HASH') {
 7063:         foreach my $user (keys(%{$usershash})) {
 7064:             my ($uname,$udom) = split(/:/,$user);
 7065:             next if ($udom eq '' || $uname eq '');
 7066:             my ($id,$newuser);
 7067:             if (ref($usershash->{$user}) eq 'HASH') {
 7068:                 $newuser = $usershash->{$user}->{'newuser'};
 7069:                 $id = $usershash->{$user}->{'id'};
 7070:             }
 7071:             my $inst_response;
 7072:             if (ref($checks) eq 'HASH') {
 7073:                 if (defined($checks->{'username'})) {
 7074:                     ($inst_response,%{$inst_results->{$user}}) = 
 7075:                         &Apache::lonnet::get_instuser($udom,$uname);
 7076:                 } elsif (defined($checks->{'id'})) {
 7077:                     ($inst_response,%{$inst_results->{$user}}) =
 7078:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 7079:                 }
 7080:             } else {
 7081:                 ($inst_response,%{$inst_results->{$user}}) =
 7082:                     &Apache::lonnet::get_instuser($udom,$uname);
 7083:                 return;
 7084:             }
 7085:             if (!$got_rules->{$udom}) {
 7086:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 7087:                                                   ['usercreation'],$udom);
 7088:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 7089:                     foreach my $item ('username','id') {
 7090:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 7091:                             $$curr_rules{$udom}{$item} = 
 7092:                                 $domconfig{'usercreation'}{$item.'_rule'};
 7093:                         }
 7094:                     }
 7095:                 }
 7096:                 $got_rules->{$udom} = 1;  
 7097:             }
 7098:             foreach my $item (keys(%{$checks})) {
 7099:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 7100:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 7101:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 7102:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 7103:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 7104:                                 if ($rule_check{$rule}) {
 7105:                                     $$rulematch{$user}{$item} = $rule;
 7106:                                     if ($inst_response eq 'ok') {
 7107:                                         if (ref($inst_results) eq 'HASH') {
 7108:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 7109:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 7110:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 7111:                                                 }
 7112:                                             }
 7113:                                         }
 7114:                                     }
 7115:                                     last;
 7116:                                 }
 7117:                             }
 7118:                         }
 7119:                     }
 7120:                 }
 7121:             }
 7122:         }
 7123:     }
 7124:     return;
 7125: }
 7126: 
 7127: sub user_rule_formats {
 7128:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 7129:     my %text = ( 
 7130:                  'username' => 'Usernames',
 7131:                  'id'       => 'IDs',
 7132:                );
 7133:     my $output;
 7134:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 7135:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 7136:         if (@{$ruleorder} > 0) {
 7137:             $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>';
 7138:             foreach my $rule (@{$ruleorder}) {
 7139:                 if (ref($curr_rules) eq 'ARRAY') {
 7140:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 7141:                         if (ref($rules->{$rule}) eq 'HASH') {
 7142:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 7143:                                         $rules->{$rule}{'desc'}.'</li>';
 7144:                         }
 7145:                     }
 7146:                 }
 7147:             }
 7148:             $output .= '</ul>';
 7149:         }
 7150:     }
 7151:     return $output;
 7152: }
 7153: 
 7154: sub instrule_disallow_msg {
 7155:     my ($checkitem,$domdesc,$count,$mode) = @_;
 7156:     my $response;
 7157:     my %text = (
 7158:                   item   => 'username',
 7159:                   items  => 'usernames',
 7160:                   match  => 'matches',
 7161:                   do     => 'does',
 7162:                   action => 'a username',
 7163:                   one    => 'one',
 7164:                );
 7165:     if ($count > 1) {
 7166:         $text{'item'} = 'usernames';
 7167:         $text{'match'} ='match';
 7168:         $text{'do'} = 'do';
 7169:         $text{'action'} = 'usernames',
 7170:         $text{'one'} = 'ones';
 7171:     }
 7172:     if ($checkitem eq 'id') {
 7173:         $text{'items'} = 'IDs';
 7174:         $text{'item'} = 'ID';
 7175:         $text{'action'} = 'an ID';
 7176:         if ($count > 1) {
 7177:             $text{'item'} = 'IDs';
 7178:             $text{'action'} = 'IDs';
 7179:         }
 7180:     }
 7181:     $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 />';
 7182:     if ($mode eq 'upload') {
 7183:         if ($checkitem eq 'username') {
 7184:             $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'}.");
 7185:         } elsif ($checkitem eq 'id') {
 7186:             $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.");
 7187:         }
 7188:     } elsif ($mode eq 'selfcreate') {
 7189:         if ($checkitem eq 'id') {
 7190:             $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.");
 7191:         }
 7192:     } else {
 7193:         if ($checkitem eq 'username') {
 7194:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 7195:         } elsif ($checkitem eq 'id') {
 7196:             $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.");
 7197:         }
 7198:     }
 7199:     return $response;
 7200: }
 7201: 
 7202: sub personal_data_fieldtitles {
 7203:     my %fieldtitles = &Apache::lonlocal::texthash (
 7204:                         id => 'Student/Employee ID',
 7205:                         permanentemail => 'E-mail address',
 7206:                         lastname => 'Last Name',
 7207:                         firstname => 'First Name',
 7208:                         middlename => 'Middle Name',
 7209:                         generation => 'Generation',
 7210:                         gen => 'Generation',
 7211:                         inststatus => 'Affiliation',
 7212:                    );
 7213:     return %fieldtitles;
 7214: }
 7215: 
 7216: sub sorted_inst_types {
 7217:     my ($dom) = @_;
 7218:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 7219:     my $othertitle = &mt('All users');
 7220:     if ($env{'request.course.id'}) {
 7221:         $othertitle  = &mt('Any users');
 7222:     }
 7223:     my @types;
 7224:     if (ref($order) eq 'ARRAY') {
 7225:         @types = @{$order};
 7226:     }
 7227:     if (@types == 0) {
 7228:         if (ref($usertypes) eq 'HASH') {
 7229:             @types = sort(keys(%{$usertypes}));
 7230:         }
 7231:     }
 7232:     if (keys(%{$usertypes}) > 0) {
 7233:         $othertitle = &mt('Other users');
 7234:     }
 7235:     return ($othertitle,$usertypes,\@types);
 7236: }
 7237: 
 7238: sub get_institutional_codes {
 7239:     my ($settings,$allcourses,$LC_code) = @_;
 7240: # Get complete list of course sections to update
 7241:     my @currsections = ();
 7242:     my @currxlists = ();
 7243:     my $coursecode = $$settings{'internal.coursecode'};
 7244: 
 7245:     if ($$settings{'internal.sectionnums'} ne '') {
 7246:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 7247:     }
 7248: 
 7249:     if ($$settings{'internal.crosslistings'} ne '') {
 7250:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 7251:     }
 7252: 
 7253:     if (@currxlists > 0) {
 7254:         foreach (@currxlists) {
 7255:             if (m/^([^:]+):(\w*)$/) {
 7256:                 unless (grep/^$1$/,@{$allcourses}) {
 7257:                     push @{$allcourses},$1;
 7258:                     $$LC_code{$1} = $2;
 7259:                 }
 7260:             }
 7261:         }
 7262:     }
 7263:  
 7264:     if (@currsections > 0) {
 7265:         foreach (@currsections) {
 7266:             if (m/^(\w+):(\w*)$/) {
 7267:                 my $sec = $coursecode.$1;
 7268:                 my $lc_sec = $2;
 7269:                 unless (grep/^$sec$/,@{$allcourses}) {
 7270:                     push @{$allcourses},$sec;
 7271:                     $$LC_code{$sec} = $lc_sec;
 7272:                 }
 7273:             }
 7274:         }
 7275:     }
 7276:     return;
 7277: }
 7278: 
 7279: =pod
 7280: 
 7281: =head1 Slot Helpers
 7282: 
 7283: =over 4
 7284: 
 7285: =item * sorted_slots()
 7286: 
 7287: Sorts an array of slot names in order of slot start time (earliest first).
 7288: 
 7289: Inputs:
 7290: 
 7291: =over 4
 7292: 
 7293: slotsarr  - Reference to array of unsorted slot names.
 7294: 
 7295: slots     - Reference to hash of hash, where outer hash keys are slot names.
 7296: 
 7297: =back
 7298: 
 7299: Returns:
 7300: 
 7301: =over 4
 7302: 
 7303: sorted   - An array of slot names sorted by the start time of the slot.
 7304: 
 7305: =back
 7306: 
 7307: =back
 7308: 
 7309: =cut
 7310: 
 7311: 
 7312: sub sorted_slots {
 7313:     my ($slotsarr,$slots) = @_;
 7314:     my @sorted;
 7315:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 7316:         @sorted =
 7317:             sort {
 7318:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 7319:                          return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
 7320:                      }
 7321:                      if (ref($slots->{$a})) { return -1;}
 7322:                      if (ref($slots->{$b})) { return 1;}
 7323:                      return 0;
 7324:                  } @{$slotsarr};
 7325:     }
 7326:     return @sorted;
 7327: }
 7328: 
 7329: =pod
 7330: 
 7331: =back
 7332: 
 7333: =head1 HTTP Helpers
 7334: 
 7335: =over 4
 7336: 
 7337: =item * &get_unprocessed_cgi($query,$possible_names)
 7338: 
 7339: Modify the %env hash to contain unprocessed CGI form parameters held in
 7340: $query.  The parameters listed in $possible_names (an array reference),
 7341: will be set in $env{'form.name'} if they do not already exist.
 7342: 
 7343: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 7344: $possible_names is an ref to an array of form element names.  As an example:
 7345: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 7346: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 7347: 
 7348: =cut
 7349: 
 7350: sub get_unprocessed_cgi {
 7351:   my ($query,$possible_names)= @_;
 7352:   # $Apache::lonxml::debug=1;
 7353:   foreach my $pair (split(/&/,$query)) {
 7354:     my ($name, $value) = split(/=/,$pair);
 7355:     $name = &unescape($name);
 7356:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 7357:       $value =~ tr/+/ /;
 7358:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 7359:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 7360:     }
 7361:   }
 7362: }
 7363: 
 7364: =pod
 7365: 
 7366: =item * &cacheheader() 
 7367: 
 7368: returns cache-controlling header code
 7369: 
 7370: =cut
 7371: 
 7372: sub cacheheader {
 7373:     unless ($env{'request.method'} eq 'GET') { return ''; }
 7374:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 7375:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 7376:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 7377:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 7378:     return $output;
 7379: }
 7380: 
 7381: =pod
 7382: 
 7383: =item * &no_cache($r) 
 7384: 
 7385: specifies header code to not have cache
 7386: 
 7387: =cut
 7388: 
 7389: sub no_cache {
 7390:     my ($r) = @_;
 7391:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 7392: 	$env{'request.method'} ne 'GET') { return ''; }
 7393:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 7394:     $r->no_cache(1);
 7395:     $r->header_out("Expires" => $date);
 7396:     $r->header_out("Pragma" => "no-cache");
 7397: }
 7398: 
 7399: sub content_type {
 7400:     my ($r,$type,$charset) = @_;
 7401:     if ($r) {
 7402: 	#  Note that printout.pl calls this with undef for $r.
 7403: 	&no_cache($r);
 7404:     }
 7405:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 7406:     unless ($charset) {
 7407: 	$charset=&Apache::lonlocal::current_encoding;
 7408:     }
 7409:     if ($charset) { $type.='; charset='.$charset; }
 7410:     if ($r) {
 7411: 	$r->content_type($type);
 7412:     } else {
 7413: 	print("Content-type: $type\n\n");
 7414:     }
 7415: }
 7416: 
 7417: =pod
 7418: 
 7419: =item * &add_to_env($name,$value) 
 7420: 
 7421: adds $name to the %env hash with value
 7422: $value, if $name already exists, the entry is converted to an array
 7423: reference and $value is added to the array.
 7424: 
 7425: =cut
 7426: 
 7427: sub add_to_env {
 7428:   my ($name,$value)=@_;
 7429:   if (defined($env{$name})) {
 7430:     if (ref($env{$name})) {
 7431:       #already have multiple values
 7432:       push(@{ $env{$name} },$value);
 7433:     } else {
 7434:       #first time seeing multiple values, convert hash entry to an arrayref
 7435:       my $first=$env{$name};
 7436:       undef($env{$name});
 7437:       push(@{ $env{$name} },$first,$value);
 7438:     }
 7439:   } else {
 7440:     $env{$name}=$value;
 7441:   }
 7442: }
 7443: 
 7444: =pod
 7445: 
 7446: =item * &get_env_multiple($name) 
 7447: 
 7448: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7449: values may be defined and end up as an array ref.
 7450: 
 7451: returns an array of values
 7452: 
 7453: =cut
 7454: 
 7455: sub get_env_multiple {
 7456:     my ($name) = @_;
 7457:     my @values;
 7458:     if (defined($env{$name})) {
 7459:         # exists is it an array
 7460:         if (ref($env{$name})) {
 7461:             @values=@{ $env{$name} };
 7462:         } else {
 7463:             $values[0]=$env{$name};
 7464:         }
 7465:     }
 7466:     return(@values);
 7467: }
 7468: 
 7469: sub ask_for_embedded_content {
 7470:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 7471:     my $upload_output = '
 7472:    <form name="upload_embedded" action="'.$actionurl.'"
 7473:                   method="post" enctype="multipart/form-data">';
 7474:     $upload_output .= $state;
 7475:     $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
 7476: 
 7477:     my $num = 0;
 7478:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
 7479:         $upload_output .= &start_data_table_row().
 7480:             '<td>'.$embed_file.'</td><td>';
 7481:         if ($args->{'ignore_remote_references'}
 7482:             && $embed_file =~ m{^\w+://}) {
 7483:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 7484:         } elsif ($args->{'error_on_invalid_names'}
 7485:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 7486: 
 7487:             $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
 7488: 
 7489:         } else {
 7490:             $upload_output .='
 7491:            <input name="embedded_item_'.$num.'" type="file" value="" />
 7492:            <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
 7493:             my $attrib = join(':',@{$$allfiles{$embed_file}});
 7494:             $upload_output .=
 7495:                 "\n\t\t".
 7496:                 '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 7497:                 $attrib.'" />';
 7498:             if (exists($$codebase{$embed_file})) {
 7499:                 $upload_output .=
 7500:                     "\n\t\t".
 7501:                     '<input name="codebase_'.$num.'" type="hidden" value="'.
 7502:                     &escape($$codebase{$embed_file}).'" />';
 7503:             }
 7504:         }
 7505:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
 7506:         $num++;
 7507:     }
 7508:     $upload_output .= &Apache::loncommon::end_data_table().'<br />
 7509:    <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
 7510:    <input type ="submit" value="'.&mt('Upload Listed Files').'" />
 7511:    '.&mt('(only files for which a location has been provided will be uploaded)').'
 7512:    </form>';
 7513:     return $upload_output;
 7514: }
 7515: 
 7516: sub upload_embedded {
 7517:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
 7518:         $current_disk_usage) = @_;
 7519:     my $output;
 7520:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
 7521:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
 7522:         my $orig_uploaded_filename =
 7523:             $env{'form.embedded_item_'.$i.'.filename'};
 7524: 
 7525:         $env{'form.embedded_orig_'.$i} =
 7526:             &unescape($env{'form.embedded_orig_'.$i});
 7527:         my ($path,$fname) =
 7528:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
 7529:         # no path, whole string is fname
 7530:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
 7531: 
 7532:         $path = $env{'form.currentpath'}.$path;
 7533:         $fname = &Apache::lonnet::clean_filename($fname);
 7534:         # See if there is anything left
 7535:         next if ($fname eq '');
 7536: 
 7537:         # Check if file already exists as a file or directory.
 7538:         my ($state,$msg);
 7539:         if ($context eq 'portfolio') {
 7540:             my $port_path = $dirpath;
 7541:             if ($group ne '') {
 7542:                 $port_path = "groups/$group/$port_path";
 7543:             }
 7544:             ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
 7545:                                               $dir_root,$port_path,$disk_quota,
 7546:                                               $current_disk_usage,$uname,$udom);
 7547:             if ($state eq 'will_exceed_quota'
 7548:                 || $state eq 'file_locked'
 7549:                 || $state eq 'file_exists' ) {
 7550:                 $output .= $msg;
 7551:                 next;
 7552:             }
 7553:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
 7554:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
 7555:             if ($state eq 'exists') {
 7556:                 $output .= $msg;
 7557:                 next;
 7558:             }
 7559:         }
 7560:         # Check if extension is valid
 7561:         if (($fname =~ /\.(\w+)$/) &&
 7562:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7563:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
 7564:             next;
 7565:         } elsif (($fname =~ /\.(\w+)$/) &&
 7566:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
 7567:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7568:             next;
 7569:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
 7570:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7571:             next;
 7572:         }
 7573: 
 7574:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
 7575:         if ($context eq 'portfolio') {
 7576:             my $result=
 7577:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
 7578:                                                 $dirpath.$path);
 7579:             if ($result !~ m|^/uploaded/|) {
 7580:                 $output .= '<span class="LC_error">'
 7581:                       .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
 7582:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
 7583:                       .'</span><br />';
 7584:                 next;
 7585:             } else {
 7586:                 $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
 7587:                            $path.$fname.'</span>').'</p>';     
 7588:             }
 7589:         } else {
 7590: # Save the file
 7591:             my $target = $env{'form.embedded_item_'.$i};
 7592:             my $fullpath = $dir_root.$dirpath.'/'.$path;
 7593:             my $dest = $fullpath.$fname;
 7594:             my $url = $url_root.$dirpath.'/'.$path.$fname;
 7595:             my @parts=split(/\//,$fullpath);
 7596:             my $count;
 7597:             my $filepath = $dir_root;
 7598:             for ($count=4;$count<=$#parts;$count++) {
 7599:                 $filepath .= "/$parts[$count]";
 7600:                 if ((-e $filepath)!=1) {
 7601:                     mkdir($filepath,0770);
 7602:                 }
 7603:             }
 7604:             my $fh;
 7605:             if (!open($fh,'>'.$dest)) {
 7606:                 &Apache::lonnet::logthis('Failed to create '.$dest);
 7607:                 $output .= '<span class="LC_error">'.
 7608:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7609:                            '</span><br />';
 7610:             } else {
 7611:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
 7612:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
 7613:                     $output .= '<span class="LC_error">'.
 7614:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
 7615:                               '</span><br />';
 7616:                 } else {
 7617:                     if ($context eq 'testbank') {
 7618:                         $output .= &mt('Embedded file uploaded successfully:').
 7619:                                    '&nbsp;<a href="'.$url.'">'.
 7620:                                    $orig_uploaded_filename.'</a><br />';
 7621:                     } else {
 7622:                         $output .= '<font size="+2">'.
 7623:                                    &mt('View embedded file: [_1]','<a href="'.$url.'">'.
 7624:                                    $orig_uploaded_filename.'</a>').'</font><br />';
 7625:                     }
 7626:                 }
 7627:                 close($fh);
 7628:             }
 7629:         }
 7630:     }
 7631:     return $output;
 7632: }
 7633: 
 7634: sub check_for_existing {
 7635:     my ($path,$fname,$element) = @_;
 7636:     my ($state,$msg);
 7637:     if (-d $path.'/'.$fname) {
 7638:         $state = 'exists';
 7639:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7640:     } elsif (-e $path.'/'.$fname) {
 7641:         $state = 'exists';
 7642:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
 7643:     }
 7644:     if ($state eq 'exists') {
 7645:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
 7646:     }
 7647:     return ($state,$msg);
 7648: }
 7649: 
 7650: sub check_for_upload {
 7651:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
 7652:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
 7653:     my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
 7654:     my $getpropath = 1;
 7655:     my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
 7656:                                             $getpropath);
 7657:     my $found_file = 0;
 7658:     my $locked_file = 0;
 7659:     foreach my $line (@dir_list) {
 7660:         my ($file_name)=split(/\&/,$line,2);
 7661:         if ($file_name eq $fname){
 7662:             $file_name = $path.$file_name;
 7663:             if ($group ne '') {
 7664:                 $file_name = $group.$file_name;
 7665:             }
 7666:             $found_file = 1;
 7667:             if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
 7668:                 $locked_file = 1;
 7669:             }
 7670:         }
 7671:     }
 7672:     if (($current_disk_usage + $filesize) > $disk_quota){
 7673:         my $msg = '<span class="LC_error">'.
 7674:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
 7675:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
 7676:         return ('will_exceed_quota',$msg);
 7677:     } elsif ($found_file) {
 7678:         if ($locked_file) {
 7679:             my $msg = '<span class="LC_error">';
 7680:             $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>');
 7681:             $msg .= '</span><br />';
 7682:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
 7683:             return ('file_locked',$msg);
 7684:         } else {
 7685:             my $msg = '<span class="LC_error">';
 7686:             $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'});
 7687:             $msg .= '</span>';
 7688:             $msg .= '<br />';
 7689:             $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
 7690:             return ('file_exists',$msg);
 7691:         }
 7692:     }
 7693: }
 7694: 
 7695: 
 7696: =pod
 7697: 
 7698: =back
 7699: 
 7700: =head1 CSV Upload/Handling functions
 7701: 
 7702: =over 4
 7703: 
 7704: =item * &upfile_store($r)
 7705: 
 7706: Store uploaded file, $r should be the HTTP Request object,
 7707: needs $env{'form.upfile'}
 7708: returns $datatoken to be put into hidden field
 7709: 
 7710: =cut
 7711: 
 7712: sub upfile_store {
 7713:     my $r=shift;
 7714:     $env{'form.upfile'}=~s/\r/\n/gs;
 7715:     $env{'form.upfile'}=~s/\f/\n/gs;
 7716:     $env{'form.upfile'}=~s/\n+/\n/gs;
 7717:     $env{'form.upfile'}=~s/\n+$//gs;
 7718: 
 7719:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 7720: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 7721:     {
 7722:         my $datafile = $r->dir_config('lonDaemons').
 7723:                            '/tmp/'.$datatoken.'.tmp';
 7724:         if ( open(my $fh,">$datafile") ) {
 7725:             print $fh $env{'form.upfile'};
 7726:             close($fh);
 7727:         }
 7728:     }
 7729:     return $datatoken;
 7730: }
 7731: 
 7732: =pod
 7733: 
 7734: =item * &load_tmp_file($r)
 7735: 
 7736: Load uploaded file from tmp, $r should be the HTTP Request object,
 7737: needs $env{'form.datatoken'},
 7738: sets $env{'form.upfile'} to the contents of the file
 7739: 
 7740: =cut
 7741: 
 7742: sub load_tmp_file {
 7743:     my $r=shift;
 7744:     my @studentdata=();
 7745:     {
 7746:         my $studentfile = $r->dir_config('lonDaemons').
 7747:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 7748:         if ( open(my $fh,"<$studentfile") ) {
 7749:             @studentdata=<$fh>;
 7750:             close($fh);
 7751:         }
 7752:     }
 7753:     $env{'form.upfile'}=join('',@studentdata);
 7754: }
 7755: 
 7756: =pod
 7757: 
 7758: =item * &upfile_record_sep()
 7759: 
 7760: Separate uploaded file into records
 7761: returns array of records,
 7762: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 7763: 
 7764: =cut
 7765: 
 7766: sub upfile_record_sep {
 7767:     if ($env{'form.upfiletype'} eq 'xml') {
 7768:     } else {
 7769: 	my @records;
 7770: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 7771: 	    if ($line=~/^\s*$/) { next; }
 7772: 	    push(@records,$line);
 7773: 	}
 7774: 	return @records;
 7775:     }
 7776: }
 7777: 
 7778: =pod
 7779: 
 7780: =item * &record_sep($record)
 7781: 
 7782: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 7783: 
 7784: =cut
 7785: 
 7786: sub takeleft {
 7787:     my $index=shift;
 7788:     return substr('0000'.$index,-4,4);
 7789: }
 7790: 
 7791: sub record_sep {
 7792:     my $record=shift;
 7793:     my %components=();
 7794:     if ($env{'form.upfiletype'} eq 'xml') {
 7795:     } elsif ($env{'form.upfiletype'} eq 'space') {
 7796:         my $i=0;
 7797:         foreach my $field (split(/\s+/,$record)) {
 7798:             $field=~s/^(\"|\')//;
 7799:             $field=~s/(\"|\')$//;
 7800:             $components{&takeleft($i)}=$field;
 7801:             $i++;
 7802:         }
 7803:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 7804:         my $i=0;
 7805:         foreach my $field (split(/\t/,$record)) {
 7806:             $field=~s/^(\"|\')//;
 7807:             $field=~s/(\"|\')$//;
 7808:             $components{&takeleft($i)}=$field;
 7809:             $i++;
 7810:         }
 7811:     } else {
 7812:         my $separator=',';
 7813:         if ($env{'form.upfiletype'} eq 'semisv') {
 7814:             $separator=';';
 7815:         }
 7816:         my $i=0;
 7817: # the character we are looking for to indicate the end of a quote or a record 
 7818:         my $looking_for=$separator;
 7819: # do not add the characters to the fields
 7820:         my $ignore=0;
 7821: # we just encountered a separator (or the beginning of the record)
 7822:         my $just_found_separator=1;
 7823: # store the field we are working on here
 7824:         my $field='';
 7825: # work our way through all characters in record
 7826:         foreach my $character ($record=~/(.)/g) {
 7827:             if ($character eq $looking_for) {
 7828:                if ($character ne $separator) {
 7829: # Found the end of a quote, again looking for separator
 7830:                   $looking_for=$separator;
 7831:                   $ignore=1;
 7832:                } else {
 7833: # Found a separator, store away what we got
 7834:                   $components{&takeleft($i)}=$field;
 7835: 	          $i++;
 7836:                   $just_found_separator=1;
 7837:                   $ignore=0;
 7838:                   $field='';
 7839:                }
 7840:                next;
 7841:             }
 7842: # single or double quotation marks after a separator indicate beginning of a quote
 7843: # we are now looking for the end of the quote and need to ignore separators
 7844:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 7845:                $looking_for=$character;
 7846:                next;
 7847:             }
 7848: # ignore would be true after we reached the end of a quote
 7849:             if ($ignore) { next; }
 7850:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 7851:             $field.=$character;
 7852:             $just_found_separator=0; 
 7853:         }
 7854: # catch the very last entry, since we never encountered the separator
 7855:         $components{&takeleft($i)}=$field;
 7856:     }
 7857:     return %components;
 7858: }
 7859: 
 7860: ######################################################
 7861: ######################################################
 7862: 
 7863: =pod
 7864: 
 7865: =item * &upfile_select_html()
 7866: 
 7867: Return HTML code to select a file from the users machine and specify 
 7868: the file type.
 7869: 
 7870: =cut
 7871: 
 7872: ######################################################
 7873: ######################################################
 7874: sub upfile_select_html {
 7875:     my %Types = (
 7876:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 7877:                  semisv => &mt('Semicolon separated values'),
 7878:                  space => &mt('Space separated'),
 7879:                  tab   => &mt('Tabulator separated'),
 7880: #                 xml   => &mt('HTML/XML'),
 7881:                  );
 7882:     my $Str = '<input type="file" name="upfile" size="50" />'.
 7883:         '<br />'.&mt('Type').': <select name="upfiletype">';
 7884:     foreach my $type (sort(keys(%Types))) {
 7885:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 7886:     }
 7887:     $Str .= "</select>\n";
 7888:     return $Str;
 7889: }
 7890: 
 7891: sub get_samples {
 7892:     my ($records,$toget) = @_;
 7893:     my @samples=({});
 7894:     my $got=0;
 7895:     foreach my $rec (@$records) {
 7896: 	my %temp = &record_sep($rec);
 7897: 	if (! grep(/\S/, values(%temp))) { next; }
 7898: 	if (%temp) {
 7899: 	    $samples[$got]=\%temp;
 7900: 	    $got++;
 7901: 	    if ($got == $toget) { last; }
 7902: 	}
 7903:     }
 7904:     return \@samples;
 7905: }
 7906: 
 7907: ######################################################
 7908: ######################################################
 7909: 
 7910: =pod
 7911: 
 7912: =item * &csv_print_samples($r,$records)
 7913: 
 7914: Prints a table of sample values from each column uploaded $r is an
 7915: Apache Request ref, $records is an arrayref from
 7916: &Apache::loncommon::upfile_record_sep
 7917: 
 7918: =cut
 7919: 
 7920: ######################################################
 7921: ######################################################
 7922: sub csv_print_samples {
 7923:     my ($r,$records) = @_;
 7924:     my $samples = &get_samples($records,5);
 7925: 
 7926:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 7927:               &start_data_table_header_row());
 7928:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 7929:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
 7930:     }
 7931:     $r->print(&end_data_table_header_row());
 7932:     foreach my $hash (@$samples) {
 7933: 	$r->print(&start_data_table_row());
 7934: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7935: 	    $r->print('<td>');
 7936: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 7937: 	    $r->print('</td>');
 7938: 	}
 7939: 	$r->print(&end_data_table_row());
 7940:     }
 7941:     $r->print(&end_data_table().'<br />'."\n");
 7942: }
 7943: 
 7944: ######################################################
 7945: ######################################################
 7946: 
 7947: =pod
 7948: 
 7949: =item * &csv_print_select_table($r,$records,$d)
 7950: 
 7951: Prints a table to create associations between values and table columns.
 7952: 
 7953: $r is an Apache Request ref,
 7954: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 7955: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 7956: 
 7957: =cut
 7958: 
 7959: ######################################################
 7960: ######################################################
 7961: sub csv_print_select_table {
 7962:     my ($r,$records,$d) = @_;
 7963:     my $i=0;
 7964:     my $samples = &get_samples($records,1);
 7965:     $r->print(&mt('Associate columns with student attributes.')."\n".
 7966: 	      &start_data_table().&start_data_table_header_row().
 7967:               '<th>'.&mt('Attribute').'</th>'.
 7968:               '<th>'.&mt('Column').'</th>'.
 7969:               &end_data_table_header_row()."\n");
 7970:     foreach my $array_ref (@$d) {
 7971: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 7972: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
 7973: 
 7974: 	$r->print('<td><select name=f'.$i.
 7975: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 7976: 	$r->print('<option value="none"></option>');
 7977: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 7978: 	    $r->print('<option value="'.$sample.'"'.
 7979:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 7980:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
 7981: 	}
 7982: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 7983: 	$i++;
 7984:     }
 7985:     $r->print(&end_data_table());
 7986:     $i--;
 7987:     return $i;
 7988: }
 7989: 
 7990: ######################################################
 7991: ######################################################
 7992: 
 7993: =pod
 7994: 
 7995: =item * &csv_samples_select_table($r,$records,$d)
 7996: 
 7997: Prints a table of sample values from the upload and can make associate samples to internal names.
 7998: 
 7999: $r is an Apache Request ref,
 8000: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 8001: $d is an array of 2 element arrays (internal name, displayed name)
 8002: 
 8003: =cut
 8004: 
 8005: ######################################################
 8006: ######################################################
 8007: sub csv_samples_select_table {
 8008:     my ($r,$records,$d) = @_;
 8009:     my $i=0;
 8010:     #
 8011:     my $max_samples = 5;
 8012:     my $samples = &get_samples($records,$max_samples);
 8013:     $r->print(&start_data_table().
 8014:               &start_data_table_header_row().'<th>'.
 8015:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 8016:               &end_data_table_header_row());
 8017: 
 8018:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 8019: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 8020: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 8021: 	foreach my $option (@$d) {
 8022: 	    my ($value,$display,$defaultcol)=@{ $option };
 8023: 	    $r->print('<option value="'.$value.'"'.
 8024:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 8025:                       $display.'</option>');
 8026: 	}
 8027: 	$r->print('</select></td><td>');
 8028: 	foreach my $line (0..($max_samples-1)) {
 8029: 	    if (defined($samples->[$line]{$key})) { 
 8030: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 8031: 	    }
 8032: 	}
 8033: 	$r->print('</td>'.&end_data_table_row());
 8034: 	$i++;
 8035:     }
 8036:     $r->print(&end_data_table());
 8037:     $i--;
 8038:     return($i);
 8039: }
 8040: 
 8041: ######################################################
 8042: ######################################################
 8043: 
 8044: =pod
 8045: 
 8046: =item * &clean_excel_name($name)
 8047: 
 8048: Returns a replacement for $name which does not contain any illegal characters.
 8049: 
 8050: =cut
 8051: 
 8052: ######################################################
 8053: ######################################################
 8054: sub clean_excel_name {
 8055:     my ($name) = @_;
 8056:     $name =~ s/[:\*\?\/\\]//g;
 8057:     if (length($name) > 31) {
 8058:         $name = substr($name,0,31);
 8059:     }
 8060:     return $name;
 8061: }
 8062: 
 8063: =pod
 8064: 
 8065: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
 8066: 
 8067: Returns either 1 or undef
 8068: 
 8069: 1 if the part is to be hidden, undef if it is to be shown
 8070: 
 8071: Arguments are:
 8072: 
 8073: $id the id of the part to be checked
 8074: $symb, optional the symb of the resource to check
 8075: $udom, optional the domain of the user to check for
 8076: $uname, optional the username of the user to check for
 8077: 
 8078: =cut
 8079: 
 8080: sub check_if_partid_hidden {
 8081:     my ($id,$symb,$udom,$uname) = @_;
 8082:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 8083: 					 $symb,$udom,$uname);
 8084:     my $truth=1;
 8085:     #if the string starts with !, then the list is the list to show not hide
 8086:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 8087:     my @hiddenlist=split(/,/,$hiddenparts);
 8088:     foreach my $checkid (@hiddenlist) {
 8089: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 8090:     }
 8091:     return !$truth;
 8092: }
 8093: 
 8094: 
 8095: ############################################################
 8096: ############################################################
 8097: 
 8098: =pod
 8099: 
 8100: =back 
 8101: 
 8102: =head1 cgi-bin script and graphing routines
 8103: 
 8104: =over 4
 8105: 
 8106: =item * &get_cgi_id()
 8107: 
 8108: Inputs: none
 8109: 
 8110: Returns an id which can be used to pass environment variables
 8111: to various cgi-bin scripts.  These environment variables will
 8112: be removed from the users environment after a given time by
 8113: the routine &Apache::lonnet::transfer_profile_to_env.
 8114: 
 8115: =cut
 8116: 
 8117: ############################################################
 8118: ############################################################
 8119: my $uniq=0;
 8120: sub get_cgi_id {
 8121:     $uniq=($uniq+1)%100000;
 8122:     return (time.'_'.$$.'_'.$uniq);
 8123: }
 8124: 
 8125: ############################################################
 8126: ############################################################
 8127: 
 8128: =pod
 8129: 
 8130: =item * &DrawBarGraph()
 8131: 
 8132: Facilitates the plotting of data in a (stacked) bar graph.
 8133: Puts plot definition data into the users environment in order for 
 8134: graph.png to plot it.  Returns an <img> tag for the plot.
 8135: The bars on the plot are labeled '1','2',...,'n'.
 8136: 
 8137: Inputs:
 8138: 
 8139: =over 4
 8140: 
 8141: =item $Title: string, the title of the plot
 8142: 
 8143: =item $xlabel: string, text describing the X-axis of the plot
 8144: 
 8145: =item $ylabel: string, text describing the Y-axis of the plot
 8146: 
 8147: =item $Max: scalar, the maximum Y value to use in the plot
 8148: If $Max is < any data point, the graph will not be rendered.
 8149: 
 8150: =item $colors: array ref holding the colors to be used for the data sets when
 8151: they are plotted.  If undefined, default values will be used.
 8152: 
 8153: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 8154: 
 8155: =item @Values: An array of array references.  Each array reference holds data
 8156: to be plotted in a stacked bar chart.
 8157: 
 8158: =item If the final element of @Values is a hash reference the key/value
 8159: pairs will be added to the graph definition.
 8160: 
 8161: =back
 8162: 
 8163: Returns:
 8164: 
 8165: An <img> tag which references graph.png and the appropriate identifying
 8166: information for the plot.
 8167: 
 8168: =cut
 8169: 
 8170: ############################################################
 8171: ############################################################
 8172: sub DrawBarGraph {
 8173:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 8174:     #
 8175:     if (! defined($colors)) {
 8176:         $colors = ['#33ff00', 
 8177:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 8178:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 8179:                   ]; 
 8180:     }
 8181:     my $extra_settings = {};
 8182:     if (ref($Values[-1]) eq 'HASH') {
 8183:         $extra_settings = pop(@Values);
 8184:     }
 8185:     #
 8186:     my $identifier = &get_cgi_id();
 8187:     my $id = 'cgi.'.$identifier;        
 8188:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 8189:         return '';
 8190:     }
 8191:     #
 8192:     my @Labels;
 8193:     if (defined($labels)) {
 8194:         @Labels = @$labels;
 8195:     } else {
 8196:         for (my $i=0;$i<@{$Values[0]};$i++) {
 8197:             push (@Labels,$i+1);
 8198:         }
 8199:     }
 8200:     #
 8201:     my $NumBars = scalar(@{$Values[0]});
 8202:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 8203:     my %ValuesHash;
 8204:     my $NumSets=1;
 8205:     foreach my $array (@Values) {
 8206:         next if (! ref($array));
 8207:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 8208:             join(',',@$array);
 8209:     }
 8210:     #
 8211:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 8212:     if ($NumBars < 3) {
 8213:         $width = 120+$NumBars*32;
 8214:         $xskip = 1;
 8215:         $bar_width = 30;
 8216:     } elsif ($NumBars < 5) {
 8217:         $width = 120+$NumBars*20;
 8218:         $xskip = 1;
 8219:         $bar_width = 20;
 8220:     } elsif ($NumBars < 10) {
 8221:         $width = 120+$NumBars*15;
 8222:         $xskip = 1;
 8223:         $bar_width = 15;
 8224:     } elsif ($NumBars <= 25) {
 8225:         $width = 120+$NumBars*11;
 8226:         $xskip = 5;
 8227:         $bar_width = 8;
 8228:     } elsif ($NumBars <= 50) {
 8229:         $width = 120+$NumBars*8;
 8230:         $xskip = 5;
 8231:         $bar_width = 4;
 8232:     } else {
 8233:         $width = 120+$NumBars*8;
 8234:         $xskip = 5;
 8235:         $bar_width = 4;
 8236:     }
 8237:     #
 8238:     $Max = 1 if ($Max < 1);
 8239:     if ( int($Max) < $Max ) {
 8240:         $Max++;
 8241:         $Max = int($Max);
 8242:     }
 8243:     $Title  = '' if (! defined($Title));
 8244:     $xlabel = '' if (! defined($xlabel));
 8245:     $ylabel = '' if (! defined($ylabel));
 8246:     $ValuesHash{$id.'.title'}    = &escape($Title);
 8247:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 8248:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 8249:     $ValuesHash{$id.'.y_max_value'} = $Max;
 8250:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 8251:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 8252:     $ValuesHash{$id.'.PlotType'} = 'bar';
 8253:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8254:     $ValuesHash{$id.'.height'}   = $height;
 8255:     $ValuesHash{$id.'.width'}    = $width;
 8256:     $ValuesHash{$id.'.xskip'}    = $xskip;
 8257:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 8258:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 8259:     #
 8260:     # Deal with other parameters
 8261:     while (my ($key,$value) = each(%$extra_settings)) {
 8262:         $ValuesHash{$id.'.'.$key} = $value;
 8263:     }
 8264:     #
 8265:     &Apache::lonnet::appenv(\%ValuesHash);
 8266:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8267: }
 8268: 
 8269: ############################################################
 8270: ############################################################
 8271: 
 8272: =pod
 8273: 
 8274: =item * &DrawXYGraph()
 8275: 
 8276: Facilitates the plotting of data in an XY graph.
 8277: Puts plot definition data into the users environment in order for 
 8278: graph.png to plot it.  Returns an <img> tag for the plot.
 8279: 
 8280: Inputs:
 8281: 
 8282: =over 4
 8283: 
 8284: =item $Title: string, the title of the plot
 8285: 
 8286: =item $xlabel: string, text describing the X-axis of the plot
 8287: 
 8288: =item $ylabel: string, text describing the Y-axis of the plot
 8289: 
 8290: =item $Max: scalar, the maximum Y value to use in the plot
 8291: If $Max is < any data point, the graph will not be rendered.
 8292: 
 8293: =item $colors: Array ref containing the hex color codes for the data to be 
 8294: plotted in.  If undefined, default values will be used.
 8295: 
 8296: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8297: 
 8298: =item $Ydata: Array ref containing Array refs.  
 8299: Each of the contained arrays will be plotted as a separate curve.
 8300: 
 8301: =item %Values: hash indicating or overriding any default values which are 
 8302: passed to graph.png.  
 8303: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8304: 
 8305: =back
 8306: 
 8307: Returns:
 8308: 
 8309: An <img> tag which references graph.png and the appropriate identifying
 8310: information for the plot.
 8311: 
 8312: =cut
 8313: 
 8314: ############################################################
 8315: ############################################################
 8316: sub DrawXYGraph {
 8317:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 8318:     #
 8319:     # Create the identifier for the graph
 8320:     my $identifier = &get_cgi_id();
 8321:     my $id = 'cgi.'.$identifier;
 8322:     #
 8323:     $Title  = '' if (! defined($Title));
 8324:     $xlabel = '' if (! defined($xlabel));
 8325:     $ylabel = '' if (! defined($ylabel));
 8326:     my %ValuesHash = 
 8327:         (
 8328:          $id.'.title'  => &escape($Title),
 8329:          $id.'.xlabel' => &escape($xlabel),
 8330:          $id.'.ylabel' => &escape($ylabel),
 8331:          $id.'.y_max_value'=> $Max,
 8332:          $id.'.labels'     => join(',',@$Xlabels),
 8333:          $id.'.PlotType'   => 'XY',
 8334:          );
 8335:     #
 8336:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8337:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8338:     }
 8339:     #
 8340:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 8341:         return '';
 8342:     }
 8343:     my $NumSets=1;
 8344:     foreach my $array (@{$Ydata}){
 8345:         next if (! ref($array));
 8346:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8347:     }
 8348:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 8349:     #
 8350:     # Deal with other parameters
 8351:     while (my ($key,$value) = each(%Values)) {
 8352:         $ValuesHash{$id.'.'.$key} = $value;
 8353:     }
 8354:     #
 8355:     &Apache::lonnet::appenv(\%ValuesHash);
 8356:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8357: }
 8358: 
 8359: ############################################################
 8360: ############################################################
 8361: 
 8362: =pod
 8363: 
 8364: =item * &DrawXYYGraph()
 8365: 
 8366: Facilitates the plotting of data in an XY graph with two Y axes.
 8367: Puts plot definition data into the users environment in order for 
 8368: graph.png to plot it.  Returns an <img> tag for the plot.
 8369: 
 8370: Inputs:
 8371: 
 8372: =over 4
 8373: 
 8374: =item $Title: string, the title of the plot
 8375: 
 8376: =item $xlabel: string, text describing the X-axis of the plot
 8377: 
 8378: =item $ylabel: string, text describing the Y-axis of the plot
 8379: 
 8380: =item $colors: Array ref containing the hex color codes for the data to be 
 8381: plotted in.  If undefined, default values will be used.
 8382: 
 8383: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 8384: 
 8385: =item $Ydata1: The first data set
 8386: 
 8387: =item $Min1: The minimum value of the left Y-axis
 8388: 
 8389: =item $Max1: The maximum value of the left Y-axis
 8390: 
 8391: =item $Ydata2: The second data set
 8392: 
 8393: =item $Min2: The minimum value of the right Y-axis
 8394: 
 8395: =item $Max2: The maximum value of the left Y-axis
 8396: 
 8397: =item %Values: hash indicating or overriding any default values which are 
 8398: passed to graph.png.  
 8399: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 8400: 
 8401: =back
 8402: 
 8403: Returns:
 8404: 
 8405: An <img> tag which references graph.png and the appropriate identifying
 8406: information for the plot.
 8407: 
 8408: =cut
 8409: 
 8410: ############################################################
 8411: ############################################################
 8412: sub DrawXYYGraph {
 8413:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 8414:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 8415:     #
 8416:     # Create the identifier for the graph
 8417:     my $identifier = &get_cgi_id();
 8418:     my $id = 'cgi.'.$identifier;
 8419:     #
 8420:     $Title  = '' if (! defined($Title));
 8421:     $xlabel = '' if (! defined($xlabel));
 8422:     $ylabel = '' if (! defined($ylabel));
 8423:     my %ValuesHash = 
 8424:         (
 8425:          $id.'.title'  => &escape($Title),
 8426:          $id.'.xlabel' => &escape($xlabel),
 8427:          $id.'.ylabel' => &escape($ylabel),
 8428:          $id.'.labels' => join(',',@$Xlabels),
 8429:          $id.'.PlotType' => 'XY',
 8430:          $id.'.NumSets' => 2,
 8431:          $id.'.two_axes' => 1,
 8432:          $id.'.y1_max_value' => $Max1,
 8433:          $id.'.y1_min_value' => $Min1,
 8434:          $id.'.y2_max_value' => $Max2,
 8435:          $id.'.y2_min_value' => $Min2,
 8436:          );
 8437:     #
 8438:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 8439:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 8440:     }
 8441:     #
 8442:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 8443:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 8444:         return '';
 8445:     }
 8446:     my $NumSets=1;
 8447:     foreach my $array ($Ydata1,$Ydata2){
 8448:         next if (! ref($array));
 8449:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 8450:     }
 8451:     #
 8452:     # Deal with other parameters
 8453:     while (my ($key,$value) = each(%Values)) {
 8454:         $ValuesHash{$id.'.'.$key} = $value;
 8455:     }
 8456:     #
 8457:     &Apache::lonnet::appenv(\%ValuesHash);
 8458:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 8459: }
 8460: 
 8461: ############################################################
 8462: ############################################################
 8463: 
 8464: =pod
 8465: 
 8466: =back 
 8467: 
 8468: =head1 Statistics helper routines?  
 8469: 
 8470: Bad place for them but what the hell.
 8471: 
 8472: =over 4
 8473: 
 8474: =item * &chartlink()
 8475: 
 8476: Returns a link to the chart for a specific student.  
 8477: 
 8478: Inputs:
 8479: 
 8480: =over 4
 8481: 
 8482: =item $linktext: The text of the link
 8483: 
 8484: =item $sname: The students username
 8485: 
 8486: =item $sdomain: The students domain
 8487: 
 8488: =back
 8489: 
 8490: =back
 8491: 
 8492: =cut
 8493: 
 8494: ############################################################
 8495: ############################################################
 8496: sub chartlink {
 8497:     my ($linktext, $sname, $sdomain) = @_;
 8498:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 8499:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 8500:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 8501:        '">'.$linktext.'</a>';
 8502: }
 8503: 
 8504: #######################################################
 8505: #######################################################
 8506: 
 8507: =pod
 8508: 
 8509: =head1 Course Environment Routines
 8510: 
 8511: =over 4
 8512: 
 8513: =item * &restore_course_settings()
 8514: 
 8515: =item * &store_course_settings()
 8516: 
 8517: Restores/Store indicated form parameters from the course environment.
 8518: Will not overwrite existing values of the form parameters.
 8519: 
 8520: Inputs: 
 8521: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 8522: 
 8523: a hash ref describing the data to be stored.  For example:
 8524:    
 8525: %Save_Parameters = ('Status' => 'scalar',
 8526:     'chartoutputmode' => 'scalar',
 8527:     'chartoutputdata' => 'scalar',
 8528:     'Section' => 'array',
 8529:     'Group' => 'array',
 8530:     'StudentData' => 'array',
 8531:     'Maps' => 'array');
 8532: 
 8533: Returns: both routines return nothing
 8534: 
 8535: =back
 8536: 
 8537: =cut
 8538: 
 8539: #######################################################
 8540: #######################################################
 8541: sub store_course_settings {
 8542:     return &store_settings($env{'request.course.id'},@_);
 8543: }
 8544: 
 8545: sub store_settings {
 8546:     # save to the environment
 8547:     # appenv the same items, just to be safe
 8548:     my $udom  = $env{'user.domain'};
 8549:     my $uname = $env{'user.name'};
 8550:     my ($context,$prefix,$Settings) = @_;
 8551:     my %SaveHash;
 8552:     my %AppHash;
 8553:     while (my ($setting,$type) = each(%$Settings)) {
 8554:         my $basename = join('.','internal',$context,$prefix,$setting);
 8555:         my $envname = 'environment.'.$basename;
 8556:         if (exists($env{'form.'.$setting})) {
 8557:             # Save this value away
 8558:             if ($type eq 'scalar' &&
 8559:                 (! exists($env{$envname}) || 
 8560:                  $env{$envname} ne $env{'form.'.$setting})) {
 8561:                 $SaveHash{$basename} = $env{'form.'.$setting};
 8562:                 $AppHash{$envname}   = $env{'form.'.$setting};
 8563:             } elsif ($type eq 'array') {
 8564:                 my $stored_form;
 8565:                 if (ref($env{'form.'.$setting})) {
 8566:                     $stored_form = join(',',
 8567:                                         map {
 8568:                                             &escape($_);
 8569:                                         } sort(@{$env{'form.'.$setting}}));
 8570:                 } else {
 8571:                     $stored_form = 
 8572:                         &escape($env{'form.'.$setting});
 8573:                 }
 8574:                 # Determine if the array contents are the same.
 8575:                 if ($stored_form ne $env{$envname}) {
 8576:                     $SaveHash{$basename} = $stored_form;
 8577:                     $AppHash{$envname}   = $stored_form;
 8578:                 }
 8579:             }
 8580:         }
 8581:     }
 8582:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 8583:                                           $udom,$uname);
 8584:     if ($put_result !~ /^(ok|delayed)/) {
 8585:         &Apache::lonnet::logthis('unable to save form parameters, '.
 8586:                                  'got error:'.$put_result);
 8587:     }
 8588:     # Make sure these settings stick around in this session, too
 8589:     &Apache::lonnet::appenv(\%AppHash);
 8590:     return;
 8591: }
 8592: 
 8593: sub restore_course_settings {
 8594:     return &restore_settings($env{'request.course.id'},@_);
 8595: }
 8596: 
 8597: sub restore_settings {
 8598:     my ($context,$prefix,$Settings) = @_;
 8599:     while (my ($setting,$type) = each(%$Settings)) {
 8600:         next if (exists($env{'form.'.$setting}));
 8601:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 8602:             '.'.$setting;
 8603:         if (exists($env{$envname})) {
 8604:             if ($type eq 'scalar') {
 8605:                 $env{'form.'.$setting} = $env{$envname};
 8606:             } elsif ($type eq 'array') {
 8607:                 $env{'form.'.$setting} = [ 
 8608:                                            map { 
 8609:                                                &unescape($_); 
 8610:                                            } split(',',$env{$envname})
 8611:                                            ];
 8612:             }
 8613:         }
 8614:     }
 8615: }
 8616: 
 8617: #######################################################
 8618: #######################################################
 8619: 
 8620: =pod
 8621: 
 8622: =head1 Domain E-mail Routines  
 8623: 
 8624: =over 4
 8625: 
 8626: =item * &build_recipient_list()
 8627: 
 8628: Build recipient lists for four types of e-mail:
 8629: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
 8630: (d) Help requests, generated by
 8631: lonerrorhandler.pm, CHECKRPMS, loncron, and lonsupportreq.pm respectively.
 8632: 
 8633: Inputs:
 8634: defmail (scalar - email address of default recipient), 
 8635: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
 8636: defdom (domain for which to retrieve configuration settings),
 8637: origmail (scalar - email address of recipient from loncapa.conf, 
 8638: i.e., predates configuration by DC via domainprefs.pm 
 8639: 
 8640: Returns: comma separated list of addresses to which to send e-mail.
 8641: 
 8642: =back
 8643: 
 8644: =cut
 8645: 
 8646: ############################################################
 8647: ############################################################
 8648: sub build_recipient_list {
 8649:     my ($defmail,$mailing,$defdom,$origmail) = @_;
 8650:     my @recipients;
 8651:     my $otheremails;
 8652:     my %domconfig =
 8653:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
 8654:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 8655:         if (exists($domconfig{'contacts'}{$mailing})) {
 8656:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
 8657:                 my @contacts = ('adminemail','supportemail');
 8658:                 foreach my $item (@contacts) {
 8659:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
 8660:                         my $addr = $domconfig{'contacts'}{$item};
 8661:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
 8662:                             push(@recipients,$addr);
 8663:                         }
 8664:                     }
 8665:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
 8666:                 }
 8667:             }
 8668:         } elsif ($origmail ne '') {
 8669:             push(@recipients,$origmail);
 8670:         }
 8671:     } elsif ($origmail ne '') {
 8672:         push(@recipients,$origmail);
 8673:     }
 8674:     if (defined($defmail)) {
 8675:         if ($defmail ne '') {
 8676:             push(@recipients,$defmail);
 8677:         }
 8678:     }
 8679:     if ($otheremails) {
 8680:         my @others;
 8681:         if ($otheremails =~ /,/) {
 8682:             @others = split(/,/,$otheremails);
 8683:         } else {
 8684:             push(@others,$otheremails);
 8685:         }
 8686:         foreach my $addr (@others) {
 8687:             if (!grep(/^\Q$addr\E$/,@recipients)) {
 8688:                 push(@recipients,$addr);
 8689:             }
 8690:         }
 8691:     }
 8692:     my $recipientlist = join(',',@recipients); 
 8693:     return $recipientlist;
 8694: }
 8695: 
 8696: ############################################################
 8697: ############################################################
 8698: 
 8699: =pod
 8700: 
 8701: =head1 Course Catalog Routines
 8702: 
 8703: =over 4
 8704: 
 8705: =item * &gather_categories()
 8706: 
 8707: Converts category definitions - keys of categories hash stored in  
 8708: coursecategories in configuration.db on the primary library server in a 
 8709: domain - to an array.  Also generates javascript and idx hash used to 
 8710: generate Domain Coordinator interface for editing Course Categories.
 8711: 
 8712: Inputs:
 8713: 
 8714: categories (reference to hash of category definitions).
 8715: 
 8716: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8717:       categories and subcategories).
 8718: 
 8719: idx (reference to hash of counters used in Domain Coordinator interface for 
 8720:       editing Course Categories).
 8721: 
 8722: jsarray (reference to array of categories used to create Javascript arrays for
 8723:          Domain Coordinator interface for editing Course Categories).
 8724: 
 8725: Returns: nothing
 8726: 
 8727: Side effects: populates cats, idx and jsarray. 
 8728: 
 8729: =cut
 8730: 
 8731: sub gather_categories {
 8732:     my ($categories,$cats,$idx,$jsarray) = @_;
 8733:     my %counters;
 8734:     my $num = 0;
 8735:     foreach my $item (keys(%{$categories})) {
 8736:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
 8737:         if ($container eq '' && $depth == 0) {
 8738:             $cats->[$depth][$categories->{$item}] = $cat;
 8739:         } else {
 8740:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
 8741:         }
 8742:         my ($escitem,$tail) = split(/:/,$item,2);
 8743:         if ($counters{$tail} eq '') {
 8744:             $counters{$tail} = $num;
 8745:             $num ++;
 8746:         }
 8747:         if (ref($idx) eq 'HASH') {
 8748:             $idx->{$item} = $counters{$tail};
 8749:         }
 8750:         if (ref($jsarray) eq 'ARRAY') {
 8751:             push(@{$jsarray->[$counters{$tail}]},$item);
 8752:         }
 8753:     }
 8754:     return;
 8755: }
 8756: 
 8757: =pod
 8758: 
 8759: =item * &extract_categories()
 8760: 
 8761: Used to generate breadcrumb trails for course categories.
 8762: 
 8763: Inputs:
 8764: 
 8765: categories (reference to hash of category definitions).
 8766: 
 8767: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8768:       categories and subcategories).
 8769: 
 8770: trails (reference to array of breacrumb trails for each category).
 8771: 
 8772: allitems (reference to hash - key is category key 
 8773:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8774: 
 8775: idx (reference to hash of counters used in Domain Coordinator interface for
 8776:       editing Course Categories).
 8777: 
 8778: jsarray (reference to array of categories used to create Javascript arrays for
 8779:          Domain Coordinator interface for editing Course Categories).
 8780: 
 8781: subcats (reference to hash of arrays containing all subcategories within each 
 8782:          category, -recursive)
 8783: 
 8784: Returns: nothing
 8785: 
 8786: Side effects: populates trails and allitems hash references.
 8787: 
 8788: =cut
 8789: 
 8790: sub extract_categories {
 8791:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
 8792:     if (ref($categories) eq 'HASH') {
 8793:         &gather_categories($categories,$cats,$idx,$jsarray);
 8794:         if (ref($cats->[0]) eq 'ARRAY') {
 8795:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
 8796:                 my $name = $cats->[0][$i];
 8797:                 my $item = &escape($name).'::0';
 8798:                 my $trailstr;
 8799:                 if ($name eq 'instcode') {
 8800:                     $trailstr = &mt('Official courses (with institutional codes)');
 8801:                 } else {
 8802:                     $trailstr = $name;
 8803:                 }
 8804:                 if ($allitems->{$item} eq '') {
 8805:                     push(@{$trails},$trailstr);
 8806:                     $allitems->{$item} = scalar(@{$trails})-1;
 8807:                 }
 8808:                 my @parents = ($name);
 8809:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
 8810:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
 8811:                         my $category = $cats->[1]{$name}[$j];
 8812:                         if (ref($subcats) eq 'HASH') {
 8813:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
 8814:                         }
 8815:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
 8816:                     }
 8817:                 } else {
 8818:                     if (ref($subcats) eq 'HASH') {
 8819:                         $subcats->{$item} = [];
 8820:                     }
 8821:                 }
 8822:             }
 8823:         }
 8824:     }
 8825:     return;
 8826: }
 8827: 
 8828: =pod
 8829: 
 8830: =item *&recurse_categories()
 8831: 
 8832: Recursively used to generate breadcrumb trails for course categories.
 8833: 
 8834: Inputs:
 8835: 
 8836: cats (reference to array of arrays/hashes which encapsulates hierarchy of
 8837:       categories and subcategories).
 8838: 
 8839: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
 8840: 
 8841: category (current course category, for which breadcrumb trail is being generated).
 8842: 
 8843: trails (reference to array of breadcrumb trails for each category).
 8844: 
 8845: allitems (reference to hash - key is category key
 8846:          (format: escaped(name):escaped(parent category):depth in hierarchy).
 8847: 
 8848: parents (array containing containers directories for current category, 
 8849:          back to top level). 
 8850: 
 8851: Returns: nothing
 8852: 
 8853: Side effects: populates trails and allitems hash references
 8854: 
 8855: =cut
 8856: 
 8857: sub recurse_categories {
 8858:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
 8859:     my $shallower = $depth - 1;
 8860:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
 8861:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
 8862:             my $name = $cats->[$depth]{$category}[$k];
 8863:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8864:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8865:             if ($allitems->{$item} eq '') {
 8866:                 push(@{$trails},$trailstr);
 8867:                 $allitems->{$item} = scalar(@{$trails})-1;
 8868:             }
 8869:             my $deeper = $depth+1;
 8870:             push(@{$parents},$category);
 8871:             if (ref($subcats) eq 'HASH') {
 8872:                 my $subcat = &escape($name).':'.$category.':'.$depth;
 8873:                 for (my $j=@{$parents}; $j>=0; $j--) {
 8874:                     my $higher;
 8875:                     if ($j > 0) {
 8876:                         $higher = &escape($parents->[$j]).':'.
 8877:                                   &escape($parents->[$j-1]).':'.$j;
 8878:                     } else {
 8879:                         $higher = &escape($parents->[$j]).'::'.$j;
 8880:                     }
 8881:                     push(@{$subcats->{$higher}},$subcat);
 8882:                 }
 8883:             }
 8884:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
 8885:                                 $subcats);
 8886:             pop(@{$parents});
 8887:         }
 8888:     } else {
 8889:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
 8890:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
 8891:         if ($allitems->{$item} eq '') {
 8892:             push(@{$trails},$trailstr);
 8893:             $allitems->{$item} = scalar(@{$trails})-1;
 8894:         }
 8895:     }
 8896:     return;
 8897: }
 8898: 
 8899: =pod
 8900: 
 8901: =item *&assign_categories_table()
 8902: 
 8903: Create a datatable for display of hierarchical categories in a domain,
 8904: with checkboxes to allow a course to be categorized. 
 8905: 
 8906: Inputs:
 8907: 
 8908: cathash - reference to hash of categories defined for the domain (from
 8909:           configuration.db)
 8910: 
 8911: currcat - scalar with an & separated list of categories assigned to a course. 
 8912: 
 8913: Returns: $output (markup to be displayed) 
 8914: 
 8915: =cut
 8916: 
 8917: sub assign_categories_table {
 8918:     my ($cathash,$currcat) = @_;
 8919:     my $output;
 8920:     if (ref($cathash) eq 'HASH') {
 8921:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
 8922:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
 8923:         $maxdepth = scalar(@cats);
 8924:         if (@cats > 0) {
 8925:             my $itemcount = 0;
 8926:             if (ref($cats[0]) eq 'ARRAY') {
 8927:                 $output = &Apache::loncommon::start_data_table();
 8928:                 my @currcategories;
 8929:                 if ($currcat ne '') {
 8930:                     @currcategories = split('&',$currcat);
 8931:                 }
 8932:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
 8933:                     my $parent = $cats[0][$i];
 8934:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8935:                     next if ($parent eq 'instcode');
 8936:                     my $item = &escape($parent).'::0';
 8937:                     my $checked = '';
 8938:                     if (@currcategories > 0) {
 8939:                         if (grep(/^\Q$item\E$/,@currcategories)) {
 8940:                             $checked = ' checked="checked" ';
 8941:                         }
 8942:                     }
 8943:                     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
 8944:                                '<input type="checkbox" name="usecategory" value="'.
 8945:                                $item.'"'.$checked.' />'.$parent.'</span>'.
 8946:                                '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
 8947:                     my $depth = 1;
 8948:                     push(@path,$parent);
 8949:                     $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
 8950:                     pop(@path);
 8951:                     $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 8952:                     $itemcount ++;
 8953:                 }
 8954:                 $output .= &Apache::loncommon::end_data_table();
 8955:             }
 8956:         }
 8957:     }
 8958:     return $output;
 8959: }
 8960: 
 8961: =pod
 8962: 
 8963: =item *&assign_category_rows()
 8964: 
 8965: Create a datatable row for display of nested categories in a domain,
 8966: with checkboxes to allow a course to be categorized,called recursively.
 8967: 
 8968: Inputs:
 8969: 
 8970: itemcount - track row number for alternating colors
 8971: 
 8972: cats - reference to array of arrays/hashes which encapsulates hierarchy of
 8973:       categories and subcategories.
 8974: 
 8975: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
 8976: 
 8977: parent - parent of current category item
 8978: 
 8979: path - Array containing all categories back up through the hierarchy from the
 8980:        current category to the top level.
 8981: 
 8982: currcategories - reference to array of current categories assigned to the course
 8983: 
 8984: Returns: $output (markup to be displayed).
 8985: 
 8986: =cut
 8987: 
 8988: sub assign_category_rows {
 8989:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
 8990:     my ($text,$name,$item,$chgstr);
 8991:     if (ref($cats) eq 'ARRAY') {
 8992:         my $maxdepth = scalar(@{$cats});
 8993:         if (ref($cats->[$depth]) eq 'HASH') {
 8994:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 8995:                 my $numchildren = @{$cats->[$depth]{$parent}};
 8996:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8997:                 $text .= '<td><table class="LC_datatable">';
 8998:                 for (my $j=0; $j<$numchildren; $j++) {
 8999:                     $name = $cats->[$depth]{$parent}[$j];
 9000:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
 9001:                     my $deeper = $depth+1;
 9002:                     my $checked = '';
 9003:                     if (ref($currcategories) eq 'ARRAY') {
 9004:                         if (@{$currcategories} > 0) {
 9005:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
 9006:                                 $checked = ' checked="checked" ';
 9007:                             }
 9008:                         }
 9009:                     }
 9010:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
 9011:                              '<input type="checkbox" name="usecategory" value="'.
 9012:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
 9013:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
 9014:                              '</td><td>';
 9015:                     if (ref($path) eq 'ARRAY') {
 9016:                         push(@{$path},$name);
 9017:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
 9018:                         pop(@{$path});
 9019:                     }
 9020:                     $text .= '</td></tr>';
 9021:                 }
 9022:                 $text .= '</table></td>';
 9023:             }
 9024:         }
 9025:     }
 9026:     return $text;
 9027: }
 9028: 
 9029: ############################################################
 9030: ############################################################
 9031: 
 9032: 
 9033: sub commit_customrole {
 9034:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
 9035:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
 9036:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 9037:                          ($end?', ending '.localtime($end):'').': <b>'.
 9038:               &Apache::lonnet::assigncustomrole(
 9039:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
 9040:                  '</b><br />';
 9041:     return $output;
 9042: }
 9043: 
 9044: sub commit_standardrole {
 9045:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9046:     my ($output,$logmsg,$linefeed);
 9047:     if ($context eq 'auto') {
 9048:         $linefeed = "\n";
 9049:     } else {
 9050:         $linefeed = "<br />\n";
 9051:     }  
 9052:     if ($three eq 'st') {
 9053:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 9054:                                          $one,$two,$sec,$context);
 9055:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 9056:             ($result eq 'unknown_course') || ($result eq 'refused')) {
 9057:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
 9058:         } else {
 9059:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 9060:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9061:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9062:             if ($context eq 'auto') {
 9063:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 9064:             } else {
 9065:                $output .= '<b>'.$result.'</b>'.$linefeed.
 9066:                &mt('Add to classlist').': <b>ok</b>';
 9067:             }
 9068:             $output .= $linefeed;
 9069:         }
 9070:     } else {
 9071:         $output = &mt('Assigning').' '.$three.' in '.$url.
 9072:                ($start?', '.&mt('starting').' '.localtime($start):'').
 9073:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 9074:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
 9075:         if ($context eq 'auto') {
 9076:             $output .= $result.$linefeed;
 9077:         } else {
 9078:             $output .= '<b>'.$result.'</b>'.$linefeed;
 9079:         }
 9080:     }
 9081:     return $output;
 9082: }
 9083: 
 9084: sub commit_studentrole {
 9085:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 9086:     my ($result,$linefeed,$oldsecurl,$newsecurl);
 9087:     if ($context eq 'auto') {
 9088:         $linefeed = "\n";
 9089:     } else {
 9090:         $linefeed = '<br />'."\n";
 9091:     }
 9092:     if (defined($one) && defined($two)) {
 9093:         my $cid=$one.'_'.$two;
 9094:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 9095:         my $secchange = 0;
 9096:         my $expire_role_result;
 9097:         my $modify_section_result;
 9098:         if ($oldsec ne '-1') { 
 9099:             if ($oldsec ne $sec) {
 9100:                 $secchange = 1;
 9101:                 my $now = time;
 9102:                 my $uurl='/'.$cid;
 9103:                 $uurl=~s/\_/\//g;
 9104:                 if ($oldsec) {
 9105:                     $uurl.='/'.$oldsec;
 9106:                 }
 9107:                 $oldsecurl = $uurl;
 9108:                 $expire_role_result = 
 9109:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
 9110:                 if ($env{'request.course.sec'} ne '') { 
 9111:                     if ($expire_role_result eq 'refused') {
 9112:                         my @roles = ('st');
 9113:                         my @statuses = ('previous');
 9114:                         my @roledoms = ($one);
 9115:                         my $withsec = 1;
 9116:                         my %roleshash = 
 9117:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 9118:                                               \@statuses,\@roles,\@roledoms,$withsec);
 9119:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
 9120:                             my ($oldstart,$oldend) = 
 9121:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
 9122:                             if ($oldend > 0 && $oldend <= $now) {
 9123:                                 $expire_role_result = 'ok';
 9124:                             }
 9125:                         }
 9126:                     }
 9127:                 }
 9128:                 $result = $expire_role_result;
 9129:             }
 9130:         }
 9131:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 9132:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
 9133:             if ($modify_section_result =~ /^ok/) {
 9134:                 if ($secchange == 1) {
 9135:                     if ($sec eq '') {
 9136:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
 9137:                     } else {
 9138:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
 9139:                     }
 9140:                 } elsif ($oldsec eq '-1') {
 9141:                     if ($sec eq '') {
 9142:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
 9143:                     } else {
 9144:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9145:                     }
 9146:                 } else {
 9147:                     if ($sec eq '') {
 9148:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
 9149:                     } else {
 9150:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
 9151:                     }
 9152:                 }
 9153:             } else {
 9154:                 if ($secchange) {       
 9155:                     $$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;
 9156:                 } else {
 9157:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
 9158:                 }
 9159:             }
 9160:             $result = $modify_section_result;
 9161:         } elsif ($secchange == 1) {
 9162:             if ($oldsec eq '') {
 9163:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
 9164:             } else {
 9165:                 $$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;
 9166:             }
 9167:             if ($expire_role_result eq 'refused') {
 9168:                 my $newsecurl = '/'.$cid;
 9169:                 $newsecurl =~ s/\_/\//g;
 9170:                 if ($sec ne '') {
 9171:                     $newsecurl.='/'.$sec;
 9172:                 }
 9173:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
 9174:                     if ($sec eq '') {
 9175:                         $$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;
 9176:                     } else {
 9177:                         $$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;
 9178:                     }
 9179:                 }
 9180:             }
 9181:         }
 9182:     } else {
 9183:         $$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;
 9184:         $result = "error: incomplete course id\n";
 9185:     }
 9186:     return $result;
 9187: }
 9188: 
 9189: ############################################################
 9190: ############################################################
 9191: 
 9192: sub check_clone {
 9193:     my ($args,$linefeed) = @_;
 9194:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 9195:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 9196:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 9197:     my $clonemsg;
 9198:     my $can_clone = 0;
 9199: 
 9200:     if ($clonehome eq 'no_host') {
 9201:         $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'});     
 9202:     } else {
 9203: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 9204: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 9205: 	    $can_clone = 1;
 9206: 	} else {
 9207: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 9208: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 9209: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 9210:             if (grep(/^\*$/,@cloners)) {
 9211:                 $can_clone = 1;
 9212:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 9213:                 $can_clone = 1;
 9214:             } else {
 9215: 	        my %roleshash =
 9216: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 9217: 					 $args->{'ccdomain'},
 9218:                                          'userroles',['active'],['cc'],
 9219: 					 [$args->{'clonedomain'}]);
 9220: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 9221: 		    $can_clone = 1;
 9222: 	        } else {
 9223:                     $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'});
 9224: 	        }
 9225: 	    }
 9226:         }
 9227:     }
 9228:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 9229: }
 9230: 
 9231: sub construct_course {
 9232:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 9233:     my $outcome;
 9234:     my $linefeed =  '<br />'."\n";
 9235:     if ($context eq 'auto') {
 9236:         $linefeed = "\n";
 9237:     }
 9238: 
 9239: #
 9240: # Are we cloning?
 9241: #
 9242:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 9243:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 9244: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 9245: 	if ($context ne 'auto') {
 9246:             if ($clonemsg ne '') {
 9247: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 9248:             }
 9249: 	}
 9250: 	$outcome .= $clonemsg.$linefeed;
 9251: 
 9252:         if (!$can_clone) {
 9253: 	    return (0,$outcome);
 9254: 	}
 9255:     }
 9256: 
 9257: #
 9258: # Open course
 9259: #
 9260:     my $crstype = lc($args->{'crstype'});
 9261:     my %cenv=();
 9262:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 9263:                                              $args->{'cdescr'},
 9264:                                              $args->{'curl'},
 9265:                                              $args->{'course_home'},
 9266:                                              $args->{'nonstandard'},
 9267:                                              $args->{'crscode'},
 9268:                                              $args->{'ccuname'}.':'.
 9269:                                              $args->{'ccdomain'},
 9270:                                              $args->{'crstype'});
 9271: 
 9272:     # Note: The testing routines depend on this being output; see 
 9273:     # Utils::Course. This needs to at least be output as a comment
 9274:     # if anyone ever decides to not show this, and Utils::Course::new
 9275:     # will need to be suitably modified.
 9276:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 9277: #
 9278: # Check if created correctly
 9279: #
 9280:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 9281:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 9282:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 9283: 
 9284: #
 9285: # Do the cloning
 9286: #   
 9287:     if ($can_clone && $cloneid) {
 9288: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 9289: 	if ($context ne 'auto') {
 9290: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 9291: 	}
 9292: 	$outcome .= $clonemsg.$linefeed;
 9293: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 9294: # Copy all files
 9295: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
 9296: # Restore URL
 9297: 	$cenv{'url'}=$oldcenv{'url'};
 9298: # Restore title
 9299: 	$cenv{'description'}=$oldcenv{'description'};
 9300: # Mark as cloned
 9301: 	$cenv{'clonedfrom'}=$cloneid;
 9302: # Need to clone grading mode
 9303:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
 9304:         $cenv{'grading'}=$newenv{'grading'};
 9305: # Do not clone these environment entries
 9306:         &Apache::lonnet::del('environment',
 9307:                   ['default_enrollment_start_date',
 9308:                    'default_enrollment_end_date',
 9309:                    'question.email',
 9310:                    'policy.email',
 9311:                    'comment.email',
 9312:                    'pch.users.denied',
 9313:                    'plc.users.denied',
 9314:                    'hidefromcat',
 9315:                    'categories'],
 9316:                    $$crsudom,$$crsunum);
 9317:     }
 9318: 
 9319: #
 9320: # Set environment (will override cloned, if existing)
 9321: #
 9322:     my @sections = ();
 9323:     my @xlists = ();
 9324:     if ($args->{'crstype'}) {
 9325:         $cenv{'type'}=$args->{'crstype'};
 9326:     }
 9327:     if ($args->{'crsid'}) {
 9328:         $cenv{'courseid'}=$args->{'crsid'};
 9329:     }
 9330:     if ($args->{'crscode'}) {
 9331:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 9332:     }
 9333:     if ($args->{'crsquota'} ne '') {
 9334:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 9335:     } else {
 9336:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 9337:     }
 9338:     if ($args->{'ccuname'}) {
 9339:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 9340:                                         ':'.$args->{'ccdomain'};
 9341:     } else {
 9342:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 9343:     }
 9344:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 9345:     if ($args->{'crssections'}) {
 9346:         $cenv{'internal.sectionnums'} = '';
 9347:         if ($args->{'crssections'} =~ m/,/) {
 9348:             @sections = split/,/,$args->{'crssections'};
 9349:         } else {
 9350:             $sections[0] = $args->{'crssections'};
 9351:         }
 9352:         if (@sections > 0) {
 9353:             foreach my $item (@sections) {
 9354:                 my ($sec,$gp) = split/:/,$item;
 9355:                 my $class = $args->{'crscode'}.$sec;
 9356:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 9357:                 $cenv{'internal.sectionnums'} .= $item.',';
 9358:                 unless ($addcheck eq 'ok') {
 9359:                     push @badclasses, $class;
 9360:                 }
 9361:             }
 9362:             $cenv{'internal.sectionnums'} =~ s/,$//;
 9363:         }
 9364:     }
 9365: # do not hide course coordinator from staff listing, 
 9366: # even if privileged
 9367:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9368: # add crosslistings
 9369:     if ($args->{'crsxlist'}) {
 9370:         $cenv{'internal.crosslistings'}='';
 9371:         if ($args->{'crsxlist'} =~ m/,/) {
 9372:             @xlists = split/,/,$args->{'crsxlist'};
 9373:         } else {
 9374:             $xlists[0] = $args->{'crsxlist'};
 9375:         }
 9376:         if (@xlists > 0) {
 9377:             foreach my $item (@xlists) {
 9378:                 my ($xl,$gp) = split/:/,$item;
 9379:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 9380:                 $cenv{'internal.crosslistings'} .= $item.',';
 9381:                 unless ($addcheck eq 'ok') {
 9382:                     push @badclasses, $xl;
 9383:                 }
 9384:             }
 9385:             $cenv{'internal.crosslistings'} =~ s/,$//;
 9386:         }
 9387:     }
 9388:     if ($args->{'autoadds'}) {
 9389:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 9390:     }
 9391:     if ($args->{'autodrops'}) {
 9392:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 9393:     }
 9394: # check for notification of enrollment changes
 9395:     my @notified = ();
 9396:     if ($args->{'notify_owner'}) {
 9397:         if ($args->{'ccuname'} ne '') {
 9398:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 9399:         }
 9400:     }
 9401:     if ($args->{'notify_dc'}) {
 9402:         if ($uname ne '') { 
 9403:             push(@notified,$uname.':'.$udom);
 9404:         }
 9405:     }
 9406:     if (@notified > 0) {
 9407:         my $notifylist;
 9408:         if (@notified > 1) {
 9409:             $notifylist = join(',',@notified);
 9410:         } else {
 9411:             $notifylist = $notified[0];
 9412:         }
 9413:         $cenv{'internal.notifylist'} = $notifylist;
 9414:     }
 9415:     if (@badclasses > 0) {
 9416:         my %lt=&Apache::lonlocal::texthash(
 9417:                 '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',
 9418:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 9419:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 9420:         );
 9421:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 9422:                            ' ('.$lt{'adby'}.')';
 9423:         if ($context eq 'auto') {
 9424:             $outcome .= $badclass_msg.$linefeed;
 9425:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 9426:             foreach my $item (@badclasses) {
 9427:                 if ($context eq 'auto') {
 9428:                     $outcome .= " - $item\n";
 9429:                 } else {
 9430:                     $outcome .= "<li>$item</li>\n";
 9431:                 }
 9432:             }
 9433:             if ($context eq 'auto') {
 9434:                 $outcome .= $linefeed;
 9435:             } else {
 9436:                 $outcome .= "</ul><br /><br /></div>\n";
 9437:             }
 9438:         } 
 9439:     }
 9440:     if ($args->{'no_end_date'}) {
 9441:         $args->{'endaccess'} = 0;
 9442:     }
 9443:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 9444:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 9445:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 9446:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 9447:     if ($args->{'showphotos'}) {
 9448:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 9449:     }
 9450:     $cenv{'internal.authtype'} = $args->{'authtype'};
 9451:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 9452:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 9453:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 9454:             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'); 
 9455:             if ($context eq 'auto') {
 9456:                 $outcome .= $krb_msg;
 9457:             } else {
 9458:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 9459:             }
 9460:             $outcome .= $linefeed;
 9461:         }
 9462:     }
 9463:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 9464:        if ($args->{'setpolicy'}) {
 9465:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9466:        }
 9467:        if ($args->{'setcontent'}) {
 9468:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 9469:        }
 9470:     }
 9471:     if ($args->{'reshome'}) {
 9472: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 9473: 	$cenv{'reshome'}=~s/\/+$/\//;
 9474:     }
 9475: #
 9476: # course has keyed access
 9477: #
 9478:     if ($args->{'setkeys'}) {
 9479:        $cenv{'keyaccess'}='yes';
 9480:     }
 9481: # if specified, key authority is not course, but user
 9482: # only active if keyaccess is yes
 9483:     if ($args->{'keyauth'}) {
 9484: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 9485: 	$user = &LONCAPA::clean_username($user);
 9486: 	$domain = &LONCAPA::clean_username($domain);
 9487: 	if ($user ne '' && $domain ne '') {
 9488: 	    $cenv{'keyauth'}=$user.':'.$domain;
 9489: 	}
 9490:     }
 9491: 
 9492:     if ($args->{'disresdis'}) {
 9493:         $cenv{'pch.roles.denied'}='st';
 9494:     }
 9495:     if ($args->{'disablechat'}) {
 9496:         $cenv{'plc.roles.denied'}='st';
 9497:     }
 9498: 
 9499:     # Record we've not yet viewed the Course Initialization Helper for this 
 9500:     # course
 9501:     $cenv{'course.helper.not.run'} = 1;
 9502:     #
 9503:     # Use new Randomseed
 9504:     #
 9505:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 9506:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 9507:     #
 9508:     # The encryption code and receipt prefix for this course
 9509:     #
 9510:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 9511:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 9512:     #
 9513:     # By default, use standard grading
 9514:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 9515: 
 9516:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 9517:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 9518: #
 9519: # Open all assignments
 9520: #
 9521:     if ($args->{'openall'}) {
 9522:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 9523:        my %storecontent = ($storeunder         => time,
 9524:                            $storeunder.'.type' => 'date_start');
 9525:        
 9526:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 9527:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 9528:    }
 9529: #
 9530: # Set first page
 9531: #
 9532:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 9533: 	    || ($cloneid)) {
 9534: 	use LONCAPA::map;
 9535: 	$outcome .= &mt('Setting first resource').': ';
 9536: 
 9537: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 9538:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 9539: 
 9540:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 9541:         my $title; my $url;
 9542:         if ($args->{'firstres'} eq 'syl') {
 9543: 	    $title=&mt('Syllabus');
 9544:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 9545:         } else {
 9546:             $title=&mt('Navigate Contents');
 9547:             $url='/adm/navmaps';
 9548:         }
 9549: 
 9550:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 9551: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 9552: 
 9553: 	if ($errtext) { $fatal=2; }
 9554:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 9555:     }
 9556: 
 9557:     return (1,$outcome);
 9558: }
 9559: 
 9560: ############################################################
 9561: ############################################################
 9562: 
 9563: sub course_type {
 9564:     my ($cid) = @_;
 9565:     if (!defined($cid)) {
 9566:         $cid = $env{'request.course.id'};
 9567:     }
 9568:     if (defined($env{'course.'.$cid.'.type'})) {
 9569:         return $env{'course.'.$cid.'.type'};
 9570:     } else {
 9571:         return 'Course';
 9572:     }
 9573: }
 9574: 
 9575: sub group_term {
 9576:     my $crstype = &course_type();
 9577:     my %names = (
 9578:                   'Course'    => 'group',
 9579:                   'Community' => 'group',
 9580:                 );
 9581:     return $names{$crstype};
 9582: }
 9583: 
 9584: sub icon {
 9585:     my ($file)=@_;
 9586:     my $curfext = lc((split(/\./,$file))[-1]);
 9587:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 9588:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 9589:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 9590: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 9591: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9592: 	            $curfext.".gif") {
 9593: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 9594: 		$curfext.".gif";
 9595: 	}
 9596:     }
 9597:     return &lonhttpdurl($iconname);
 9598: } 
 9599: 
 9600: sub lonhttpdurl {
 9601: #
 9602: # Had been used for "small fry" static images on separate port 8080.
 9603: # Modify here if lightweight http functionality desired again.
 9604: # Currently eliminated due to increasing firewall issues.
 9605: #
 9606:     my ($url)=@_;
 9607:     return $url;
 9608: }
 9609: 
 9610: sub connection_aborted {
 9611:     my ($r)=@_;
 9612:     $r->print(" ");$r->rflush();
 9613:     my $c = $r->connection;
 9614:     return $c->aborted();
 9615: }
 9616: 
 9617: #    Escapes strings that may have embedded 's that will be put into
 9618: #    strings as 'strings'.
 9619: sub escape_single {
 9620:     my ($input) = @_;
 9621:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 9622:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 9623:     return $input;
 9624: }
 9625: 
 9626: #  Same as escape_single, but escape's "'s  This 
 9627: #  can be used for  "strings"
 9628: sub escape_double {
 9629:     my ($input) = @_;
 9630:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 9631:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 9632:     return $input;
 9633: }
 9634:  
 9635: #   Escapes the last element of a full URL.
 9636: sub escape_url {
 9637:     my ($url)   = @_;
 9638:     my @urlslices = split(/\//, $url,-1);
 9639:     my $lastitem = &escape(pop(@urlslices));
 9640:     return join('/',@urlslices).'/'.$lastitem;
 9641: }
 9642: 
 9643: sub compare_arrays {
 9644:     my ($arrayref1,$arrayref2) = @_;
 9645:     my (@difference,%count);
 9646:     @difference = ();
 9647:     %count = ();
 9648:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
 9649:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
 9650:         foreach my $element (keys(%count)) {
 9651:             if ($count{$element} == 1) {
 9652:                 push(@difference,$element);
 9653:             }
 9654:         }
 9655:     }
 9656:     return @difference;
 9657: }
 9658: 
 9659: # -------------------------------------------------------- Initliaze user login
 9660: sub init_user_environment {
 9661:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 9662:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 9663: 
 9664:     my $public=($username eq 'public' && $domain eq 'public');
 9665: 
 9666: # See if old ID present, if so, remove
 9667: 
 9668:     my ($filename,$cookie,$userroles);
 9669:     my $now=time;
 9670: 
 9671:     if ($public) {
 9672: 	my $max_public=100;
 9673: 	my $oldest;
 9674: 	my $oldest_time=0;
 9675: 	for(my $next=1;$next<=$max_public;$next++) {
 9676: 	    if (-e $lonids."/publicuser_$next.id") {
 9677: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 9678: 		if ($mtime<$oldest_time || !$oldest_time) {
 9679: 		    $oldest_time=$mtime;
 9680: 		    $oldest=$next;
 9681: 		}
 9682: 	    } else {
 9683: 		$cookie="publicuser_$next";
 9684: 		last;
 9685: 	    }
 9686: 	}
 9687: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 9688:     } else {
 9689: 	# if this isn't a robot, kill any existing non-robot sessions
 9690: 	if (!$args->{'robot'}) {
 9691: 	    opendir(DIR,$lonids);
 9692: 	    while ($filename=readdir(DIR)) {
 9693: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 9694: 		    unlink($lonids.'/'.$filename);
 9695: 		}
 9696: 	    }
 9697: 	    closedir(DIR);
 9698: 	}
 9699: # Give them a new cookie
 9700: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 9701: 		                   : $now.$$.int(rand(10000)));
 9702: 	$cookie="$username\_$id\_$domain\_$authhost";
 9703:     
 9704: # Initialize roles
 9705: 
 9706: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 9707:     }
 9708: # ------------------------------------ Check browser type and MathML capability
 9709: 
 9710:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 9711:         $clientunicode,$clientos) = &decode_user_agent($r);
 9712: 
 9713: # -------------------------------------- Any accessibility options to remember?
 9714:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 9715: 	foreach my $option ('imagesuppress','appletsuppress',
 9716: 			    'embedsuppress','fontenhance','blackwhite') {
 9717: 	    if ($form->{$option} eq 'true') {
 9718: 		&Apache::lonnet::put('environment',{$option => 'on'},
 9719: 				     $domain,$username);
 9720: 	    } else {
 9721: 		&Apache::lonnet::del('environment',[$option],
 9722: 				     $domain,$username);
 9723: 	    }
 9724: 	}
 9725:     }
 9726: # ------------------------------------------------------------- Get environment
 9727: 
 9728:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 9729:     my ($tmp) = keys(%userenv);
 9730:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9731: 	# default remote control to off
 9732: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 9733:     } else {
 9734: 	undef(%userenv);
 9735:     }
 9736:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 9737: 	$form->{'interface'}=$userenv{'interface'};
 9738:     }
 9739:     $env{'environment.remote'}=$userenv{'remote'};
 9740:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 9741: 
 9742: # --------------- Do not trust query string to be put directly into environment
 9743:     foreach my $option ('imagesuppress','appletsuppress',
 9744: 			'embedsuppress','fontenhance','blackwhite',
 9745: 			'interface','localpath','localres') {
 9746: 	$form->{$option}=~s/[\n\r\=]//gs;
 9747:     }
 9748: # --------------------------------------------------------- Write first profile
 9749: 
 9750:     {
 9751: 	my %initial_env = 
 9752: 	    ("user.name"          => $username,
 9753: 	     "user.domain"        => $domain,
 9754: 	     "user.home"          => $authhost,
 9755: 	     "browser.type"       => $clientbrowser,
 9756: 	     "browser.version"    => $clientversion,
 9757: 	     "browser.mathml"     => $clientmathml,
 9758: 	     "browser.unicode"    => $clientunicode,
 9759: 	     "browser.os"         => $clientos,
 9760: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 9761: 	     "request.course.fn"  => '',
 9762: 	     "request.course.uri" => '',
 9763: 	     "request.course.sec" => '',
 9764: 	     "request.role"       => 'cm',
 9765: 	     "request.role.adv"   => $env{'user.adv'},
 9766: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 9767: 
 9768:         if ($form->{'localpath'}) {
 9769: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 9770: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 9771:         }
 9772: 	
 9773: 	if ($public) {
 9774: 	    $initial_env{"environment.remote"} = "off";
 9775: 	}
 9776: 	if ($form->{'interface'}) {
 9777: 	    $form->{'interface'}=~s/\W//gs;
 9778: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 9779: 	    $env{'browser.interface'}=$form->{'interface'};
 9780: 	    foreach my $option ('imagesuppress','appletsuppress',
 9781: 				'embedsuppress','fontenhance','blackwhite') {
 9782: 		if (($form->{$option} eq 'true') ||
 9783: 		    ($userenv{$option} eq 'on')) {
 9784: 		    $initial_env{"browser.$option"} = "on";
 9785: 		}
 9786: 	    }
 9787: 	}
 9788: 
 9789:         foreach my $tool ('aboutme','blog','portfolio') {
 9790:             $userenv{'availabletools.'.$tool} =
 9791:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
 9792:         }
 9793: 
 9794:         foreach my $crstype ('official','unofficial','community') {
 9795:             $userenv{'canrequest.'.$crstype} =
 9796:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
 9797:                                                   'reload','requestcourses');
 9798:         }
 9799: 
 9800: 	$env{'user.environment'} = "$lonids/$cookie.id";
 9801: 	
 9802: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 9803: 		 &GDBM_WRCREAT(),0640)) {
 9804: 	    &_add_to_env(\%disk_env,\%initial_env);
 9805: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 9806: 	    &_add_to_env(\%disk_env,$userroles);
 9807: 	    if (ref($args->{'extra_env'})) {
 9808: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 9809: 	    }
 9810: 	    untie(%disk_env);
 9811: 	} else {
 9812: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 9813: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 9814: 	    return 'error: '.$!;
 9815: 	}
 9816:     }
 9817:     $env{'request.role'}='cm';
 9818:     $env{'request.role.adv'}=$env{'user.adv'};
 9819:     $env{'browser.type'}=$clientbrowser;
 9820: 
 9821:     return $cookie;
 9822: 
 9823: }
 9824: 
 9825: sub _add_to_env {
 9826:     my ($idf,$env_data,$prefix) = @_;
 9827:     if (ref($env_data) eq 'HASH') {
 9828:         while (my ($key,$value) = each(%$env_data)) {
 9829: 	    $idf->{$prefix.$key} = $value;
 9830: 	    $env{$prefix.$key}   = $value;
 9831:         }
 9832:     }
 9833: }
 9834: 
 9835: # --- Get the symbolic name of a problem and the url
 9836: sub get_symb {
 9837:     my ($request,$silent) = @_;
 9838:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 9839:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
 9840:     if ($symb eq '') {
 9841:         if (!$silent) {
 9842:             $request->print("Unable to handle ambiguous references:$url:.");
 9843:             return ();
 9844:         }
 9845:     }
 9846:     &Apache::lonenc::check_decrypt(\$symb);
 9847:     return ($symb);
 9848: }
 9849: 
 9850: # --------------------------------------------------------------Get annotation
 9851: 
 9852: sub get_annotation {
 9853:     my ($symb,$enc) = @_;
 9854: 
 9855:     my $key = $symb;
 9856:     if (!$enc) {
 9857:         $key =
 9858:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
 9859:     }
 9860:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
 9861:     return $annotation{$key};
 9862: }
 9863: 
 9864: sub clean_symb {
 9865:     my ($symb,$delete_enc) = @_;
 9866: 
 9867:     &Apache::lonenc::check_decrypt(\$symb);
 9868:     my $enc = $env{'request.enc'};
 9869:     if ($delete_enc) {
 9870:         delete($env{'request.enc'});
 9871:     }
 9872: 
 9873:     return ($symb,$enc);
 9874: }
 9875: 
 9876: =pod
 9877: 
 9878: =back
 9879: 
 9880: =cut
 9881: 
 9882: 1;
 9883: __END__;
 9884: 

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