File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.535: download - view: text, annotated - select for diffs
Tue May 15 20:05:13 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_3_99_0, HEAD
- respect a users set pgbg

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

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