File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.595: download - view: text, annotated - select for diffs
Fri Oct 26 00:22:36 2007 UTC (16 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- xhtml

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.595 2007/10/26 00:22:36 albertel 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 HTML::Entities;
   65: use Apache::lonhtmlcommon();
   66: use Apache::loncoursedata();
   67: use Apache::lontexconvert();
   68: use Apache::lonclonecourse();
   69: use LONCAPA qw(:DEFAULT :match);
   70: 
   71: # ---------------------------------------------- Designs
   72: use vars qw(%defaultdesign);
   73: 
   74: my $readit;
   75: 
   76: 
   77: ##
   78: ## Global Variables
   79: ##
   80: 
   81: # ----------------------------------------------- Filetypes/Languages/Copyright
   82: my %language;
   83: my %supported_language;
   84: my %cprtag;
   85: my %scprtag;
   86: my %fe; my %fd; my %fm;
   87: my %category_extensions;
   88: 
   89: # ---------------------------------------------- Thesaurus variables
   90: #
   91: # %Keywords:
   92: #      A hash used by &keyword to determine if a word is considered a keyword.
   93: # $thesaurus_db_file 
   94: #      Scalar containing the full path to the thesaurus database.
   95: 
   96: my %Keywords;
   97: my $thesaurus_db_file;
   98: 
   99: #
  100: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  101: # thesaurus.tab, and filecategories.tab.
  102: #
  103: BEGIN {
  104:     # Variable initialization
  105:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  106:     #
  107:     unless ($readit) {
  108: # ------------------------------------------------------------------- languages
  109:     {
  110:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  111:                                    '/language.tab';
  112:         if ( open(my $fh,"<$langtabfile") ) {
  113:             while (my $line = <$fh>) {
  114:                 next if ($line=~/^\#/);
  115:                 chomp($line);
  116:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  117:                 $language{$key}=$val.' - '.$enc;
  118:                 if ($sup) {
  119:                     $supported_language{$key}=$sup;
  120:                 }
  121:             }
  122:             close($fh);
  123:         }
  124:     }
  125: # ------------------------------------------------------------------ copyrights
  126:     {
  127:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  128:                                   '/copyright.tab';
  129:         if ( open (my $fh,"<$copyrightfile") ) {
  130:             while (my $line = <$fh>) {
  131:                 next if ($line=~/^\#/);
  132:                 chomp($line);
  133:                 my ($key,$val)=(split(/\s+/,$line,2));
  134:                 $cprtag{$key}=$val;
  135:             }
  136:             close($fh);
  137:         }
  138:     }
  139: # ----------------------------------------------------------- source copyrights
  140:     {
  141:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  142:                                   '/source_copyright.tab';
  143:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  144:             while (my $line = <$fh>) {
  145:                 next if ($line =~ /^\#/);
  146:                 chomp($line);
  147:                 my ($key,$val)=(split(/\s+/,$line,2));
  148:                 $scprtag{$key}=$val;
  149:             }
  150:             close($fh);
  151:         }
  152:     }
  153: 
  154: # -------------------------------------------------------------- default domain designs
  155:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  156:     my $designfile = $designdir.'/default.tab';
  157:     if ( open (my $fh,"<$designfile") ) {
  158:         while (my $line = <$fh>) {
  159:             next if ($line =~ /^\#/);
  160:             chomp($line);
  161:             my ($key,$val)=(split(/\=/,$line));
  162:             if ($val) { $defaultdesign{$key}=$val; }
  163:         }
  164:         close($fh);
  165:     }
  166: 
  167: # ------------------------------------------------------------- file categories
  168:     {
  169:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  170:                                   '/filecategories.tab';
  171:         if ( open (my $fh,"<$categoryfile") ) {
  172: 	    while (my $line = <$fh>) {
  173: 		next if ($line =~ /^\#/);
  174: 		chomp($line);
  175:                 my ($extension,$category)=(split(/\s+/,$line,2));
  176:                 push @{$category_extensions{lc($category)}},$extension;
  177:             }
  178:             close($fh);
  179:         }
  180: 
  181:     }
  182: # ------------------------------------------------------------------ file types
  183:     {
  184:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  185:                '/filetypes.tab';
  186:         if ( open (my $fh,"<$typesfile") ) {
  187:             while (my $line = <$fh>) {
  188: 		next if ($line =~ /^\#/);
  189: 		chomp($line);
  190:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  191:                 if ($descr ne '') {
  192:                     $fe{$ending}=lc($emb);
  193:                     $fd{$ending}=$descr;
  194:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  195:                 }
  196:             }
  197:             close($fh);
  198:         }
  199:     }
  200:     &Apache::lonnet::logthis(
  201:               "<font color=yellow>INFO: Read file types</font>");
  202:     $readit=1;
  203:     }  # end of unless($readit) 
  204:     
  205: }
  206: 
  207: ###############################################################
  208: ##           HTML and Javascript Helper Functions            ##
  209: ###############################################################
  210: 
  211: =pod 
  212: 
  213: =head1 HTML and Javascript Functions
  214: 
  215: =over 4
  216: 
  217: =item * browser_and_searcher_javascript ()
  218: 
  219: X<browsing, javascript>X<searching, javascript>Returns a string
  220: containing javascript with two functions, C<openbrowser> and
  221: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  222: tags.
  223: 
  224: =item * openbrowser(formname,elementname,only,omit) [javascript]
  225: 
  226: inputs: formname, elementname, only, omit
  227: 
  228: formname and elementname indicate the name of the html form and name of
  229: the element that the results of the browsing selection are to be placed in. 
  230: 
  231: Specifying 'only' will restrict the browser to displaying only files
  232: with the given extension.  Can be a comma separated list.
  233: 
  234: Specifying 'omit' will restrict the browser to NOT displaying files
  235: with the given extension.  Can be a comma separated list.
  236: 
  237: =item * opensearcher(formname, elementname) [javascript]
  238: 
  239: Inputs: formname, elementname
  240: 
  241: formname and elementname specify the name of the html form and the name
  242: of the element the selection from the search results will be placed in.
  243: 
  244: =cut
  245: 
  246: sub browser_and_searcher_javascript {
  247:     my ($mode)=@_;
  248:     if (!defined($mode)) { $mode='edit'; }
  249:     my $resurl=&escape_single(&lastresurl());
  250:     return <<END;
  251: // <!-- BEGIN LON-CAPA Internal
  252:     var editbrowser = null;
  253:     function openbrowser(formname,elementname,only,omit,titleelement) {
  254:         var url = '$resurl/?';
  255:         if (editbrowser == null) {
  256:             url += 'launch=1&';
  257:         }
  258:         url += 'catalogmode=interactive&';
  259:         url += 'mode=$mode&';
  260:         url += 'form=' + formname + '&';
  261:         if (only != null) {
  262:             url += 'only=' + only + '&';
  263:         } else {
  264:             url += 'only=&';
  265: 	}
  266:         if (omit != null) {
  267:             url += 'omit=' + omit + '&';
  268:         } else {
  269:             url += 'omit=&';
  270: 	}
  271:         if (titleelement != null) {
  272:             url += 'titleelement=' + titleelement + '&';
  273:         } else {
  274: 	    url += 'titleelement=&';
  275: 	}
  276:         url += 'element=' + elementname + '';
  277:         var title = 'Browser';
  278:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  279:         options += ',width=700,height=600';
  280:         editbrowser = open(url,title,options,'1');
  281:         editbrowser.focus();
  282:     }
  283:     var editsearcher;
  284:     function opensearcher(formname,elementname,titleelement) {
  285:         var url = '/adm/searchcat?';
  286:         if (editsearcher == null) {
  287:             url += 'launch=1&';
  288:         }
  289:         url += 'catalogmode=interactive&';
  290:         url += 'mode=$mode&';
  291:         url += 'form=' + formname + '&';
  292:         if (titleelement != null) {
  293:             url += 'titleelement=' + titleelement + '&';
  294:         } else {
  295: 	    url += 'titleelement=&';
  296: 	}
  297:         url += 'element=' + elementname + '';
  298:         var title = 'Search';
  299:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  300:         options += ',width=700,height=600';
  301:         editsearcher = open(url,title,options,'1');
  302:         editsearcher.focus();
  303:     }
  304: // END LON-CAPA Internal -->
  305: END
  306: }
  307: 
  308: sub lastresurl {
  309:     if ($env{'environment.lastresurl'}) {
  310: 	return $env{'environment.lastresurl'}
  311:     } else {
  312: 	return '/res';
  313:     }
  314: }
  315: 
  316: sub storeresurl {
  317:     my $resurl=&Apache::lonnet::clutter(shift);
  318:     unless ($resurl=~/^\/res/) { return 0; }
  319:     $resurl=~s/\/$//;
  320:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  321:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  322:     return 1;
  323: }
  324: 
  325: sub studentbrowser_javascript {
  326:    unless (
  327:             (($env{'request.course.id'}) && 
  328:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  329: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  330: 					  '/'.$env{'request.course.sec'})
  331: 	      ))
  332:          || ($env{'request.role'}=~/^(au|dc|su)/)
  333:           ) { return ''; }  
  334:    return (<<'ENDSTDBRW');
  335: <script type="text/javascript" language="Javascript" >
  336:     var stdeditbrowser;
  337:     function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
  338:         var url = '/adm/pickstudent?';
  339:         var filter;
  340: 	if (!ignorefilter) {
  341: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  342: 	}
  343:         if (filter != null) {
  344:            if (filter != '') {
  345:                url += 'filter='+filter+'&';
  346: 	   }
  347:         }
  348:         url += 'form=' + formname + '&unameelement='+uname+
  349:                                     '&udomelement='+udom;
  350: 	if (roleflag) { url+="&roles=1"; }
  351:         var title = 'Student_Browser';
  352:         var options = 'scrollbars=1,resizable=1,menubar=0';
  353:         options += ',width=700,height=600';
  354:         stdeditbrowser = open(url,title,options,'1');
  355:         stdeditbrowser.focus();
  356:     }
  357: </script>
  358: ENDSTDBRW
  359: }
  360: 
  361: sub selectstudent_link {
  362:    my ($form,$unameele,$udomele)=@_;
  363:    if ($env{'request.course.id'}) {  
  364:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  365: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  366: 					'/'.$env{'request.course.sec'})) {
  367: 	   return '';
  368:        }
  369:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  370:         '","'.$udomele.'","","1");'."'>".&mt('Select User')."</a>";
  371:    }
  372:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  373:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  374:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  375:    }
  376:    return '';
  377: }
  378: 
  379: sub coursebrowser_javascript {
  380:     my ($domainfilter,$sec_element,$formname)=@_;
  381:     my $crs_or_grp_alert = &mt('Please select the type of LON-CAPA entity - Course or Group - for which you wish to add/modify a user role');
  382:    my $output = '
  383: <script type="text/javascript">
  384:     var stdeditbrowser;'."\n";
  385:    $output .= <<"ENDSTDBRW";
  386:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
  387:         var url = '/adm/pickcourse?';
  388:         var domainfilter = '';
  389:         var formid = getFormIdByName(formname);
  390:         if (formid > -1) {
  391:             var domid = getIndexByName(formid,udom);
  392:             if (domid > -1) {
  393:                 if (document.forms[formid].elements[domid].type == 'select-one') {
  394:                     domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  395:                 }
  396:                 if (document.forms[formid].elements[domid].type == 'hidden') {
  397:                     domainfilter=document.forms[formid].elements[domid].value;
  398:                 }
  399:             }
  400:         }
  401:         if (domainfilter != null) {
  402:            if (domainfilter != '') {
  403:                url += 'domainfilter='+domainfilter+'&';
  404: 	   }
  405:         }
  406:         url += 'form=' + formname + '&cnumelement='+uname+
  407: 	                            '&cdomelement='+udom+
  408:                                     '&cnameelement='+desc;
  409:         if (extra_element !=null && extra_element != '') {
  410:             if (formname == 'rolechoice' || formname == 'studentform') {
  411:                 url += '&roleelement='+extra_element;
  412:                 if (domainfilter == null || domainfilter == '') {
  413:                     url += '&domainfilter='+extra_element;
  414:                 }
  415:             }
  416:             else {
  417:                 if (formname == 'portform') {
  418:                     url += '&setroles='+extra_element;
  419:                 }
  420:             }     
  421:         }
  422:         if (multflag !=null && multflag != '') {
  423:             url += '&multiple='+multflag;
  424:         }
  425:         if (crstype == 'Course/Group') {
  426:             if (formname == 'cu') {
  427:                 crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value; 
  428:                 if (crstype == "") {
  429:                     alert("$crs_or_grp_alert");
  430:                     return;
  431:                 }
  432:             }
  433:         }
  434:         if (crstype !=null && crstype != '') {
  435:             url += '&type='+crstype;
  436:         }
  437:         var title = 'Course_Browser';
  438:         var options = 'scrollbars=1,resizable=1,menubar=0';
  439:         options += ',width=700,height=600';
  440:         stdeditbrowser = open(url,title,options,'1');
  441:         stdeditbrowser.focus();
  442:     }
  443: 
  444:     function getFormIdByName(formname) {
  445:         for (var i=0;i<document.forms.length;i++) {
  446:             if (document.forms[i].name == formname) {
  447:                 return i;
  448:             }
  449:         }
  450:         return -1; 
  451:     }
  452: 
  453:     function getIndexByName(formid,item) {
  454:         for (var i=0;i<document.forms[formid].elements.length;i++) {
  455:             if (document.forms[formid].elements[i].name == item) {
  456:                 return i;
  457:             }
  458:         }
  459:         return -1;
  460:     }
  461: ENDSTDBRW
  462:     if ($sec_element ne '') {
  463:         $output .= &setsec_javascript($sec_element,$formname);
  464:     }
  465:     $output .= '
  466: </script>';
  467:     return $output;
  468: }
  469: 
  470: sub setsec_javascript {
  471:     my ($sec_element,$formname) = @_;
  472:     my $setsections = qq|
  473: function setSect(sectionlist) {
  474:     var sectionsArray = sectionlist.split(",");
  475:     var numSections = sectionsArray.length;
  476:     document.$formname.$sec_element.length = 0;
  477:     if (numSections == 0) {
  478:         document.$formname.$sec_element.multiple=false;
  479:         document.$formname.$sec_element.size=1;
  480:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  481:     } else {
  482:         if (numSections == 1) {
  483:             document.$formname.$sec_element.multiple=false;
  484:             document.$formname.$sec_element.size=1;
  485:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  486:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  487:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  488:         } else {
  489:             for (var i=0; i<numSections; i++) {
  490:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  491:             }
  492:             document.$formname.$sec_element.multiple=true
  493:             if (numSections < 3) {
  494:                 document.$formname.$sec_element.size=numSections;
  495:             } else {
  496:                 document.$formname.$sec_element.size=3;
  497:             }
  498:             document.$formname.$sec_element.options[0].selected = false
  499:         }
  500:     }
  501: }
  502: |;
  503:     return $setsections;
  504: }
  505: 
  506: 
  507: sub selectcourse_link {
  508:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
  509:    return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  510:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
  511: }
  512: 
  513: sub check_uncheck_jscript {
  514:     my $jscript = <<"ENDSCRT";
  515: function checkAll(field) {
  516:     if (field.length > 0) {
  517:         for (i = 0; i < field.length; i++) {
  518:             field[i].checked = true ;
  519:         }
  520:     } else {
  521:         field.checked = true
  522:     }
  523: }
  524:  
  525: function uncheckAll(field) {
  526:     if (field.length > 0) {
  527:         for (i = 0; i < field.length; i++) {
  528:             field[i].checked = false ;
  529:         }
  530:     } else {
  531:         field.checked = false ;
  532:     }
  533: }
  534: ENDSCRT
  535:     return $jscript;
  536: }
  537: 
  538: 
  539: =pod
  540: 
  541: =item * linked_select_forms(...)
  542: 
  543: linked_select_forms returns a string containing a <script></script> block
  544: and html for two <select> menus.  The select menus will be linked in that
  545: changing the value of the first menu will result in new values being placed
  546: in the second menu.  The values in the select menu will appear in alphabetical
  547: order.
  548: 
  549: linked_select_forms takes the following ordered inputs:
  550: 
  551: =over 4
  552: 
  553: =item * $formname, the name of the <form> tag
  554: 
  555: =item * $middletext, the text which appears between the <select> tags
  556: 
  557: =item * $firstdefault, the default value for the first menu
  558: 
  559: =item * $firstselectname, the name of the first <select> tag
  560: 
  561: =item * $secondselectname, the name of the second <select> tag
  562: 
  563: =item * $hashref, a reference to a hash containing the data for the menus.
  564: 
  565: =back 
  566: 
  567: Below is an example of such a hash.  Only the 'text', 'default', and 
  568: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  569: values for the first select menu.  The text that coincides with the 
  570: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  571: and text for the second menu are given in the hash pointed to by 
  572: $menu{$choice1}->{'select2'}.  
  573: 
  574:  my %menu = ( A1 => { text =>"Choice A1" ,
  575:                        default => "B3",
  576:                        select2 => { 
  577:                            B1 => "Choice B1",
  578:                            B2 => "Choice B2",
  579:                            B3 => "Choice B3",
  580:                            B4 => "Choice B4"
  581:                            }
  582:                    },
  583:                A2 => { text =>"Choice A2" ,
  584:                        default => "C2",
  585:                        select2 => { 
  586:                            C1 => "Choice C1",
  587:                            C2 => "Choice C2",
  588:                            C3 => "Choice C3"
  589:                            }
  590:                    },
  591:                A3 => { text =>"Choice A3" ,
  592:                        default => "D6",
  593:                        select2 => { 
  594:                            D1 => "Choice D1",
  595:                            D2 => "Choice D2",
  596:                            D3 => "Choice D3",
  597:                            D4 => "Choice D4",
  598:                            D5 => "Choice D5",
  599:                            D6 => "Choice D6",
  600:                            D7 => "Choice D7"
  601:                            }
  602:                    }
  603:                );
  604: 
  605: =cut
  606: 
  607: sub linked_select_forms {
  608:     my ($formname,
  609:         $middletext,
  610:         $firstdefault,
  611:         $firstselectname,
  612:         $secondselectname, 
  613:         $hashref
  614:         ) = @_;
  615:     my $second = "document.$formname.$secondselectname";
  616:     my $first = "document.$formname.$firstselectname";
  617:     # output the javascript to do the changing
  618:     my $result = '';
  619:     $result.="<script type=\"text/javascript\">\n";
  620:     $result.="var select2data = new Object();\n";
  621:     $" = '","';
  622:     my $debug = '';
  623:     foreach my $s1 (sort(keys(%$hashref))) {
  624:         $result.="select2data.d_$s1 = new Object();\n";        
  625:         $result.="select2data.d_$s1.def = new String('".
  626:             $hashref->{$s1}->{'default'}."');\n";
  627:         $result.="select2data.d_$s1.values = new Array(";        
  628:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  629:         $result.="\"@s2values\");\n";
  630:         $result.="select2data.d_$s1.texts = new Array(";        
  631:         my @s2texts;
  632:         foreach my $value (@s2values) {
  633:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  634:         }
  635:         $result.="\"@s2texts\");\n";
  636:     }
  637:     $"=' ';
  638:     $result.= <<"END";
  639: 
  640: function select1_changed() {
  641:     // Determine new choice
  642:     var newvalue = "d_" + $first.value;
  643:     // update select2
  644:     var values     = select2data[newvalue].values;
  645:     var texts      = select2data[newvalue].texts;
  646:     var select2def = select2data[newvalue].def;
  647:     var i;
  648:     // out with the old
  649:     for (i = 0; i < $second.options.length; i++) {
  650:         $second.options[i] = null;
  651:     }
  652:     // in with the nuclear
  653:     for (i=0;i<values.length; i++) {
  654:         $second.options[i] = new Option(values[i]);
  655:         $second.options[i].value = values[i];
  656:         $second.options[i].text = texts[i];
  657:         if (values[i] == select2def) {
  658:             $second.options[i].selected = true;
  659:         }
  660:     }
  661: }
  662: </script>
  663: END
  664:     # output the initial values for the selection lists
  665:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  666:     foreach my $value (sort(keys(%$hashref))) {
  667:         $result.="    <option value=\"$value\" ";
  668:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  669:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  670:     }
  671:     $result .= "</select>\n";
  672:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  673:     $result .= $middletext;
  674:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  675:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  676:     foreach my $value (sort(keys(%select2))) {
  677:         $result.="    <option value=\"$value\" ";        
  678:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  679:         $result.=">".&mt($select2{$value})."</option>\n";
  680:     }
  681:     $result .= "</select>\n";
  682:     #    return $debug;
  683:     return $result;
  684: }   #  end of sub linked_select_forms {
  685: 
  686: =pod
  687: 
  688: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  689: 
  690: Returns a string corresponding to an HTML link to the given help
  691: $topic, where $topic corresponds to the name of a .tex file in
  692: /home/httpd/html/adm/help/tex, with underscores replaced by
  693: spaces. 
  694: 
  695: $text will optionally be linked to the same topic, allowing you to
  696: link text in addition to the graphic. If you do not want to link
  697: text, but wish to specify one of the later parameters, pass an
  698: empty string. 
  699: 
  700: $stayOnPage is a value that will be interpreted as a boolean. If true,
  701: the link will not open a new window. If false, the link will open
  702: a new window using Javascript. (Default is false.) 
  703: 
  704: $width and $height are optional numerical parameters that will
  705: override the width and height of the popped up window, which may
  706: be useful for certain help topics with big pictures included. 
  707: 
  708: =cut
  709: 
  710: sub help_open_topic {
  711:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  712:     $text = "" if (not defined $text);
  713:     $stayOnPage = 0 if (not defined $stayOnPage);
  714:     if ($env{'browser.interface'} eq 'textual') {
  715: 	$stayOnPage=1;
  716:     }
  717:     $width = 350 if (not defined $width);
  718:     $height = 400 if (not defined $height);
  719:     my $filename = $topic;
  720:     $filename =~ s/ /_/g;
  721: 
  722:     my $template = "";
  723:     my $link;
  724:     
  725:     $topic=~s/\W/\_/g;
  726: 
  727:     if (!$stayOnPage) {
  728: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  729:     } else {
  730: 	$link = "/adm/help/${filename}.hlp";
  731:     }
  732: 
  733:     # Add the text
  734:     if ($text ne "") {
  735: 	$template .= 
  736:             "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  737:             "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  738:     }
  739: 
  740:     # Add the graphic
  741:     my $title = &mt('Online Help');
  742:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  743:     $template .= <<"ENDTEMPLATE";
  744:  <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  745: ENDTEMPLATE
  746:     if ($text ne '') { $template.='</td></tr></table>' };
  747:     return $template;
  748: 
  749: }
  750: 
  751: # This is a quicky function for Latex cheatsheet editing, since it 
  752: # appears in at least four places
  753: sub helpLatexCheatsheet {
  754:     my $other = shift;
  755:     my $addOther = '';
  756:     if ($other) {
  757: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  758: 						       undef, undef, 600) .
  759: 							   '</td><td>';
  760:     }
  761:     return '<table><tr><td>'.
  762: 	$addOther .
  763: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  764: 					    undef,undef,600)
  765: 	.'</td><td>'.
  766: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  767: 					    undef,undef,600)
  768: 	.'</td></tr></table>';
  769: }
  770: 
  771: sub general_help {
  772:     my $helptopic='Student_Intro';
  773:     if ($env{'request.role'}=~/^(ca|au)/) {
  774: 	$helptopic='Authoring_Intro';
  775:     } elsif ($env{'request.role'}=~/^cc/) {
  776: 	$helptopic='Course_Coordination_Intro';
  777:     }
  778:     return $helptopic;
  779: }
  780: 
  781: sub update_help_link {
  782:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
  783:     my $origurl = $ENV{'REQUEST_URI'};
  784:     $origurl=~s|^/~|/priv/|;
  785:     my $timestamp = time;
  786:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  787:         $$datum = &escape($$datum);
  788:     }
  789: 
  790:     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";
  791:     my $output .= <<"ENDOUTPUT";
  792: <script type="text/javascript">
  793: banner_link = '$banner_link';
  794: </script>
  795: ENDOUTPUT
  796:     return $output;
  797: }
  798: 
  799: # now just updates the help link and generates a blue icon
  800: sub help_open_menu {
  801:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
  802: 	= @_;    
  803:     $stayOnPage = 0 if (not defined $stayOnPage);
  804:     # only use pop-up help (stayOnPage == 0)
  805:     # if environment.remote is on (using remote control UI)
  806:     if ($env{'browser.interface'} eq 'textual' ||
  807:     	$env{'environment.remote'} eq 'off' ) {
  808:         $stayOnPage=1;
  809:     }
  810:     my $output;
  811:     if ($component_help) {
  812: 	if (!$text) {
  813: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
  814: 				       $width,$height);
  815: 	} else {
  816: 	    my $help_text;
  817: 	    $help_text=&unescape($topic);
  818: 	    $output='<table><tr><td>'.
  819: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  820: 				 $width,$height).'</td></tr></table>';
  821: 	}
  822:     }
  823:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
  824:     return $output.$banner_link;
  825: }
  826: 
  827: sub top_nav_help {
  828:     my ($text) = @_;
  829:     $text = &mt($text);
  830:     my $stay_on_page = 
  831: 	($env{'browser.interface'}  eq 'textual' ||
  832: 	 $env{'environment.remote'} eq 'off' );
  833:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
  834: 	                     : "javascript:helpMenu('open')";
  835:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
  836: 
  837:     my $title = &mt('Get help');
  838: 
  839:     return <<"END";
  840: $banner_link
  841:  <a href="$link" title="$title">$text</a>
  842: END
  843: }
  844: 
  845: sub help_menu_js {
  846:     my ($text) = @_;
  847: 
  848:     my $stayOnPage = 
  849: 	($env{'browser.interface'}  eq 'textual' ||
  850: 	 $env{'environment.remote'} eq 'off' );
  851: 
  852:     my $width = 620;
  853:     my $height = 600;
  854:     my $helptopic=&general_help();
  855:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
  856:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  857:     my $start_page =
  858:         &Apache::loncommon::start_page('Help Menu', undef,
  859: 				       {'frameset'    => 1,
  860: 					'js_ready'    => 1,
  861: 					'add_entries' => {
  862: 					    'border' => '0',
  863: 					    'rows'   => "110,*",},});
  864:     my $end_page =
  865:         &Apache::loncommon::end_page({'frameset' => 1,
  866: 				      'js_ready' => 1,});
  867: 
  868:     my $template .= <<"ENDTEMPLATE";
  869: <script type="text/javascript">
  870: // <!-- BEGIN LON-CAPA Internal
  871: // <![CDATA[
  872: var banner_link = '';
  873: function helpMenu(target) {
  874:     var caller = this;
  875:     if (target == 'open') {
  876:         var newWindow = null;
  877:         try {
  878:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  879:         }
  880:         catch(error) {
  881:             writeHelp(caller);
  882:             return;
  883:         }
  884:         if (newWindow) {
  885:             caller = newWindow;
  886:         }
  887:     }
  888:     writeHelp(caller);
  889:     return;
  890: }
  891: function writeHelp(caller) {
  892:     caller.document.writeln('$start_page<frame name="bannerframe"  src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
  893:     caller.document.close()
  894:     caller.focus()
  895: }
  896: // ]]>
  897: // END LON-CAPA Internal -->
  898: </script>
  899: ENDTEMPLATE
  900:     return $template;
  901: }
  902: 
  903: sub help_open_bug {
  904:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  905:     unless ($env{'user.adv'}) { return ''; }
  906:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  907:     $text = "" if (not defined $text);
  908:     $stayOnPage = 0 if (not defined $stayOnPage);
  909:     if ($env{'browser.interface'} eq 'textual' ||
  910: 	$env{'environment.remote'} eq 'off' ) {
  911: 	$stayOnPage=1;
  912:     }
  913:     $width = 600 if (not defined $width);
  914:     $height = 600 if (not defined $height);
  915: 
  916:     $topic=~s/\W+/\+/g;
  917:     my $link='';
  918:     my $template='';
  919:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
  920: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
  921:     if (!$stayOnPage)
  922:     {
  923: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  924:     }
  925:     else
  926:     {
  927: 	$link = $url;
  928:     }
  929:     # Add the text
  930:     if ($text ne "")
  931:     {
  932: 	$template .= 
  933:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  934:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  935:     }
  936: 
  937:     # Add the graphic
  938:     my $title = &mt('Report a Bug');
  939:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
  940:     $template .= <<"ENDTEMPLATE";
  941:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
  942: ENDTEMPLATE
  943:     if ($text ne '') { $template.='</td></tr></table>' };
  944:     return $template;
  945: 
  946: }
  947: 
  948: sub help_open_faq {
  949:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  950:     unless ($env{'user.adv'}) { return ''; }
  951:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  952:     $text = "" if (not defined $text);
  953:     $stayOnPage = 0 if (not defined $stayOnPage);
  954:     if ($env{'browser.interface'} eq 'textual' ||
  955: 	$env{'environment.remote'} eq 'off' ) {
  956: 	$stayOnPage=1;
  957:     }
  958:     $width = 350 if (not defined $width);
  959:     $height = 400 if (not defined $height);
  960: 
  961:     $topic=~s/\W+/\+/g;
  962:     my $link='';
  963:     my $template='';
  964:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  965:     if (!$stayOnPage)
  966:     {
  967: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  968:     }
  969:     else
  970:     {
  971: 	$link = $url;
  972:     }
  973: 
  974:     # Add the text
  975:     if ($text ne "")
  976:     {
  977: 	$template .= 
  978:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
  979:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  980:     }
  981: 
  982:     # Add the graphic
  983:     my $title = &mt('View the FAQ');
  984:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
  985:     $template .= <<"ENDTEMPLATE";
  986:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
  987: ENDTEMPLATE
  988:     if ($text ne '') { $template.='</td></tr></table>' };
  989:     return $template;
  990: 
  991: }
  992: 
  993: ###############################################################
  994: ###############################################################
  995: 
  996: =pod
  997: 
  998: =item * change_content_javascript():
  999: 
 1000: This and the next function allow you to create small sections of an
 1001: otherwise static HTML page that you can update on the fly with
 1002: Javascript, even in Netscape 4.
 1003: 
 1004: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1005: must be written to the HTML page once. It will prove the Javascript
 1006: function "change(name, content)". Calling the change function with the
 1007: name of the section 
 1008: you want to update, matching the name passed to C<changable_area>, and
 1009: the new content you want to put in there, will put the content into
 1010: that area.
 1011: 
 1012: B<Note>: Netscape 4 only reserves enough space for the changable area
 1013: to contain room for the original contents. You need to "make space"
 1014: for whatever changes you wish to make, and be B<sure> to check your
 1015: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1016: it's adequate for updating a one-line status display, but little more.
 1017: This script will set the space to 100% width, so you only need to
 1018: worry about height in Netscape 4.
 1019: 
 1020: Modern browsers are much less limiting, and if you can commit to the
 1021: user not using Netscape 4, this feature may be used freely with
 1022: pretty much any HTML.
 1023: 
 1024: =cut
 1025: 
 1026: sub change_content_javascript {
 1027:     # If we're on Netscape 4, we need to use Layer-based code
 1028:     if ($env{'browser.type'} eq 'netscape' &&
 1029: 	$env{'browser.version'} =~ /^4\./) {
 1030: 	return (<<NETSCAPE4);
 1031: 	function change(name, content) {
 1032: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1033: 	    doc.open();
 1034: 	    doc.write(content);
 1035: 	    doc.close();
 1036: 	}
 1037: NETSCAPE4
 1038:     } else {
 1039: 	# Otherwise, we need to use semi-standards-compliant code
 1040: 	# (technically, "innerHTML" isn't standard but the equivalent
 1041: 	# is really scary, and every useful browser supports it
 1042: 	return (<<DOMBASED);
 1043: 	function change(name, content) {
 1044: 	    element = document.getElementById(name);
 1045: 	    element.innerHTML = content;
 1046: 	}
 1047: DOMBASED
 1048:     }
 1049: }
 1050: 
 1051: =pod
 1052: 
 1053: =item * changable_area($name, $origContent):
 1054: 
 1055: This provides a "changable area" that can be modified on the fly via
 1056: the Javascript code provided in C<change_content_javascript>. $name is
 1057: the name you will use to reference the area later; do not repeat the
 1058: same name on a given HTML page more then once. $origContent is what
 1059: the area will originally contain, which can be left blank.
 1060: 
 1061: =cut
 1062: 
 1063: sub changable_area {
 1064:     my ($name, $origContent) = @_;
 1065: 
 1066:     if ($env{'browser.type'} eq 'netscape' &&
 1067: 	$env{'browser.version'} =~ /^4\./) {
 1068: 	# If this is netscape 4, we need to use the Layer tag
 1069: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1070:     } else {
 1071: 	return "<span id='$name'>$origContent</span>";
 1072:     }
 1073: }
 1074: 
 1075: =pod
 1076: 
 1077: =item * viewport_geometry_js {
 1078: 
 1079: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1080: 
 1081: =cut
 1082: 
 1083: 
 1084: sub viewport_geometry_js { 
 1085:     return <<"GEOMETRY";
 1086: var Geometry = {};
 1087: function init_geometry() {
 1088:     if (Geometry.init) { return };
 1089:     Geometry.init=1;
 1090:     if (window.innerHeight) {
 1091:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1092:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1093:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1094:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1095:     }
 1096:     else if (document.documentElement && document.documentElement.clientHeight) {
 1097:         Geometry.getViewportHeight =
 1098:             function() { return document.documentElement.clientHeight; };
 1099:         Geometry.getViewportWidth =
 1100:             function() { return document.documentElement.clientWidth; };
 1101: 
 1102:         Geometry.getHorizontalScroll =
 1103:             function() { return document.documentElement.scrollLeft; };
 1104:         Geometry.getVerticalScroll =
 1105:             function() { return document.documentElement.scrollTop; };
 1106:     }
 1107:     else if (document.body.clientHeight) {
 1108:         Geometry.getViewportHeight =
 1109:             function() { return document.body.clientHeight; };
 1110:         Geometry.getViewportWidth =
 1111:             function() { return document.body.clientWidth; };
 1112:         Geometry.getHorizontalScroll =
 1113:             function() { return document.body.scrollLeft; };
 1114:         Geometry.getVerticalScroll =
 1115:             function() { return document.body.scrollTop; };
 1116:     }
 1117: }
 1118: 
 1119: GEOMETRY
 1120: }
 1121: 
 1122: =pod
 1123: 
 1124: =item * viewport_size_js {
 1125: 
 1126: 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. 
 1127: 
 1128: =cut
 1129: 
 1130: sub viewport_size_js {
 1131:     my $geometry = &viewport_geometry_js();
 1132:     return <<"DIMS";
 1133: 
 1134: $geometry
 1135: 
 1136: function getViewportDims(width,height) {
 1137:     init_geometry();
 1138:     width.value = Geometry.getViewportWidth();
 1139:     height.value = Geometry.getViewportHeight();
 1140:     return;
 1141: }
 1142: 
 1143: DIMS
 1144: }
 1145: 
 1146: =pod
 1147: 
 1148: =item * resize_textarea_js
 1149: 
 1150: emits the needed javascript to resize a textarea to be as big as possible
 1151: 
 1152: creates a function resize_textrea that takes two IDs first should be
 1153: the id of the element to resize, second should be the id of a div that
 1154: surrounds everything that comes after the textarea, this routine needs
 1155: to be attached to the <body> for the onload and onresize events.
 1156: 
 1157: 
 1158: =cut
 1159: 
 1160: sub resize_textarea_js {
 1161:     my $geometry = &viewport_geometry_js();
 1162:     return <<"RESIZE";
 1163:     <script type="text/javascript">
 1164: $geometry
 1165: 
 1166: function getX(element) {
 1167:     var x = 0;
 1168:     while (element) {
 1169: 	x += element.offsetLeft;
 1170: 	element = element.offsetParent;
 1171:     }
 1172:     return x;
 1173: }
 1174: function getY(element) {
 1175:     var y = 0;
 1176:     while (element) {
 1177: 	y += element.offsetTop;
 1178: 	element = element.offsetParent;
 1179:     }
 1180:     return y;
 1181: }
 1182: 
 1183: 
 1184: function resize_textarea(textarea_id,bottom_id) {
 1185:     init_geometry();
 1186:     var textarea        = document.getElementById(textarea_id);
 1187:     //alert(textarea);
 1188: 
 1189:     var textarea_top    = getY(textarea);
 1190:     var textarea_height = textarea.offsetHeight;
 1191:     var bottom          = document.getElementById(bottom_id);
 1192:     var bottom_top      = getY(bottom);
 1193:     var bottom_height   = bottom.offsetHeight;
 1194:     var window_height   = Geometry.getViewportHeight();
 1195:     var fudge           = 23;
 1196:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1197:     if (new_height < 300) {
 1198: 	new_height = 300;
 1199:     }
 1200:     textarea.style.height=new_height+'px';
 1201: }
 1202: </script>
 1203: RESIZE
 1204: 
 1205: }
 1206: 
 1207: =pod
 1208: 
 1209: =back
 1210:  
 1211: =head1 Excel and CSV file utility routines
 1212: 
 1213: =over 4
 1214: 
 1215: =cut
 1216: 
 1217: ###############################################################
 1218: ###############################################################
 1219: 
 1220: =pod
 1221: 
 1222: =item * csv_translate($text) 
 1223: 
 1224: Translate $text to allow it to be output as a 'comma separated values' 
 1225: format.
 1226: 
 1227: =cut
 1228: 
 1229: ###############################################################
 1230: ###############################################################
 1231: sub csv_translate {
 1232:     my $text = shift;
 1233:     $text =~ s/\"/\"\"/g;
 1234:     $text =~ s/\n/ /g;
 1235:     return $text;
 1236: }
 1237: 
 1238: ###############################################################
 1239: ###############################################################
 1240: 
 1241: =pod
 1242: 
 1243: =item * define_excel_formats
 1244: 
 1245: Define some commonly used Excel cell formats.
 1246: 
 1247: Currently supported formats:
 1248: 
 1249: =over 4
 1250: 
 1251: =item header
 1252: 
 1253: =item bold
 1254: 
 1255: =item h1
 1256: 
 1257: =item h2
 1258: 
 1259: =item h3
 1260: 
 1261: =item h4
 1262: 
 1263: =item i
 1264: 
 1265: =item date
 1266: 
 1267: =back
 1268: 
 1269: Inputs: $workbook
 1270: 
 1271: Returns: $format, a hash reference.
 1272: 
 1273: =cut
 1274: 
 1275: ###############################################################
 1276: ###############################################################
 1277: sub define_excel_formats {
 1278:     my ($workbook) = @_;
 1279:     my $format;
 1280:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1281:                                                 bottom    => 1,
 1282:                                                 align     => 'center');
 1283:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1284:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1285:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1286:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1287:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1288:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1289:     $format->{'date'} = $workbook->add_format(num_format=>
 1290:                                             'mm/dd/yyyy hh:mm:ss');
 1291:     return $format;
 1292: }
 1293: 
 1294: ###############################################################
 1295: ###############################################################
 1296: 
 1297: =pod
 1298: 
 1299: =item * create_workbook
 1300: 
 1301: Create an Excel worksheet.  If it fails, output message on the
 1302: request object and return undefs.
 1303: 
 1304: Inputs: Apache request object
 1305: 
 1306: Returns (undef) on failure, 
 1307:     Excel worksheet object, scalar with filename, and formats 
 1308:     from &Apache::loncommon::define_excel_formats on success
 1309: 
 1310: =cut
 1311: 
 1312: ###############################################################
 1313: ###############################################################
 1314: sub create_workbook {
 1315:     my ($r) = @_;
 1316:         #
 1317:     # Create the excel spreadsheet
 1318:     my $filename = '/prtspool/'.
 1319:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1320:         time.'_'.rand(1000000000).'.xls';
 1321:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1322:     if (! defined($workbook)) {
 1323:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1324:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1325:                             "This error has been logged.  ".
 1326:                             "Please alert your LON-CAPA administrator").
 1327:                   '</p>');
 1328:         return (undef);
 1329:     }
 1330:     #
 1331:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1332:     #
 1333:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1334:     return ($workbook,$filename,$format);
 1335: }
 1336: 
 1337: ###############################################################
 1338: ###############################################################
 1339: 
 1340: =pod
 1341: 
 1342: =item * create_text_file
 1343: 
 1344: Create a file to write to and eventually make available to the user.
 1345: If file creation fails, outputs an error message on the request object and 
 1346: return undefs.
 1347: 
 1348: Inputs: Apache request object, and file suffix
 1349: 
 1350: Returns (undef) on failure, 
 1351:     Filehandle and filename on success.
 1352: 
 1353: =cut
 1354: 
 1355: ###############################################################
 1356: ###############################################################
 1357: sub create_text_file {
 1358:     my ($r,$suffix) = @_;
 1359:     if (! defined($suffix)) { $suffix = 'txt'; };
 1360:     my $fh;
 1361:     my $filename = '/prtspool/'.
 1362:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1363:         time.'_'.rand(1000000000).'.'.$suffix;
 1364:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1365:     if (! defined($fh)) {
 1366:         $r->log_error("Couldn't open $filename for output $!");
 1367:         $r->print("Problems occured in creating the output file.  ".
 1368:                   "This error has been logged.  ".
 1369:                   "Please alert your LON-CAPA administrator.");
 1370:     }
 1371:     return ($fh,$filename)
 1372: }
 1373: 
 1374: 
 1375: =pod 
 1376: 
 1377: =back
 1378: 
 1379: =cut
 1380: 
 1381: ###############################################################
 1382: ##        Home server <option> list generating code          ##
 1383: ###############################################################
 1384: 
 1385: # ------------------------------------------
 1386: 
 1387: sub domain_select {
 1388:     my ($name,$value,$multiple)=@_;
 1389:     my %domains=map { 
 1390: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1391:     } &Apache::lonnet::all_domains();
 1392:     if ($multiple) {
 1393: 	$domains{''}=&mt('Any domain');
 1394: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1395: 	return &multiple_select_form($name,$value,4,\%domains);
 1396:     } else {
 1397: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1398: 	return &select_form($name,$value,%domains);
 1399:     }
 1400: }
 1401: 
 1402: #-------------------------------------------
 1403: 
 1404: =pod
 1405: 
 1406: =head1 Routines for form select boxes
 1407: 
 1408: =over 4
 1409: 
 1410: =item * multiple_select_form($name,$value,$size,$hash,$order)
 1411: 
 1412: Returns a string containing a <select> element int multiple mode
 1413: 
 1414: 
 1415: Args:
 1416:   $name - name of the <select> element
 1417:   $value - scalar or array ref of values that should already be selected
 1418:   $size - number of rows long the select element is
 1419:   $hash - the elements should be 'option' => 'shown text'
 1420:           (shown text should already have been &mt())
 1421:   $order - (optional) array ref of the order to show the elements in
 1422: 
 1423: =cut
 1424: 
 1425: #-------------------------------------------
 1426: sub multiple_select_form {
 1427:     my ($name,$value,$size,$hash,$order)=@_;
 1428:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1429:     my $output='';
 1430:     if (! defined($size)) {
 1431:         $size = 4;
 1432:         if (scalar(keys(%$hash))<4) {
 1433:             $size = scalar(keys(%$hash));
 1434:         }
 1435:     }
 1436:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1437:     my @order;
 1438:     if (ref($order) eq 'ARRAY')  {
 1439:         @order = @{$order};
 1440:     } else {
 1441:         @order = sort(keys(%$hash));
 1442:     }
 1443:     if (exists($$hash{'select_form_order'})) {
 1444:         @order = @{$$hash{'select_form_order'}};
 1445:     }
 1446:         
 1447:     foreach my $key (@order) {
 1448:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1449:         $output.='selected="selected" ' if ($selected{$key});
 1450:         $output.='>'.$hash->{$key}."</option>\n";
 1451:     }
 1452:     $output.="</select>\n";
 1453:     return $output;
 1454: }
 1455: 
 1456: #-------------------------------------------
 1457: 
 1458: =pod
 1459: 
 1460: =item * select_form($defdom,$name,%hash)
 1461: 
 1462: Returns a string containing a <select name='$name' size='1'> form to 
 1463: allow a user to select options from a hash option_name => displayed text.  
 1464: See lonrights.pm for an example invocation and use.
 1465: 
 1466: =cut
 1467: 
 1468: #-------------------------------------------
 1469: sub select_form {
 1470:     my ($def,$name,%hash) = @_;
 1471:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1472:     my @keys;
 1473:     if (exists($hash{'select_form_order'})) {
 1474: 	@keys=@{$hash{'select_form_order'}};
 1475:     } else {
 1476: 	@keys=sort(keys(%hash));
 1477:     }
 1478:     foreach my $key (@keys) {
 1479:         $selectform.=
 1480: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1481:             ($key eq $def ? 'selected="selected" ' : '').
 1482:                 ">".&mt($hash{$key})."</option>\n";
 1483:     }
 1484:     $selectform.="</select>";
 1485:     return $selectform;
 1486: }
 1487: 
 1488: # For display filters
 1489: 
 1490: sub display_filter {
 1491:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 1492:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 1493:     return '<nobr><label>'.&mt('Records [_1]',
 1494: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 1495: 							   (&mt('all'),10,20,50,100,1000,10000))).
 1496: 	   '</label></nobr> <nobr>'.
 1497:            &mt('Filter [_1]',
 1498: 	   &select_form($env{'form.displayfilter'},
 1499: 			'displayfilter',
 1500: 			('currentfolder' => 'Current folder/page',
 1501: 			 'containing' => 'Containing phrase',
 1502: 			 'none' => 'None'))).
 1503: 			 '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
 1504: }
 1505: 
 1506: sub gradeleveldescription {
 1507:     my $gradelevel=shift;
 1508:     my %gradelevels=(0 => 'Not specified',
 1509: 		     1 => 'Grade 1',
 1510: 		     2 => 'Grade 2',
 1511: 		     3 => 'Grade 3',
 1512: 		     4 => 'Grade 4',
 1513: 		     5 => 'Grade 5',
 1514: 		     6 => 'Grade 6',
 1515: 		     7 => 'Grade 7',
 1516: 		     8 => 'Grade 8',
 1517: 		     9 => 'Grade 9',
 1518: 		     10 => 'Grade 10',
 1519: 		     11 => 'Grade 11',
 1520: 		     12 => 'Grade 12',
 1521: 		     13 => 'Grade 13',
 1522: 		     14 => '100 Level',
 1523: 		     15 => '200 Level',
 1524: 		     16 => '300 Level',
 1525: 		     17 => '400 Level',
 1526: 		     18 => 'Graduate Level');
 1527:     return &mt($gradelevels{$gradelevel});
 1528: }
 1529: 
 1530: sub select_level_form {
 1531:     my ($deflevel,$name)=@_;
 1532:     unless ($deflevel) { $deflevel=0; }
 1533:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1534:     for (my $i=0; $i<=18; $i++) {
 1535:         $selectform.="<option value=\"$i\" ".
 1536:             ($i==$deflevel ? 'selected="selected" ' : '').
 1537:                 ">".&gradeleveldescription($i)."</option>\n";
 1538:     }
 1539:     $selectform.="</select>";
 1540:     return $selectform;
 1541: }
 1542: 
 1543: #-------------------------------------------
 1544: 
 1545: =pod
 1546: 
 1547: =item * select_dom_form($defdom,$name,$includeempty,$showdomdesc)
 1548: 
 1549: Returns a string containing a <select name='$name' size='1'> form to 
 1550: allow a user to select the domain to preform an operation in.  
 1551: See loncreateuser.pm for an example invocation and use.
 1552: 
 1553: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1554: selected");
 1555: 
 1556: If the $showdomdesc flag is set, the domain name is followed by the domain description. 
 1557: 
 1558: =cut
 1559: 
 1560: #-------------------------------------------
 1561: sub select_dom_form {
 1562:     my ($defdom,$name,$includeempty,$showdomdesc) = @_;
 1563:     my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 1564:     if ($includeempty) { @domains=('',@domains); }
 1565:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1566:     foreach my $dom (@domains) {
 1567:         $selectdomain.="<option value=\"$dom\" ".
 1568:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 1569:         if ($showdomdesc) {
 1570:             if ($dom ne '') {
 1571:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 1572:                 if ($domdesc ne '') {
 1573:                     $selectdomain .= ' ('.$domdesc.')';
 1574:                 }
 1575:             } 
 1576:         }
 1577:         $selectdomain .= "</option>\n";
 1578:     }
 1579:     $selectdomain.="</select>";
 1580:     return $selectdomain;
 1581: }
 1582: 
 1583: #-------------------------------------------
 1584: 
 1585: =pod
 1586: 
 1587: =item * home_server_form_item($domain,$name,$defaultflag)
 1588: 
 1589: input: 4 arguments (two required, two optional) - 
 1590:     $domain - domain of new user
 1591:     $name - name of form element
 1592:     $default - Value of 'default' causes a default item to be first 
 1593:                             option, and selected by default. 
 1594:     $hide - Value of 'hide' causes hiding of the name of the server, 
 1595:                             if 1 server found, or default, if 0 found.
 1596: output: returns 2 items: 
 1597: (a) form element which contains either:
 1598:    (i) <select name="$name">
 1599:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 1600:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 1601:        </select>
 1602:        form item if there are multiple library servers in $domain, or
 1603:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 1604:        if there is only one library server in $domain.
 1605: 
 1606: (b) number of library servers found.
 1607: 
 1608: See loncreateuser.pm for example of use.
 1609: 
 1610: =cut
 1611: 
 1612: #-------------------------------------------
 1613: sub home_server_form_item {
 1614:     my ($domain,$name,$default,$hide) = @_;
 1615:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 1616:     my $result;
 1617:     my $numlib = keys(%servers);
 1618:     if ($numlib > 1) {
 1619:         $result .= '<select name="'.$name.'" />'."\n";
 1620:         if ($default) {
 1621:             $result .= '<option value="default" selected>'.&mt('default').
 1622:                        '</option>'."\n";
 1623:         }
 1624:         foreach my $hostid (sort(keys(%servers))) {
 1625:             $result.= '<option value="'.$hostid.'">'.
 1626: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 1627:         }
 1628:         $result .= '</select>'."\n";
 1629:     } elsif ($numlib == 1) {
 1630:         my $hostid;
 1631:         foreach my $item (keys(%servers)) {
 1632:             $hostid = $item;
 1633:         }
 1634:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 1635:                    $hostid.'" />';
 1636:                    if (!$hide) {
 1637:                        $result .= $hostid.' '.$servers{$hostid};
 1638:                    }
 1639:                    $result .= "\n";
 1640:     } elsif ($default) {
 1641:         $result .= '<input type="hidden" name="'.$name.
 1642:                    '" value="default" />';
 1643:                    if (!$hide) {
 1644:                        $result .= &mt('default');
 1645:                    }
 1646:                    $result .= "\n";
 1647:     }
 1648:     return ($result,$numlib);
 1649: }
 1650: 
 1651: =pod
 1652: 
 1653: =back 
 1654: 
 1655: =cut
 1656: 
 1657: ###############################################################
 1658: ##                  Decoding User Agent                      ##
 1659: ###############################################################
 1660: 
 1661: =pod
 1662: 
 1663: =head1 Decoding the User Agent
 1664: 
 1665: =over 4
 1666: 
 1667: =item * &decode_user_agent()
 1668: 
 1669: Inputs: $r
 1670: 
 1671: Outputs:
 1672: 
 1673: =over 4
 1674: 
 1675: =item * $httpbrowser
 1676: 
 1677: =item * $clientbrowser
 1678: 
 1679: =item * $clientversion
 1680: 
 1681: =item * $clientmathml
 1682: 
 1683: =item * $clientunicode
 1684: 
 1685: =item * $clientos
 1686: 
 1687: =back
 1688: 
 1689: =back 
 1690: 
 1691: =cut
 1692: 
 1693: ###############################################################
 1694: ###############################################################
 1695: sub decode_user_agent {
 1696:     my ($r)=@_;
 1697:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1698:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1699:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1700:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1701:     my $clientbrowser='unknown';
 1702:     my $clientversion='0';
 1703:     my $clientmathml='';
 1704:     my $clientunicode='0';
 1705:     for (my $i=0;$i<=$#browsertype;$i++) {
 1706:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1707: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1708: 	    $clientbrowser=$bname;
 1709:             $httpbrowser=~/$vreg/i;
 1710: 	    $clientversion=$1;
 1711:             $clientmathml=($clientversion>=$minv);
 1712:             $clientunicode=($clientversion>=$univ);
 1713: 	}
 1714:     }
 1715:     my $clientos='unknown';
 1716:     if (($httpbrowser=~/linux/i) ||
 1717:         ($httpbrowser=~/unix/i) ||
 1718:         ($httpbrowser=~/ux/i) ||
 1719:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1720:     if (($httpbrowser=~/vax/i) ||
 1721:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1722:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1723:     if (($httpbrowser=~/mac/i) ||
 1724:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1725:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1726:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1727:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1728:             $clientunicode,$clientos,);
 1729: }
 1730: 
 1731: ###############################################################
 1732: ##    Authentication changing form generation subroutines    ##
 1733: ###############################################################
 1734: ##
 1735: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1736: ## hash, and have reasonable default values.
 1737: ##
 1738: ##    formname = the name given in the <form> tag.
 1739: #-------------------------------------------
 1740: 
 1741: =pod
 1742: 
 1743: =head1 Authentication Routines
 1744: 
 1745: =over 4
 1746: 
 1747: =item * authform_xxxxxx
 1748: 
 1749: The authform_xxxxxx subroutines provide javascript and html forms which 
 1750: handle some of the conveniences required for authentication forms.  
 1751: This is not an optimal method, but it works.  
 1752: 
 1753: See loncreateuser.pm for invocation and use examples.
 1754: 
 1755: =over 4
 1756: 
 1757: =item * authform_header
 1758: 
 1759: =item * authform_authorwarning
 1760: 
 1761: =item * authform_nochange
 1762: 
 1763: =item * authform_kerberos
 1764: 
 1765: =item * authform_internal
 1766: 
 1767: =item * authform_filesystem
 1768: 
 1769: =back
 1770: 
 1771: =back 
 1772: 
 1773: =cut
 1774: 
 1775: #-------------------------------------------
 1776: sub authform_header{  
 1777:     my %in = (
 1778:         formname => 'cu',
 1779:         kerb_def_dom => '',
 1780:         @_,
 1781:     );
 1782:     $in{'formname'} = 'document.' . $in{'formname'};
 1783:     my $result='';
 1784: 
 1785: #---------------------------------------------- Code for upper case translation
 1786:     my $Javascript_toUpperCase;
 1787:     unless ($in{kerb_def_dom}) {
 1788:         $Javascript_toUpperCase =<<"END";
 1789:         switch (choice) {
 1790:            case 'krb': currentform.elements[choicearg].value =
 1791:                currentform.elements[choicearg].value.toUpperCase();
 1792:                break;
 1793:            default:
 1794:         }
 1795: END
 1796:     } else {
 1797:         $Javascript_toUpperCase = "";
 1798:     }
 1799: 
 1800:     my $radioval = "'nochange'";
 1801:     if (defined($in{'curr_authtype'})) {
 1802:         if ($in{'curr_authtype'} ne '') {
 1803:             $radioval = "'".$in{'curr_authtype'}."arg'";
 1804:         }
 1805:     }
 1806:     my $argfield = 'null';
 1807:     if (defined($in{'mode'})) {
 1808:         if ($in{'mode'} eq 'modifycourse')  {
 1809:             if (defined($in{'curr_autharg'})) {
 1810:                 if ($in{'curr_autharg'} ne '') {
 1811:                     $argfield = "'$in{'curr_autharg'}'";
 1812:                 }
 1813:             }
 1814:         }
 1815:     }
 1816: 
 1817:     $result.=<<"END";
 1818: var current = new Object();
 1819: current.radiovalue = $radioval;
 1820: current.argfield = $argfield;
 1821: 
 1822: function changed_radio(choice,currentform) {
 1823:     var choicearg = choice + 'arg';
 1824:     // If a radio button in changed, we need to change the argfield
 1825:     if (current.radiovalue != choice) {
 1826:         current.radiovalue = choice;
 1827:         if (current.argfield != null) {
 1828:             currentform.elements[current.argfield].value = '';
 1829:         }
 1830:         if (choice == 'nochange') {
 1831:             current.argfield = null;
 1832:         } else {
 1833:             current.argfield = choicearg;
 1834:             switch(choice) {
 1835:                 case 'krb': 
 1836:                     currentform.elements[current.argfield].value = 
 1837:                         "$in{'kerb_def_dom'}";
 1838:                 break;
 1839:               default:
 1840:                 break;
 1841:             }
 1842:         }
 1843:     }
 1844:     return;
 1845: }
 1846: 
 1847: function changed_text(choice,currentform) {
 1848:     var choicearg = choice + 'arg';
 1849:     if (currentform.elements[choicearg].value !='') {
 1850:         $Javascript_toUpperCase
 1851:         // clear old field
 1852:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1853:             currentform.elements[current.argfield].value = '';
 1854:         }
 1855:         current.argfield = choicearg;
 1856:     }
 1857:     set_auth_radio_buttons(choice,currentform);
 1858:     return;
 1859: }
 1860: 
 1861: function set_auth_radio_buttons(newvalue,currentform) {
 1862:     var i=0;
 1863:     while (i < currentform.login.length) {
 1864:         if (currentform.login[i].value == newvalue) { break; }
 1865:         i++;
 1866:     }
 1867:     if (i == currentform.login.length) {
 1868:         return;
 1869:     }
 1870:     current.radiovalue = newvalue;
 1871:     currentform.login[i].checked = true;
 1872:     return;
 1873: }
 1874: END
 1875:     return $result;
 1876: }
 1877: 
 1878: sub authform_authorwarning{
 1879:     my $result='';
 1880:     $result='<i>'.
 1881:         &mt('As a general rule, only authors or co-authors should be '.
 1882:             'filesystem authenticated '.
 1883:             '(which allows access to the server filesystem).')."</i>\n";
 1884:     return $result;
 1885: }
 1886: 
 1887: sub authform_nochange{  
 1888:     my %in = (
 1889:               formname => 'document.cu',
 1890:               kerb_def_dom => 'MSU.EDU',
 1891:               @_,
 1892:           );
 1893:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
 1894:     my $result;
 1895:     if (keys(%can_assign) == 0) {
 1896:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
 1897:     } else {
 1898:         $result = '<label>'.&mt('[_1] Do not change login data',
 1899:                   '<input type="radio" name="login" value="nochange" '.
 1900:                   'checked="checked" onclick="'.
 1901:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1902: 	    '</label>';
 1903:     }
 1904:     return $result;
 1905: }
 1906: 
 1907: sub authform_kerberos {
 1908:     my %in = (
 1909:               formname => 'document.cu',
 1910:               kerb_def_dom => 'MSU.EDU',
 1911:               kerb_def_auth => 'krb4',
 1912:               @_,
 1913:               );
 1914:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 1915:         $autharg,$jscall);
 1916:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 1917:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1918:        $check5 = ' checked="on"';
 1919:     } else {
 1920:        $check4 = ' checked="on"';
 1921:     }
 1922:     $krbarg = $in{'kerb_def_dom'};
 1923:     if (defined($in{'curr_authtype'})) {
 1924:         if ($in{'curr_authtype'} eq 'krb') {
 1925:             $krbcheck = ' checked="on"';
 1926:             if (defined($in{'curr_kerb_ver'})) {
 1927:                 if ($in{'curr_krb_ver'} eq '5') {
 1928:                     $check5 = ' checked="on"';
 1929:                     $check4 = '';
 1930:                 } else {
 1931:                     $check4 = ' checked="on"';
 1932:                     $check5 = '';
 1933:                 }
 1934:             }
 1935:             if (defined($in{'curr_autharg'})) {
 1936:                 $krbarg = $in{'curr_autharg'};
 1937:             }
 1938:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 1939:                 if (defined($in{'curr_autharg'})) {
 1940:                     $result = 
 1941:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 1942:         $in{'curr_autharg'},$krbver);
 1943:                 } else {
 1944:                     $result =
 1945:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 1946:                 }
 1947:                 return $result; 
 1948:             }
 1949:         }
 1950:     } else {
 1951:         if ($authnum == 1) {
 1952:             $authtype = '<input type="hidden" name="login" value="krb">';
 1953:         }
 1954:     }
 1955:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 1956:         return;
 1957:     } elsif ($authtype eq '') {
 1958:         if (defined($in{'mode'})) {
 1959:             if ($in{'mode'} eq 'modifycourse') {
 1960:                 if ($authnum == 1) {
 1961:                     $authtype = '<input type="hidden" name="login" value="krb">';
 1962:                 }
 1963:             }
 1964:         }
 1965:     }
 1966:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1967:     if ($authtype eq '') {
 1968:         $authtype = '<input type="radio" name="login" value="krb" '.
 1969:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 1970:                     $krbcheck.' />';
 1971:     }
 1972:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 1973:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
 1974:          $in{'curr_authtype'} eq 'krb5') ||
 1975:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
 1976:          $in{'curr_authtype'} eq 'krb4')) {
 1977:         $result .= &mt
 1978:         ('[_1] Kerberos authenticated with domain [_2] '.
 1979:          '[_3] Version 4 [_4] Version 5 [_5]',
 1980:          '<label>'.$authtype,
 1981:          '</label><input type="text" size="10" name="krbarg" '.
 1982:              'value="'.$krbarg.'" '.
 1983:              'onchange="'.$jscall.'" />',
 1984:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 1985:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 1986: 	 '</label>');
 1987:     } elsif ($can_assign{'krb4'}) {
 1988:         $result .= &mt
 1989:         ('[_1] Kerberos authenticated with domain [_2] '.
 1990:          '[_3] Version 4 [_4]',
 1991:          '<label>'.$authtype,
 1992:          '</label><input type="text" size="10" name="krbarg" '.
 1993:              'value="'.$krbarg.'" '.
 1994:              'onchange="'.$jscall.'" />',
 1995:          '<label><input type="hidden" name="krbver" value="4" />',
 1996:          '</label>');
 1997:     } elsif ($can_assign{'krb5'}) {
 1998:         $result .= &mt
 1999:         ('[_1] Kerberos authenticated with domain [_2] '.
 2000:          '[_3] Version 5 [_4]',
 2001:          '<label>'.$authtype,
 2002:          '</label><input type="text" size="10" name="krbarg" '.
 2003:              'value="'.$krbarg.'" '.
 2004:              'onchange="'.$jscall.'" />',
 2005:          '<label><input type="hidden" name="krbver" value="5" />',
 2006:          '</label>');
 2007:     }
 2008:     return $result;
 2009: }
 2010: 
 2011: sub authform_internal{  
 2012:     my %in = (
 2013:                 formname => 'document.cu',
 2014:                 kerb_def_dom => 'MSU.EDU',
 2015:                 @_,
 2016:                 );
 2017:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2018:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2019:     if (defined($in{'curr_authtype'})) {
 2020:         if ($in{'curr_authtype'} eq 'int') {
 2021:             if ($can_assign{'int'}) {
 2022:                 $intcheck = 'checked="on" ';
 2023:                 if (defined($in{'curr_autharg'})) {
 2024:                     $intarg = $in{'curr_autharg'};
 2025:                 }
 2026:             } else {
 2027:                 $result = &mt('Currently internally authenticated.');
 2028:                 return $result;
 2029:             }
 2030:         }
 2031:     } else {
 2032:         if ($authnum == 1) {
 2033:             $authtype = '<input type="hidden" name="login" value="int">';
 2034:         }
 2035:     }
 2036:     if (!$can_assign{'int'}) {
 2037:         return;
 2038:     } elsif ($authtype eq '') {
 2039:         if (defined($in{'mode'})) {
 2040:             if ($in{'mode'} eq 'modifycourse') {
 2041:                 if ($authnum == 1) {
 2042:                     $authtype = '<input type="hidden" name="login" value="int">';
 2043:                 }
 2044:             }
 2045:         }
 2046:     }
 2047:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2048:     if ($authtype eq '') {
 2049:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2050:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2051:     }
 2052:     $autharg = '<input type="text" size="10" name="intarg" value="'.
 2053:                $intarg.'" onchange="'.$jscall.'" />';
 2054:     $result = &mt
 2055:         ('[_1] Internally authenticated (with initial password [_2])',
 2056:          '<label>'.$authtype,'</label>'.$autharg);
 2057:     return $result;
 2058: }
 2059: 
 2060: sub authform_local{  
 2061:     my %in = (
 2062:               formname => 'document.cu',
 2063:               kerb_def_dom => 'MSU.EDU',
 2064:               @_,
 2065:               );
 2066:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2067:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2068:     if (defined($in{'curr_authtype'})) {
 2069:         if ($in{'curr_authtype'} eq 'loc') {
 2070:             if ($can_assign{'loc'}) {
 2071:                 $loccheck = 'checked="on" ';
 2072:                 if (defined($in{'curr_autharg'})) {
 2073:                     $locarg = $in{'curr_autharg'};
 2074:                 }
 2075:             } else {
 2076:                 $result = &mt('Currently using local (institutional) authentication.');
 2077:                 return $result;
 2078:             }
 2079:         }
 2080:     } else {
 2081:         if ($authnum == 1) {
 2082:             $authtype = '<input type="hidden" name="login" value="loc">';
 2083:         }
 2084:     }
 2085:     if (!$can_assign{'loc'}) {
 2086:         return;
 2087:     } elsif ($authtype eq '') {
 2088:         if (defined($in{'mode'})) {
 2089:             if ($in{'mode'} eq 'modifycourse') {
 2090:                 if ($authnum == 1) {
 2091:                     $authtype = '<input type="hidden" name="login" value="loc">';
 2092:                 }
 2093:             }
 2094:         }
 2095:     }
 2096:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2097:     if ($authtype eq '') {
 2098:         $authtype = '<input type="radio" name="login" value="loc" '.
 2099:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2100:                     $jscall.'" />';
 2101:     }
 2102:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2103:                $locarg.'" onchange="'.$jscall.'" />';
 2104:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2105:                   '<label>'.$authtype,'</label>'.$autharg);
 2106:     return $result;
 2107: }
 2108: 
 2109: sub authform_filesystem{  
 2110:     my %in = (
 2111:               formname => 'document.cu',
 2112:               kerb_def_dom => 'MSU.EDU',
 2113:               @_,
 2114:               );
 2115:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2116:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
 2117:     if (defined($in{'curr_authtype'})) {
 2118:         if ($in{'curr_authtype'} eq 'fsys') {
 2119:             if ($can_assign{'fsys'}) {
 2120:                 $fsyscheck = 'checked="on" ';
 2121:             } else {
 2122:                 $result = &mt('Currently Filesystem Authenticated.');
 2123:                 return $result;
 2124:             }           
 2125:         }
 2126:     } else {
 2127:         if ($authnum == 1) {
 2128:             $authtype = '<input type="hidden" name="login" value="fsys">';
 2129:         }
 2130:     }
 2131:     if (!$can_assign{'fsys'}) {
 2132:         return;
 2133:     } elsif ($authtype eq '') {
 2134:         if (defined($in{'mode'})) {
 2135:             if ($in{'mode'} eq 'modifycourse') {
 2136:                 if ($authnum == 1) {
 2137:                     $authtype = '<input type="hidden" name="login" value="fsys">';
 2138:                 }
 2139:             }
 2140:         }
 2141:     }
 2142:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2143:     if ($authtype eq '') {
 2144:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2145:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2146:                     $jscall.'" />';
 2147:     }
 2148:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2149:                ' onchange="'.$jscall.'" />';
 2150:     $result = &mt
 2151:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2152:          '<label><input type="radio" name="login" value="fsys" '.
 2153:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2154:          '</label><input type="text" size="10" name="fsysarg" value="" '.
 2155:                   'onchange="'.$jscall.'" />');
 2156:     return $result;
 2157: }
 2158: 
 2159: sub get_assignable_auth {
 2160:     my ($dom) = @_;
 2161:     if ($dom eq '') {
 2162:         $dom = $env{'request.role.domain'};
 2163:     }
 2164:     my %can_assign = (
 2165:                           krb4 => 1,
 2166:                           krb5 => 1,
 2167:                           int  => 1,
 2168:                           loc  => 1,
 2169:                      );
 2170:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2171:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2172:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2173:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2174:             my $context;
 2175:             if ($env{'request.role'} =~ /^au/) {
 2176:                 $context = 'author';
 2177:             } elsif ($env{'request.role'} =~ /^dc/) {
 2178:                 $context = 'domain';
 2179:             } elsif ($env{'request.course.id'}) {
 2180:                 $context = 'course';
 2181:             }
 2182:             if ($context) {
 2183:                 if (ref($authhash->{$context}) eq 'HASH') {
 2184:                    %can_assign = %{$authhash->{$context}}; 
 2185:                 }
 2186:             }
 2187:         }
 2188:     }
 2189:     my $authnum = 0;
 2190:     foreach my $key (keys(%can_assign)) {
 2191:         if ($can_assign{$key}) {
 2192:             $authnum ++;
 2193:         }
 2194:     }
 2195:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2196:         $authnum --;
 2197:     }
 2198:     return ($authnum,%can_assign);
 2199: }
 2200: 
 2201: ###############################################################
 2202: ##    Get Authentication Defaults for Domain                 ##
 2203: ###############################################################
 2204: 
 2205: =pod
 2206: 
 2207: =head1 Domains and Authentication
 2208: 
 2209: Returns default authentication type and an associated argument as
 2210: listed in file 'domain.tab'.
 2211: 
 2212: =over 4
 2213: 
 2214: =item * get_auth_defaults
 2215: 
 2216: get_auth_defaults($target_domain) returns the default authentication
 2217: type and an associated argument (initial password or a kerberos domain).
 2218: These values are stored in lonTabs/domain.tab
 2219: 
 2220: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 2221: 
 2222: If target_domain is not found in domain.tab, returns nothing ('').
 2223: 
 2224: =cut
 2225: 
 2226: #-------------------------------------------
 2227: sub get_auth_defaults {
 2228:     my $domain=shift;
 2229:     return (&Apache::lonnet::domain($domain,'auth_def'),
 2230: 	    &Apache::lonnet::domain($domain,'auth_arg_def'));
 2231: 	    
 2232: }
 2233: ###############################################################
 2234: ##   End Get Authentication Defaults for Domain              ##
 2235: ###############################################################
 2236: 
 2237: ###############################################################
 2238: ##    Get Kerberos Defaults for Domain                 ##
 2239: ###############################################################
 2240: ##
 2241: ## Returns default kerberos version and an associated argument
 2242: ## as listed in file domain.tab. If not listed, provides
 2243: ## appropriate default domain and kerberos version.
 2244: ##
 2245: #-------------------------------------------
 2246: 
 2247: =pod
 2248: 
 2249: =item * get_kerberos_defaults
 2250: 
 2251: get_kerberos_defaults($target_domain) returns the default kerberos
 2252: version and domain. If not found in domain.tabs, it defaults to
 2253: version 4 and the domain of the server.
 2254: 
 2255: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2256: 
 2257: =cut
 2258: 
 2259: #-------------------------------------------
 2260: sub get_kerberos_defaults {
 2261:     my $domain=shift;
 2262:     my ($krbdef,$krbdefdom) =
 2263:         &Apache::loncommon::get_auth_defaults($domain);
 2264:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 2265:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2266:         my $krbdefdom=$1;
 2267:         $krbdefdom=~tr/a-z/A-Z/;
 2268:         $krbdef = "krb4";
 2269:     }
 2270:     return ($krbdef,$krbdefdom);
 2271: }
 2272: 
 2273: =pod
 2274: 
 2275: =back
 2276: 
 2277: =cut
 2278: 
 2279: ###############################################################
 2280: ##                Thesaurus Functions                        ##
 2281: ###############################################################
 2282: 
 2283: =pod
 2284: 
 2285: =head1 Thesaurus Functions
 2286: 
 2287: =over 4
 2288: 
 2289: =item * initialize_keywords
 2290: 
 2291: Initializes the package variable %Keywords if it is empty.  Uses the
 2292: package variable $thesaurus_db_file.
 2293: 
 2294: =cut
 2295: 
 2296: ###################################################
 2297: 
 2298: sub initialize_keywords {
 2299:     return 1 if (scalar keys(%Keywords));
 2300:     # If we are here, %Keywords is empty, so fill it up
 2301:     #   Make sure the file we need exists...
 2302:     if (! -e $thesaurus_db_file) {
 2303:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2304:                                  " failed because it does not exist");
 2305:         return 0;
 2306:     }
 2307:     #   Set up the hash as a database
 2308:     my %thesaurus_db;
 2309:     if (! tie(%thesaurus_db,'GDBM_File',
 2310:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2311:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2312:                                  $thesaurus_db_file);
 2313:         return 0;
 2314:     } 
 2315:     #  Get the average number of appearances of a word.
 2316:     my $avecount = $thesaurus_db{'average.count'};
 2317:     #  Put keywords (those that appear > average) into %Keywords
 2318:     while (my ($word,$data)=each (%thesaurus_db)) {
 2319:         my ($count,undef) = split /:/,$data;
 2320:         $Keywords{$word}++ if ($count > $avecount);
 2321:     }
 2322:     untie %thesaurus_db;
 2323:     # Remove special values from %Keywords.
 2324:     foreach my $value ('total.count','average.count') {
 2325:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2326:   }
 2327:     return 1;
 2328: }
 2329: 
 2330: ###################################################
 2331: 
 2332: =pod
 2333: 
 2334: =item * keyword($word)
 2335: 
 2336: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2337: than the average number of times in the thesaurus database.  Calls 
 2338: &initialize_keywords
 2339: 
 2340: =cut
 2341: 
 2342: ###################################################
 2343: 
 2344: sub keyword {
 2345:     return if (!&initialize_keywords());
 2346:     my $word=lc(shift());
 2347:     $word=~s/\W//g;
 2348:     return exists($Keywords{$word});
 2349: }
 2350: 
 2351: ###############################################################
 2352: 
 2353: =pod 
 2354: 
 2355: =item * get_related_words
 2356: 
 2357: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2358: an array of words.  If the keyword is not in the thesaurus, an empty array
 2359: will be returned.  The order of the words returned is determined by the
 2360: database which holds them.
 2361: 
 2362: Uses global $thesaurus_db_file.
 2363: 
 2364: =cut
 2365: 
 2366: ###############################################################
 2367: sub get_related_words {
 2368:     my $keyword = shift;
 2369:     my %thesaurus_db;
 2370:     if (! -e $thesaurus_db_file) {
 2371:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 2372:                                  "failed because the file does not exist");
 2373:         return ();
 2374:     }
 2375:     if (! tie(%thesaurus_db,'GDBM_File',
 2376:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2377:         return ();
 2378:     } 
 2379:     my @Words=();
 2380:     my $count=0;
 2381:     if (exists($thesaurus_db{$keyword})) {
 2382: 	# The first element is the number of times
 2383: 	# the word appears.  We do not need it now.
 2384: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 2385: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 2386: 	my $threshold=$mostfrequentcount/10;
 2387:         foreach my $possibleword (@RelatedWords) {
 2388:             my ($word,$wordcount)=split(/\,/,$possibleword);
 2389:             if ($wordcount>$threshold) {
 2390: 		push(@Words,$word);
 2391:                 $count++;
 2392:                 if ($count>10) { last; }
 2393: 	    }
 2394:         }
 2395:     }
 2396:     untie %thesaurus_db;
 2397:     return @Words;
 2398: }
 2399: 
 2400: =pod
 2401: 
 2402: =back
 2403: 
 2404: =cut
 2405: 
 2406: # -------------------------------------------------------------- Plaintext name
 2407: =pod
 2408: 
 2409: =head1 User Name Functions
 2410: 
 2411: =over 4
 2412: 
 2413: =item * plainname($uname,$udom,$first)
 2414: 
 2415: Takes a users logon name and returns it as a string in
 2416: "first middle last generation" form 
 2417: if $first is set to 'lastname' then it returns it as
 2418: 'lastname generation, firstname middlename' if their is a lastname
 2419: 
 2420: =cut
 2421: 
 2422: 
 2423: ###############################################################
 2424: sub plainname {
 2425:     my ($uname,$udom,$first)=@_;
 2426:     return if (!defined($uname) || !defined($udom));
 2427:     my %names=&getnames($uname,$udom);
 2428:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 2429: 					  $names{'middlename'},
 2430: 					  $names{'lastname'},
 2431: 					  $names{'generation'},$first);
 2432:     $name=~s/^\s+//;
 2433:     $name=~s/\s+$//;
 2434:     $name=~s/\s+/ /g;
 2435:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 2436:     return $name;
 2437: }
 2438: 
 2439: # -------------------------------------------------------------------- Nickname
 2440: =pod
 2441: 
 2442: =item * nickname($uname,$udom)
 2443: 
 2444: Gets a users name and returns it as a string as
 2445: 
 2446: "&quot;nickname&quot;"
 2447: 
 2448: if the user has a nickname or
 2449: 
 2450: "first middle last generation"
 2451: 
 2452: if the user does not
 2453: 
 2454: =cut
 2455: 
 2456: sub nickname {
 2457:     my ($uname,$udom)=@_;
 2458:     return if (!defined($uname) || !defined($udom));
 2459:     my %names=&getnames($uname,$udom);
 2460:     my $name=$names{'nickname'};
 2461:     if ($name) {
 2462:        $name='&quot;'.$name.'&quot;'; 
 2463:     } else {
 2464:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 2465: 	     $names{'lastname'}.' '.$names{'generation'};
 2466:        $name=~s/\s+$//;
 2467:        $name=~s/\s+/ /g;
 2468:     }
 2469:     return $name;
 2470: }
 2471: 
 2472: sub getnames {
 2473:     my ($uname,$udom)=@_;
 2474:     return if (!defined($uname) || !defined($udom));
 2475:     if ($udom eq 'public' && $uname eq 'public') {
 2476: 	return ('lastname' => &mt('Public'));
 2477:     }
 2478:     my $id=$uname.':'.$udom;
 2479:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 2480:     if ($cached) {
 2481: 	return %{$names};
 2482:     } else {
 2483: 	my %loadnames=&Apache::lonnet::get('environment',
 2484:                     ['firstname','middlename','lastname','generation','nickname'],
 2485: 					 $udom,$uname);
 2486: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2487: 	return %loadnames;
 2488:     }
 2489: }
 2490: 
 2491: # -------------------------------------------------------------------- getemails
 2492: =pod
 2493: 
 2494: =item * getemails($uname,$udom)
 2495: 
 2496: Gets a user's email information and returns it as a hash with keys:
 2497: notification, critnotification, permanentemail
 2498: 
 2499: For notification and critnotification, values are comma-separated lists 
 2500: of e-mail address(es); for permanentemail, value is a single e-mail address.
 2501:  
 2502: =cut
 2503: 
 2504: sub getemails {
 2505:     my ($uname,$udom)=@_;
 2506:     if ($udom eq 'public' && $uname eq 'public') {
 2507: 	return;
 2508:     }
 2509:     if (!$udom) { $udom=$env{'user.domain'}; }
 2510:     if (!$uname) { $uname=$env{'user.name'}; }
 2511:     my $id=$uname.':'.$udom;
 2512:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 2513:     if ($cached) {
 2514: 	return %{$names};
 2515:     } else {
 2516: 	my %loadnames=&Apache::lonnet::get('environment',
 2517:                     			   ['notification','critnotification',
 2518: 					    'permanentemail'],
 2519: 					   $udom,$uname);
 2520: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 2521: 	return %loadnames;
 2522:     }
 2523: }
 2524: 
 2525: sub flush_email_cache {
 2526:     my ($uname,$udom)=@_;
 2527:     if (!$udom)  { $udom =$env{'user.domain'}; }
 2528:     if (!$uname) { $uname=$env{'user.name'};   }
 2529:     return if ($udom eq 'public' && $uname eq 'public');
 2530:     my $id=$uname.':'.$udom;
 2531:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 2532: }
 2533: 
 2534: # ------------------------------------------------------------------ Screenname
 2535: 
 2536: =pod
 2537: 
 2538: =item * screenname($uname,$udom)
 2539: 
 2540: Gets a users screenname and returns it as a string
 2541: 
 2542: =cut
 2543: 
 2544: sub screenname {
 2545:     my ($uname,$udom)=@_;
 2546:     if ($uname eq $env{'user.name'} &&
 2547: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2548:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2549:     return $names{'screenname'};
 2550: }
 2551: 
 2552: 
 2553: # ------------------------------------------------------------- Message Wrapper
 2554: 
 2555: sub messagewrapper {
 2556:     my ($link,$username,$domain,$subject,$text)=@_;
 2557:     return 
 2558:         '<a href="/adm/email?compose=individual&amp;'.
 2559:         'recname='.$username.'&amp;recdom='.$domain.
 2560: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 2561:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2562: }
 2563: # --------------------------------------------------------------- Notes Wrapper
 2564: 
 2565: sub noteswrapper {
 2566:     my ($link,$un,$do)=@_;
 2567:     return 
 2568: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2569: }
 2570: # ------------------------------------------------------------- Aboutme Wrapper
 2571: 
 2572: sub aboutmewrapper {
 2573:     my ($link,$username,$domain,$target)=@_;
 2574:     if (!defined($username)  && !defined($domain)) {
 2575:         return;
 2576:     }
 2577:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2578: 	($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
 2579: }
 2580: 
 2581: # ------------------------------------------------------------ Syllabus Wrapper
 2582: 
 2583: 
 2584: sub syllabuswrapper {
 2585:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2586:     if ($fontcolor) { 
 2587:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2588:     }
 2589:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2590: }
 2591: 
 2592: sub track_student_link {
 2593:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2594:     my $link ="/adm/trackstudent?";
 2595:     my $title = 'View recent activity';
 2596:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2597:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2598:         $link .= "selected_student=$sname:$sdom";
 2599:         $title .= ' of this student';
 2600:     } 
 2601:     if (defined($target) && $target !~ /^\s*$/) {
 2602:         $target = qq{target="$target"};
 2603:     } else {
 2604:         $target = '';
 2605:     }
 2606:     if ($start) { $link.='&amp;start='.$start; }
 2607:     $title = &mt($title);
 2608:     $linktext = &mt($linktext);
 2609:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 2610: 	&help_open_topic('View_recent_activity');
 2611: }
 2612: 
 2613: # ===================================================== Display a student photo
 2614: 
 2615: 
 2616: sub student_image_tag {
 2617:     my ($domain,$user)=@_;
 2618:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 2619:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 2620: 	return '<img src="'.$imgsrc.'" align="right" />';
 2621:     } else {
 2622: 	return '';
 2623:     }
 2624: }
 2625: 
 2626: =pod
 2627: 
 2628: =back
 2629: 
 2630: =head1 Access .tab File Data
 2631: 
 2632: =over 4
 2633: 
 2634: =item * languageids() 
 2635: 
 2636: returns list of all language ids
 2637: 
 2638: =cut
 2639: 
 2640: sub languageids {
 2641:     return sort(keys(%language));
 2642: }
 2643: 
 2644: =pod
 2645: 
 2646: =item * languagedescription() 
 2647: 
 2648: returns description of a specified language id
 2649: 
 2650: =cut
 2651: 
 2652: sub languagedescription {
 2653:     my $code=shift;
 2654:     return  ($supported_language{$code}?'* ':'').
 2655:             $language{$code}.
 2656: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2657: }
 2658: 
 2659: sub plainlanguagedescription {
 2660:     my $code=shift;
 2661:     return $language{$code};
 2662: }
 2663: 
 2664: sub supportedlanguagecode {
 2665:     my $code=shift;
 2666:     return $supported_language{$code};
 2667: }
 2668: 
 2669: =pod
 2670: 
 2671: =item * copyrightids() 
 2672: 
 2673: returns list of all copyrights
 2674: 
 2675: =cut
 2676: 
 2677: sub copyrightids {
 2678:     return sort(keys(%cprtag));
 2679: }
 2680: 
 2681: =pod
 2682: 
 2683: =item * copyrightdescription() 
 2684: 
 2685: returns description of a specified copyright id
 2686: 
 2687: =cut
 2688: 
 2689: sub copyrightdescription {
 2690:     return &mt($cprtag{shift(@_)});
 2691: }
 2692: 
 2693: =pod
 2694: 
 2695: =item * source_copyrightids() 
 2696: 
 2697: returns list of all source copyrights
 2698: 
 2699: =cut
 2700: 
 2701: sub source_copyrightids {
 2702:     return sort(keys(%scprtag));
 2703: }
 2704: 
 2705: =pod
 2706: 
 2707: =item * source_copyrightdescription() 
 2708: 
 2709: returns description of a specified source copyright id
 2710: 
 2711: =cut
 2712: 
 2713: sub source_copyrightdescription {
 2714:     return &mt($scprtag{shift(@_)});
 2715: }
 2716: 
 2717: =pod
 2718: 
 2719: =item * filecategories() 
 2720: 
 2721: returns list of all file categories
 2722: 
 2723: =cut
 2724: 
 2725: sub filecategories {
 2726:     return sort(keys(%category_extensions));
 2727: }
 2728: 
 2729: =pod
 2730: 
 2731: =item * filecategorytypes() 
 2732: 
 2733: returns list of file types belonging to a given file
 2734: category
 2735: 
 2736: =cut
 2737: 
 2738: sub filecategorytypes {
 2739:     my ($cat) = @_;
 2740:     return @{$category_extensions{lc($cat)}};
 2741: }
 2742: 
 2743: =pod
 2744: 
 2745: =item * fileembstyle() 
 2746: 
 2747: returns embedding style for a specified file type
 2748: 
 2749: =cut
 2750: 
 2751: sub fileembstyle {
 2752:     return $fe{lc(shift(@_))};
 2753: }
 2754: 
 2755: sub filemimetype {
 2756:     return $fm{lc(shift(@_))};
 2757: }
 2758: 
 2759: 
 2760: sub filecategoryselect {
 2761:     my ($name,$value)=@_;
 2762:     return &select_form($value,$name,
 2763: 			'' => &mt('Any category'),
 2764: 			map { $_,$_ } sort(keys(%category_extensions)));
 2765: }
 2766: 
 2767: =pod
 2768: 
 2769: =item * filedescription() 
 2770: 
 2771: returns description for a specified file type
 2772: 
 2773: =cut
 2774: 
 2775: sub filedescription {
 2776:     my $file_description = $fd{lc(shift())};
 2777:     $file_description =~ s:([\[\]]):~$1:g;
 2778:     return &mt($file_description);
 2779: }
 2780: 
 2781: =pod
 2782: 
 2783: =item * filedescriptionex() 
 2784: 
 2785: returns description for a specified file type with
 2786: extra formatting
 2787: 
 2788: =cut
 2789: 
 2790: sub filedescriptionex {
 2791:     my $ex=shift;
 2792:     my $file_description = $fd{lc($ex)};
 2793:     $file_description =~ s:([\[\]]):~$1:g;
 2794:     return '.'.$ex.' '.&mt($file_description);
 2795: }
 2796: 
 2797: # End of .tab access
 2798: =pod
 2799: 
 2800: =back
 2801: 
 2802: =cut
 2803: 
 2804: # ------------------------------------------------------------------ File Types
 2805: sub fileextensions {
 2806:     return sort(keys(%fe));
 2807: }
 2808: 
 2809: # ----------------------------------------------------------- Display Languages
 2810: # returns a hash with all desired display languages
 2811: #
 2812: 
 2813: sub display_languages {
 2814:     my %languages=();
 2815:     foreach my $lang (&preferred_languages()) {
 2816: 	$languages{$lang}=1;
 2817:     }
 2818:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2819:     if ($env{'form.displaylanguage'}) {
 2820: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2821: 	    $languages{$lang}=1;
 2822:         }
 2823:     }
 2824:     return %languages;
 2825: }
 2826: 
 2827: sub preferred_languages {
 2828:     my @languages=();
 2829:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2830: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2831: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2832:     }
 2833:     if ($env{'environment.languages'}) {
 2834: 	@languages=(@languages,
 2835: 		    split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
 2836:     }
 2837:     my $browser=$ENV{'HTTP_ACCEPT_LANGUAGE'};
 2838:     if ($browser) {
 2839: 	my @browser = 
 2840: 	    map { (split(/\s*;\s*/,$_))[0] } (split(/\s*,\s*/,$browser));
 2841: 	push(@languages,@browser);
 2842:     }
 2843:     if (&Apache::lonnet::domain($env{'user.domain'},'lang_def')) {
 2844: 	@languages=(@languages,
 2845: 		    &Apache::lonnet::domain($env{'user.domain'},
 2846: 					    'lang_def'));
 2847:     }
 2848:     if (&Apache::lonnet::domain($env{'request.role.domain'},'lang_def')) {
 2849: 	@languages=(@languages,
 2850: 		    &Apache::lonnet::domain($env{'request.role.domain'},
 2851: 					    'lang_def'));
 2852:     }
 2853:     if (&Apache::lonnet::domain($Apache::lonnet::perlvar{'lonDefDomain'},
 2854: 				'lang_def')) {
 2855: 	@languages=(@languages,
 2856: 		    &Apache::lonnet::domain($Apache::lonnet::perlvar{'lonDefDomain'},
 2857: 					    'lang_def'));
 2858:     }
 2859: # turn "en-ca" into "en-ca,en"
 2860:     my @genlanguages;
 2861:     foreach my $lang (@languages) {
 2862: 	unless ($lang=~/\w/) { next; }
 2863: 	push(@genlanguages,$lang);
 2864: 	if ($lang=~/(\-|\_)/) {
 2865: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2866: 	}
 2867:     }
 2868:     #uniqueify the languages list
 2869:     my %count;
 2870:     @genlanguages = map { $count{$_}++ == 0 ? $_ : () } @genlanguages;
 2871:     return @genlanguages;
 2872: }
 2873: 
 2874: sub languages {
 2875:     my ($possible_langs) = @_;
 2876:     my @preferred_langs = &preferred_languages();
 2877:     if (!ref($possible_langs)) {
 2878: 	if( wantarray ) {
 2879: 	    return @preferred_langs;
 2880: 	} else {
 2881: 	    return $preferred_langs[0];
 2882: 	}
 2883:     }
 2884:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 2885:     my @preferred_possibilities;
 2886:     foreach my $preferred_lang (@preferred_langs) {
 2887: 	if (exists($possibilities{$preferred_lang})) {
 2888: 	    push(@preferred_possibilities, $preferred_lang);
 2889: 	}
 2890:     }
 2891:     if( wantarray ) {
 2892: 	return @preferred_possibilities;
 2893:     }
 2894:     return $preferred_possibilities[0];
 2895: }
 2896: 
 2897: ###############################################################
 2898: ##               Student Answer Attempts                     ##
 2899: ###############################################################
 2900: 
 2901: =pod
 2902: 
 2903: =head1 Alternate Problem Views
 2904: 
 2905: =over 4
 2906: 
 2907: =item * get_previous_attempt($symb, $username, $domain, $course,
 2908:     $getattempt, $regexp, $gradesub)
 2909: 
 2910: Return string with previous attempt on problem. Arguments:
 2911: 
 2912: =over 4
 2913: 
 2914: =item * $symb: Problem, including path
 2915: 
 2916: =item * $username: username of the desired student
 2917: 
 2918: =item * $domain: domain of the desired student
 2919: 
 2920: =item * $course: Course ID
 2921: 
 2922: =item * $getattempt: Leave blank for all attempts, otherwise put
 2923:     something
 2924: 
 2925: =item * $regexp: if string matches this regexp, the string will be
 2926:     sent to $gradesub
 2927: 
 2928: =item * $gradesub: routine that processes the string if it matches $regexp
 2929: 
 2930: =back
 2931: 
 2932: The output string is a table containing all desired attempts, if any.
 2933: 
 2934: =cut
 2935: 
 2936: sub get_previous_attempt {
 2937:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2938:   my $prevattempts='';
 2939:   no strict 'refs';
 2940:   if ($symb) {
 2941:     my (%returnhash)=
 2942:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2943:     if ($returnhash{'version'}) {
 2944:       my %lasthash=();
 2945:       my $version;
 2946:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2947:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2948: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 2949:         }
 2950:       }
 2951:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2952:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2953:       foreach my $key (sort(keys(%lasthash))) {
 2954: 	my ($ign,@parts) = split(/\./,$key);
 2955: 	if ($#parts > 0) {
 2956: 	  my $data=$parts[-1];
 2957: 	  pop(@parts);
 2958: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2959: 	} else {
 2960: 	  if ($#parts == 0) {
 2961: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2962: 	  } else {
 2963: 	    $prevattempts.='<th>'.$ign.'</th>';
 2964: 	  }
 2965: 	}
 2966:       }
 2967:       if ($getattempt eq '') {
 2968: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2969: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2970: 	    foreach my $key (sort(keys(%lasthash))) {
 2971: 		my $value = &format_previous_attempt_value($key,
 2972: 							   $returnhash{$version.':'.$key});
 2973: 		$prevattempts.='<td>'.$value.'&nbsp;</td>';   
 2974: 	    }
 2975: 	 }
 2976:       }
 2977:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2978:       foreach my $key (sort(keys(%lasthash))) {
 2979: 	my $value = &format_previous_attempt_value($key,$lasthash{$key});
 2980: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2981: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2982:       }
 2983:       $prevattempts.='</tr></table></td></tr></table>';
 2984:     } else {
 2985:       $prevattempts='Nothing submitted - no attempts.';
 2986:     }
 2987:   } else {
 2988:     $prevattempts='No data.';
 2989:   }
 2990: }
 2991: 
 2992: sub format_previous_attempt_value {
 2993:     my ($key,$value) = @_;
 2994:     if ($key =~ /timestamp/) {
 2995: 	$value = &Apache::lonlocal::locallocaltime($value);
 2996:     } elsif (ref($value) eq 'ARRAY') {
 2997: 	$value = '('.join(', ', @{ $value }).')';
 2998:     } else {
 2999: 	$value = &unescape($value);
 3000:     }
 3001:     return $value;
 3002: }
 3003: 
 3004: 
 3005: sub relative_to_absolute {
 3006:     my ($url,$output)=@_;
 3007:     my $parser=HTML::TokeParser->new(\$output);
 3008:     my $token;
 3009:     my $thisdir=$url;
 3010:     my @rlinks=();
 3011:     while ($token=$parser->get_token) {
 3012: 	if ($token->[0] eq 'S') {
 3013: 	    if ($token->[1] eq 'a') {
 3014: 		if ($token->[2]->{'href'}) {
 3015: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3016: 		}
 3017: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3018: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3019: 	    } elsif ($token->[1] eq 'base') {
 3020: 		$thisdir=$token->[2]->{'href'};
 3021: 	    }
 3022: 	}
 3023:     }
 3024:     $thisdir=~s-/[^/]*$--;
 3025:     foreach my $link (@rlinks) {
 3026: 	unless (($link=~/^http:\/\//i) ||
 3027: 		($link=~/^\//) ||
 3028: 		($link=~/^javascript:/i) ||
 3029: 		($link=~/^mailto:/i) ||
 3030: 		($link=~/^\#/)) {
 3031: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3032: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3033: 	}
 3034:     }
 3035: # -------------------------------------------------- Deal with Applet codebases
 3036:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3037:     return $output;
 3038: }
 3039: 
 3040: =pod
 3041: 
 3042: =item * get_student_view
 3043: 
 3044: show a snapshot of what student was looking at
 3045: 
 3046: =cut
 3047: 
 3048: sub get_student_view {
 3049:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3050:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3051:   my (%form);
 3052:   my @elements=('symb','courseid','domain','username');
 3053:   foreach my $element (@elements) {
 3054:       $form{'grade_'.$element}=eval '$'.$element #'
 3055:   }
 3056:   if (defined($moreenv)) {
 3057:       %form=(%form,%{$moreenv});
 3058:   }
 3059:   if (defined($target)) { $form{'grade_target'} = $target; }
 3060:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3061:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 3062:   $userview=~s/\<body[^\>]*\>//gi;
 3063:   $userview=~s/\<\/body\>//gi;
 3064:   $userview=~s/\<html\>//gi;
 3065:   $userview=~s/\<\/html\>//gi;
 3066:   $userview=~s/\<head\>//gi;
 3067:   $userview=~s/\<\/head\>//gi;
 3068:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3069:   $userview=&relative_to_absolute($feedurl,$userview);
 3070:   return $userview;
 3071: }
 3072: 
 3073: =pod
 3074: 
 3075: =item * get_student_answers() 
 3076: 
 3077: show a snapshot of how student was answering problem
 3078: 
 3079: =cut
 3080: 
 3081: sub get_student_answers {
 3082:   my ($symb,$username,$domain,$courseid,%form) = @_;
 3083:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3084:   my (%moreenv);
 3085:   my @elements=('symb','courseid','domain','username');
 3086:   foreach my $element (@elements) {
 3087:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 3088:   }
 3089:   $moreenv{'grade_target'}='answer';
 3090:   %moreenv=(%form,%moreenv);
 3091:   $feedurl = &Apache::lonnet::clutter($feedurl);
 3092:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 3093:   return $userview;
 3094: }
 3095: 
 3096: =pod
 3097: 
 3098: =item * &submlink()
 3099: 
 3100: Inputs: $text $uname $udom $symb $target
 3101: 
 3102: Returns: A link to grades.pm such as to see the SUBM view of a student
 3103: 
 3104: =cut
 3105: 
 3106: ###############################################
 3107: sub submlink {
 3108:     my ($text,$uname,$udom,$symb,$target)=@_;
 3109:     if (!($uname && $udom)) {
 3110: 	(my $cursymb, my $courseid,$udom,$uname)=
 3111: 	    &Apache::lonnet::whichuser($symb);
 3112: 	if (!$symb) { $symb=$cursymb; }
 3113:     }
 3114:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3115:     $symb=&escape($symb);
 3116:     if ($target) { $target="target=\"$target\""; }
 3117:     return '<a href="/adm/grades?&command=submission&'.
 3118: 	'symb='.$symb.'&student='.$uname.
 3119: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 3120: }
 3121: ##############################################
 3122: 
 3123: =pod
 3124: 
 3125: =item * &pgrdlink()
 3126: 
 3127: Inputs: $text $uname $udom $symb $target
 3128: 
 3129: Returns: A link to grades.pm such as to see the PGRD view of a student
 3130: 
 3131: =cut
 3132: 
 3133: ###############################################
 3134: sub pgrdlink {
 3135:     my $link=&submlink(@_);
 3136:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 3137:     return $link;
 3138: }
 3139: ##############################################
 3140: 
 3141: =pod
 3142: 
 3143: =item * &pprmlink()
 3144: 
 3145: Inputs: $text $uname $udom $symb $target
 3146: 
 3147: Returns: A link to parmset.pm such as to see the PPRM view of a
 3148: student and a specific resource
 3149: 
 3150: =cut
 3151: 
 3152: ###############################################
 3153: sub pprmlink {
 3154:     my ($text,$uname,$udom,$symb,$target)=@_;
 3155:     if (!($uname && $udom)) {
 3156: 	(my $cursymb, my $courseid,$udom,$uname)=
 3157: 	    &Apache::lonnet::whichuser($symb);
 3158: 	if (!$symb) { $symb=$cursymb; }
 3159:     }
 3160:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 3161:     $symb=&escape($symb);
 3162:     if ($target) { $target="target=\"$target\""; }
 3163:     return '<a href="/adm/parmset?command=set&amp;'.
 3164: 	'symb='.$symb.'&amp;uname='.$uname.
 3165: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 3166: }
 3167: ##############################################
 3168: 
 3169: =pod
 3170: 
 3171: =back
 3172: 
 3173: =cut
 3174: 
 3175: ###############################################
 3176: 
 3177: 
 3178: sub timehash {
 3179:     my @ltime=localtime(shift);
 3180:     return ( 'seconds' => $ltime[0],
 3181:              'minutes' => $ltime[1],
 3182:              'hours'   => $ltime[2],
 3183:              'day'     => $ltime[3],
 3184:              'month'   => $ltime[4]+1,
 3185:              'year'    => $ltime[5]+1900,
 3186:              'weekday' => $ltime[6],
 3187:              'dayyear' => $ltime[7]+1,
 3188:              'dlsav'   => $ltime[8] );
 3189: }
 3190: 
 3191: sub utc_string {
 3192:     my ($date)=@_;
 3193:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 3194: }
 3195: 
 3196: sub maketime {
 3197:     my %th=@_;
 3198:     return POSIX::mktime(
 3199:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 3200:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 3201: }
 3202: 
 3203: #########################################
 3204: 
 3205: sub findallcourses {
 3206:     my ($roles,$uname,$udom) = @_;
 3207:     my %roles;
 3208:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 3209:     my %courses;
 3210:     my $now=time;
 3211:     if (!defined($uname)) {
 3212:         $uname = $env{'user.name'};
 3213:     }
 3214:     if (!defined($udom)) {
 3215:         $udom = $env{'user.domain'};
 3216:     }
 3217:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 3218:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 3219:         if (!%roles) {
 3220:             %roles = (
 3221:                        cc => 1,
 3222:                        in => 1,
 3223:                        ep => 1,
 3224:                        ta => 1,
 3225:                        cr => 1,
 3226:                        st => 1,
 3227:              );
 3228:         }
 3229:         foreach my $entry (keys(%roleshash)) {
 3230:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 3231:             if ($trole =~ /^cr/) { 
 3232:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 3233:             } else {
 3234:                 next if (!exists($roles{$trole}));
 3235:             }
 3236:             if ($tend) {
 3237:                 next if ($tend < $now);
 3238:             }
 3239:             if ($tstart) {
 3240:                 next if ($tstart > $now);
 3241:             }
 3242:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
 3243:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 3244:             if ($secpart eq '') {
 3245:                 ($cnum,$role) = split(/_/,$cnumpart); 
 3246:                 $sec = 'none';
 3247:                 $realsec = '';
 3248:             } else {
 3249:                 $cnum = $cnumpart;
 3250:                 ($sec,$role) = split(/_/,$secpart);
 3251:                 $realsec = $sec;
 3252:             }
 3253:             $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
 3254:         }
 3255:     } else {
 3256:         foreach my $key (keys(%env)) {
 3257: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 3258:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 3259: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 3260: 	        next if ($role eq 'ca' || $role eq 'aa');
 3261: 	        next if (%roles && !exists($roles{$role}));
 3262: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 3263:                 my $active=1;
 3264:                 if ($starttime) {
 3265: 		    if ($now<$starttime) { $active=0; }
 3266:                 }
 3267:                 if ($endtime) {
 3268:                     if ($now>$endtime) { $active=0; }
 3269:                 }
 3270:                 if ($active) {
 3271:                     if ($sec eq '') {
 3272:                         $sec = 'none';
 3273:                     }
 3274:                     $courses{$cdom.'_'.$cnum}{$sec} = 
 3275:                                      $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
 3276:                 }
 3277:             }
 3278:         }
 3279:     }
 3280:     return %courses;
 3281: }
 3282: 
 3283: ###############################################
 3284: 
 3285: sub blockcheck {
 3286:     my ($setters,$activity,$uname,$udom) = @_;
 3287: 
 3288:     if (!defined($udom)) {
 3289:         $udom = $env{'user.domain'};
 3290:     }
 3291:     if (!defined($uname)) {
 3292:         $uname = $env{'user.name'};
 3293:     }
 3294: 
 3295:     # If uname and udom are for a course, check for blocks in the course.
 3296: 
 3297:     if (&Apache::lonnet::is_course($udom,$uname)) {
 3298:         my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
 3299:         my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
 3300:         return ($startblock,$endblock);
 3301:     }
 3302: 
 3303:     my $startblock = 0;
 3304:     my $endblock = 0;
 3305:     my %live_courses = &findallcourses(undef,$uname,$udom);
 3306: 
 3307:     # If uname is for a user, and activity is course-specific, i.e.,
 3308:     # boards, chat or groups, check for blocking in current course only.
 3309: 
 3310:     if (($activity eq 'boards' || $activity eq 'chat' ||
 3311:          $activity eq 'groups') && ($env{'request.course.id'})) {
 3312:         foreach my $key (keys(%live_courses)) {
 3313:             if ($key ne $env{'request.course.id'}) {
 3314:                 delete($live_courses{$key});
 3315:             }
 3316:         }
 3317:     }
 3318: 
 3319:     my $otheruser = 0;
 3320:     my %own_courses;
 3321:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 3322:         # Resource belongs to user other than current user.
 3323:         $otheruser = 1;
 3324:         # Gather courses for current user
 3325:         %own_courses = 
 3326:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 3327:     }
 3328: 
 3329:     # Gather active course roles - course coordinator, instructor, 
 3330:     # exam proctor, ta, student, or custom role.
 3331: 
 3332:     foreach my $course (keys(%live_courses)) {
 3333:         my ($cdom,$cnum);
 3334:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 3335:             $cdom = $env{'course.'.$course.'.domain'};
 3336:             $cnum = $env{'course.'.$course.'.num'};
 3337:         } else {
 3338:             ($cdom,$cnum) = split(/_/,$course); 
 3339:         }
 3340:         my $no_ownblock = 0;
 3341:         my $no_userblock = 0;
 3342:         if ($otheruser && $activity ne 'com') {
 3343:             # Check if current user has 'evb' priv for this
 3344:             if (defined($own_courses{$course})) {
 3345:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 3346:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3347:                     if ($sec ne 'none') {
 3348:                         $checkrole .= '/'.$sec;
 3349:                     }
 3350:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3351:                         $no_ownblock = 1;
 3352:                         last;
 3353:                     }
 3354:                 }
 3355:             }
 3356:             # if they have 'evb' priv and are currently not playing student
 3357:             next if (($no_ownblock) &&
 3358:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 3359:         }
 3360:         foreach my $sec (keys(%{$live_courses{$course}})) {
 3361:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 3362:             if ($sec ne 'none') {
 3363:                 $checkrole .= '/'.$sec;
 3364:             }
 3365:             if ($otheruser) {
 3366:                 # Resource belongs to user other than current user.
 3367:                 # Assemble privs for that user, and check for 'evb' priv.
 3368:                 my ($trole,$tdom,$tnum,$tsec);
 3369:                 my $entry = $live_courses{$course}{$sec};
 3370:                 if ($entry =~ /^cr/) {
 3371:                     ($trole,$tdom,$tnum,$tsec) = 
 3372:                       ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 3373:                 } else {
 3374:                     ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 3375:                 }
 3376:                 my ($spec,$area,$trest,%allroles,%userroles);
 3377:                 $area = '/'.$tdom.'/'.$tnum;
 3378:                 $trest = $tnum;
 3379:                 if ($tsec ne '') {
 3380:                     $area .= '/'.$tsec;
 3381:                     $trest .= '/'.$tsec;
 3382:                 }
 3383:                 $spec = $trole.'.'.$area;
 3384:                 if ($trole =~ /^cr/) {
 3385:                     &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 3386:                                                       $tdom,$spec,$trest,$area);
 3387:                 } else {
 3388:                     &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 3389:                                                        $tdom,$spec,$trest,$area);
 3390:                 }
 3391:                 my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 3392:                 if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 3393:                     if ($1) {
 3394:                         $no_userblock = 1;
 3395:                         last;
 3396:                     }
 3397:                 }
 3398:             } else {
 3399:                 # Resource belongs to current user
 3400:                 # Check for 'evb' priv via lonnet::allowed().
 3401:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 3402:                     $no_ownblock = 1;
 3403:                     last;
 3404:                 }
 3405:             }
 3406:         }
 3407:         # if they have the evb priv and are currently not playing student
 3408:         next if (($no_ownblock) &&
 3409:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 3410:         next if ($no_userblock);
 3411: 
 3412:         # Retrieve blocking times and identity of blocker for course
 3413:         # of specified user, unless user has 'evb' privilege.
 3414:         
 3415:         my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
 3416:         if (($start != 0) && 
 3417:             (($startblock == 0) || ($startblock > $start))) {
 3418:             $startblock = $start;
 3419:         }
 3420:         if (($end != 0)  &&
 3421:             (($endblock == 0) || ($endblock < $end))) {
 3422:             $endblock = $end;
 3423:         }
 3424:     }
 3425:     return ($startblock,$endblock);
 3426: }
 3427: 
 3428: sub get_blocks {
 3429:     my ($setters,$activity,$cdom,$cnum) = @_;
 3430:     my $startblock = 0;
 3431:     my $endblock = 0;
 3432:     my $course = $cdom.'_'.$cnum;
 3433:     $setters->{$course} = {};
 3434:     $setters->{$course}{'staff'} = [];
 3435:     $setters->{$course}{'times'} = [];
 3436:     my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 3437:     foreach my $record (keys(%records)) {
 3438:         my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
 3439:         if ($start <= time && $end >= time) {
 3440:             my ($staff_name,$staff_dom,$title,$blocks) =
 3441:                 &parse_block_record($records{$record});
 3442:             if ($blocks->{$activity} eq 'on') {
 3443:                 push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 3444:                 push(@{$$setters{$course}{'times'}}, [$start,$end]);
 3445:                 if ( ($startblock == 0) || ($startblock > $start) ) {
 3446:                     $startblock = $start;
 3447:                 }
 3448:                 if ( ($endblock == 0) || ($endblock < $end) ) {
 3449:                     $endblock = $end;
 3450:                 }
 3451:             }
 3452:         }
 3453:     }
 3454:     return ($startblock,$endblock);
 3455: }
 3456: 
 3457: sub parse_block_record {
 3458:     my ($record) = @_;
 3459:     my ($setuname,$setudom,$title,$blocks);
 3460:     if (ref($record) eq 'HASH') {
 3461:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 3462:         $title = &unescape($record->{'event'});
 3463:         $blocks = $record->{'blocks'};
 3464:     } else {
 3465:         my @data = split(/:/,$record,3);
 3466:         if (scalar(@data) eq 2) {
 3467:             $title = $data[1];
 3468:             ($setuname,$setudom) = split(/@/,$data[0]);
 3469:         } else {
 3470:             ($setuname,$setudom,$title) = @data;
 3471:         }
 3472:         $blocks = { 'com' => 'on' };
 3473:     }
 3474:     return ($setuname,$setudom,$title,$blocks);
 3475: }
 3476: 
 3477: sub build_block_table {
 3478:     my ($startblock,$endblock,$setters) = @_;
 3479:     my %lt = &Apache::lonlocal::texthash(
 3480:         'cacb' => 'Currently active communication blocks',
 3481:         'cour' => 'Course',
 3482:         'dura' => 'Duration',
 3483:         'blse' => 'Block set by'
 3484:     );
 3485:     my $output;
 3486:     $output = '<br />'.$lt{'cacb'}.':<br />';
 3487:     $output .= &start_data_table();
 3488:     $output .= '
 3489: <tr>
 3490:  <th>'.$lt{'cour'}.'</th>
 3491:  <th>'.$lt{'dura'}.'</th>
 3492:  <th>'.$lt{'blse'}.'</th>
 3493: </tr>
 3494: ';
 3495:     foreach my $course (keys(%{$setters})) {
 3496:         my %courseinfo=&Apache::lonnet::coursedescription($course);
 3497:         for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
 3498:             my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
 3499:             my $fullname = &plainname($uname,$udom);
 3500:             if (defined($env{'user.name'}) && defined($env{'user.domain'})
 3501:                 && $env{'user.name'} ne 'public' 
 3502:                 && $env{'user.domain'} ne 'public') {
 3503:                 $fullname = &aboutmewrapper($fullname,$uname,$udom);
 3504:             }
 3505:             my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
 3506:             $openblock = &Apache::lonlocal::locallocaltime($openblock);
 3507:             $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
 3508:             $output .= &Apache::loncommon::start_data_table_row().
 3509:                        '<td>'.$courseinfo{'description'}.'</td>'.
 3510:                        '<td>'.$openblock.' to '.$closeblock.'</td>'.
 3511:                        '<td>'.$fullname.'</td>'.
 3512:                         &Apache::loncommon::end_data_table_row();
 3513:         }
 3514:     }
 3515:     $output .= &end_data_table();
 3516: }
 3517: 
 3518: sub blocking_status {
 3519:     my ($activity,$uname,$udom) = @_;
 3520:     my %setters;
 3521:     my ($blocked,$output,$ownitem,$is_course);
 3522:     my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
 3523:     if ($startblock && $endblock) {
 3524:         $blocked = 1;
 3525:         if (wantarray) {
 3526:             my $category;
 3527:             if ($activity eq 'boards') {
 3528:                 $category = 'Discussion posts in this course';
 3529:             } elsif ($activity eq 'blogs') {
 3530:                 $category = 'Blogs';
 3531:             } elsif ($activity eq 'port') {
 3532:                 if (defined($uname) && defined($udom)) {
 3533:                     if ($uname eq $env{'user.name'} &&
 3534:                         $udom eq $env{'user.domain'}) {
 3535:                         $ownitem = 1;
 3536:                     }
 3537:                 }
 3538:                 $is_course = &Apache::lonnet::is_course($udom,$uname);
 3539:                 if ($ownitem) { 
 3540:                     $category = 'Your portfolio files';  
 3541:                 } elsif ($is_course) {
 3542:                     my $coursedesc;
 3543:                     foreach my $course (keys(%setters)) {
 3544:                         my %courseinfo =
 3545:                              &Apache::lonnet::coursedescription($course);
 3546:                         $coursedesc = $courseinfo{'description'};
 3547:                     }
 3548:                     $category = "Group files in the course '$coursedesc'";
 3549:                 } else {
 3550:                     $category = 'Portfolio files belonging to ';
 3551:                     if ($env{'user.name'} eq 'public' && 
 3552:                         $env{'user.domain'} eq 'public') {
 3553:                         $category .= &plainname($uname,$udom);
 3554:                     } else {
 3555:                         $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);  
 3556:                     }
 3557:                 }
 3558:             } elsif ($activity eq 'groups') {
 3559:                 $category = 'Groups in this course';
 3560:             }
 3561:             my $showstart = &Apache::lonlocal::locallocaltime($startblock);
 3562:             my $showend = &Apache::lonlocal::locallocaltime($endblock);
 3563:             $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
 3564:             if (!($activity eq 'port' && !($ownitem) && !($is_course))) { 
 3565:                 $output .= &build_block_table($startblock,$endblock,\%setters);
 3566:             }
 3567:         }
 3568:     }
 3569:     if (wantarray) {
 3570:         return ($blocked,$output);
 3571:     } else {
 3572:         return $blocked;
 3573:     }
 3574: }
 3575: 
 3576: ###############################################
 3577: 
 3578: =pod
 3579: 
 3580: =head1 Domain Template Functions
 3581: 
 3582: =over 4
 3583: 
 3584: =item * &determinedomain()
 3585: 
 3586: Inputs: $domain (usually will be undef)
 3587: 
 3588: Returns: Determines which domain should be used for designs
 3589: 
 3590: =cut
 3591: 
 3592: ###############################################
 3593: sub determinedomain {
 3594:     my $domain=shift;
 3595:     if (! $domain) {
 3596:         # Determine domain if we have not been given one
 3597:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 3598:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 3599:         if ($env{'request.role.domain'}) { 
 3600:             $domain=$env{'request.role.domain'}; 
 3601:         }
 3602:     }
 3603:     return $domain;
 3604: }
 3605: ###############################################
 3606: 
 3607: sub devalidate_domconfig_cache {
 3608:     my ($udom)=@_;
 3609:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 3610: }
 3611: 
 3612: # ---------------------- Get domain configuration for a domain
 3613: sub get_domainconf {
 3614:     my ($udom) = @_;
 3615:     my $cachetime=1800;
 3616:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 3617:     if (defined($cached)) { return %{$result}; }
 3618: 
 3619:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 3620: 					     ['login','rolecolors'],$udom);
 3621:     my %designhash;
 3622:     if (keys(%domconfig) > 0) {
 3623:         if (ref($domconfig{'login'}) eq 'HASH') {
 3624:             foreach my $key (keys(%{$domconfig{'login'}})) {
 3625:                 $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 3626:             }
 3627:         }
 3628:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 3629:             foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 3630:                 if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 3631:                     foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 3632:                         $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 3633:                     }
 3634:                 }
 3635:             }
 3636:         }
 3637:     } else {
 3638:         my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 3639:         my $designfile =  $designdir.'/'.$udom.'.tab';
 3640:         if (-e $designfile) {
 3641:             if ( open (my $fh,"<$designfile") ) {
 3642:                 while (my $line = <$fh>) {
 3643:                     next if ($line =~ /^\#/);
 3644:                     chomp($line);
 3645:                     my ($key,$val)=(split(/\=/,$line));
 3646:                     if ($val) { $designhash{$udom.'.'.$key}=$val; }
 3647:                 }
 3648:                 close($fh);
 3649:             }
 3650:         }
 3651:         if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
 3652:             $designhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 3653:         }
 3654:     }
 3655:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 3656: 				  $cachetime);
 3657:     return %designhash;
 3658: }
 3659: 
 3660: =pod
 3661: 
 3662: =item * &domainlogo()
 3663: 
 3664: Inputs: $domain (usually will be undef)
 3665: 
 3666: Returns: A link to a domain logo, if the domain logo exists.
 3667: If the domain logo does not exist, a description of the domain.
 3668: 
 3669: =cut
 3670: 
 3671: ###############################################
 3672: sub domainlogo {
 3673:     my $domain = &determinedomain(shift);
 3674:     my %designhash = &get_domainconf($domain);    
 3675:     # See if there is a logo
 3676:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 3677:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 3678:         if ($imgsrc =~ m{^/(adm|res)/}) {
 3679: 	    if ($imgsrc =~ m{^/res/}) {
 3680: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 3681: 		&Apache::lonnet::repcopy($local_name);
 3682: 	    }
 3683: 	   $imgsrc = &lonhttpdurl($imgsrc);
 3684:         } 
 3685:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 3686:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 3687:         return &Apache::lonnet::domain($domain,'description');
 3688:     } else {
 3689:         return '';
 3690:     }
 3691: }
 3692: ##############################################
 3693: 
 3694: =pod
 3695: 
 3696: =item * &designparm()
 3697: 
 3698: Inputs: $which parameter; $domain (usually will be undef)
 3699: 
 3700: Returns: value of designparamter $which
 3701: 
 3702: =cut
 3703: 
 3704: 
 3705: ##############################################
 3706: sub designparm {
 3707:     my ($which,$domain)=@_;
 3708:     if ($env{'browser.blackwhite'} eq 'on') {
 3709: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 3710: 	    return '#000000';
 3711: 	}
 3712: 	if ($which=~/\.(pgbg|sidebg)$/) {
 3713: 	    return '#FFFFFF';
 3714: 	}
 3715: 	if ($which=~/\.tabbg$/) {
 3716: 	    return '#CCCCCC';
 3717: 	}
 3718:     }
 3719:     if (exists($env{'environment.color.'.$which})) {
 3720: 	return $env{'environment.color.'.$which};
 3721:     }
 3722:     $domain=&determinedomain($domain);
 3723:     my %domdesign = &get_domainconf($domain);
 3724:     my $output;
 3725:     if ($domdesign{$domain.'.'.$which} ne '') {
 3726: 	$output = $domdesign{$domain.'.'.$which};
 3727:     } else {
 3728:         $output = $defaultdesign{$which};
 3729:     }
 3730:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 3731:         ($which =~ /login\.(img|logo|domlogo)/)) {
 3732:         if ($output =~ m{^/(adm|res)/}) {
 3733: 	    if ($output =~ m{^/res/}) {
 3734: 		my $local_name = &Apache::lonnet::filelocation('',$output);
 3735: 		&Apache::lonnet::repcopy($local_name);
 3736: 	    }
 3737:             $output = &lonhttpdurl($output);
 3738:         }
 3739:     }
 3740:     return $output;
 3741: }
 3742: 
 3743: ###############################################
 3744: ###############################################
 3745: 
 3746: =pod
 3747: 
 3748: =back
 3749: 
 3750: =head1 HTML Helpers
 3751: 
 3752: =over 4
 3753: 
 3754: =item * &bodytag()
 3755: 
 3756: Returns a uniform header for LON-CAPA web pages.
 3757: 
 3758: Inputs: 
 3759: 
 3760: =over 4
 3761: 
 3762: =item * $title, A title to be displayed on the page.
 3763: 
 3764: =item * $function, the current role (can be undef).
 3765: 
 3766: =item * $addentries, extra parameters for the <body> tag.
 3767: 
 3768: =item * $bodyonly, if defined, only return the <body> tag.
 3769: 
 3770: =item * $domain, if defined, force a given domain.
 3771: 
 3772: =item * $forcereg, if page should register as content page (relevant for 
 3773:             text interface only)
 3774: 
 3775: =item * $customtitle, alternate text to use instead of $title
 3776:                       in the title box that appears, this text
 3777:                       is not auto translated like the $title is
 3778: 
 3779: =item * $notopbar, if true, keep the 'what is this' info but remove the
 3780:                    navigational links
 3781: 
 3782: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 3783: 
 3784: =item * $notitle, if true keep the nav controls, but remove the title bar
 3785: 
 3786: =item * $no_inline_link, if true and in remote mode, don't show the 
 3787:          'Switch To Inline Menu' link
 3788: 
 3789: =item * $args, optional argument valid values are
 3790:             no_auto_mt_title -> prevents &mt()ing the title arg
 3791:             inherit_jsmath -> when creating popup window in a page,
 3792:                               should it have jsmath forced on by the
 3793:                               current page
 3794: 
 3795: =back
 3796: 
 3797: Returns: A uniform header for LON-CAPA web pages.  
 3798: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 3799: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 3800: other decorations will be returned.
 3801: 
 3802: =cut
 3803: 
 3804: sub bodytag {
 3805:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 3806: 	$notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
 3807: 
 3808:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 3809: 
 3810:     $function = &get_users_function() if (!$function);
 3811:     my $img =    &designparm($function.'.img',$domain);
 3812:     my $font =   &designparm($function.'.font',$domain);
 3813:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 3814: 
 3815:     my %design = ( 'style'   => 'margin-top: 0px',
 3816: 		   'bgcolor' => $pgbg,
 3817: 		   'text'    => $font,
 3818:                    'alink'   => &designparm($function.'.alink',$domain),
 3819: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 3820: 		   'link'    => &designparm($function.'.link',$domain),);
 3821:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 3822: 
 3823:  # role and realm
 3824:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 3825:     if ($role  eq 'ca') {
 3826:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 3827:         $realm = &plainname($rname,$rdom);
 3828:     } 
 3829: # realm
 3830:     if ($env{'request.course.id'}) {
 3831:         if ($env{'request.role'} !~ /^cr/) {
 3832:             $role = &Apache::lonnet::plaintext($role,&course_type());
 3833:         }
 3834: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 3835:     } else {
 3836:         $role = &Apache::lonnet::plaintext($role);
 3837:     }
 3838: 
 3839:     if (!$realm) { $realm='&nbsp;'; }
 3840: # Set messages
 3841:     my $messages=&domainlogo($domain);
 3842: 
 3843:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 3844: 
 3845: # construct main body tag
 3846:     my $bodytag = "<body $extra_body_attr>".
 3847: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 3848: 
 3849:     if ($bodyonly) {
 3850:         return $bodytag;
 3851:     } elsif ($env{'browser.interface'} eq 'textual') {
 3852: # Accessibility
 3853:           
 3854: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 3855: 	if (!$notitle) {
 3856: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 3857: 	}
 3858: 	return $bodytag;
 3859:     }
 3860: 
 3861:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 3862:     if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3863: 	undef($role);
 3864:     } else {
 3865: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
 3866:     }
 3867:     
 3868:     my $roleinfo=(<<ENDROLE);
 3869: <td class="LC_title_bar_who">
 3870: <div class="LC_title_bar_name">
 3871:     $name
 3872:     &nbsp;
 3873: </div>
 3874: <div class="LC_title_bar_role">
 3875: $role&nbsp;
 3876: </div>
 3877: <div class="LC_title_bar_realm">
 3878: $realm&nbsp;
 3879: </div>
 3880: </td>
 3881: ENDROLE
 3882: 
 3883:     my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
 3884:     if ($customtitle) {
 3885:         $titleinfo = $customtitle;
 3886:     }
 3887:     #
 3888:     # Extra info if you are the DC
 3889:     my $dc_info = '';
 3890:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 3891:                         $env{'course.'.$env{'request.course.id'}.
 3892:                                  '.domain'}.'/'})) {
 3893:         my $cid = $env{'request.course.id'};
 3894:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 3895:         $dc_info =~ s/\s+$//;
 3896:         $dc_info = '('.$dc_info.')';
 3897:     }
 3898: 
 3899:     if ($env{'environment.remote'} eq 'off') {
 3900:         # No Remote
 3901: 	if ($env{'request.state'} eq 'construct') {
 3902: 	    $forcereg=1;
 3903: 	}
 3904: 
 3905: 	if (!$customtitle && $env{'request.state'} eq 'construct') {
 3906: 	    # this is for resources; directories have customtitle, and crumbs
 3907:             # and select recent are created in lonpubdir.pm  
 3908: 	    my ($uname,$thisdisfn)=
 3909: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 3910: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 3911: 	    $formaction=~s/\/+/\//g;
 3912: 
 3913: 	    my $parentpath = '';
 3914: 	    my $lastitem = '';
 3915: 	    if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 3916: 		$parentpath = $1;
 3917: 		$lastitem = $2;
 3918: 	    } else {
 3919: 		$lastitem = $thisdisfn;
 3920: 	    }
 3921: 	    $titleinfo = 
 3922: 		&Apache::loncommon::help_open_menu('','',3,'Authoring').
 3923: 		'<b>Construction Space</b>:&nbsp;'. 
 3924: 		'<form name="dirs" method="post" action="'.$formaction
 3925: 		.'" target="_top"><tt><b>'
 3926: 		.&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 3927: 		.&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 3928: 		.'</form>'
 3929: 		.&Apache::lonmenu::constspaceform();
 3930:         }
 3931: 
 3932:         my $titletable;
 3933: 	if (!$notitle) {
 3934: 	    $titletable =
 3935: 		'<table id="LC_title_bar">'.
 3936:                          "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
 3937: 			 '</tr></table>';
 3938: 	}
 3939: 	if ($notopbar) {
 3940: 	    $bodytag .= $titletable;
 3941: 	} else {
 3942: 	    if ($env{'request.state'} eq 'construct') {
 3943:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 3944: 							  $titletable);
 3945:             } else {
 3946:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 3947: 		    $titletable;
 3948:             }
 3949:         }
 3950:         return $bodytag;
 3951:     }
 3952: 
 3953: #
 3954: # Top frame rendering, Remote is up
 3955: #
 3956: 
 3957:     my $imgsrc = $img;
 3958:     if ($img =~ /^\/adm/) {
 3959:         $imgsrc = &lonhttpdurl($img);
 3960:     }
 3961:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 3962: 
 3963:     # Explicit link to get inline menu
 3964:     my $menu= ($no_inline_link?''
 3965: 	       :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
 3966:     #
 3967:     if ($notitle) {
 3968: 	return $bodytag;
 3969:     }
 3970:     return(<<ENDBODY);
 3971: $bodytag
 3972: <table id="LC_title_bar" class="LC_with_remote">
 3973: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
 3974:     <td class="LC_title_bar_domain_logo">$messages&nbsp;</td>
 3975: </tr>
 3976: <tr><td>$titleinfo $dc_info $menu</td>
 3977: $roleinfo
 3978: </tr>
 3979: </table>
 3980: ENDBODY
 3981: }
 3982: 
 3983: sub make_attr_string {
 3984:     my ($register,$attr_ref) = @_;
 3985: 
 3986:     if ($attr_ref && !ref($attr_ref)) {
 3987: 	die("addentries Must be a hash ref ".
 3988: 	    join(':',caller(1))." ".
 3989: 	    join(':',caller(0))." ");
 3990:     }
 3991: 
 3992:     if ($register) {
 3993: 	my ($on_load,$on_unload);
 3994: 	foreach my $key (keys(%{$attr_ref})) {
 3995: 	    if      (lc($key) eq 'onload') {
 3996: 		$on_load.=$attr_ref->{$key}.';';
 3997: 		delete($attr_ref->{$key});
 3998: 
 3999: 	    } elsif (lc($key) eq 'onunload') {
 4000: 		$on_unload.=$attr_ref->{$key}.';';
 4001: 		delete($attr_ref->{$key});
 4002: 	    }
 4003: 	}
 4004: 	$attr_ref->{'onload'}  =
 4005: 	    &Apache::lonmenu::loadevents().  $on_load;
 4006: 	$attr_ref->{'onunload'}=
 4007: 	    &Apache::lonmenu::unloadevents().$on_unload;
 4008:     }
 4009: 
 4010: # Accessibility font enhance
 4011:     if ($env{'browser.fontenhance'} eq 'on') {
 4012: 	my $style;
 4013: 	foreach my $key (keys(%{$attr_ref})) {
 4014: 	    if (lc($key) eq 'style') {
 4015: 		$style.=$attr_ref->{$key}.';';
 4016: 		delete($attr_ref->{$key});
 4017: 	    }
 4018: 	}
 4019: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 4020:     }
 4021: 
 4022:     if ($env{'browser.blackwhite'} eq 'on') {
 4023: 	delete($attr_ref->{'font'});
 4024: 	delete($attr_ref->{'link'});
 4025: 	delete($attr_ref->{'alink'});
 4026: 	delete($attr_ref->{'vlink'});
 4027: 	delete($attr_ref->{'bgcolor'});
 4028: 	delete($attr_ref->{'background'});
 4029:     }
 4030: 
 4031:     my $attr_string;
 4032:     foreach my $attr (keys(%$attr_ref)) {
 4033: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 4034:     }
 4035:     return $attr_string;
 4036: }
 4037: 
 4038: 
 4039: ###############################################
 4040: ###############################################
 4041: 
 4042: =pod
 4043: 
 4044: =item * &endbodytag()
 4045: 
 4046: Returns a uniform footer for LON-CAPA web pages.
 4047: 
 4048: Inputs: none
 4049: 
 4050: =cut
 4051: 
 4052: sub endbodytag {
 4053:     my $endbodytag='</body>';
 4054:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 4055:     if ( exists( $env{'internal.head.redirect'} ) ) {
 4056: 	$endbodytag=
 4057: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
 4058: 	    &mt('Continue').'</a>'.
 4059: 	    $endbodytag;
 4060:     }
 4061:     return $endbodytag;
 4062: }
 4063: 
 4064: =pod
 4065: 
 4066: =item * &standard_css()
 4067: 
 4068: Returns a style sheet
 4069: 
 4070: Inputs: (all optional)
 4071:             domain         -> force to color decorate a page for a specific
 4072:                                domain
 4073:             function       -> force usage of a specific rolish color scheme
 4074:             bgcolor        -> override the default page bgcolor
 4075: 
 4076: =cut
 4077: 
 4078: sub standard_css {
 4079:     my ($function,$domain,$bgcolor) = @_;
 4080:     $function  = &get_users_function() if (!$function);
 4081:     my $img    = &designparm($function.'.img',   $domain);
 4082:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 4083:     my $font   = &designparm($function.'.font',  $domain);
 4084:     my $sidebg = &designparm($function.'.sidebg',$domain);
 4085:     my $pgbg_or_bgcolor =
 4086: 	         $bgcolor ||
 4087: 	         &designparm($function.'.pgbg',  $domain);
 4088:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 4089:     my $alink  = &designparm($function.'.alink', $domain);
 4090:     my $vlink  = &designparm($function.'.vlink', $domain);
 4091:     my $link   = &designparm($function.'.link',  $domain);
 4092: 
 4093:     my $sans                 = 'Arial,Helvetica,sans-serif';
 4094:     my $mono                 = 'monospace';
 4095:     my $data_table_head      = $tabbg;
 4096:     my $data_table_light     = '#EEEEEE';
 4097:     my $data_table_dark      = '#DDDDDD';
 4098:     my $data_table_darker    = '#CCCCCC';
 4099:     my $data_table_highlight = '#FFFF00';
 4100:     my $mail_new             = '#FFBB77';
 4101:     my $mail_new_hover       = '#DD9955';
 4102:     my $mail_read            = '#BBBB77';
 4103:     my $mail_read_hover      = '#999944';
 4104:     my $mail_replied         = '#AAAA88';
 4105:     my $mail_replied_hover   = '#888855';
 4106:     my $mail_other           = '#99BBBB';
 4107:     my $mail_other_hover     = '#669999';
 4108:     my $table_header         = '#DDDDDD';
 4109:     my $feedback_link_bg     = '#BBBBBB';
 4110: 
 4111:     my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
 4112: 	                                              : '0px 3px 0px 4px';
 4113: 
 4114: 
 4115:     return <<END;
 4116: h1, h2, h3, th { font-family: $sans }
 4117: a:focus { color: red; background: yellow } 
 4118: table.thinborder,
 4119: 
 4120: table.thinborder tr th {
 4121:   border-style: solid;
 4122:   border-width: 1px;
 4123:   background: $tabbg;
 4124: }
 4125: table.thinborder tr td {
 4126:   border-style: solid;
 4127:   border-width: 1px
 4128: }
 4129: 
 4130: form, .inline { display: inline; }
 4131: .center { text-align: center; }
 4132: .LC_filename {font-family: $mono; white-space:pre;}
 4133: .LC_error {
 4134:   color: red;
 4135:   font-size: larger;
 4136: }
 4137: .LC_warning,
 4138: .LC_diff_removed {
 4139:   color: red;
 4140: }
 4141: 
 4142: .LC_info,
 4143: .LC_success,
 4144: .LC_diff_added {
 4145:   color: green;
 4146: }
 4147: .LC_unknown {
 4148:   color: yellow;
 4149: }
 4150: 
 4151: .LC_icon {
 4152:   border: 0px;
 4153: }
 4154: .LC_indexer_icon {
 4155:   border: 0px;
 4156:   height: 22px;
 4157: }
 4158: .LC_docs_spacer {
 4159:   width: 25px;
 4160:   height: 1px;
 4161:   border: 0px;
 4162: }
 4163: 
 4164: .LC_internal_info {
 4165:   color: #999;
 4166: }
 4167: 
 4168: table.LC_pastsubmission {
 4169:   border: 1px solid black;
 4170:   margin: 2px;
 4171: }
 4172: 
 4173: table#LC_top_nav, table#LC_menubuttons {
 4174:   width: 100%;
 4175:   background: $pgbg;
 4176:   border: 2px;
 4177:   border-collapse: separate;
 4178:   padding: 0px;
 4179: }
 4180: 
 4181: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
 4182: table#LC_title_bar.LC_with_remote {
 4183:   width: 100%;
 4184:   border-color: $pgbg;
 4185:   border-style: solid;
 4186:   border-width: $border;
 4187: 
 4188:   background: $pgbg;
 4189:   font-family: $sans;
 4190:   border-collapse: collapse;
 4191:   padding: 0px;
 4192: }
 4193: 
 4194: table.LC_docs_path {
 4195:   width: 100%;
 4196:   border: 0;
 4197:   background: $pgbg;
 4198:   font-family: $sans;
 4199:   border-collapse: collapse;
 4200:   padding: 0px;
 4201: }
 4202: 
 4203: table#LC_title_bar td {
 4204:   background: $tabbg;
 4205: }
 4206: table#LC_title_bar td.LC_title_bar_who {
 4207:   background: $tabbg;
 4208:   color: $font;
 4209:   font: small $sans;
 4210:   text-align: right;
 4211: }
 4212: span.LC_metadata {
 4213:     font-family: $sans;
 4214: }
 4215: span.LC_title_bar_title {
 4216:   font: bold x-large $sans;
 4217: }
 4218: table#LC_title_bar td.LC_title_bar_domain_logo {
 4219:   background: $sidebg;
 4220:   text-align: right;
 4221:   padding: 0px;
 4222: }
 4223: table#LC_title_bar td.LC_title_bar_role_logo {
 4224:   background: $sidebg;
 4225:   padding: 0px;
 4226: }
 4227: 
 4228: table#LC_menubuttons_mainmenu {
 4229:   width: 100%;
 4230:   border: 0px;
 4231:   border-spacing: 1px;
 4232:   padding: 0px 1px;
 4233:   margin: 0px;
 4234:   border-collapse: separate;
 4235: }
 4236: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 4237:   border: 0px;
 4238: }
 4239: table#LC_top_nav td {
 4240:   background: $tabbg;
 4241:   border: 0px;
 4242:   font-size: small;
 4243: }
 4244: table#LC_top_nav td a, div#LC_top_nav a {
 4245:   color: $font;
 4246:   font-family: $sans;
 4247: }
 4248: table#LC_top_nav td.LC_top_nav_logo {
 4249:   background: $tabbg;
 4250:   text-align: left;
 4251:   white-space: nowrap;
 4252:   width: 31px;
 4253: }
 4254: table#LC_top_nav td.LC_top_nav_logo img {
 4255:   border: 0px;
 4256:   vertical-align: bottom;
 4257: }
 4258: table#LC_top_nav td.LC_top_nav_exit,
 4259: table#LC_top_nav td.LC_top_nav_help {
 4260:   width: 2.0em;
 4261: }
 4262: table#LC_top_nav td.LC_top_nav_login {
 4263:   width: 4.0em;
 4264:   text-align: center;
 4265: }
 4266: table.LC_breadcrumbs td, table.LC_docs_path td  {
 4267:   background: $tabbg;
 4268:   color: $font;
 4269:   font-family: $sans;
 4270:   font-size: smaller;
 4271: }
 4272: table.LC_breadcrumbs td.LC_breadcrumbs_component,
 4273: table.LC_docs_path td.LC_docs_path_component {
 4274:   background: $tabbg;
 4275:   color: $font;
 4276:   font-family: $sans;
 4277:   font-size: larger;
 4278:   text-align: right;
 4279: }
 4280: td.LC_table_cell_checkbox {
 4281:   text-align: center;
 4282: }
 4283: 
 4284: table#LC_mainmenu td.LC_mainmenu_column {
 4285:     vertical-align: top;
 4286: }
 4287: 
 4288: .LC_menubuttons_inline_text {
 4289:   color: $font;
 4290:   font-family: $sans;
 4291:   font-size: smaller;
 4292: }
 4293: 
 4294: .LC_menubuttons_link {
 4295:   text-decoration: none;
 4296: }
 4297: 
 4298: .LC_menubuttons_category {
 4299:   color: $font;
 4300:   background: $pgbg;
 4301:   font-family: $sans;
 4302:   font-size: larger;
 4303:   font-weight: bold;
 4304: }
 4305: 
 4306: td.LC_menubuttons_text {
 4307:   width: 90%;
 4308:   color: $font;
 4309:   font-family: $sans;
 4310: }
 4311: 
 4312: td.LC_menubuttons_img {
 4313: }
 4314: 
 4315: .LC_current_location {
 4316:   font-family: $sans;
 4317:   background: $tabbg;
 4318: }
 4319: .LC_new_mail {
 4320:   font-family: $sans;
 4321:   font-weight: bold;
 4322: }
 4323: 
 4324: .LC_rolesmenu_is {
 4325:   font-family: $sans;
 4326: }
 4327: 
 4328: .LC_rolesmenu_selected {
 4329:   font-family: $sans;
 4330: }
 4331: 
 4332: .LC_rolesmenu_future {
 4333:   font-family: $sans;
 4334: }
 4335: 
 4336: 
 4337: .LC_rolesmenu_will {
 4338:   font-family: $sans;
 4339: }
 4340: 
 4341: .LC_rolesmenu_will_not {
 4342:   font-family: $sans;
 4343: }
 4344: 
 4345: .LC_rolesmenu_expired {
 4346:   font-family: $sans;
 4347: }
 4348: 
 4349: .LC_rolesinfo {
 4350:   font-family: $sans;
 4351: }
 4352: 
 4353: .LC_dropadd_labeltext {
 4354:   font-family: $sans;
 4355:   text-align: right;
 4356: }
 4357: 
 4358: .LC_preferences_labeltext {
 4359:   font-family: $sans;
 4360:   text-align: right;
 4361: }
 4362: 
 4363: table.LC_aboutme_port {
 4364:   border: 0px;
 4365:   border-collapse: collapse;
 4366:   border-spacing: 0px;
 4367: }
 4368: table.LC_data_table, table.LC_mail_list {
 4369:   border: 1px solid #000000;
 4370:   border-collapse: separate;
 4371:   border-spacing: 1px;
 4372: }
 4373: .LC_data_table_dense {
 4374:   font-size: small;
 4375: }
 4376: table.LC_nested_outer {
 4377:   border: 1px solid #000000;
 4378:   border-collapse: collapse;
 4379:   border-spacing: 0px;
 4380:   width: 100%;
 4381: }
 4382: table.LC_nested {
 4383:   border: 0px;
 4384:   border-collapse: collapse;
 4385:   border-spacing: 0px;
 4386:   width: 100%;
 4387: }
 4388: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
 4389: table.LC_prior_tries tr th {
 4390:   font-weight: bold;
 4391:   background-color: $data_table_head;
 4392:   font-size: smaller;
 4393: }
 4394: table.LC_data_table tr td, 
 4395: table.LC_aboutme_port tr td {
 4396:   background-color: $data_table_light;
 4397:   padding: 2px;
 4398: }
 4399: table.LC_data_table tr.LC_even_row td,
 4400: table.LC_aboutme_port tr.LC_even_row td {
 4401:   background-color: $data_table_dark;
 4402: }
 4403: table.LC_data_table tr.LC_data_table_highlight td {
 4404:   background-color: $data_table_darker;
 4405: }
 4406: table.LC_data_table tr.LC_empty_row td,
 4407: table.LC_nested tr.LC_empty_row td {
 4408:   background-color: #FFFFFF;
 4409:   font-weight: bold;
 4410:   font-style: italic;
 4411:   text-align: center;
 4412:   padding: 8px;
 4413: }
 4414: table.LC_nested tr.LC_empty_row td {
 4415:   padding: 4ex
 4416: }
 4417: table.LC_nested_outer tr th {
 4418:   font-weight: bold;
 4419:   background-color: $data_table_head;
 4420:   font-size: smaller;
 4421:   border-bottom: 1px solid #000000;
 4422: }
 4423: table.LC_nested_outer tr td.LC_subheader {
 4424:   background-color: $data_table_head;
 4425:   font-weight: bold;
 4426:   font-size: small;
 4427:   border-bottom: 1px solid #000000;
 4428:   text-align: right;
 4429: }
 4430: table.LC_nested tr.LC_info_row td {
 4431:   background-color: #CCC;
 4432:   font-weight: bold;
 4433:   font-size: small;
 4434:   text-align: center;
 4435: }
 4436: table.LC_nested tr.LC_info_row td.LC_left_item,
 4437: table.LC_nested_outer tr th.LC_left_item {
 4438:   text-align: left;
 4439: }
 4440: table.LC_nested td {
 4441:   background-color: #FFF;
 4442:   font-size: small;
 4443: }
 4444: table.LC_nested_outer tr th.LC_right_item,
 4445: table.LC_nested tr.LC_info_row td.LC_right_item,
 4446: table.LC_nested tr.LC_odd_row td.LC_right_item,
 4447: table.LC_nested tr td.LC_right_item {
 4448:   text-align: right;
 4449: }
 4450: 
 4451: table.LC_nested tr.LC_odd_row td {
 4452:   background-color: #EEE;
 4453: }
 4454: 
 4455: table.LC_createuser {
 4456: }
 4457: 
 4458: table.LC_createuser tr.LC_section_row td {
 4459:   font-size: smaller;
 4460: }
 4461: 
 4462: table.LC_createuser tr.LC_info_row td  {
 4463:   background-color: #CCC;
 4464:   font-weight: bold;
 4465:   text-align: center;
 4466: }
 4467: 
 4468: table.LC_calendar {
 4469:   border: 1px solid #000000;
 4470:   border-collapse: collapse;
 4471: }
 4472: table.LC_calendar_pickdate {
 4473:   font-size: xx-small;
 4474: }
 4475: table.LC_calendar tr td {
 4476:   border: 1px solid #000000;
 4477:   vertical-align: top;
 4478: }
 4479: table.LC_calendar tr td.LC_calendar_day_empty {
 4480:   background-color: $data_table_dark;
 4481: }
 4482: table.LC_calendar tr td.LC_calendar_day_current {
 4483:   background-color: $data_table_highlight;
 4484: }
 4485: 
 4486: table.LC_mail_list tr.LC_mail_new {
 4487:   background-color: $mail_new;
 4488: }
 4489: table.LC_mail_list tr.LC_mail_new:hover {
 4490:   background-color: $mail_new_hover;
 4491: }
 4492: table.LC_mail_list tr.LC_mail_read {
 4493:   background-color: $mail_read;
 4494: }
 4495: table.LC_mail_list tr.LC_mail_read:hover {
 4496:   background-color: $mail_read_hover;
 4497: }
 4498: table.LC_mail_list tr.LC_mail_replied {
 4499:   background-color: $mail_replied;
 4500: }
 4501: table.LC_mail_list tr.LC_mail_replied:hover {
 4502:   background-color: $mail_replied_hover;
 4503: }
 4504: table.LC_mail_list tr.LC_mail_other {
 4505:   background-color: $mail_other;
 4506: }
 4507: table.LC_mail_list tr.LC_mail_other:hover {
 4508:   background-color: $mail_other_hover;
 4509: }
 4510: table.LC_mail_list tr.LC_mail_even {
 4511: }
 4512: table.LC_mail_list tr.LC_mail_odd {
 4513: }
 4514: 
 4515: 
 4516: table#LC_portfolio_actions {
 4517:   width: auto;
 4518:   background: $pgbg;
 4519:   border: 0px;
 4520:   border-spacing: 2px 2px;
 4521:   padding: 0px;
 4522:   margin: 0px;
 4523:   border-collapse: separate;
 4524: }
 4525: table#LC_portfolio_actions td.LC_label {
 4526:   background: $tabbg;
 4527:   text-align: right;
 4528: }
 4529: table#LC_portfolio_actions td.LC_value {
 4530:   background: $tabbg;
 4531: }
 4532: 
 4533: table#LC_cstr_controls {
 4534:   width: 100%;
 4535:   border-collapse: collapse;
 4536: }
 4537: table#LC_cstr_controls tr td {
 4538:   border: 4px solid $pgbg;
 4539:   padding: 4px;
 4540:   text-align: center;
 4541:   background: $tabbg;
 4542: }
 4543: table#LC_cstr_controls tr th {
 4544:   border: 4px solid $pgbg;
 4545:   background: $table_header;
 4546:   text-align: center;
 4547:   font-family: $sans;
 4548:   font-size: smaller;
 4549: }
 4550: 
 4551: table#LC_browser {
 4552:  
 4553: }
 4554: table#LC_browser tr th {
 4555:   background: $table_header;
 4556: }
 4557: table#LC_browser tr td {
 4558:   padding: 2px;
 4559: }
 4560: table#LC_browser tr.LC_browser_file,
 4561: table#LC_browser tr.LC_browser_file_published {
 4562:   background: #CCFF88;
 4563: }
 4564: table#LC_browser tr.LC_browser_file_locked,
 4565: table#LC_browser tr.LC_browser_file_unpublished {
 4566:   background: #FFAA99;
 4567: }
 4568: table#LC_browser tr.LC_browser_file_obsolete {
 4569:   background: #AAAAAA;
 4570: }
 4571: table#LC_browser tr.LC_browser_file_modified,
 4572: table#LC_browser tr.LC_browser_file_metamodified {
 4573:   background: #FFFF77;
 4574: }
 4575: table#LC_browser tr.LC_browser_folder {
 4576:   background: #CCCCFF;
 4577: }
 4578: span.LC_current_location {
 4579:   font-size: x-large;
 4580:   background: $pgbg;
 4581: }
 4582: 
 4583: span.LC_parm_menu_item {
 4584:   font-size: larger;
 4585:   font-family: $sans;
 4586: }
 4587: span.LC_parm_scope_all {
 4588:   color: red;
 4589: }
 4590: span.LC_parm_scope_folder {
 4591:   color: green;
 4592: }
 4593: span.LC_parm_scope_resource {
 4594:   color: orange;
 4595: }
 4596: span.LC_parm_part {
 4597:   color: blue;
 4598: }
 4599: span.LC_parm_folder, span.LC_parm_symb {
 4600:   font-size: x-small;
 4601:   font-family: $mono;
 4602:   color: #AAAAAA;
 4603: }
 4604: 
 4605: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
 4606: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
 4607:   border: 1px solid black;
 4608:   border-collapse: collapse;
 4609: }
 4610: table.LC_parm_overview_restrictions td {
 4611:   border-width: 1px 4px 1px 4px;
 4612:   border-style: solid;
 4613:   border-color: $pgbg;
 4614:   text-align: center;
 4615: }
 4616: table.LC_parm_overview_restrictions th {
 4617:   background: $tabbg;
 4618:   border-width: 1px 4px 1px 4px;
 4619:   border-style: solid;
 4620:   border-color: $pgbg;
 4621: }
 4622: table#LC_helpmenu {
 4623:   border: 0px;
 4624:   height: 55px;
 4625:   border-spacing: 0px;
 4626: }
 4627: 
 4628: table#LC_helpmenu fieldset legend {
 4629:   font-size: larger;
 4630:   font-weight: bold;
 4631: }
 4632: table#LC_helpmenu_links {
 4633:   width: 100%;
 4634:   border: 1px solid black;
 4635:   background: $pgbg;
 4636:   padding: 0px;
 4637:   border-spacing: 1px;
 4638: }
 4639: table#LC_helpmenu_links tr td {
 4640:   padding: 1px;
 4641:   background: $tabbg;
 4642:   text-align: center;
 4643:   font-weight: bold;
 4644: }
 4645: 
 4646: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
 4647: table#LC_helpmenu_links a:active {
 4648:   text-decoration: none;
 4649:   color: $font;
 4650: }
 4651: table#LC_helpmenu_links a:hover {
 4652:   text-decoration: underline;
 4653:   color: $vlink;
 4654: }
 4655: 
 4656: .LC_chrt_popup_exists {
 4657:   border: 1px solid #339933;
 4658:   margin: -1px;
 4659: }
 4660: .LC_chrt_popup_up {
 4661:   border: 1px solid yellow;
 4662:   margin: -1px;
 4663: }
 4664: .LC_chrt_popup {
 4665:   border: 1px solid #8888FF;
 4666:   background: #CCCCFF;
 4667: }
 4668: table.LC_pick_box {
 4669:   border-collapse: separate;
 4670:   background: white;
 4671:   border: 1px solid black;
 4672:   border-spacing: 1px;
 4673: }
 4674: table.LC_pick_box td.LC_pick_box_title {
 4675:   background: $tabbg;
 4676:   font-weight: bold;
 4677:   text-align: right;
 4678:   width: 184px;
 4679:   padding: 8px;
 4680: }
 4681: table.LC_pick_box td.LC_pick_box_value {
 4682:   text-align: left;
 4683:   padding: 8px;
 4684: }
 4685: table.LC_pick_box td.LC_pick_box_select {
 4686:   text-align: left;
 4687:   padding: 8px;
 4688: }
 4689: table.LC_pick_box td.LC_pick_box_separator {
 4690:   padding: 0px;
 4691:   height: 1px;
 4692:   background: black;
 4693: }
 4694: table.LC_pick_box td.LC_pick_box_submit {
 4695:   text-align: right;
 4696: }
 4697: table.LC_pick_box td.LC_evenrow_value {
 4698:   text-align: left;
 4699:   padding: 8px;
 4700:   background-color: $data_table_light;
 4701: }
 4702: table.LC_pick_box td.LC_oddrow_value {
 4703:   text-align: left;
 4704:   padding: 8px;
 4705:   background-color: $data_table_light;
 4706: }
 4707: table.LC_helpform_receipt {
 4708:   width: 620px;
 4709:   border-collapse: separate;
 4710:   background: white;
 4711:   border: 1px solid black;
 4712:   border-spacing: 1px;
 4713: }
 4714: table.LC_helpform_receipt td.LC_pick_box_title {
 4715:   background: $tabbg;
 4716:   font-weight: bold;
 4717:   text-align: right;
 4718:   width: 184px;
 4719:   padding: 8px;
 4720: }
 4721: table.LC_helpform_receipt td.LC_evenrow_value {
 4722:   text-align: left;
 4723:   padding: 8px;
 4724:   background-color: $data_table_light;
 4725: }
 4726: table.LC_helpform_receipt td.LC_oddrow_value {
 4727:   text-align: left;
 4728:   padding: 8px;
 4729:   background-color: $data_table_light;
 4730: }
 4731: table.LC_helpform_receipt td.LC_pick_box_separator {
 4732:   padding: 0px;
 4733:   height: 1px;
 4734:   background: black;
 4735: }
 4736: span.LC_helpform_receipt_cat {
 4737:   font-weight: bold;
 4738: }
 4739: table.LC_group_priv_box {
 4740:   background: white;
 4741:   border: 1px solid black;
 4742:   border-spacing: 1px;
 4743: }
 4744: table.LC_group_priv_box td.LC_pick_box_title {
 4745:   background: $tabbg;
 4746:   font-weight: bold;
 4747:   text-align: right;
 4748:   width: 184px;
 4749: }
 4750: table.LC_group_priv_box td.LC_groups_fixed {
 4751:   background: $data_table_light;
 4752:   text-align: center;
 4753: }
 4754: table.LC_group_priv_box td.LC_groups_optional {
 4755:   background: $data_table_dark;
 4756:   text-align: center;
 4757: }
 4758: table.LC_group_priv_box td.LC_groups_functionality {
 4759:   background: $data_table_darker;
 4760:   text-align: center;
 4761:   font-weight: bold;
 4762: }
 4763: table.LC_group_priv td {
 4764:   text-align: left;
 4765:   padding: 0px;
 4766: }
 4767: 
 4768: table.LC_notify_front_page {
 4769:   background: white;
 4770:   border: 1px solid black;
 4771:   padding: 8px;
 4772: }
 4773: table.LC_notify_front_page td {
 4774:   padding: 8px;
 4775: }
 4776: .LC_navbuttons {
 4777:   margin: 2ex 0ex 2ex 0ex;
 4778: }
 4779: .LC_topic_bar {
 4780:   font-family: $sans;
 4781:   font-weight: bold;
 4782:   width: 100%;
 4783:   background: $tabbg;
 4784:   vertical-align: middle;
 4785:   margin: 2ex 0ex 2ex 0ex;
 4786: }
 4787: .LC_topic_bar span {
 4788:   vertical-align: middle;
 4789: }
 4790: .LC_topic_bar img {
 4791:   vertical-align: bottom;
 4792: }
 4793: table.LC_course_group_status {
 4794:   margin: 20px;
 4795: }
 4796: table.LC_status_selector td {
 4797:   vertical-align: top;
 4798:   text-align: center;
 4799:   padding: 4px;
 4800: }
 4801: table.LC_descriptive_input td.LC_description {
 4802:   vertical-align: top;
 4803:   text-align: right;
 4804:   font-weight: bold;
 4805: }
 4806: table.LC_feedback_link {
 4807:     background: $feedback_link_bg;
 4808: }
 4809: span.LC_feedback_link {
 4810:     background: $feedback_link_bg;
 4811:     font-size: larger;
 4812: }
 4813: 
 4814: table.LC_prior_tries {
 4815:   border: 1px solid #000000;
 4816:   border-collapse: separate;
 4817:   border-spacing: 1px;
 4818: }
 4819: 
 4820: table.LC_prior_tries td {
 4821:   padding: 2px;
 4822: }
 4823: 
 4824: .LC_answer_correct {
 4825:   background: #AAFFAA;
 4826:   color: black;
 4827: }
 4828: .LC_answer_charged_try {
 4829:   background: #FFAAAA ! important;
 4830:   color: black;
 4831: }
 4832: .LC_answer_not_charged_try, 
 4833: .LC_answer_no_grade,
 4834: .LC_answer_late {
 4835:   background: #FFFFAA;
 4836:   color: black;
 4837: }
 4838: .LC_answer_previous {
 4839:   background: #AAAAFF;
 4840:   color: black;
 4841: }
 4842: .LC_answer_no_message {
 4843:   background: #FFFFFF;
 4844:   color: black;
 4845: }
 4846: .LC_answer_unknown {
 4847:   background: orange;
 4848:   color: black;
 4849: }
 4850: 
 4851: 
 4852: span.LC_prior_numerical,
 4853: span.LC_prior_string,
 4854: span.LC_prior_custom,
 4855: span.LC_prior_reaction,
 4856: span.LC_prior_math {
 4857:   font-family: monospace;
 4858:   white-space: pre;
 4859: }
 4860: 
 4861: span.LC_prior_string {
 4862:   font-family: monospace;
 4863:   white-space: pre;
 4864: }
 4865: 
 4866: table.LC_prior_option {
 4867:   width: 100%;
 4868:   border-collapse: collapse;
 4869: }
 4870: table.LC_prior_rank, table.LC_prior_match {
 4871:   border-collapse: collapse;
 4872: }
 4873: table.LC_prior_option tr td,
 4874: table.LC_prior_rank tr td,
 4875: table.LC_prior_match tr td {
 4876:   border: 1px solid #000000;
 4877: }
 4878: 
 4879: span.LC_nobreak {
 4880:   white-space: nowrap;
 4881: }
 4882: 
 4883: span.LC_cusr_emph {
 4884:   font-style: italic;
 4885: }
 4886: 
 4887: table.LC_docs_documents {
 4888:   background: #BBBBBB;
 4889:   border-width: 0px;
 4890:   border-collapse: collapse;
 4891: }
 4892: 
 4893: table.LC_docs_documents td.LC_docs_document {
 4894:   border: 2px solid black;
 4895:   padding: 4px;
 4896: }
 4897: 
 4898: .LC_docs_course_commands div {
 4899:   float: left;
 4900:   border: 4px solid #AAAAAA;
 4901:   padding: 4px;
 4902:   background: #DDDDCC;
 4903: }
 4904: 
 4905: .LC_docs_entry_move {
 4906:   border: 0px;
 4907:   border-collapse: collapse;
 4908: }
 4909: 
 4910: .LC_docs_entry_move td {
 4911:   border: 2px solid #BBBBBB;
 4912:   background: #DDDDDD;
 4913: }
 4914: 
 4915: .LC_docs_editor td.LC_docs_entry_commands {
 4916:   background: #DDDDDD;
 4917:   font-size: x-small;
 4918: }
 4919: .LC_docs_copy {
 4920:   color: #000099;
 4921: }
 4922: .LC_docs_cut {
 4923:   color: #550044;
 4924: }
 4925: .LC_docs_rename {
 4926:   color: #009900;
 4927: }
 4928: .LC_docs_remove {
 4929:   color: #990000;
 4930: }
 4931: 
 4932: .LC_docs_reinit_warn,
 4933: .LC_docs_ext_edit {
 4934:   font-size: x-small;
 4935: }
 4936: 
 4937: .LC_docs_editor td.LC_docs_entry_title,
 4938: .LC_docs_editor td.LC_docs_entry_icon {
 4939:   background: #FFFFBB;
 4940: }
 4941: .LC_docs_editor td.LC_docs_entry_parameter {
 4942:   background: #BBBBFF;
 4943:   font-size: x-small;
 4944:   white-space: nowrap;
 4945: }
 4946: 
 4947: table.LC_docs_adddocs td,
 4948: table.LC_docs_adddocs th {
 4949:   border: 1px solid #BBBBBB;
 4950:   padding: 4px;
 4951:   background: #DDDDDD;
 4952: }
 4953: 
 4954: table.LC_sty_begin {
 4955:   background: #BBFFBB;
 4956: }
 4957: table.LC_sty_end {
 4958:   background: #FFBBBB;
 4959: }
 4960: 
 4961: table.LC_double_column {
 4962:   border-width: 0px;
 4963:   border-collapse: collapse;
 4964:   width: 100%;
 4965:   padding: 2px;
 4966: }
 4967: 
 4968: table.LC_double_column tr td.LC_left_col {
 4969:   top: 2px;
 4970:   left: 2px;
 4971:   width: 47%;
 4972:   vertical-align: top;
 4973: }
 4974: 
 4975: table.LC_double_column tr td.LC_right_col {
 4976:   top: 2px;
 4977:   right: 2px; 
 4978:   width: 47%;
 4979:   vertical-align: top;
 4980: }
 4981: 
 4982: span.LC_role_level {
 4983:   font-weight: bold;
 4984: }
 4985: 
 4986: div.LC_left_float {
 4987:   float: left;
 4988:   padding-right: 5%;
 4989:   padding:bottom: 4px;
 4990: }
 4991: 
 4992: div.LC_clear_float_header {
 4993:   padding:bottom: 2px;
 4994: }
 4995: 
 4996: div.LC_clear_float_footer {
 4997:   padding:top: 10px;
 4998:   clear: both;
 4999: }
 5000: 
 5001: END
 5002: }
 5003: 
 5004: =pod
 5005: 
 5006: =item * &headtag()
 5007: 
 5008: Returns a uniform footer for LON-CAPA web pages.
 5009: 
 5010: Inputs: $title - optional title for the head
 5011:         $head_extra - optional extra HTML to put inside the <head>
 5012:         $args - optional arguments
 5013:             force_register - if is true call registerurl so the remote is 
 5014:                              informed
 5015:             redirect       -> array ref of
 5016:                                    1- seconds before redirect occurs
 5017:                                    2- url to redirect to
 5018:                                    3- whether the side effect should occur
 5019:                            (side effect of setting 
 5020:                                $env{'internal.head.redirect'} to the url 
 5021:                                redirected too)
 5022:             domain         -> force to color decorate a page for a specific
 5023:                                domain
 5024:             function       -> force usage of a specific rolish color scheme
 5025:             bgcolor        -> override the default page bgcolor
 5026:             no_auto_mt_title
 5027:                            -> prevent &mt()ing the title arg
 5028: 
 5029: =cut
 5030: 
 5031: sub headtag {
 5032:     my ($title,$head_extra,$args) = @_;
 5033:     
 5034:     my $function = $args->{'function'} || &get_users_function();
 5035:     my $domain   = $args->{'domain'}   || &determinedomain();
 5036:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 5037:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 5038: 		   $Apache::lonnet::perlvar{'lonVersion'},
 5039: 		   #time(),
 5040: 		   $env{'environment.color.timestamp'},
 5041: 		   $function,$domain,$bgcolor);
 5042: 
 5043:     $url = '/adm/css/'.&escape($url).'.css';
 5044: 
 5045:     my $result =
 5046: 	'<head>'.
 5047: 	&font_settings();
 5048: 
 5049:     if (!$args->{'frameset'}) {
 5050: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 5051:     }
 5052:     if ($args->{'force_register'}) {
 5053: 	$result .= &Apache::lonmenu::registerurl(1);
 5054:     }
 5055:     if (!$args->{'no_nav_bar'} 
 5056: 	&& !$args->{'only_body'}
 5057: 	&& !$args->{'frameset'}) {
 5058: 	$result .= &help_menu_js();
 5059:     }
 5060: 
 5061:     if (ref($args->{'redirect'})) {
 5062: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 5063: 	$url = &Apache::lonenc::check_encrypt($url);
 5064: 	if (!$inhibit_continue) {
 5065: 	    $env{'internal.head.redirect'} = $url;
 5066: 	}
 5067: 	$result.=<<ADDMETA
 5068: <meta http-equiv="pragma" content="no-cache" />
 5069: <meta http-equiv="Refresh" content="$time; url=$url" />
 5070: ADDMETA
 5071:     }
 5072:     if (!defined($title)) {
 5073: 	$title = 'The LearningOnline Network with CAPA';
 5074:     }
 5075:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5076:     $result .= '<title> LON-CAPA '.$title.'</title>'
 5077: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 5078: 	.$head_extra;
 5079:     return $result;
 5080: }
 5081: 
 5082: =pod
 5083: 
 5084: =item * &font_settings()
 5085: 
 5086: Returns neccessary <meta> to set the proper encoding
 5087: 
 5088: Inputs: none
 5089: 
 5090: =cut
 5091: 
 5092: sub font_settings {
 5093:     my $headerstring='';
 5094:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
 5095: 	$headerstring.=
 5096: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
 5097:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 5098: 	$headerstring.=
 5099: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 5100:     }
 5101:     return $headerstring;
 5102: }
 5103: 
 5104: =pod
 5105: 
 5106: =item * &xml_begin()
 5107: 
 5108: Returns the needed doctype and <html>
 5109: 
 5110: Inputs: none
 5111: 
 5112: =cut
 5113: 
 5114: sub xml_begin {
 5115:     my $output='';
 5116: 
 5117:     if ($env{'internal.start_page'}==1) {
 5118: 	&Apache::lonhtmlcommon::init_htmlareafields();
 5119:     }
 5120: 
 5121:     if ($env{'browser.mathml'}) {
 5122: 	$output='<?xml version="1.0"?>'
 5123:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 5124: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 5125:             
 5126: #	    .'<!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">] >'
 5127: 	    .'<!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">'
 5128:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 5129: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 5130:     } else {
 5131: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 5132:     }
 5133:     return $output;
 5134: }
 5135: 
 5136: =pod
 5137: 
 5138: =item * &endheadtag()
 5139: 
 5140: Returns a uniform </head> for LON-CAPA web pages.
 5141: 
 5142: Inputs: none
 5143: 
 5144: =cut
 5145: 
 5146: sub endheadtag {
 5147:     return '</head>';
 5148: }
 5149: 
 5150: =pod
 5151: 
 5152: =item * &head()
 5153: 
 5154: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 5155: 
 5156: Inputs: $title - optional title for the page
 5157:         $head_extra - optional extra HTML to put inside the <head>
 5158: 
 5159: =cut
 5160: 
 5161: sub head {
 5162:     my ($title,$head_extra,$args) = @_;
 5163:     return &headtag($title,$head_extra,$args).&endheadtag();
 5164: }
 5165: 
 5166: =pod
 5167: 
 5168: =item * &start_page()
 5169: 
 5170: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 5171: 
 5172: Inputs: $title - optional title for the page
 5173:         $head_extra - optional extra HTML to incude inside the <head>
 5174:         $args - additional optional args supported are:
 5175:                   only_body      -> is true will set &bodytag() onlybodytag
 5176:                                     arg on
 5177:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
 5178:                   add_entries    -> additional attributes to add to the  <body>
 5179:                   domain         -> force to color decorate a page for a 
 5180:                                     specific domain
 5181:                   function       -> force usage of a specific rolish color
 5182:                                     scheme
 5183:                   redirect       -> see &headtag()
 5184:                   bgcolor        -> override the default page bg color
 5185:                   js_ready       -> return a string ready for being used in 
 5186:                                     a javascript writeln
 5187:                   html_encode    -> return a string ready for being used in 
 5188:                                     a html attribute
 5189:                   force_register -> if is true will turn on the &bodytag()
 5190:                                     $forcereg arg
 5191:                   body_title     -> alternate text to use instead of $title
 5192:                                     in the title box that appears, this text
 5193:                                     is not auto translated like the $title is
 5194:                   frameset       -> if true will start with a <frameset>
 5195:                                     rather than <body>
 5196:                   no_title       -> if true the title bar won't be shown
 5197:                   skip_phases    -> hash ref of 
 5198:                                     head -> skip the <html><head> generation
 5199:                                     body -> skip all <body> generation
 5200: 
 5201:                   no_inline_link -> if true and in remote mode, don't show the 
 5202:                                     'Switch To Inline Menu' link
 5203: 
 5204:                   no_auto_mt_title -> prevent &mt()ing the title arg
 5205: 
 5206:                   inherit_jsmath -> when creating popup window in a page,
 5207:                                     should it have jsmath forced on by the
 5208:                                     current page
 5209: 
 5210: =cut
 5211: 
 5212: sub start_page {
 5213:     my ($title,$head_extra,$args) = @_;
 5214:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 5215:     my %head_args;
 5216:     foreach my $arg ('redirect','force_register','domain','function',
 5217: 		     'bgcolor','frameset','no_nav_bar','only_body',
 5218: 		     'no_auto_mt_title') {
 5219: 	if (defined($args->{$arg})) {
 5220: 	    $head_args{$arg} = $args->{$arg};
 5221: 	}
 5222:     }
 5223: 
 5224:     $env{'internal.start_page'}++;
 5225:     my $result;
 5226:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 5227: 	$result.=
 5228: 	    &xml_begin().
 5229: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 5230:     }
 5231:     
 5232:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 5233: 	if ($args->{'frameset'}) {
 5234: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 5235: 						$args->{'add_entries'});
 5236: 	    $result .= "\n<frameset $attr_string>\n";
 5237: 	} else {
 5238: 	    $result .=
 5239: 		&bodytag($title, 
 5240: 			 $args->{'function'},       $args->{'add_entries'},
 5241: 			 $args->{'only_body'},      $args->{'domain'},
 5242: 			 $args->{'force_register'}, $args->{'body_title'},
 5243: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 5244: 			 $args->{'no_title'},       $args->{'no_inline_link'},
 5245: 			 $args);
 5246: 	}
 5247:     }
 5248: 
 5249:     if ($args->{'js_ready'}) {
 5250: 	$result = &js_ready($result);
 5251:     }
 5252:     if ($args->{'html_encode'}) {
 5253: 	$result = &html_encode($result);
 5254:     }
 5255:     return $result;
 5256: }
 5257: 
 5258: 
 5259: =pod
 5260: 
 5261: =item * &head()
 5262: 
 5263: Returns a complete </body></html> section for LON-CAPA web pages.
 5264: 
 5265: Inputs:         $args - additional optional args supported are:
 5266:                  js_ready     -> return a string ready for being used in 
 5267:                                  a javascript writeln
 5268:                  html_encode  -> return a string ready for being used in 
 5269:                                  a html attribute
 5270:                  frameset     -> if true will start with a <frameset>
 5271:                                  rather than <body>
 5272:                  dicsussion   -> if true will get discussion from
 5273:                                   lonxml::xmlend
 5274:                                  (you can pass the target and parser arguments
 5275:                                   through optional 'target' and 'parser' args
 5276:                                   to this routine)
 5277: 
 5278: =cut
 5279: 
 5280: sub end_page {
 5281:     my ($args) = @_;
 5282:     $env{'internal.end_page'}++;
 5283:     my $result;
 5284:     if ($args->{'discussion'}) {
 5285: 	my ($target,$parser);
 5286: 	if (ref($args->{'discussion'})) {
 5287: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 5288: 				$args->{'discussion'}{'parser'});
 5289: 	}
 5290: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 5291:     }
 5292: 
 5293:     if ($args->{'frameset'}) {
 5294: 	$result .= '</frameset>';
 5295:     } else {
 5296: 	$result .= &endbodytag();
 5297:     }
 5298:     $result .= "\n</html>";
 5299: 
 5300:     if ($args->{'js_ready'}) {
 5301: 	$result = &js_ready($result);
 5302:     }
 5303: 
 5304:     if ($args->{'html_encode'}) {
 5305: 	$result = &html_encode($result);
 5306:     }
 5307: 
 5308:     return $result;
 5309: }
 5310: 
 5311: sub html_encode {
 5312:     my ($result) = @_;
 5313: 
 5314:     $result = &HTML::Entities::encode($result,'<>&"');
 5315:     
 5316:     return $result;
 5317: }
 5318: sub js_ready {
 5319:     my ($result) = @_;
 5320: 
 5321:     $result =~ s/[\n\r]/ /xmsg;
 5322:     $result =~ s/\\/\\\\/xmsg;
 5323:     $result =~ s/'/\\'/xmsg;
 5324:     $result =~ s{</}{<\\/}xmsg;
 5325:     
 5326:     return $result;
 5327: }
 5328: 
 5329: sub validate_page {
 5330:     if (  exists($env{'internal.start_page'})
 5331: 	  &&     $env{'internal.start_page'} > 1) {
 5332: 	&Apache::lonnet::logthis('start_page called multiple times '.
 5333: 				 $env{'internal.start_page'}.' '.
 5334: 				 $ENV{'request.filename'});
 5335:     }
 5336:     if (  exists($env{'internal.end_page'})
 5337: 	  &&     $env{'internal.end_page'} > 1) {
 5338: 	&Apache::lonnet::logthis('end_page called multiple times '.
 5339: 				 $env{'internal.end_page'}.' '.
 5340: 				 $env{'request.filename'});
 5341:     }
 5342:     if (     exists($env{'internal.start_page'})
 5343: 	&& ! exists($env{'internal.end_page'})) {
 5344: 	&Apache::lonnet::logthis('start_page called without end_page '.
 5345: 				 $env{'request.filename'});
 5346:     }
 5347:     if (   ! exists($env{'internal.start_page'})
 5348: 	&&   exists($env{'internal.end_page'})) {
 5349: 	&Apache::lonnet::logthis('end_page called without start_page'.
 5350: 				 $env{'request.filename'});
 5351:     }
 5352: }
 5353: 
 5354: sub simple_error_page {
 5355:     my ($r,$title,$msg) = @_;
 5356:     my $page =
 5357: 	&Apache::loncommon::start_page($title).
 5358: 	&mt($msg).
 5359: 	&Apache::loncommon::end_page();
 5360:     if (ref($r)) {
 5361: 	$r->print($page);
 5362: 	return;
 5363:     }
 5364:     return $page;
 5365: }
 5366: 
 5367: {
 5368:     my $row_count;
 5369:     sub start_data_table {
 5370: 	my ($add_class) = @_;
 5371: 	my $css_class = (join(' ','LC_data_table',$add_class));
 5372: 	undef($row_count);
 5373: 	return '<table class="'.$css_class.'">'."\n";
 5374:     }
 5375: 
 5376:     sub end_data_table {
 5377: 	undef($row_count);
 5378: 	return '</table>'."\n";;
 5379:     }
 5380: 
 5381:     sub start_data_table_row {
 5382: 	my ($add_class) = @_;
 5383: 	$row_count++;
 5384: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
 5385: 	$css_class = (join(' ',$css_class,$add_class));
 5386: 	return  '<tr class="'.$css_class.'">'."\n";;
 5387:     }
 5388:     
 5389:     sub continue_data_table_row {
 5390: 	my ($add_class) = @_;
 5391: 	my $css_class = ($row_count % 2)?'':'LC_even_row';
 5392: 	$css_class = (join(' ',$css_class,$add_class));
 5393: 	return  '<tr class="'.$css_class.'">'."\n";;
 5394:     }
 5395: 
 5396:     sub end_data_table_row {
 5397: 	return '</tr>'."\n";;
 5398:     }
 5399: 
 5400:     sub start_data_table_empty_row {
 5401: 	$row_count++;
 5402: 	return  '<tr class="LC_empty_row" >'."\n";;
 5403:     }
 5404: 
 5405:     sub end_data_table_empty_row {
 5406: 	return '</tr>'."\n";;
 5407:     }
 5408: 
 5409:     sub start_data_table_header_row {
 5410: 	return  '<tr class="LC_header_row">'."\n";;
 5411:     }
 5412: 
 5413:     sub end_data_table_header_row {
 5414: 	return '</tr>'."\n";;
 5415:     }
 5416: }
 5417: 
 5418: =pod
 5419: 
 5420: =item * &inhibit_menu_check($arg)
 5421: 
 5422: Checks for a inhibitmenu state and generates output to preserve it
 5423: 
 5424: Inputs:         $arg - can be any of
 5425:                      - undef - in which case the return value is a string 
 5426:                                to add  into arguments list of a uri
 5427:                      - 'input' - in which case the return value is a HTML
 5428:                                  <form> <input> field of type hidden to
 5429:                                  preserve the value
 5430:                      - a url - in which case the return value is the url with
 5431:                                the neccesary cgi args added to preserve the
 5432:                                inhibitmenu state
 5433:                      - a ref to a url - no return value, but the string is
 5434:                                         updated to include the neccessary cgi
 5435:                                         args to preserve the inhibitmenu state
 5436: 
 5437: =cut
 5438: 
 5439: sub inhibit_menu_check {
 5440:     my ($arg) = @_;
 5441:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5442:     if ($arg eq 'input') {
 5443: 	if ($env{'form.inhibitmenu'}) {
 5444: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 5445: 	} else {
 5446: 	    return
 5447: 	}
 5448:     }
 5449:     if ($env{'form.inhibitmenu'}) {
 5450: 	if (ref($arg)) {
 5451: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5452: 	} elsif ($arg eq '') {
 5453: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 5454: 	} else {
 5455: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 5456: 	}
 5457:     }
 5458:     if (!ref($arg)) {
 5459: 	return $arg;
 5460:     }
 5461: }
 5462: 
 5463: ###############################################
 5464: 
 5465: =pod
 5466: 
 5467: =back
 5468: 
 5469: =head1 User Information Routines
 5470: 
 5471: =over 4
 5472: 
 5473: =item * &get_users_function()
 5474: 
 5475: Used by &bodytag to determine the current users primary role.
 5476: Returns either 'student','coordinator','admin', or 'author'.
 5477: 
 5478: =cut
 5479: 
 5480: ###############################################
 5481: sub get_users_function {
 5482:     my $function = 'student';
 5483:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 5484:         $function='coordinator';
 5485:     }
 5486:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 5487:         $function='admin';
 5488:     }
 5489:     if (($env{'request.role'}=~/^(au|ca)/) ||
 5490:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 5491:         $function='author';
 5492:     }
 5493:     return $function;
 5494: }
 5495: 
 5496: ###############################################
 5497: 
 5498: =pod
 5499: 
 5500: =item * &check_user_status()
 5501: 
 5502: Determines current status of supplied role for a
 5503: specific user. Roles can be active, previous or future.
 5504: 
 5505: Inputs: 
 5506: user's domain, user's username, course's domain,
 5507: course's number, optional section ID.
 5508: 
 5509: Outputs:
 5510: role status: active, previous or future. 
 5511: 
 5512: =cut
 5513: 
 5514: sub check_user_status {
 5515:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 5516:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 5517:     my @uroles = keys %userinfo;
 5518:     my $srchstr;
 5519:     my $active_chk = 'none';
 5520:     my $now = time;
 5521:     if (@uroles > 0) {
 5522:         if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
 5523:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 5524:         } else {
 5525:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 5526:         }
 5527:         if (grep/^\Q$srchstr\E$/,@uroles) {
 5528:             my $role_end = 0;
 5529:             my $role_start = 0;
 5530:             $active_chk = 'active';
 5531:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 5532:                 $role_end = $1;
 5533:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 5534:                     $role_start = $1;
 5535:                 }
 5536:             }
 5537:             if ($role_start > 0) {
 5538:                 if ($now < $role_start) {
 5539:                     $active_chk = 'future';
 5540:                 }
 5541:             }
 5542:             if ($role_end > 0) {
 5543:                 if ($now > $role_end) {
 5544:                     $active_chk = 'previous';
 5545:                 }
 5546:             }
 5547:         }
 5548:     }
 5549:     return $active_chk;
 5550: }
 5551: 
 5552: ###############################################
 5553: 
 5554: =pod
 5555: 
 5556: =item * &get_sections()
 5557: 
 5558: Determines all the sections for a course including
 5559: sections with students and sections containing other roles.
 5560: Incoming parameters: 
 5561: 
 5562: 1. domain
 5563: 2. course number 
 5564: 3. reference to array containing roles for which sections should 
 5565: be gathered (optional).
 5566: 4. reference to array containing status types for which sections 
 5567: should be gathered (optional).
 5568: 
 5569: If the third argument is undefined, sections are gathered for any role. 
 5570: If the fourth argument is undefined, sections are gathered for any status.
 5571: Permissible values are 'active' or 'future' or 'previous'.
 5572:  
 5573: Returns section hash (keys are section IDs, values are
 5574: number of users in each section), subject to the
 5575: optional roles filter, optional status filter 
 5576: 
 5577: =cut
 5578: 
 5579: ###############################################
 5580: sub get_sections {
 5581:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 5582:     if (!defined($cdom) || !defined($cnum)) {
 5583:         my $cid =  $env{'request.course.id'};
 5584: 
 5585: 	return if (!defined($cid));
 5586: 
 5587:         $cdom = $env{'course.'.$cid.'.domain'};
 5588:         $cnum = $env{'course.'.$cid.'.num'};
 5589:     }
 5590: 
 5591:     my %sectioncount;
 5592:     my $now = time;
 5593: 
 5594:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 5595: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 5596: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 5597: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 5598:         my $start_index = &Apache::loncoursedata::CL_START();
 5599:         my $end_index = &Apache::loncoursedata::CL_END();
 5600:         my $status;
 5601: 	while (my ($student,$data) = each(%$classlist)) {
 5602: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 5603: 				                     $data->[$status_index],
 5604:                                                      $data->[$start_index],
 5605:                                                      $data->[$end_index]);
 5606:             if ($stu_status eq 'Active') {
 5607:                 $status = 'active';
 5608:             } elsif ($end < $now) {
 5609:                 $status = 'previous';
 5610:             } elsif ($start > $now) {
 5611:                 $status = 'future';
 5612:             } 
 5613: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 5614:                 if ((!defined($possible_status)) || (($status ne '') && 
 5615:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 5616: 		    $sectioncount{$section}++;
 5617:                 }
 5618: 	    }
 5619: 	}
 5620:     }
 5621:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 5622:     foreach my $user (sort(keys(%courseroles))) {
 5623: 	if ($user !~ /^(\w{2})/) { next; }
 5624: 	my ($role) = ($user =~ /^(\w{2})/);
 5625: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 5626: 	my ($section,$status);
 5627: 	if ($role eq 'cr' &&
 5628: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 5629: 	    $section=$1;
 5630: 	}
 5631: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 5632: 	if (!defined($section) || $section eq '-1') { next; }
 5633:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 5634:         if ($end == -1 && $start == -1) {
 5635:             next; #deleted role
 5636:         }
 5637:         if (!defined($possible_status)) { 
 5638:             $sectioncount{$section}++;
 5639:         } else {
 5640:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 5641:                 $status = 'active';
 5642:             } elsif ($end < $now) {
 5643:                 $status = 'future';
 5644:             } elsif ($start > $now) {
 5645:                 $status = 'previous';
 5646:             }
 5647:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 5648:                 $sectioncount{$section}++;
 5649:             }
 5650:         }
 5651:     }
 5652:     return %sectioncount;
 5653: }
 5654: 
 5655: ###############################################
 5656: 
 5657: =pod
 5658: 
 5659: =item * &get_course_users()
 5660: 
 5661: Retrieves usernames:domains for users in the specified course
 5662: with specific role(s), and access status. 
 5663: 
 5664: Incoming parameters:
 5665: 1. course domain
 5666: 2. course number
 5667: 3. access status: users must have - either active, 
 5668: previous, future, or all.
 5669: 4. reference to array of permissible roles
 5670: 5. reference to array of section restrictions (optional)
 5671: 6. reference to results object (hash of hashes).
 5672: 7. reference to optional userdata hash
 5673: Keys of top level hash are roles.
 5674: Keys of inner hashes are username:domain, with 
 5675: values set to access type.
 5676: Optional userdata hash returns an array with arguments in the 
 5677: same order as loncoursedata::get_classlist() for student data.
 5678: 
 5679: Entries for end, start, section and status are blank because
 5680: of the possibility of multiple values for non-student roles.
 5681: 
 5682: =cut
 5683: 
 5684: ###############################################
 5685: 
 5686: sub get_course_users {
 5687:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
 5688:     my %idx = ();
 5689:     my %seclists;
 5690: 
 5691:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 5692:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 5693:     $idx{end} = &Apache::loncoursedata::CL_END();
 5694:     $idx{start} = &Apache::loncoursedata::CL_START();
 5695:     $idx{id} = &Apache::loncoursedata::CL_ID();
 5696:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 5697:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 5698:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 5699: 
 5700:     if (grep(/^st$/,@{$roles})) {
 5701:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 5702:         my $now = time;
 5703:         foreach my $student (keys(%{$classlist})) {
 5704:             my $match = 0;
 5705:             my $secmatch = 0;
 5706:             my $section = $$classlist{$student}[$idx{section}];
 5707:             if ($section eq '') {
 5708:                 $section = 'none';
 5709:             }
 5710:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 5711:                 if (grep(/^all$/,@{$sections})) {
 5712:                     $secmatch = 1;
 5713:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 5714:                     if (grep(/^none$/,@{$sections})) {
 5715:                         $secmatch = 1;
 5716:                     }
 5717:                 } else {  
 5718: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 5719: 		        $secmatch = 1;
 5720:                     }
 5721: 		}
 5722:                 if (!$secmatch) {
 5723:                     next;
 5724:                 }
 5725:             }
 5726:             push(@{$seclists{$student}},$section); 
 5727:             if (defined($$types{'active'})) {
 5728:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 5729:                     push(@{$$users{st}{$student}},'active');
 5730:                     $match = 1;
 5731:                 }
 5732:             }
 5733:             if (defined($$types{'previous'})) {
 5734:                 if ($$classlist{$student}[$idx{end}] <= $now) {
 5735:                     push(@{$$users{st}{$student}},'previous');
 5736:                     $match = 1;
 5737:                 }
 5738:             }
 5739:             if (defined($$types{'future'})) {
 5740:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
 5741:                     push(@{$$users{st}{$student}},'future');
 5742:                     $match = 1;
 5743:                 }
 5744:             }
 5745:             if ($match && ref($userdata) eq 'HASH') {
 5746:                 $$userdata{$student} = $$classlist{$student};
 5747:             }
 5748:         }
 5749:     }
 5750:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 5751:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 5752:         my $now = time;
 5753:         foreach my $person (sort(keys(%coursepersonnel))) {
 5754:             my $match = 0;
 5755:             my $secmatch = 0;
 5756:             my $status;
 5757:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 5758:             $user =~ s/:$//;
 5759:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 5760:             if ($end == -1 || $start == -1) {
 5761:                 next;
 5762:             }
 5763:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 5764:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 5765:                 my ($uname,$udom) = split(/:/,$user);
 5766:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 5767:                     if (grep(/^all$/,@{$sections})) {
 5768:                         $secmatch = 1;
 5769:                     } elsif ($usec eq '') {
 5770:                         if (grep(/^none$/,@{$sections})) {
 5771:                             $secmatch = 1;
 5772:                         }
 5773:                     } else {
 5774:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 5775:                             $secmatch = 1;
 5776:                         }
 5777:                     }
 5778:                     if (!$secmatch) {
 5779:                         next;
 5780:                     }
 5781:                 }
 5782:                 if ($usec eq '') {
 5783:                     $usec = 'none';
 5784:                 }
 5785:                 if ($uname ne '' && $udom ne '') {
 5786:                     if ($end > 0 && $end < $now) {
 5787:                         $status = 'previous';
 5788:                     } elsif ($start > $now) {
 5789:                         $status = 'future';
 5790:                     } else {
 5791:                         $status = 'active';
 5792:                     }
 5793:                     foreach my $type (keys(%{$types})) { 
 5794:                         if ($status eq $type) {
 5795:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 5796:                                 push(@{$$users{$role}{$user}},$type);
 5797:                             }
 5798:                             $match = 1;
 5799:                         }
 5800:                     }
 5801:                     if (($match) && (ref($userdata) eq 'HASH')) {
 5802:                         if (!exists($$userdata{$uname.':'.$udom})) {
 5803: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 5804:                         }
 5805:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 5806:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 5807:                         }
 5808:                     }
 5809:                 }
 5810:             }
 5811:         }
 5812:         if (grep(/^ow$/,@{$roles})) {
 5813:             if ((defined($cdom)) && (defined($cnum))) {
 5814:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 5815:                 if ( defined($csettings{'internal.courseowner'}) ) {
 5816:                     my $owner = $csettings{'internal.courseowner'};
 5817:                     if ($owner !~ /^[^:]+:[^:]+$/) {
 5818:                         $owner = $owner.':'.$cdom;
 5819:                     }
 5820:                     @{$$users{'ow'}{$owner}} = 'any';
 5821:                     if (defined($userdata) && 
 5822: 			!exists($$userdata{$owner.':'.$cdom})) {
 5823: 			&get_user_info($cdom,$owner,\%idx,$userdata);
 5824:                         if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
 5825:                             push(@{$seclists{$owner.':'.$cdom}},'none');
 5826:                         }
 5827: 		    }
 5828:                 }
 5829:             }
 5830:         }
 5831:         foreach my $user (keys(%seclists)) {
 5832:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 5833:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 5834:         }
 5835:     }
 5836:     return;
 5837: }
 5838: 
 5839: sub get_user_info {
 5840:     my ($udom,$uname,$idx,$userdata) = @_;
 5841:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 5842: 	&plainname($uname,$udom,'lastname');
 5843:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 5844:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 5845:     return;
 5846: }
 5847: 
 5848: ###############################################
 5849: 
 5850: =pod
 5851: 
 5852: =item * &get_user_quota()
 5853: 
 5854: Retrieves quota assigned for storage of portfolio files for a user  
 5855: 
 5856: Incoming parameters:
 5857: 1. user's username
 5858: 2. user's domain
 5859: 
 5860: Returns:
 5861: 1. Disk quota (in Mb) assigned to student.
 5862: 2. (Optional) Type of setting: custom or default
 5863:    (individually assigned or default for user's 
 5864:    institutional status).
 5865: 3. (Optional) - User's institutional status (e.g., faculty, staff
 5866:    or student - types as defined in localenroll::inst_usertypes 
 5867:    for user's domain, which determines default quota for user.
 5868: 4. (Optional) - Default quota which would apply to the user.
 5869: 
 5870: If a value has been stored in the user's environment, 
 5871: it will return that, otherwise it returns the maximal default
 5872: defined for the user's instituional status(es) in the domain.
 5873: 
 5874: =cut
 5875: 
 5876: ###############################################
 5877: 
 5878: 
 5879: sub get_user_quota {
 5880:     my ($uname,$udom) = @_;
 5881:     my ($quota,$quotatype,$settingstatus,$defquota);
 5882:     if (!defined($udom)) {
 5883:         $udom = $env{'user.domain'};
 5884:     }
 5885:     if (!defined($uname)) {
 5886:         $uname = $env{'user.name'};
 5887:     }
 5888:     if (($udom eq '' || $uname eq '') ||
 5889:         ($udom eq 'public') && ($uname eq 'public')) {
 5890:         $quota = 0;
 5891:         $quotatype = 'default';
 5892:         $defquota = 0; 
 5893:     } else {
 5894:         my $inststatus;
 5895:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 5896:             $quota = $env{'environment.portfolioquota'};
 5897:             $inststatus = $env{'environment.inststatus'};
 5898:         } else {
 5899:             my %userenv = 
 5900:                 &Apache::lonnet::get('environment',['portfolioquota',
 5901:                                      'inststatus'],$udom,$uname);
 5902:             my ($tmp) = keys(%userenv);
 5903:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5904:                 $quota = $userenv{'portfolioquota'};
 5905:                 $inststatus = $userenv{'inststatus'};
 5906:             } else {
 5907:                 undef(%userenv);
 5908:             }
 5909:         }
 5910:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 5911:         if ($quota eq '') {
 5912:             $quota = $defquota;
 5913:             $quotatype = 'default';
 5914:         } else {
 5915:             $quotatype = 'custom';
 5916:         }
 5917:     }
 5918:     if (wantarray) {
 5919:         return ($quota,$quotatype,$settingstatus,$defquota);
 5920:     } else {
 5921:         return $quota;
 5922:     }
 5923: }
 5924: 
 5925: ###############################################
 5926: 
 5927: =pod
 5928: 
 5929: =item * &default_quota()
 5930: 
 5931: Retrieves default quota assigned for storage of user portfolio files,
 5932: given an (optional) user's institutional status.
 5933: 
 5934: Incoming parameters:
 5935: 1. domain
 5936: 2. (Optional) institutional status(es).  This is a : separated list of 
 5937:    status types (e.g., faculty, staff, student etc.)
 5938:    which apply to the user for whom the default is being retrieved.
 5939:    If the institutional status string in undefined, the domain
 5940:    default quota will be returned. 
 5941: 
 5942: Returns:
 5943: 1. Default disk quota (in Mb) for user portfolios in the domain.
 5944: 2. (Optional) institutional type which determined the value of the
 5945:    default quota.
 5946: 
 5947: If a value has been stored in the domain's configuration db,
 5948: it will return that, otherwise it returns 20 (for backwards 
 5949: compatibility with domains which have not set up a configuration
 5950: db file; the original statically defined portfolio quota was 20 Mb). 
 5951: 
 5952: If the user's status includes multiple types (e.g., staff and student),
 5953: the largest default quota which applies to the user determines the
 5954: default quota returned.
 5955: 
 5956: =cut
 5957: 
 5958: ###############################################
 5959: 
 5960: 
 5961: sub default_quota {
 5962:     my ($udom,$inststatus) = @_;
 5963:     my ($defquota,$settingstatus);
 5964:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 5965:                                             ['quota'],$udom);
 5966:     if (ref($quotahash{'quota'}) eq 'HASH') {
 5967:         if ($inststatus ne '') {
 5968:             my @statuses = split(/:/,$inststatus);
 5969:             foreach my $item (@statuses) {
 5970:                 if ($quotahash{'quota'}{$item} ne '') {
 5971:                     if ($defquota eq '') {
 5972:                         $defquota = $quotahash{'quota'}{$item};
 5973:                         $settingstatus = $item;
 5974:                     } elsif ($quotahash{'quota'}{$item} > $defquota) {
 5975:                         $defquota = $quotahash{'quota'}{$item};
 5976:                         $settingstatus = $item;
 5977:                     }
 5978:                 }
 5979:             }
 5980:         }
 5981:         if ($defquota eq '') {
 5982:             $defquota = $quotahash{'quota'}{'default'};
 5983:             $settingstatus = 'default';
 5984:         }
 5985:     } else {
 5986:         $settingstatus = 'default';
 5987:         $defquota = 20;
 5988:     }
 5989:     if (wantarray) {
 5990:         return ($defquota,$settingstatus);
 5991:     } else {
 5992:         return $defquota;
 5993:     }
 5994: }
 5995: 
 5996: sub get_secgrprole_info {
 5997:     my ($cdom,$cnum,$needroles,$type)  = @_;
 5998:     my %sections_count = &get_sections($cdom,$cnum);
 5999:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 6000:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 6001:     my @groups = sort(keys(%curr_groups));
 6002:     my $allroles = [];
 6003:     my $rolehash;
 6004:     my $accesshash = {
 6005:                      active => 'Currently has access',
 6006:                      future => 'Will have future access',
 6007:                      previous => 'Previously had access',
 6008:                   };
 6009:     if ($needroles) {
 6010:         $rolehash = {'all' => 'all'};
 6011:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 6012: 	if (&Apache::lonnet::error(%user_roles)) {
 6013: 	    undef(%user_roles);
 6014: 	}
 6015:         foreach my $item (keys(%user_roles)) {
 6016:             my ($role)=split(/\:/,$item,2);
 6017:             if ($role eq 'cr') { next; }
 6018:             if ($role =~ /^cr/) {
 6019:                 $$rolehash{$role} = (split('/',$role))[3];
 6020:             } else {
 6021:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 6022:             }
 6023:         }
 6024:         foreach my $key (sort(keys(%{$rolehash}))) {
 6025:             push(@{$allroles},$key);
 6026:         }
 6027:         push (@{$allroles},'st');
 6028:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 6029:     }
 6030:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 6031: }
 6032: 
 6033: sub user_picker {
 6034:     my ($dom,$srch,$forcenewuser,$caller) = @_;
 6035:     my $currdom = $dom;
 6036:     my %curr_selected = (
 6037:                         srchin => 'dom',
 6038:                         srchby => 'lastname',
 6039:                       );
 6040:     my $srchterm;
 6041:     if (ref($srch) eq 'HASH') {
 6042:         if ($srch->{'srchby'} ne '') {
 6043:             $curr_selected{'srchby'} = $srch->{'srchby'};
 6044:         }
 6045:         if ($srch->{'srchin'} ne '') {
 6046:             $curr_selected{'srchin'} = $srch->{'srchin'};
 6047:         }
 6048:         if ($srch->{'srchtype'} ne '') {
 6049:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 6050:         }
 6051:         if ($srch->{'srchdomain'} ne '') {
 6052:             $currdom = $srch->{'srchdomain'};
 6053:         }
 6054:         $srchterm = $srch->{'srchterm'};
 6055:     }
 6056:     my %lt=&Apache::lonlocal::texthash(
 6057:                     'usr'       => 'Search criteria',
 6058:                     'doma'      => 'Domain/institution to search',
 6059:                     'uname'     => 'username',
 6060:                     'lastname'  => 'last name',
 6061:                     'lastfirst' => 'last name, first name',
 6062:                     'crs'       => 'in this course',
 6063:                     'dom'       => 'in selected LON-CAPA domain', 
 6064:                     'alc'       => 'all LON-CAPA',
 6065:                     'instd'     => 'in institutional directory for selected domain',
 6066:                     'exact'     => 'is',
 6067:                     'contains'  => 'contains',
 6068:                     'begins'    => 'begins with',
 6069:                     'youm'      => "You must include some text to search for.",
 6070:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 6071:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 6072:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 6073:                     'ymcd'      => "You must choose a domain when using a domain search.",
 6074:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 6075:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 6076:                      'thfo'     => "The following need to be corrected before the search can be run:",
 6077:                                        );
 6078:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 6079:     my $srchinsel = ' <select name="srchin">';
 6080: 
 6081:     my @srchins = ('crs','dom','alc','instd');
 6082: 
 6083:     foreach my $option (@srchins) {
 6084:         # FIXME 'alc' option unavailable until 
 6085:         #       loncreateuser::print_user_query_page()
 6086:         #       has been completed.
 6087:         next if ($option eq 'alc');
 6088:         next if ($option eq 'crs' && !$env{'request.course.id'});
 6089:         if ($curr_selected{'srchin'} eq $option) {
 6090:             $srchinsel .= ' 
 6091:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6092:         } else {
 6093:             $srchinsel .= '
 6094:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6095:         }
 6096:     }
 6097:     $srchinsel .= "\n  </select>\n";
 6098: 
 6099:     my $srchbysel =  ' <select name="srchby">';
 6100:     foreach my $option ('lastname','lastfirst','uname') {
 6101:         if ($curr_selected{'srchby'} eq $option) {
 6102:             $srchbysel .= '
 6103:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6104:         } else {
 6105:             $srchbysel .= '
 6106:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6107:          }
 6108:     }
 6109:     $srchbysel .= "\n  </select>\n";
 6110: 
 6111:     my $srchtypesel = ' <select name="srchtype">';
 6112:     foreach my $option ('begins','contains','exact') {
 6113:         if ($curr_selected{'srchtype'} eq $option) {
 6114:             $srchtypesel .= '
 6115:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 6116:         } else {
 6117:             $srchtypesel .= '
 6118:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 6119:         }
 6120:     }
 6121:     $srchtypesel .= "\n  </select>\n";
 6122: 
 6123:     my ($newuserscript,$new_user_create);
 6124: 
 6125:     if ($forcenewuser) {
 6126:         if (ref($srch) eq 'HASH') {
 6127:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
 6128: 	        $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>';
 6129:             }
 6130:         }
 6131: 
 6132:         $newuserscript = <<"ENDSCRIPT";
 6133: 
 6134: function setSearch(createnew,callingForm) {
 6135:     if (createnew == 1) {
 6136:         for (var i=0; i<callingForm.srchby.length; i++) {
 6137:             if (callingForm.srchby.options[i].value == 'uname') {
 6138:                 callingForm.srchby.selectedIndex = i;
 6139:             }
 6140:         }
 6141:         for (var i=0; i<callingForm.srchin.length; i++) {
 6142:             if ( callingForm.srchin.options[i].value == 'dom') {
 6143: 		callingForm.srchin.selectedIndex = i;
 6144:             }
 6145:         }
 6146:         for (var i=0; i<callingForm.srchtype.length; i++) {
 6147:             if (callingForm.srchtype.options[i].value == 'exact') {
 6148:                 callingForm.srchtype.selectedIndex = i;
 6149:             }
 6150:         }
 6151:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 6152:             if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
 6153:                 callingForm.srchdomain.selectedIndex = i;
 6154:             }
 6155:         }
 6156:     }
 6157: }
 6158: ENDSCRIPT
 6159: 
 6160:     }
 6161: 
 6162:     my $output = <<"END_BLOCK";
 6163: <script type="text/javascript">
 6164: function validateEntry(callingForm) {
 6165: 
 6166:     var checkok = 1;
 6167:     var srchin;
 6168:     for (var i=0; i<callingForm.srchin.length; i++) {
 6169: 	if ( callingForm.srchin[i].checked ) {
 6170: 	    srchin = callingForm.srchin[i].value;
 6171: 	}
 6172:     }
 6173: 
 6174:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 6175:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 6176:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 6177:     var srchterm =  callingForm.srchterm.value;
 6178:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 6179:     var msg = "";
 6180: 
 6181:     if (srchterm == "") {
 6182:         checkok = 0;
 6183:         msg += "$lt{'youm'}\\n";
 6184:     }
 6185: 
 6186:     if (srchtype== 'begins') {
 6187:         if (srchterm.length < 2) {
 6188:             checkok = 0;
 6189:             msg += "$lt{'thte'}\\n";
 6190:         }
 6191:     }
 6192: 
 6193:     if (srchtype== 'contains') {
 6194:         if (srchterm.length < 3) {
 6195:             checkok = 0;
 6196:             msg += "$lt{'thet'}\\n";
 6197:         }
 6198:     }
 6199:     if (srchin == 'instd') {
 6200:         if (srchdomain == '') {
 6201:             checkok = 0;
 6202:             msg += "$lt{'yomc'}\\n";
 6203:         }
 6204:     }
 6205:     if (srchin == 'dom') {
 6206:         if (srchdomain == '') {
 6207:             checkok = 0;
 6208:             msg += "$lt{'ymcd'}\\n";
 6209:         }
 6210:     }
 6211:     if (srchby == 'lastfirst') {
 6212:         if (srchterm.indexOf(",") == -1) {
 6213:             checkok = 0;
 6214:             msg += "$lt{'whus'}\\n";
 6215:         }
 6216:         if (srchterm.indexOf(",") == srchterm.length -1) {
 6217:             checkok = 0;
 6218:             msg += "$lt{'whse'}\\n";
 6219:         }
 6220:     }
 6221:     if (checkok == 0) {
 6222:         alert("$lt{'thfo'}\\n"+msg);
 6223:         return;
 6224:     }
 6225:     if (checkok == 1) {
 6226:         callingForm.submit();
 6227:     }
 6228: }
 6229: 
 6230: $newuserscript
 6231: 
 6232: </script>
 6233: 
 6234: $new_user_create
 6235: 
 6236: <table>
 6237:  <tr>
 6238:   <td>$lt{'doma'}:</td>
 6239:   <td>$domform</td>
 6240:   </td>
 6241:  </tr>
 6242:  <tr>
 6243:   <td>$lt{'usr'}:</td>
 6244:   <td>$srchbysel
 6245:       $srchtypesel 
 6246:       <input type="text" size="15" name="srchterm" value="$srchterm" />
 6247:       $srchinsel 
 6248:   </td>
 6249:  </tr>
 6250: </table>
 6251: <br />
 6252: END_BLOCK
 6253: 
 6254:     return $output;
 6255: }
 6256: 
 6257: sub username_rule_check {
 6258:     my ($srch,$caller) = @_;
 6259:     my ($response,@curr_rules,%inst_results,$rulematch);
 6260:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($srch->{'srchdomain'});
 6261:     if (ref($srch) eq 'HASH') {
 6262:         (my $inst_response,%inst_results) = 
 6263:             &Apache::lonnet::get_instuser($srch->{'srchdomain'},
 6264:                                           $srch->{'srchterm'});
 6265:         my %domconfig = &Apache::lonnet::get_dom('configuration',
 6266:                               ['usercreation'],$srch->{'srchdomain'});
 6267:         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6268:             if (ref($domconfig{'usercreation'}{'username_rule'}) eq 'ARRAY') {
 6269:                 @curr_rules = @{$domconfig{'usercreation'}{'username_rule'}};
 6270:             }
 6271:         }
 6272:         if (@curr_rules > 0) {
 6273:             my $domdesc = &Apache::lonnet::domain($srch->{'srchdomain'},'description');
 6274:             my $instuser_reqd;
 6275:             my %rule_check = &Apache::lonnet::inst_rulecheck($srch->{'srchdomain'},$srch->{'srchterm'},\@curr_rules);
 6276:             foreach my $rule (@curr_rules) {
 6277:                 if ($rule_check{$rule}) {
 6278:                     $rulematch = $rule;
 6279:                     if ($inst_response eq 'ok') {
 6280:                         if (keys(%inst_results) == 0) {
 6281:                             if ($caller eq 'new') {
 6282:                                 $response = &mt('The username you chose matches the format of usernames defined for <span class="LC_cusr_emph">[_1]</span>, but the user does not exist in the institutional directory.',$domdesc).'<br />'.&mt("You must choose a username with a different format -- one that will not conflict with 'official' institutional usernames.");
 6283:                             }
 6284:                         }
 6285:                     }
 6286:                     last;
 6287:                 }
 6288:             }
 6289:             if ($response) {
 6290:                 if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 6291:                     if (@{$ruleorder} > 0) {
 6292:                         $response .= '<br />'.&mt('Usernames with the following format(s) may <span class="LC_cusr_emph">only</span> be used for verified users at [_1]:',$domdesc).' <ul>';
 6293:                         foreach my $rule (@{$ruleorder}) {
 6294:                             if (grep(/^\Q$rule\E$/,@curr_rules)) {
 6295:                                 if (ref($rules->{$rule}) eq 'HASH') {
 6296:                                     $response .= '<li>'.$rules->{$rule}{'name'}.': '.
 6297:                                                  $rules->{$rule}{'desc'}.'</li>';
 6298:                                 }
 6299:                             }
 6300:                         }
 6301:                     }
 6302:                     $response .= '</ul>';
 6303:                 }
 6304:             }
 6305:         }
 6306:     }
 6307:     return ($response,$rulematch,$rules,%inst_results);
 6308: }
 6309: 
 6310: =pod
 6311: 
 6312: =back
 6313: 
 6314: =head1 HTTP Helpers
 6315: 
 6316: =over 4
 6317: 
 6318: =item * get_unprocessed_cgi($query,$possible_names)
 6319: 
 6320: Modify the %env hash to contain unprocessed CGI form parameters held in
 6321: $query.  The parameters listed in $possible_names (an array reference),
 6322: will be set in $env{'form.name'} if they do not already exist.
 6323: 
 6324: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 6325: $possible_names is an ref to an array of form element names.  As an example:
 6326: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 6327: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 6328: 
 6329: =cut
 6330: 
 6331: sub get_unprocessed_cgi {
 6332:   my ($query,$possible_names)= @_;
 6333:   # $Apache::lonxml::debug=1;
 6334:   foreach my $pair (split(/&/,$query)) {
 6335:     my ($name, $value) = split(/=/,$pair);
 6336:     $name = &unescape($name);
 6337:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 6338:       $value =~ tr/+/ /;
 6339:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6340:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 6341:     }
 6342:   }
 6343: }
 6344: 
 6345: =pod
 6346: 
 6347: =item * cacheheader() 
 6348: 
 6349: returns cache-controlling header code
 6350: 
 6351: =cut
 6352: 
 6353: sub cacheheader {
 6354:     unless ($env{'request.method'} eq 'GET') { return ''; }
 6355:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 6356:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 6357:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 6358:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 6359:     return $output;
 6360: }
 6361: 
 6362: =pod
 6363: 
 6364: =item * no_cache($r) 
 6365: 
 6366: specifies header code to not have cache
 6367: 
 6368: =cut
 6369: 
 6370: sub no_cache {
 6371:     my ($r) = @_;
 6372:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 6373: 	$env{'request.method'} ne 'GET') { return ''; }
 6374:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 6375:     $r->no_cache(1);
 6376:     $r->header_out("Expires" => $date);
 6377:     $r->header_out("Pragma" => "no-cache");
 6378: }
 6379: 
 6380: sub content_type {
 6381:     my ($r,$type,$charset) = @_;
 6382:     if ($r) {
 6383: 	#  Note that printout.pl calls this with undef for $r.
 6384: 	&no_cache($r);
 6385:     }
 6386:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 6387:     unless ($charset) {
 6388: 	$charset=&Apache::lonlocal::current_encoding;
 6389:     }
 6390:     if ($charset) { $type.='; charset='.$charset; }
 6391:     if ($r) {
 6392: 	$r->content_type($type);
 6393:     } else {
 6394: 	print("Content-type: $type\n\n");
 6395:     }
 6396: }
 6397: 
 6398: =pod
 6399: 
 6400: =item * add_to_env($name,$value) 
 6401: 
 6402: adds $name to the %env hash with value
 6403: $value, if $name already exists, the entry is converted to an array
 6404: reference and $value is added to the array.
 6405: 
 6406: =cut
 6407: 
 6408: sub add_to_env {
 6409:   my ($name,$value)=@_;
 6410:   if (defined($env{$name})) {
 6411:     if (ref($env{$name})) {
 6412:       #already have multiple values
 6413:       push(@{ $env{$name} },$value);
 6414:     } else {
 6415:       #first time seeing multiple values, convert hash entry to an arrayref
 6416:       my $first=$env{$name};
 6417:       undef($env{$name});
 6418:       push(@{ $env{$name} },$first,$value);
 6419:     }
 6420:   } else {
 6421:     $env{$name}=$value;
 6422:   }
 6423: }
 6424: 
 6425: =pod
 6426: 
 6427: =item * get_env_multiple($name) 
 6428: 
 6429: gets $name from the %env hash, it seemlessly handles the cases where multiple
 6430: values may be defined and end up as an array ref.
 6431: 
 6432: returns an array of values
 6433: 
 6434: =cut
 6435: 
 6436: sub get_env_multiple {
 6437:     my ($name) = @_;
 6438:     my @values;
 6439:     if (defined($env{$name})) {
 6440:         # exists is it an array
 6441:         if (ref($env{$name})) {
 6442:             @values=@{ $env{$name} };
 6443:         } else {
 6444:             $values[0]=$env{$name};
 6445:         }
 6446:     }
 6447:     return(@values);
 6448: }
 6449: 
 6450: 
 6451: =pod
 6452: 
 6453: =back
 6454: 
 6455: =head1 CSV Upload/Handling functions
 6456: 
 6457: =over 4
 6458: 
 6459: =item * upfile_store($r)
 6460: 
 6461: Store uploaded file, $r should be the HTTP Request object,
 6462: needs $env{'form.upfile'}
 6463: returns $datatoken to be put into hidden field
 6464: 
 6465: =cut
 6466: 
 6467: sub upfile_store {
 6468:     my $r=shift;
 6469:     $env{'form.upfile'}=~s/\r/\n/gs;
 6470:     $env{'form.upfile'}=~s/\f/\n/gs;
 6471:     $env{'form.upfile'}=~s/\n+/\n/gs;
 6472:     $env{'form.upfile'}=~s/\n+$//gs;
 6473: 
 6474:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 6475: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 6476:     {
 6477:         my $datafile = $r->dir_config('lonDaemons').
 6478:                            '/tmp/'.$datatoken.'.tmp';
 6479:         if ( open(my $fh,">$datafile") ) {
 6480:             print $fh $env{'form.upfile'};
 6481:             close($fh);
 6482:         }
 6483:     }
 6484:     return $datatoken;
 6485: }
 6486: 
 6487: =pod
 6488: 
 6489: =item * load_tmp_file($r)
 6490: 
 6491: Load uploaded file from tmp, $r should be the HTTP Request object,
 6492: needs $env{'form.datatoken'},
 6493: sets $env{'form.upfile'} to the contents of the file
 6494: 
 6495: =cut
 6496: 
 6497: sub load_tmp_file {
 6498:     my $r=shift;
 6499:     my @studentdata=();
 6500:     {
 6501:         my $studentfile = $r->dir_config('lonDaemons').
 6502:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 6503:         if ( open(my $fh,"<$studentfile") ) {
 6504:             @studentdata=<$fh>;
 6505:             close($fh);
 6506:         }
 6507:     }
 6508:     $env{'form.upfile'}=join('',@studentdata);
 6509: }
 6510: 
 6511: =pod
 6512: 
 6513: =item * upfile_record_sep()
 6514: 
 6515: Separate uploaded file into records
 6516: returns array of records,
 6517: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 6518: 
 6519: =cut
 6520: 
 6521: sub upfile_record_sep {
 6522:     if ($env{'form.upfiletype'} eq 'xml') {
 6523:     } else {
 6524: 	my @records;
 6525: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 6526: 	    if ($line=~/^\s*$/) { next; }
 6527: 	    push(@records,$line);
 6528: 	}
 6529: 	return @records;
 6530:     }
 6531: }
 6532: 
 6533: =pod
 6534: 
 6535: =item * record_sep($record)
 6536: 
 6537: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 6538: 
 6539: =cut
 6540: 
 6541: sub takeleft {
 6542:     my $index=shift;
 6543:     return substr('0000'.$index,-4,4);
 6544: }
 6545: 
 6546: sub record_sep {
 6547:     my $record=shift;
 6548:     my %components=();
 6549:     if ($env{'form.upfiletype'} eq 'xml') {
 6550:     } elsif ($env{'form.upfiletype'} eq 'space') {
 6551:         my $i=0;
 6552:         foreach my $field (split(/\s+/,$record)) {
 6553:             $field=~s/^(\"|\')//;
 6554:             $field=~s/(\"|\')$//;
 6555:             $components{&takeleft($i)}=$field;
 6556:             $i++;
 6557:         }
 6558:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 6559:         my $i=0;
 6560:         foreach my $field (split(/\t/,$record)) {
 6561:             $field=~s/^(\"|\')//;
 6562:             $field=~s/(\"|\')$//;
 6563:             $components{&takeleft($i)}=$field;
 6564:             $i++;
 6565:         }
 6566:     } else {
 6567:         my $separator=',';
 6568:         if ($env{'form.upfiletype'} eq 'semisv') {
 6569:             $separator=';';
 6570:         }
 6571:         my $i=0;
 6572: # the character we are looking for to indicate the end of a quote or a record 
 6573:         my $looking_for=$separator;
 6574: # do not add the characters to the fields
 6575:         my $ignore=0;
 6576: # we just encountered a separator (or the beginning of the record)
 6577:         my $just_found_separator=1;
 6578: # store the field we are working on here
 6579:         my $field='';
 6580: # work our way through all characters in record
 6581:         foreach my $character ($record=~/(.)/g) {
 6582:             if ($character eq $looking_for) {
 6583:                if ($character ne $separator) {
 6584: # Found the end of a quote, again looking for separator
 6585:                   $looking_for=$separator;
 6586:                   $ignore=1;
 6587:                } else {
 6588: # Found a separator, store away what we got
 6589:                   $components{&takeleft($i)}=$field;
 6590: 	          $i++;
 6591:                   $just_found_separator=1;
 6592:                   $ignore=0;
 6593:                   $field='';
 6594:                }
 6595:                next;
 6596:             }
 6597: # single or double quotation marks after a separator indicate beginning of a quote
 6598: # we are now looking for the end of the quote and need to ignore separators
 6599:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
 6600:                $looking_for=$character;
 6601:                next;
 6602:             }
 6603: # ignore would be true after we reached the end of a quote
 6604:             if ($ignore) { next; }
 6605:             if (($just_found_separator) && ($character=~/\s/)) { next; }
 6606:             $field.=$character;
 6607:             $just_found_separator=0; 
 6608:         }
 6609: # catch the very last entry, since we never encountered the separator
 6610:         $components{&takeleft($i)}=$field;
 6611:     }
 6612:     return %components;
 6613: }
 6614: 
 6615: ######################################################
 6616: ######################################################
 6617: 
 6618: =pod
 6619: 
 6620: =item * upfile_select_html()
 6621: 
 6622: Return HTML code to select a file from the users machine and specify 
 6623: the file type.
 6624: 
 6625: =cut
 6626: 
 6627: ######################################################
 6628: ######################################################
 6629: sub upfile_select_html {
 6630:     my %Types = (
 6631:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 6632:                  semisv => &mt('Semicolon separated values'),
 6633:                  space => &mt('Space separated'),
 6634:                  tab   => &mt('Tabulator separated'),
 6635: #                 xml   => &mt('HTML/XML'),
 6636:                  );
 6637:     my $Str = '<input type="file" name="upfile" size="50" />'.
 6638:         '<br />Type: <select name="upfiletype">';
 6639:     foreach my $type (sort(keys(%Types))) {
 6640:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 6641:     }
 6642:     $Str .= "</select>\n";
 6643:     return $Str;
 6644: }
 6645: 
 6646: sub get_samples {
 6647:     my ($records,$toget) = @_;
 6648:     my @samples=({});
 6649:     my $got=0;
 6650:     foreach my $rec (@$records) {
 6651: 	my %temp = &record_sep($rec);
 6652: 	if (! grep(/\S/, values(%temp))) { next; }
 6653: 	if (%temp) {
 6654: 	    $samples[$got]=\%temp;
 6655: 	    $got++;
 6656: 	    if ($got == $toget) { last; }
 6657: 	}
 6658:     }
 6659:     return \@samples;
 6660: }
 6661: 
 6662: ######################################################
 6663: ######################################################
 6664: 
 6665: =pod
 6666: 
 6667: =item * csv_print_samples($r,$records)
 6668: 
 6669: Prints a table of sample values from each column uploaded $r is an
 6670: Apache Request ref, $records is an arrayref from
 6671: &Apache::loncommon::upfile_record_sep
 6672: 
 6673: =cut
 6674: 
 6675: ######################################################
 6676: ######################################################
 6677: sub csv_print_samples {
 6678:     my ($r,$records) = @_;
 6679:     my $samples = &get_samples($records,3);
 6680: 
 6681:     $r->print(&mt('Samples').'<br />'.&start_data_table().
 6682:               &start_data_table_header_row());
 6683:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 6684:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 6685:     $r->print(&end_data_table_header_row());
 6686:     foreach my $hash (@$samples) {
 6687: 	$r->print(&start_data_table_row());
 6688: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 6689: 	    $r->print('<td>');
 6690: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 6691: 	    $r->print('</td>');
 6692: 	}
 6693: 	$r->print(&end_data_table_row());
 6694:     }
 6695:     $r->print(&end_data_table().'<br />'."\n");
 6696: }
 6697: 
 6698: ######################################################
 6699: ######################################################
 6700: 
 6701: =pod
 6702: 
 6703: =item * csv_print_select_table($r,$records,$d)
 6704: 
 6705: Prints a table to create associations between values and table columns.
 6706: 
 6707: $r is an Apache Request ref,
 6708: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 6709: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 6710: 
 6711: =cut
 6712: 
 6713: ######################################################
 6714: ######################################################
 6715: sub csv_print_select_table {
 6716:     my ($r,$records,$d) = @_;
 6717:     my $i=0;
 6718:     my $samples = &get_samples($records,1);
 6719:     $r->print(&mt('Associate columns with student attributes.')."\n".
 6720: 	      &start_data_table().&start_data_table_header_row().
 6721:               '<th>'.&mt('Attribute').'</th>'.
 6722:               '<th>'.&mt('Column').'</th>'.
 6723:               &end_data_table_header_row()."\n");
 6724:     foreach my $array_ref (@$d) {
 6725: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 6726: 	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
 6727: 
 6728: 	$r->print('<td><select name=f'.$i.
 6729: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 6730: 	$r->print('<option value="none"></option>');
 6731: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 6732: 	    $r->print('<option value="'.$sample.'"'.
 6733:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 6734:                       '>Column '.($sample+1).'</option>');
 6735: 	}
 6736: 	$r->print('</select></td>'.&end_data_table_row()."\n");
 6737: 	$i++;
 6738:     }
 6739:     $r->print(&end_data_table());
 6740:     $i--;
 6741:     return $i;
 6742: }
 6743: 
 6744: ######################################################
 6745: ######################################################
 6746: 
 6747: =pod
 6748: 
 6749: =item * csv_samples_select_table($r,$records,$d)
 6750: 
 6751: Prints a table of sample values from the upload and can make associate samples to internal names.
 6752: 
 6753: $r is an Apache Request ref,
 6754: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 6755: $d is an array of 2 element arrays (internal name, displayed name)
 6756: 
 6757: =cut
 6758: 
 6759: ######################################################
 6760: ######################################################
 6761: sub csv_samples_select_table {
 6762:     my ($r,$records,$d) = @_;
 6763:     my $i=0;
 6764:     #
 6765:     my $samples = &get_samples($records,3);
 6766:     $r->print(&start_data_table().
 6767:               &start_data_table_header_row().'<th>'.
 6768:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
 6769:               &end_data_table_header_row());
 6770: 
 6771:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 6772: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 6773: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 6774: 	foreach my $option (@$d) {
 6775: 	    my ($value,$display,$defaultcol)=@{ $option };
 6776: 	    $r->print('<option value="'.$value.'"'.
 6777:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 6778:                       $display.'</option>');
 6779: 	}
 6780: 	$r->print('</select></td><td>');
 6781: 	foreach my $line (0..2) {
 6782: 	    if (defined($samples->[$line]{$key})) { 
 6783: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 6784: 	    }
 6785: 	}
 6786: 	$r->print('</td>'.&end_data_table_row());
 6787: 	$i++;
 6788:     }
 6789:     $r->print(&end_data_table());
 6790:     $i--;
 6791:     return($i);
 6792: }
 6793: 
 6794: ######################################################
 6795: ######################################################
 6796: 
 6797: =pod
 6798: 
 6799: =item clean_excel_name($name)
 6800: 
 6801: Returns a replacement for $name which does not contain any illegal characters.
 6802: 
 6803: =cut
 6804: 
 6805: ######################################################
 6806: ######################################################
 6807: sub clean_excel_name {
 6808:     my ($name) = @_;
 6809:     $name =~ s/[:\*\?\/\\]//g;
 6810:     if (length($name) > 31) {
 6811:         $name = substr($name,0,31);
 6812:     }
 6813:     return $name;
 6814: }
 6815: 
 6816: =pod
 6817: 
 6818: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 6819: 
 6820: Returns either 1 or undef
 6821: 
 6822: 1 if the part is to be hidden, undef if it is to be shown
 6823: 
 6824: Arguments are:
 6825: 
 6826: $id the id of the part to be checked
 6827: $symb, optional the symb of the resource to check
 6828: $udom, optional the domain of the user to check for
 6829: $uname, optional the username of the user to check for
 6830: 
 6831: =cut
 6832: 
 6833: sub check_if_partid_hidden {
 6834:     my ($id,$symb,$udom,$uname) = @_;
 6835:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 6836: 					 $symb,$udom,$uname);
 6837:     my $truth=1;
 6838:     #if the string starts with !, then the list is the list to show not hide
 6839:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 6840:     my @hiddenlist=split(/,/,$hiddenparts);
 6841:     foreach my $checkid (@hiddenlist) {
 6842: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 6843:     }
 6844:     return !$truth;
 6845: }
 6846: 
 6847: 
 6848: ############################################################
 6849: ############################################################
 6850: 
 6851: =pod
 6852: 
 6853: =back 
 6854: 
 6855: =head1 cgi-bin script and graphing routines
 6856: 
 6857: =over 4
 6858: 
 6859: =item get_cgi_id
 6860: 
 6861: Inputs: none
 6862: 
 6863: Returns an id which can be used to pass environment variables
 6864: to various cgi-bin scripts.  These environment variables will
 6865: be removed from the users environment after a given time by
 6866: the routine &Apache::lonnet::transfer_profile_to_env.
 6867: 
 6868: =cut
 6869: 
 6870: ############################################################
 6871: ############################################################
 6872: my $uniq=0;
 6873: sub get_cgi_id {
 6874:     $uniq=($uniq+1)%100000;
 6875:     return (time.'_'.$$.'_'.$uniq);
 6876: }
 6877: 
 6878: ############################################################
 6879: ############################################################
 6880: 
 6881: =pod
 6882: 
 6883: =item DrawBarGraph
 6884: 
 6885: Facilitates the plotting of data in a (stacked) bar graph.
 6886: Puts plot definition data into the users environment in order for 
 6887: graph.png to plot it.  Returns an <img> tag for the plot.
 6888: The bars on the plot are labeled '1','2',...,'n'.
 6889: 
 6890: Inputs:
 6891: 
 6892: =over 4
 6893: 
 6894: =item $Title: string, the title of the plot
 6895: 
 6896: =item $xlabel: string, text describing the X-axis of the plot
 6897: 
 6898: =item $ylabel: string, text describing the Y-axis of the plot
 6899: 
 6900: =item $Max: scalar, the maximum Y value to use in the plot
 6901: If $Max is < any data point, the graph will not be rendered.
 6902: 
 6903: =item $colors: array ref holding the colors to be used for the data sets when
 6904: they are plotted.  If undefined, default values will be used.
 6905: 
 6906: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 6907: 
 6908: =item @Values: An array of array references.  Each array reference holds data
 6909: to be plotted in a stacked bar chart.
 6910: 
 6911: =item If the final element of @Values is a hash reference the key/value
 6912: pairs will be added to the graph definition.
 6913: 
 6914: =back
 6915: 
 6916: Returns:
 6917: 
 6918: An <img> tag which references graph.png and the appropriate identifying
 6919: information for the plot.
 6920: 
 6921: =cut
 6922: 
 6923: ############################################################
 6924: ############################################################
 6925: sub DrawBarGraph {
 6926:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 6927:     #
 6928:     if (! defined($colors)) {
 6929:         $colors = ['#33ff00', 
 6930:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 6931:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 6932:                   ]; 
 6933:     }
 6934:     my $extra_settings = {};
 6935:     if (ref($Values[-1]) eq 'HASH') {
 6936:         $extra_settings = pop(@Values);
 6937:     }
 6938:     #
 6939:     my $identifier = &get_cgi_id();
 6940:     my $id = 'cgi.'.$identifier;        
 6941:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 6942:         return '';
 6943:     }
 6944:     #
 6945:     my @Labels;
 6946:     if (defined($labels)) {
 6947:         @Labels = @$labels;
 6948:     } else {
 6949:         for (my $i=0;$i<@{$Values[0]};$i++) {
 6950:             push (@Labels,$i+1);
 6951:         }
 6952:     }
 6953:     #
 6954:     my $NumBars = scalar(@{$Values[0]});
 6955:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 6956:     my %ValuesHash;
 6957:     my $NumSets=1;
 6958:     foreach my $array (@Values) {
 6959:         next if (! ref($array));
 6960:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 6961:             join(',',@$array);
 6962:     }
 6963:     #
 6964:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 6965:     if ($NumBars < 3) {
 6966:         $width = 120+$NumBars*32;
 6967:         $xskip = 1;
 6968:         $bar_width = 30;
 6969:     } elsif ($NumBars < 5) {
 6970:         $width = 120+$NumBars*20;
 6971:         $xskip = 1;
 6972:         $bar_width = 20;
 6973:     } elsif ($NumBars < 10) {
 6974:         $width = 120+$NumBars*15;
 6975:         $xskip = 1;
 6976:         $bar_width = 15;
 6977:     } elsif ($NumBars <= 25) {
 6978:         $width = 120+$NumBars*11;
 6979:         $xskip = 5;
 6980:         $bar_width = 8;
 6981:     } elsif ($NumBars <= 50) {
 6982:         $width = 120+$NumBars*8;
 6983:         $xskip = 5;
 6984:         $bar_width = 4;
 6985:     } else {
 6986:         $width = 120+$NumBars*8;
 6987:         $xskip = 5;
 6988:         $bar_width = 4;
 6989:     }
 6990:     #
 6991:     $Max = 1 if ($Max < 1);
 6992:     if ( int($Max) < $Max ) {
 6993:         $Max++;
 6994:         $Max = int($Max);
 6995:     }
 6996:     $Title  = '' if (! defined($Title));
 6997:     $xlabel = '' if (! defined($xlabel));
 6998:     $ylabel = '' if (! defined($ylabel));
 6999:     $ValuesHash{$id.'.title'}    = &escape($Title);
 7000:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
 7001:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
 7002:     $ValuesHash{$id.'.y_max_value'} = $Max;
 7003:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 7004:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 7005:     $ValuesHash{$id.'.PlotType'} = 'bar';
 7006:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7007:     $ValuesHash{$id.'.height'}   = $height;
 7008:     $ValuesHash{$id.'.width'}    = $width;
 7009:     $ValuesHash{$id.'.xskip'}    = $xskip;
 7010:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 7011:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 7012:     #
 7013:     # Deal with other parameters
 7014:     while (my ($key,$value) = each(%$extra_settings)) {
 7015:         $ValuesHash{$id.'.'.$key} = $value;
 7016:     }
 7017:     #
 7018:     &Apache::lonnet::appenv(%ValuesHash);
 7019:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7020: }
 7021: 
 7022: ############################################################
 7023: ############################################################
 7024: 
 7025: =pod
 7026: 
 7027: =item DrawXYGraph
 7028: 
 7029: Facilitates the plotting of data in an XY graph.
 7030: Puts plot definition data into the users environment in order for 
 7031: graph.png to plot it.  Returns an <img> tag for the plot.
 7032: 
 7033: Inputs:
 7034: 
 7035: =over 4
 7036: 
 7037: =item $Title: string, the title of the plot
 7038: 
 7039: =item $xlabel: string, text describing the X-axis of the plot
 7040: 
 7041: =item $ylabel: string, text describing the Y-axis of the plot
 7042: 
 7043: =item $Max: scalar, the maximum Y value to use in the plot
 7044: If $Max is < any data point, the graph will not be rendered.
 7045: 
 7046: =item $colors: Array ref containing the hex color codes for the data to be 
 7047: plotted in.  If undefined, default values will be used.
 7048: 
 7049: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7050: 
 7051: =item $Ydata: Array ref containing Array refs.  
 7052: Each of the contained arrays will be plotted as a separate curve.
 7053: 
 7054: =item %Values: hash indicating or overriding any default values which are 
 7055: passed to graph.png.  
 7056: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7057: 
 7058: =back
 7059: 
 7060: Returns:
 7061: 
 7062: An <img> tag which references graph.png and the appropriate identifying
 7063: information for the plot.
 7064: 
 7065: =cut
 7066: 
 7067: ############################################################
 7068: ############################################################
 7069: sub DrawXYGraph {
 7070:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 7071:     #
 7072:     # Create the identifier for the graph
 7073:     my $identifier = &get_cgi_id();
 7074:     my $id = 'cgi.'.$identifier;
 7075:     #
 7076:     $Title  = '' if (! defined($Title));
 7077:     $xlabel = '' if (! defined($xlabel));
 7078:     $ylabel = '' if (! defined($ylabel));
 7079:     my %ValuesHash = 
 7080:         (
 7081:          $id.'.title'  => &escape($Title),
 7082:          $id.'.xlabel' => &escape($xlabel),
 7083:          $id.'.ylabel' => &escape($ylabel),
 7084:          $id.'.y_max_value'=> $Max,
 7085:          $id.'.labels'     => join(',',@$Xlabels),
 7086:          $id.'.PlotType'   => 'XY',
 7087:          );
 7088:     #
 7089:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7090:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7091:     }
 7092:     #
 7093:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 7094:         return '';
 7095:     }
 7096:     my $NumSets=1;
 7097:     foreach my $array (@{$Ydata}){
 7098:         next if (! ref($array));
 7099:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7100:     }
 7101:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 7102:     #
 7103:     # Deal with other parameters
 7104:     while (my ($key,$value) = each(%Values)) {
 7105:         $ValuesHash{$id.'.'.$key} = $value;
 7106:     }
 7107:     #
 7108:     &Apache::lonnet::appenv(%ValuesHash);
 7109:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7110: }
 7111: 
 7112: ############################################################
 7113: ############################################################
 7114: 
 7115: =pod
 7116: 
 7117: =item DrawXYYGraph
 7118: 
 7119: Facilitates the plotting of data in an XY graph with two Y axes.
 7120: Puts plot definition data into the users environment in order for 
 7121: graph.png to plot it.  Returns an <img> tag for the plot.
 7122: 
 7123: Inputs:
 7124: 
 7125: =over 4
 7126: 
 7127: =item $Title: string, the title of the plot
 7128: 
 7129: =item $xlabel: string, text describing the X-axis of the plot
 7130: 
 7131: =item $ylabel: string, text describing the Y-axis of the plot
 7132: 
 7133: =item $colors: Array ref containing the hex color codes for the data to be 
 7134: plotted in.  If undefined, default values will be used.
 7135: 
 7136: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 7137: 
 7138: =item $Ydata1: The first data set
 7139: 
 7140: =item $Min1: The minimum value of the left Y-axis
 7141: 
 7142: =item $Max1: The maximum value of the left Y-axis
 7143: 
 7144: =item $Ydata2: The second data set
 7145: 
 7146: =item $Min2: The minimum value of the right Y-axis
 7147: 
 7148: =item $Max2: The maximum value of the left Y-axis
 7149: 
 7150: =item %Values: hash indicating or overriding any default values which are 
 7151: passed to graph.png.  
 7152: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 7153: 
 7154: =back
 7155: 
 7156: Returns:
 7157: 
 7158: An <img> tag which references graph.png and the appropriate identifying
 7159: information for the plot.
 7160: 
 7161: =cut
 7162: 
 7163: ############################################################
 7164: ############################################################
 7165: sub DrawXYYGraph {
 7166:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 7167:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 7168:     #
 7169:     # Create the identifier for the graph
 7170:     my $identifier = &get_cgi_id();
 7171:     my $id = 'cgi.'.$identifier;
 7172:     #
 7173:     $Title  = '' if (! defined($Title));
 7174:     $xlabel = '' if (! defined($xlabel));
 7175:     $ylabel = '' if (! defined($ylabel));
 7176:     my %ValuesHash = 
 7177:         (
 7178:          $id.'.title'  => &escape($Title),
 7179:          $id.'.xlabel' => &escape($xlabel),
 7180:          $id.'.ylabel' => &escape($ylabel),
 7181:          $id.'.labels' => join(',',@$Xlabels),
 7182:          $id.'.PlotType' => 'XY',
 7183:          $id.'.NumSets' => 2,
 7184:          $id.'.two_axes' => 1,
 7185:          $id.'.y1_max_value' => $Max1,
 7186:          $id.'.y1_min_value' => $Min1,
 7187:          $id.'.y2_max_value' => $Max2,
 7188:          $id.'.y2_min_value' => $Min2,
 7189:          );
 7190:     #
 7191:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 7192:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 7193:     }
 7194:     #
 7195:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 7196:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 7197:         return '';
 7198:     }
 7199:     my $NumSets=1;
 7200:     foreach my $array ($Ydata1,$Ydata2){
 7201:         next if (! ref($array));
 7202:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 7203:     }
 7204:     #
 7205:     # Deal with other parameters
 7206:     while (my ($key,$value) = each(%Values)) {
 7207:         $ValuesHash{$id.'.'.$key} = $value;
 7208:     }
 7209:     #
 7210:     &Apache::lonnet::appenv(%ValuesHash);
 7211:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 7212: }
 7213: 
 7214: ############################################################
 7215: ############################################################
 7216: 
 7217: =pod
 7218: 
 7219: =back 
 7220: 
 7221: =head1 Statistics helper routines?  
 7222: 
 7223: Bad place for them but what the hell.
 7224: 
 7225: =over 4
 7226: 
 7227: =item &chartlink
 7228: 
 7229: Returns a link to the chart for a specific student.  
 7230: 
 7231: Inputs:
 7232: 
 7233: =over 4
 7234: 
 7235: =item $linktext: The text of the link
 7236: 
 7237: =item $sname: The students username
 7238: 
 7239: =item $sdomain: The students domain
 7240: 
 7241: =back
 7242: 
 7243: =back
 7244: 
 7245: =cut
 7246: 
 7247: ############################################################
 7248: ############################################################
 7249: sub chartlink {
 7250:     my ($linktext, $sname, $sdomain) = @_;
 7251:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 7252:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
 7253:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 7254:        '">'.$linktext.'</a>';
 7255: }
 7256: 
 7257: #######################################################
 7258: #######################################################
 7259: 
 7260: =pod
 7261: 
 7262: =head1 Course Environment Routines
 7263: 
 7264: =over 4
 7265: 
 7266: =item &restore_course_settings 
 7267: 
 7268: =item &store_course_settings
 7269: 
 7270: Restores/Store indicated form parameters from the course environment.
 7271: Will not overwrite existing values of the form parameters.
 7272: 
 7273: Inputs: 
 7274: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 7275: 
 7276: a hash ref describing the data to be stored.  For example:
 7277:    
 7278: %Save_Parameters = ('Status' => 'scalar',
 7279:     'chartoutputmode' => 'scalar',
 7280:     'chartoutputdata' => 'scalar',
 7281:     'Section' => 'array',
 7282:     'Group' => 'array',
 7283:     'StudentData' => 'array',
 7284:     'Maps' => 'array');
 7285: 
 7286: Returns: both routines return nothing
 7287: 
 7288: =cut
 7289: 
 7290: #######################################################
 7291: #######################################################
 7292: sub store_course_settings {
 7293:     return &store_settings($env{'request.course.id'},@_);
 7294: }
 7295: 
 7296: sub store_settings {
 7297:     # save to the environment
 7298:     # appenv the same items, just to be safe
 7299:     my $udom  = $env{'user.domain'};
 7300:     my $uname = $env{'user.name'};
 7301:     my ($context,$prefix,$Settings) = @_;
 7302:     my %SaveHash;
 7303:     my %AppHash;
 7304:     while (my ($setting,$type) = each(%$Settings)) {
 7305:         my $basename = join('.','internal',$context,$prefix,$setting);
 7306:         my $envname = 'environment.'.$basename;
 7307:         if (exists($env{'form.'.$setting})) {
 7308:             # Save this value away
 7309:             if ($type eq 'scalar' &&
 7310:                 (! exists($env{$envname}) || 
 7311:                  $env{$envname} ne $env{'form.'.$setting})) {
 7312:                 $SaveHash{$basename} = $env{'form.'.$setting};
 7313:                 $AppHash{$envname}   = $env{'form.'.$setting};
 7314:             } elsif ($type eq 'array') {
 7315:                 my $stored_form;
 7316:                 if (ref($env{'form.'.$setting})) {
 7317:                     $stored_form = join(',',
 7318:                                         map {
 7319:                                             &escape($_);
 7320:                                         } sort(@{$env{'form.'.$setting}}));
 7321:                 } else {
 7322:                     $stored_form = 
 7323:                         &escape($env{'form.'.$setting});
 7324:                 }
 7325:                 # Determine if the array contents are the same.
 7326:                 if ($stored_form ne $env{$envname}) {
 7327:                     $SaveHash{$basename} = $stored_form;
 7328:                     $AppHash{$envname}   = $stored_form;
 7329:                 }
 7330:             }
 7331:         }
 7332:     }
 7333:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 7334:                                           $udom,$uname);
 7335:     if ($put_result !~ /^(ok|delayed)/) {
 7336:         &Apache::lonnet::logthis('unable to save form parameters, '.
 7337:                                  'got error:'.$put_result);
 7338:     }
 7339:     # Make sure these settings stick around in this session, too
 7340:     &Apache::lonnet::appenv(%AppHash);
 7341:     return;
 7342: }
 7343: 
 7344: sub restore_course_settings {
 7345:     return &restore_settings($env{'request.course.id'},@_);
 7346: }
 7347: 
 7348: sub restore_settings {
 7349:     my ($context,$prefix,$Settings) = @_;
 7350:     while (my ($setting,$type) = each(%$Settings)) {
 7351:         next if (exists($env{'form.'.$setting}));
 7352:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
 7353:             '.'.$setting;
 7354:         if (exists($env{$envname})) {
 7355:             if ($type eq 'scalar') {
 7356:                 $env{'form.'.$setting} = $env{$envname};
 7357:             } elsif ($type eq 'array') {
 7358:                 $env{'form.'.$setting} = [ 
 7359:                                            map { 
 7360:                                                &unescape($_); 
 7361:                                            } split(',',$env{$envname})
 7362:                                            ];
 7363:             }
 7364:         }
 7365:     }
 7366: }
 7367: 
 7368: ############################################################
 7369: ############################################################
 7370: 
 7371: sub commit_customrole {
 7372:     my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
 7373:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
 7374:                          ($start?', '.&mt('starting').' '.localtime($start):'').
 7375:                          ($end?', ending '.localtime($end):'').': <b>'.
 7376:               &Apache::lonnet::assigncustomrole(
 7377:                  $udom,$uname,$url,$three,$four,$five,$end,$start).
 7378:                  '</b><br />';
 7379:     return $output;
 7380: }
 7381: 
 7382: sub commit_standardrole {
 7383:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 7384:     my ($output,$logmsg,$linefeed);
 7385:     if ($context eq 'auto') {
 7386:         $linefeed = "\n";
 7387:     } else {
 7388:         $linefeed = "<br />\n";
 7389:     }  
 7390:     if ($three eq 'st') {
 7391:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
 7392:                                          $one,$two,$sec,$context);
 7393:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
 7394:             ($result eq 'unknown_course')) {
 7395:             $output = "Error: $result\n"; 
 7396:         } else {
 7397:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
 7398:                ($start?', '.&mt('starting').' '.localtime($start):'').
 7399:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 7400:             if ($context eq 'auto') {
 7401:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
 7402:             } else {
 7403:                $output .= '<b>'.$result.'</b>'.$linefeed.
 7404:                &mt('Add to classlist').': <b>ok</b>';
 7405:             }
 7406:             $output .= $linefeed;
 7407:         }
 7408:     } else {
 7409:         $output = &mt('Assigning').' '.$three.' in '.$url.
 7410:                ($start?', '.&mt('starting').' '.localtime($start):'').
 7411:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
 7412:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start);
 7413:         if ($context eq 'auto') {
 7414:             $output .= $result.$linefeed;
 7415:         } else {
 7416:             $output .= '<b>'.$result.'</b>'.$linefeed;
 7417:         }
 7418:     }
 7419:     return $output;
 7420: }
 7421: 
 7422: sub commit_studentrole {
 7423:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
 7424:     my ($result,$linefeed);
 7425:     if ($context eq 'auto') {
 7426:         $linefeed = "\n";
 7427:     } else {
 7428:         $linefeed = '<br />'."\n";
 7429:     }
 7430:     if (defined($one) && defined($two)) {
 7431:         my $cid=$one.'_'.$two;
 7432:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
 7433:         my $secchange = 0;
 7434:         my $expire_role_result;
 7435:         my $modify_section_result;
 7436:         unless ($oldsec eq '-1') {
 7437:             unless ($sec eq $oldsec) {
 7438:                 $secchange = 1;
 7439:                 my $uurl='/'.$cid;
 7440:                 $uurl=~s/\_/\//g;
 7441:                 if ($oldsec) {
 7442:                     $uurl.='/'.$oldsec;
 7443:                 }
 7444:                 $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
 7445:                 $result = $expire_role_result;
 7446:             }
 7447:         }
 7448:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
 7449:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
 7450:             if ($modify_section_result =~ /^ok/) {
 7451:                 if ($secchange == 1) {
 7452:                     $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
 7453:                 } elsif ($oldsec eq '-1') {
 7454:                     $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
 7455:                 } else {
 7456:                     $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
 7457:                 }
 7458:             } else {
 7459:                 $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
 7460:             }
 7461:             $result = $modify_section_result;
 7462:         } elsif ($secchange == 1) {
 7463:             $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
 7464:         }
 7465:     } else {
 7466:         $$logmsg .= "Incomplete course id defined.  Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
 7467:         $result = "error: incomplete course id\n";
 7468:     }
 7469:     return $result;
 7470: }
 7471: 
 7472: ############################################################
 7473: ############################################################
 7474: 
 7475: sub check_clone {
 7476:     my ($args,$linefeed) = @_;
 7477:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
 7478:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
 7479:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
 7480:     my $clonemsg;
 7481:     my $can_clone = 0;
 7482: 
 7483:     if ($clonehome eq 'no_host') {
 7484:         $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'});     
 7485:     } else {
 7486: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
 7487: 	if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
 7488: 	    $can_clone = 1;
 7489: 	} else {
 7490: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
 7491: 						 $args->{'clonedomain'},$args->{'clonecourse'});
 7492: 	    my @cloners = split(/,/,$clonehash{'cloners'});
 7493:             if (grep(/^\*$/,@cloners)) {
 7494:                 $can_clone = 1;
 7495:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
 7496:                 $can_clone = 1;
 7497:             } else {
 7498: 	        my %roleshash =
 7499: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
 7500: 					 $args->{'ccdomain'},
 7501:                                          'userroles',['active'],['cc'],
 7502: 					 [$args->{'clonedomain'}]);
 7503: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
 7504: 		    $can_clone = 1;
 7505: 	        } else {
 7506:                     $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'});
 7507: 	        }
 7508: 	    }
 7509:         }
 7510:     }
 7511:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
 7512: }
 7513: 
 7514: sub construct_course {
 7515:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
 7516:     my $outcome;
 7517:     my $linefeed =  '<br />'."\n";
 7518:     if ($context eq 'auto') {
 7519:         $linefeed = "\n";
 7520:     }
 7521: 
 7522: #
 7523: # Are we cloning?
 7524: #
 7525:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
 7526:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
 7527: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
 7528: 	if ($context ne 'auto') {
 7529:             if ($clonemsg ne '') {
 7530: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
 7531:             }
 7532: 	}
 7533: 	$outcome .= $clonemsg.$linefeed;
 7534: 
 7535:         if (!$can_clone) {
 7536: 	    return (0,$outcome);
 7537: 	}
 7538:     }
 7539: 
 7540: #
 7541: # Open course
 7542: #
 7543:     my $crstype = lc($args->{'crstype'});
 7544:     my %cenv=();
 7545:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
 7546:                                              $args->{'cdescr'},
 7547:                                              $args->{'curl'},
 7548:                                              $args->{'course_home'},
 7549:                                              $args->{'nonstandard'},
 7550:                                              $args->{'crscode'},
 7551:                                              $args->{'ccuname'}.':'.
 7552:                                              $args->{'ccdomain'},
 7553:                                              $args->{'crstype'});
 7554: 
 7555:     # Note: The testing routines depend on this being output; see 
 7556:     # Utils::Course. This needs to at least be output as a comment
 7557:     # if anyone ever decides to not show this, and Utils::Course::new
 7558:     # will need to be suitably modified.
 7559:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
 7560: #
 7561: # Check if created correctly
 7562: #
 7563:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
 7564:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
 7565:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
 7566: 
 7567: #
 7568: # Do the cloning
 7569: #   
 7570:     if ($can_clone && $cloneid) {
 7571: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
 7572: 	if ($context ne 'auto') {
 7573: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
 7574: 	}
 7575: 	$outcome .= $clonemsg.$linefeed;
 7576: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
 7577: # Copy all files
 7578: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
 7579: # Restore URL
 7580: 	$cenv{'url'}=$oldcenv{'url'};
 7581: # Restore title
 7582: 	$cenv{'description'}=$oldcenv{'description'};
 7583: # restore grading mode
 7584: 	if (defined($oldcenv{'grading'})) {
 7585: 	    $cenv{'grading'}=$oldcenv{'grading'};
 7586: 	}
 7587: # Mark as cloned
 7588: 	$cenv{'clonedfrom'}=$cloneid;
 7589: 	delete($cenv{'default_enrollment_start_date'});
 7590: 	delete($cenv{'default_enrollment_end_date'});
 7591:     }
 7592: 
 7593: #
 7594: # Set environment (will override cloned, if existing)
 7595: #
 7596:     my @sections = ();
 7597:     my @xlists = ();
 7598:     if ($args->{'crstype'}) {
 7599:         $cenv{'type'}=$args->{'crstype'};
 7600:     }
 7601:     if ($args->{'crsid'}) {
 7602:         $cenv{'courseid'}=$args->{'crsid'};
 7603:     }
 7604:     if ($args->{'crscode'}) {
 7605:         $cenv{'internal.coursecode'}=$args->{'crscode'};
 7606:     }
 7607:     if ($args->{'crsquota'} ne '') {
 7608:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
 7609:     } else {
 7610:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
 7611:     }
 7612:     if ($args->{'ccuname'}) {
 7613:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
 7614:                                         ':'.$args->{'ccdomain'};
 7615:     } else {
 7616:         $cenv{'internal.courseowner'} = $args->{'curruser'};
 7617:     }
 7618: 
 7619:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
 7620:     if ($args->{'crssections'}) {
 7621:         $cenv{'internal.sectionnums'} = '';
 7622:         if ($args->{'crssections'} =~ m/,/) {
 7623:             @sections = split/,/,$args->{'crssections'};
 7624:         } else {
 7625:             $sections[0] = $args->{'crssections'};
 7626:         }
 7627:         if (@sections > 0) {
 7628:             foreach my $item (@sections) {
 7629:                 my ($sec,$gp) = split/:/,$item;
 7630:                 my $class = $args->{'crscode'}.$sec;
 7631:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
 7632:                 $cenv{'internal.sectionnums'} .= $item.',';
 7633:                 unless ($addcheck eq 'ok') {
 7634:                     push @badclasses, $class;
 7635:                 }
 7636:             }
 7637:             $cenv{'internal.sectionnums'} =~ s/,$//;
 7638:         }
 7639:     }
 7640: # do not hide course coordinator from staff listing, 
 7641: # even if privileged
 7642:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 7643: # add crosslistings
 7644:     if ($args->{'crsxlist'}) {
 7645:         $cenv{'internal.crosslistings'}='';
 7646:         if ($args->{'crsxlist'} =~ m/,/) {
 7647:             @xlists = split/,/,$args->{'crsxlist'};
 7648:         } else {
 7649:             $xlists[0] = $args->{'crsxlist'};
 7650:         }
 7651:         if (@xlists > 0) {
 7652:             foreach my $item (@xlists) {
 7653:                 my ($xl,$gp) = split/:/,$item;
 7654:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
 7655:                 $cenv{'internal.crosslistings'} .= $item.',';
 7656:                 unless ($addcheck eq 'ok') {
 7657:                     push @badclasses, $xl;
 7658:                 }
 7659:             }
 7660:             $cenv{'internal.crosslistings'} =~ s/,$//;
 7661:         }
 7662:     }
 7663:     if ($args->{'autoadds'}) {
 7664:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
 7665:     }
 7666:     if ($args->{'autodrops'}) {
 7667:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
 7668:     }
 7669: # check for notification of enrollment changes
 7670:     my @notified = ();
 7671:     if ($args->{'notify_owner'}) {
 7672:         if ($args->{'ccuname'} ne '') {
 7673:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
 7674:         }
 7675:     }
 7676:     if ($args->{'notify_dc'}) {
 7677:         if ($uname ne '') { 
 7678:             push(@notified,$uname.'@'.$udom);
 7679:         }
 7680:     }
 7681:     if (@notified > 0) {
 7682:         my $notifylist;
 7683:         if (@notified > 1) {
 7684:             $notifylist = join(',',@notified);
 7685:         } else {
 7686:             $notifylist = $notified[0];
 7687:         }
 7688:         $cenv{'internal.notifylist'} = $notifylist;
 7689:     }
 7690:     if (@badclasses > 0) {
 7691:         my %lt=&Apache::lonlocal::texthash(
 7692:                 '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',
 7693:                 'dnhr' => 'does not have rights to access enrollment in these classes',
 7694:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
 7695:         );
 7696:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
 7697:                            ' ('.$lt{'adby'}.')';
 7698:         if ($context eq 'auto') {
 7699:             $outcome .= $badclass_msg.$linefeed;
 7700:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
 7701:             foreach my $item (@badclasses) {
 7702:                 if ($context eq 'auto') {
 7703:                     $outcome .= " - $item\n";
 7704:                 } else {
 7705:                     $outcome .= "<li>$item</li>\n";
 7706:                 }
 7707:             }
 7708:             if ($context eq 'auto') {
 7709:                 $outcome .= $linefeed;
 7710:             } else {
 7711:                 $outcome .= "</ul><br /><br /></div>\n";
 7712:             }
 7713:         } 
 7714:     }
 7715:     if ($args->{'no_end_date'}) {
 7716:         $args->{'endaccess'} = 0;
 7717:     }
 7718:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
 7719:     $cenv{'internal.autoend'}=$args->{'enrollend'};
 7720:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
 7721:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
 7722:     if ($args->{'showphotos'}) {
 7723:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
 7724:     }
 7725:     $cenv{'internal.authtype'} = $args->{'authtype'};
 7726:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
 7727:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
 7728:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
 7729:             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'); 
 7730:             if ($context eq 'auto') {
 7731:                 $outcome .= $krb_msg;
 7732:             } else {
 7733:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
 7734:             }
 7735:             $outcome .= $linefeed;
 7736:         }
 7737:     }
 7738:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
 7739:        if ($args->{'setpolicy'}) {
 7740:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 7741:        }
 7742:        if ($args->{'setcontent'}) {
 7743:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
 7744:        }
 7745:     }
 7746:     if ($args->{'reshome'}) {
 7747: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
 7748: 	$cenv{'reshome'}=~s/\/+$/\//;
 7749:     }
 7750: #
 7751: # course has keyed access
 7752: #
 7753:     if ($args->{'setkeys'}) {
 7754:        $cenv{'keyaccess'}='yes';
 7755:     }
 7756: # if specified, key authority is not course, but user
 7757: # only active if keyaccess is yes
 7758:     if ($args->{'keyauth'}) {
 7759: 	my ($user,$domain) = split(':',$args->{'keyauth'});
 7760: 	$user = &LONCAPA::clean_username($user);
 7761: 	$domain = &LONCAPA::clean_username($domain);
 7762: 	if ($user ne '' && $domain ne '') {
 7763: 	    $cenv{'keyauth'}=$user.':'.$domain;
 7764: 	}
 7765:     }
 7766: 
 7767:     if ($args->{'disresdis'}) {
 7768:         $cenv{'pch.roles.denied'}='st';
 7769:     }
 7770:     if ($args->{'disablechat'}) {
 7771:         $cenv{'plc.roles.denied'}='st';
 7772:     }
 7773: 
 7774:     # Record we've not yet viewed the Course Initialization Helper for this 
 7775:     # course
 7776:     $cenv{'course.helper.not.run'} = 1;
 7777:     #
 7778:     # Use new Randomseed
 7779:     #
 7780:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
 7781:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
 7782:     #
 7783:     # The encryption code and receipt prefix for this course
 7784:     #
 7785:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
 7786:     $cenv{'internal.encpref'}=100+int(9*rand(99));
 7787:     #
 7788:     # By default, use standard grading
 7789:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
 7790: 
 7791:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
 7792:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
 7793: #
 7794: # Open all assignments
 7795: #
 7796:     if ($args->{'openall'}) {
 7797:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
 7798:        my %storecontent = ($storeunder         => time,
 7799:                            $storeunder.'.type' => 'date_start');
 7800:        
 7801:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
 7802:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
 7803:    }
 7804: #
 7805: # Set first page
 7806: #
 7807:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
 7808: 	    || ($cloneid)) {
 7809: 	use LONCAPA::map;
 7810: 	$outcome .= &mt('Setting first resource').': ';
 7811: 
 7812: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
 7813:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
 7814: 
 7815:         $outcome .= ($fatal?$errtext:'read ok').' - ';
 7816:         my $title; my $url;
 7817:         if ($args->{'firstres'} eq 'syl') {
 7818: 	    $title='Syllabus';
 7819:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
 7820:         } else {
 7821:             $title='Navigate Contents';
 7822:             $url='/adm/navmaps';
 7823:         }
 7824: 
 7825:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
 7826: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
 7827: 
 7828: 	if ($errtext) { $fatal=2; }
 7829:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
 7830:     }
 7831: 
 7832:     return (1,$outcome);
 7833: }
 7834: 
 7835: ############################################################
 7836: ############################################################
 7837: 
 7838: sub course_type {
 7839:     my ($cid) = @_;
 7840:     if (!defined($cid)) {
 7841:         $cid = $env{'request.course.id'};
 7842:     }
 7843:     if (defined($env{'course.'.$cid.'.type'})) {
 7844:         return $env{'course.'.$cid.'.type'};
 7845:     } else {
 7846:         return 'Course';
 7847:     }
 7848: }
 7849: 
 7850: sub group_term {
 7851:     my $crstype = &course_type();
 7852:     my %names = (
 7853:                   'Course' => 'group',
 7854:                   'Group' => 'team',
 7855:                 );
 7856:     return $names{$crstype};
 7857: }
 7858: 
 7859: sub icon {
 7860:     my ($file)=@_;
 7861:     my $curfext = lc((split(/\./,$file))[-1]);
 7862:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 7863:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 7864:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 7865: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 7866: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 7867: 	            $curfext.".gif") {
 7868: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 7869: 		$curfext.".gif";
 7870: 	}
 7871:     }
 7872:     return &lonhttpdurl($iconname);
 7873: } 
 7874: 
 7875: sub lonhttpd_port {
 7876:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 7877:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 7878:     # IE doesn't like a secure page getting images from a non-secure
 7879:     # port (when logging we haven't parsed the browser type so default
 7880:     # back to secure
 7881:     if ((!exists($env{'browser.type'}) || $env{'browser.type'} eq 'explorer')
 7882: 	&& $ENV{'SERVER_PORT'} == 443) {
 7883: 	return 443;
 7884:     }
 7885:     return $lonhttpd_port;
 7886: 
 7887: }
 7888: 
 7889: sub lonhttpdurl {
 7890:     my ($url)=@_;
 7891: 
 7892:     my $lonhttpd_port = &lonhttpd_port();
 7893:     if ($lonhttpd_port == 443) {
 7894: 	return 'https://'.$ENV{'SERVER_NAME'}.$url;
 7895:     }
 7896:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 7897: }
 7898: 
 7899: sub connection_aborted {
 7900:     my ($r)=@_;
 7901:     $r->print(" ");$r->rflush();
 7902:     my $c = $r->connection;
 7903:     return $c->aborted();
 7904: }
 7905: 
 7906: #    Escapes strings that may have embedded 's that will be put into
 7907: #    strings as 'strings'.
 7908: sub escape_single {
 7909:     my ($input) = @_;
 7910:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 7911:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 7912:     return $input;
 7913: }
 7914: 
 7915: #  Same as escape_single, but escape's "'s  This 
 7916: #  can be used for  "strings"
 7917: sub escape_double {
 7918:     my ($input) = @_;
 7919:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 7920:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 7921:     return $input;
 7922: }
 7923:  
 7924: #   Escapes the last element of a full URL.
 7925: sub escape_url {
 7926:     my ($url)   = @_;
 7927:     my @urlslices = split(/\//, $url,-1);
 7928:     my $lastitem = &escape(pop(@urlslices));
 7929:     return join('/',@urlslices).'/'.$lastitem;
 7930: }
 7931: 
 7932: # -------------------------------------------------------- Initliaze user login
 7933: sub init_user_environment {
 7934:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
 7935:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
 7936: 
 7937:     my $public=($username eq 'public' && $domain eq 'public');
 7938: 
 7939: # See if old ID present, if so, remove
 7940: 
 7941:     my ($filename,$cookie,$userroles);
 7942:     my $now=time;
 7943: 
 7944:     if ($public) {
 7945: 	my $max_public=100;
 7946: 	my $oldest;
 7947: 	my $oldest_time=0;
 7948: 	for(my $next=1;$next<=$max_public;$next++) {
 7949: 	    if (-e $lonids."/publicuser_$next.id") {
 7950: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
 7951: 		if ($mtime<$oldest_time || !$oldest_time) {
 7952: 		    $oldest_time=$mtime;
 7953: 		    $oldest=$next;
 7954: 		}
 7955: 	    } else {
 7956: 		$cookie="publicuser_$next";
 7957: 		last;
 7958: 	    }
 7959: 	}
 7960: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
 7961:     } else {
 7962: 	# if this isn't a robot, kill any existing non-robot sessions
 7963: 	if (!$args->{'robot'}) {
 7964: 	    opendir(DIR,$lonids);
 7965: 	    while ($filename=readdir(DIR)) {
 7966: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
 7967: 		    unlink($lonids.'/'.$filename);
 7968: 		}
 7969: 	    }
 7970: 	    closedir(DIR);
 7971: 	}
 7972: # Give them a new cookie
 7973: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
 7974: 		                   : $now);
 7975: 	$cookie="$username\_$id\_$domain\_$authhost";
 7976:     
 7977: # Initialize roles
 7978: 
 7979: 	$userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
 7980:     }
 7981: # ------------------------------------ Check browser type and MathML capability
 7982: 
 7983:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 7984:         $clientunicode,$clientos) = &decode_user_agent($r);
 7985: 
 7986: # -------------------------------------- Any accessibility options to remember?
 7987:     if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
 7988: 	foreach my $option ('imagesuppress','appletsuppress',
 7989: 			    'embedsuppress','fontenhance','blackwhite') {
 7990: 	    if ($form->{$option} eq 'true') {
 7991: 		&Apache::lonnet::put('environment',{$option => 'on'},
 7992: 				     $domain,$username);
 7993: 	    } else {
 7994: 		&Apache::lonnet::del('environment',[$option],
 7995: 				     $domain,$username);
 7996: 	    }
 7997: 	}
 7998:     }
 7999: # ------------------------------------------------------------- Get environment
 8000: 
 8001:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
 8002:     my ($tmp) = keys(%userenv);
 8003:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8004: 	# default remote control to off
 8005: 	if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
 8006:     } else {
 8007: 	undef(%userenv);
 8008:     }
 8009:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
 8010: 	$form->{'interface'}=$userenv{'interface'};
 8011:     }
 8012:     $env{'environment.remote'}=$userenv{'remote'};
 8013:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
 8014: 
 8015: # --------------- Do not trust query string to be put directly into environment
 8016:     foreach my $option ('imagesuppress','appletsuppress',
 8017: 			'embedsuppress','fontenhance','blackwhite',
 8018: 			'interface','localpath','localres') {
 8019: 	$form->{$option}=~s/[\n\r\=]//gs;
 8020:     }
 8021: # --------------------------------------------------------- Write first profile
 8022: 
 8023:     {
 8024: 	my %initial_env = 
 8025: 	    ("user.name"          => $username,
 8026: 	     "user.domain"        => $domain,
 8027: 	     "user.home"          => $authhost,
 8028: 	     "browser.type"       => $clientbrowser,
 8029: 	     "browser.version"    => $clientversion,
 8030: 	     "browser.mathml"     => $clientmathml,
 8031: 	     "browser.unicode"    => $clientunicode,
 8032: 	     "browser.os"         => $clientos,
 8033: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
 8034: 	     "request.course.fn"  => '',
 8035: 	     "request.course.uri" => '',
 8036: 	     "request.course.sec" => '',
 8037: 	     "request.role"       => 'cm',
 8038: 	     "request.role.adv"   => $env{'user.adv'},
 8039: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
 8040: 
 8041:         if ($form->{'localpath'}) {
 8042: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
 8043: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
 8044:         }
 8045: 	
 8046: 	if ($public) {
 8047: 	    $initial_env{"environment.remote"} = "off";
 8048: 	}
 8049: 	if ($form->{'interface'}) {
 8050: 	    $form->{'interface'}=~s/\W//gs;
 8051: 	    $initial_env{"browser.interface"} = $form->{'interface'};
 8052: 	    $env{'browser.interface'}=$form->{'interface'};
 8053: 	    foreach my $option ('imagesuppress','appletsuppress',
 8054: 				'embedsuppress','fontenhance','blackwhite') {
 8055: 		if (($form->{$option} eq 'true') ||
 8056: 		    ($userenv{$option} eq 'on')) {
 8057: 		    $initial_env{"browser.$option"} = "on";
 8058: 		}
 8059: 	    }
 8060: 	}
 8061: 
 8062: 	$env{'user.environment'} = "$lonids/$cookie.id";
 8063: 	
 8064: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
 8065: 		 &GDBM_WRCREAT(),0640)) {
 8066: 	    &_add_to_env(\%disk_env,\%initial_env);
 8067: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
 8068: 	    &_add_to_env(\%disk_env,$userroles);
 8069: 	    if (ref($args->{'extra_env'})) {
 8070: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
 8071: 	    }
 8072: 	    untie(%disk_env);
 8073: 	} else {
 8074: 	    &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
 8075: 			   'Could not create environment storage in lonauth: '.$!.'</font>');
 8076: 	    return 'error: '.$!;
 8077: 	}
 8078:     }
 8079:     $env{'request.role'}='cm';
 8080:     $env{'request.role.adv'}=$env{'user.adv'};
 8081:     $env{'browser.type'}=$clientbrowser;
 8082: 
 8083:     return $cookie;
 8084: 
 8085: }
 8086: 
 8087: sub _add_to_env {
 8088:     my ($idf,$env_data,$prefix) = @_;
 8089:     while (my ($key,$value) = each(%$env_data)) {
 8090: 	$idf->{$prefix.$key} = $value;
 8091: 	$env{$prefix.$key}   = $value;
 8092:     }
 8093: }
 8094: 
 8095: 
 8096: =pod
 8097: 
 8098: =back
 8099: 
 8100: =cut
 8101: 
 8102: 1;
 8103: __END__;
 8104: 

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