File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.475: download - view: text, annotated - select for diffs
Wed Nov 29 15:38:22 2006 UTC (17 years, 6 months ago) by www
Branches: MAIN
CVS tags: HEAD
Filter dialog - doesn't do anything yet, just saving my work.

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

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