File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.330: download - view: text, annotated - select for diffs
Tue Apr 11 18:43:46 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding support for <frameset> starts to start_page

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.330 2006/04/11 18:43:46 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonlocal;
   63: use HTML::Entities;
   64: 
   65: my $readit;
   66: 
   67: ##
   68: ## Global Variables
   69: ##
   70: 
   71: # ----------------------------------------------- Filetypes/Languages/Copyright
   72: my %language;
   73: my %supported_language;
   74: my %cprtag;
   75: my %scprtag;
   76: my %fe; my %fd;
   77: my %category_extensions;
   78: 
   79: # ---------------------------------------------- Designs
   80: 
   81: my %designhash;
   82: 
   83: # ---------------------------------------------- Thesaurus variables
   84: #
   85: # %Keywords:
   86: #      A hash used by &keyword to determine if a word is considered a keyword.
   87: # $thesaurus_db_file 
   88: #      Scalar containing the full path to the thesaurus database.
   89: 
   90: my %Keywords;
   91: my $thesaurus_db_file;
   92: 
   93: #
   94: # Initialize values from language.tab, copyright.tab, filetypes.tab,
   95: # thesaurus.tab, and filecategories.tab.
   96: #
   97: BEGIN {
   98:     # Variable initialization
   99:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  100:     #
  101:     unless ($readit) {
  102: # ------------------------------------------------------------------- languages
  103:     {
  104:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  105:                                    '/language.tab';
  106:         if ( open(my $fh,"<$langtabfile") ) {
  107:             while (<$fh>) {
  108:                 next if /^\#/;
  109:                 chomp;
  110:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
  111:                 $language{$key}=$val.' - '.$enc;
  112:                 if ($sup) {
  113:                     $supported_language{$key}=$sup;
  114:                 }
  115:             }
  116:             close($fh);
  117:         }
  118:     }
  119: # ------------------------------------------------------------------ copyrights
  120:     {
  121:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  122:                                   '/copyright.tab';
  123:         if ( open (my $fh,"<$copyrightfile") ) {
  124:             while (<$fh>) {
  125:                 next if /^\#/;
  126:                 chomp;
  127:                 my ($key,$val)=(split(/\s+/,$_,2));
  128:                 $cprtag{$key}=$val;
  129:             }
  130:             close($fh);
  131:         }
  132:     }
  133: # ------------------------------------------------------------------ source copyrights
  134:     {
  135:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  136:                                   '/source_copyright.tab';
  137:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  138:             while (<$fh>) {
  139:                 next if /^\#/;
  140:                 chomp;
  141:                 my ($key,$val)=(split(/\s+/,$_,2));
  142:                 $scprtag{$key}=$val;
  143:             }
  144:             close($fh);
  145:         }
  146:     }
  147: 
  148: # -------------------------------------------------------------- domain designs
  149: 
  150:     my $filename;
  151:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  152:     opendir(DIR,$designdir);
  153:     while ($filename=readdir(DIR)) {
  154: 	if ($filename!~/\.tab$/) { next; }
  155: 	my ($domain)=($filename=~/^(\w+)\./);
  156: 	{
  157: 	    my $designfile = $designdir.'/'.$filename;
  158: 	    if ( open (my $fh,"<$designfile") ) {
  159: 		while (<$fh>) {
  160: 		    next if /^\#/;
  161: 		    chomp;
  162: 		    my ($key,$val)=(split(/\=/,$_));
  163: 		    if ($val) { $designhash{$domain.'.'.$key}=$val; }
  164: 		}
  165: 		close($fh);
  166: 	    }
  167: 	}
  168: 
  169:     }
  170:     closedir(DIR);
  171: 
  172: 
  173: # ------------------------------------------------------------- file categories
  174:     {
  175:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  176:                                   '/filecategories.tab';
  177:         if ( open (my $fh,"<$categoryfile") ) {
  178:             while (<$fh>) {
  179:                 next if /^\#/;
  180:                 chomp;
  181:                 my ($extension,$category)=(split(/\s+/,$_,2));
  182:                 push @{$category_extensions{lc($category)}},$extension;
  183:             }
  184:             close($fh);
  185:         }
  186: 
  187:     }
  188: # ------------------------------------------------------------------ file types
  189:     {
  190:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  191:                '/filetypes.tab';
  192:         if ( open (my $fh,"<$typesfile") ) {
  193:             while (<$fh>) {
  194:                 next if (/^\#/);
  195:                 chomp;
  196:                 my ($ending,$emb,$descr)=split(/\s+/,$_,3);
  197:                 if ($descr ne '') {
  198:                     $fe{$ending}=lc($emb);
  199:                     $fd{$ending}=$descr;
  200:                 }
  201:             }
  202:             close($fh);
  203:         }
  204:     }
  205:     &Apache::lonnet::logthis(
  206:               "<font color=yellow>INFO: Read file types</font>");
  207:     $readit=1;
  208:     }  # end of unless($readit) 
  209:     
  210: }
  211: 
  212: ###############################################################
  213: ##           HTML and Javascript Helper Functions            ##
  214: ###############################################################
  215: 
  216: =pod 
  217: 
  218: =head1 HTML and Javascript Functions
  219: 
  220: =over 4
  221: 
  222: =item * browser_and_searcher_javascript ()
  223: 
  224: X<browsing, javascript>X<searching, javascript>Returns a string
  225: containing javascript with two functions, C<openbrowser> and
  226: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  227: tags.
  228: 
  229: =item * openbrowser(formname,elementname,only,omit) [javascript]
  230: 
  231: inputs: formname, elementname, only, omit
  232: 
  233: formname and elementname indicate the name of the html form and name of
  234: the element that the results of the browsing selection are to be placed in. 
  235: 
  236: Specifying 'only' will restrict the browser to displaying only files
  237: with the given extension.  Can be a comma separated list.
  238: 
  239: Specifying 'omit' will restrict the browser to NOT displaying files
  240: with the given extension.  Can be a comma separated list.
  241: 
  242: =item * opensearcher(formname, elementname) [javascript]
  243: 
  244: Inputs: formname, elementname
  245: 
  246: formname and elementname specify the name of the html form and the name
  247: of the element the selection from the search results will be placed in.
  248: 
  249: =cut
  250: 
  251: sub browser_and_searcher_javascript {
  252:     my ($mode)=@_;
  253:     if (!defined($mode)) { $mode='edit'; }
  254:     my $resurl=&lastresurl();
  255:     return <<END;
  256: // <!-- BEGIN LON-CAPA Internal
  257:     var editbrowser = null;
  258:     function openbrowser(formname,elementname,only,omit,titleelement) {
  259:         var url = '$resurl/?';
  260:         if (editbrowser == null) {
  261:             url += 'launch=1&';
  262:         }
  263:         url += 'catalogmode=interactive&';
  264:         url += 'mode=$mode&';
  265:         url += 'form=' + formname + '&';
  266:         if (only != null) {
  267:             url += 'only=' + only + '&';
  268:         } else {
  269:             url += 'only=&';
  270: 	}
  271:         if (omit != null) {
  272:             url += 'omit=' + omit + '&';
  273:         } else {
  274:             url += 'omit=&';
  275: 	}
  276:         if (titleelement != null) {
  277:             url += 'titleelement=' + titleelement + '&';
  278:         } else {
  279: 	    url += 'titleelement=&';
  280: 	}
  281:         url += 'element=' + elementname + '';
  282:         var title = 'Browser';
  283:         var options = 'scrollbars=1,resizable=1,menubar=1,location=1';
  284:         options += ',width=700,height=600';
  285:         editbrowser = open(url,title,options,'1');
  286:         editbrowser.focus();
  287:     }
  288:     var editsearcher;
  289:     function opensearcher(formname,elementname,titleelement) {
  290:         var url = '/adm/searchcat?';
  291:         if (editsearcher == null) {
  292:             url += 'launch=1&';
  293:         }
  294:         url += 'catalogmode=interactive&';
  295:         url += 'mode=$mode&';
  296:         url += 'form=' + formname + '&';
  297:         if (titleelement != null) {
  298:             url += 'titleelement=' + titleelement + '&';
  299:         } else {
  300: 	    url += 'titleelement=&';
  301: 	}
  302:         url += 'element=' + elementname + '';
  303:         var title = 'Search';
  304:         var options = 'scrollbars=1,resizable=1,menubar=0';
  305:         options += ',width=700,height=600';
  306:         editsearcher = open(url,title,options,'1');
  307:         editsearcher.focus();
  308:     }
  309: // END LON-CAPA Internal -->
  310: END
  311: }
  312: 
  313: sub lastresurl {
  314:     if ($env{'environment.lastresurl'}) {
  315: 	return $env{'environment.lastresurl'}
  316:     } else {
  317: 	return '/res';
  318:     }
  319: }
  320: 
  321: sub storeresurl {
  322:     my $resurl=&Apache::lonnet::clutter(shift);
  323:     unless ($resurl=~/^\/res/) { return 0; }
  324:     $resurl=~s/\/$//;
  325:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  326:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  327:     return 1;
  328: }
  329: 
  330: sub studentbrowser_javascript {
  331:    unless (
  332:             (($env{'request.course.id'}) && 
  333:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  334: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  335: 					  '/'.$env{'request.course.sec'})
  336: 	      ))
  337:          || ($env{'request.role'}=~/^(au|dc|su)/)
  338:           ) { return ''; }  
  339:    return (<<'ENDSTDBRW');
  340: <script type="text/javascript" language="Javascript" >
  341:     var stdeditbrowser;
  342:     function openstdbrowser(formname,uname,udom,roleflag) {
  343:         var url = '/adm/pickstudent?';
  344:         var filter;
  345:         eval('filter=document.'+formname+'.'+uname+'.value;');
  346:         if (filter != null) {
  347:            if (filter != '') {
  348:                url += 'filter='+filter+'&';
  349: 	   }
  350:         }
  351:         url += 'form=' + formname + '&unameelement='+uname+
  352:                                     '&udomelement='+udom;
  353: 	if (roleflag) { url+="&roles=1"; }
  354:         var title = 'Student_Browser';
  355:         var options = 'scrollbars=1,resizable=1,menubar=0';
  356:         options += ',width=700,height=600';
  357:         stdeditbrowser = open(url,title,options,'1');
  358:         stdeditbrowser.focus();
  359:     }
  360: </script>
  361: ENDSTDBRW
  362: }
  363: 
  364: sub selectstudent_link {
  365:    my ($form,$unameele,$udomele)=@_;
  366:    if ($env{'request.course.id'}) {  
  367:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  368: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  369: 					'/'.$env{'request.course.sec'})) {
  370: 	   return '';
  371:        }
  372:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  373:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  374:    }
  375:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  376:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  377:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  378:    }
  379:    return '';
  380: }
  381: 
  382: sub coursebrowser_javascript {
  383:     my ($domainfilter)=@_;
  384:    return (<<ENDSTDBRW);
  385: <script type="text/javascript" language="Javascript" >
  386:     var stdeditbrowser;
  387:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag) {
  388:         var url = '/adm/pickcourse?';
  389:         var filter;
  390:         if (filter != null) {
  391:            if (filter != '') {
  392:                url += 'filter='+filter+'&';
  393: 	   }
  394:         }
  395:         var domainfilter='$domainfilter';
  396:         if (domainfilter != null) {
  397:            if (domainfilter != '') {
  398:                url += 'domainfilter='+domainfilter+'&';
  399: 	   }
  400:         }
  401:         url += 'form=' + formname + '&cnumelement='+uname+
  402: 	                            '&cdomelement='+udom+
  403:                                     '&cnameelement='+desc;
  404:         if (extra_element !=null && extra_element != '' && formname == 'rolechoice') {
  405:             url += '&roleelement='+extra_element;
  406:             if (domainfilter == null || domainfilter == '') {
  407:                 url += '&domainfilter='+extra_element;
  408:             }
  409:         }
  410:         if (multflag !=null && multflag != '') {
  411:             url += '&multiple='+multflag;
  412:         }
  413:         var title = 'Course_Browser';
  414:         var options = 'scrollbars=1,resizable=1,menubar=0';
  415:         options += ',width=700,height=600';
  416:         stdeditbrowser = open(url,title,options,'1');
  417:         stdeditbrowser.focus();
  418:     }
  419: </script>
  420: ENDSTDBRW
  421: }
  422: 
  423: sub selectcourse_link {
  424:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag)=@_;
  425:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  426:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'");'."'>".&mt('Select Course')."</a>";
  427: }
  428: 
  429: sub check_uncheck_jscript {
  430:     my $jscript = <<"ENDSCRT";
  431: function checkAll(field) {
  432:     if (field.length > 0) {
  433:         for (i = 0; i < field.length; i++) {
  434:             field[i].checked = true ;
  435:         }
  436:     } else {
  437:         field.checked = true
  438:     }
  439: }
  440:  
  441: function uncheckAll(field) {
  442:     if (field.length > 0) {
  443:         for (i = 0; i < field.length; i++) {
  444:             field[i].checked = false ;
  445:         }     } else {
  446:         field.checked = false ;
  447:     }
  448: }
  449: ENDSCRT
  450:     return $jscript;
  451: }
  452: 
  453: 
  454: =pod
  455: 
  456: =item * linked_select_forms(...)
  457: 
  458: linked_select_forms returns a string containing a <script></script> block
  459: and html for two <select> menus.  The select menus will be linked in that
  460: changing the value of the first menu will result in new values being placed
  461: in the second menu.  The values in the select menu will appear in alphabetical
  462: order.
  463: 
  464: linked_select_forms takes the following ordered inputs:
  465: 
  466: =over 4
  467: 
  468: =item * $formname, the name of the <form> tag
  469: 
  470: =item * $middletext, the text which appears between the <select> tags
  471: 
  472: =item * $firstdefault, the default value for the first menu
  473: 
  474: =item * $firstselectname, the name of the first <select> tag
  475: 
  476: =item * $secondselectname, the name of the second <select> tag
  477: 
  478: =item * $hashref, a reference to a hash containing the data for the menus.
  479: 
  480: =back 
  481: 
  482: Below is an example of such a hash.  Only the 'text', 'default', and 
  483: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  484: values for the first select menu.  The text that coincides with the 
  485: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  486: and text for the second menu are given in the hash pointed to by 
  487: $menu{$choice1}->{'select2'}.  
  488: 
  489:  my %menu = ( A1 => { text =>"Choice A1" ,
  490:                        default => "B3",
  491:                        select2 => { 
  492:                            B1 => "Choice B1",
  493:                            B2 => "Choice B2",
  494:                            B3 => "Choice B3",
  495:                            B4 => "Choice B4"
  496:                            }
  497:                    },
  498:                A2 => { text =>"Choice A2" ,
  499:                        default => "C2",
  500:                        select2 => { 
  501:                            C1 => "Choice C1",
  502:                            C2 => "Choice C2",
  503:                            C3 => "Choice C3"
  504:                            }
  505:                    },
  506:                A3 => { text =>"Choice A3" ,
  507:                        default => "D6",
  508:                        select2 => { 
  509:                            D1 => "Choice D1",
  510:                            D2 => "Choice D2",
  511:                            D3 => "Choice D3",
  512:                            D4 => "Choice D4",
  513:                            D5 => "Choice D5",
  514:                            D6 => "Choice D6",
  515:                            D7 => "Choice D7"
  516:                            }
  517:                    }
  518:                );
  519: 
  520: =cut
  521: 
  522: sub linked_select_forms {
  523:     my ($formname,
  524:         $middletext,
  525:         $firstdefault,
  526:         $firstselectname,
  527:         $secondselectname, 
  528:         $hashref
  529:         ) = @_;
  530:     my $second = "document.$formname.$secondselectname";
  531:     my $first = "document.$formname.$firstselectname";
  532:     # output the javascript to do the changing
  533:     my $result = '';
  534:     $result.="<script type=\"text/javascript\">\n";
  535:     $result.="var select2data = new Object();\n";
  536:     $" = '","';
  537:     my $debug = '';
  538:     foreach my $s1 (sort(keys(%$hashref))) {
  539:         $result.="select2data.d_$s1 = new Object();\n";        
  540:         $result.="select2data.d_$s1.def = new String('".
  541:             $hashref->{$s1}->{'default'}."');\n";
  542:         $result.="select2data.d_$s1.values = new Array(";        
  543:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  544:         $result.="\"@s2values\");\n";
  545:         $result.="select2data.d_$s1.texts = new Array(";        
  546:         my @s2texts;
  547:         foreach my $value (@s2values) {
  548:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  549:         }
  550:         $result.="\"@s2texts\");\n";
  551:     }
  552:     $"=' ';
  553:     $result.= <<"END";
  554: 
  555: function select1_changed() {
  556:     // Determine new choice
  557:     var newvalue = "d_" + $first.value;
  558:     // update select2
  559:     var values     = select2data[newvalue].values;
  560:     var texts      = select2data[newvalue].texts;
  561:     var select2def = select2data[newvalue].def;
  562:     var i;
  563:     // out with the old
  564:     for (i = 0; i < $second.options.length; i++) {
  565:         $second.options[i] = null;
  566:     }
  567:     // in with the nuclear
  568:     for (i=0;i<values.length; i++) {
  569:         $second.options[i] = new Option(values[i]);
  570:         $second.options[i].value = values[i];
  571:         $second.options[i].text = texts[i];
  572:         if (values[i] == select2def) {
  573:             $second.options[i].selected = true;
  574:         }
  575:     }
  576: }
  577: </script>
  578: END
  579:     # output the initial values for the selection lists
  580:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  581:     foreach my $value (sort(keys(%$hashref))) {
  582:         $result.="    <option value=\"$value\" ";
  583:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  584:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  585:     }
  586:     $result .= "</select>\n";
  587:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  588:     $result .= $middletext;
  589:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  590:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  591:     foreach my $value (sort(keys(%select2))) {
  592:         $result.="    <option value=\"$value\" ";        
  593:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  594:         $result.=">".&mt($select2{$value})."</option>\n";
  595:     }
  596:     $result .= "</select>\n";
  597:     #    return $debug;
  598:     return $result;
  599: }   #  end of sub linked_select_forms {
  600: 
  601: =pod
  602: 
  603: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  604: 
  605: Returns a string corresponding to an HTML link to the given help
  606: $topic, where $topic corresponds to the name of a .tex file in
  607: /home/httpd/html/adm/help/tex, with underscores replaced by
  608: spaces. 
  609: 
  610: $text will optionally be linked to the same topic, allowing you to
  611: link text in addition to the graphic. If you do not want to link
  612: text, but wish to specify one of the later parameters, pass an
  613: empty string. 
  614: 
  615: $stayOnPage is a value that will be interpreted as a boolean. If true,
  616: the link will not open a new window. If false, the link will open
  617: a new window using Javascript. (Default is false.) 
  618: 
  619: $width and $height are optional numerical parameters that will
  620: override the width and height of the popped up window, which may
  621: be useful for certain help topics with big pictures included. 
  622: 
  623: =cut
  624: 
  625: sub help_open_topic {
  626:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  627:     $text = "" if (not defined $text);
  628:     $stayOnPage = 0 if (not defined $stayOnPage);
  629:     if ($env{'browser.interface'} eq 'textual' ||
  630: 	$env{'environment.remote'} eq 'off' ) {
  631: 	$stayOnPage=1;
  632:     }
  633:     $width = 350 if (not defined $width);
  634:     $height = 400 if (not defined $height);
  635:     my $filename = $topic;
  636:     $filename =~ s/ /_/g;
  637: 
  638:     my $template = "";
  639:     my $link;
  640: 
  641:     $topic=~s/\W/\_/g;
  642: 
  643:     if (!$stayOnPage)
  644:     {
  645: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  646:     }
  647:     else
  648:     {
  649: 	$link = "/adm/help/${filename}.hlp";
  650:     }
  651: 
  652:     # Add the text
  653:     if ($text ne "")
  654:     {
  655: 	$template .= 
  656:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  657:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  658:     }
  659: 
  660:     # Add the graphic
  661:     my $title = &mt('Online Help');
  662:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  663:     $template .= <<"ENDTEMPLATE";
  664:  <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  665: ENDTEMPLATE
  666:     if ($text ne '') { $template.='</td></tr></table>' };
  667:     return $template;
  668: 
  669: }
  670: 
  671: # This is a quicky function for Latex cheatsheet editing, since it 
  672: # appears in at least four places
  673: sub helpLatexCheatsheet {
  674:     my $other = shift;
  675:     my $addOther = '';
  676:     if ($other) {
  677: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  678: 						       undef, undef, 600) .
  679: 							   '</td><td>';
  680:     }
  681:     return '<table><tr><td>'.
  682: 	$addOther .
  683: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  684: 					    undef,undef,600)
  685: 	.'</td><td>'.
  686: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  687: 					    undef,undef,600)
  688: 	.'</td></tr></table>';
  689: }
  690: 
  691: sub help_open_menu {
  692:     my ($color,$topic,$component_help,$function,$faq,$bug,$stayOnPage,$width,$height,$text) = @_;
  693:     $text = "" if (not defined $text);
  694:     $stayOnPage = 0 if (not defined $stayOnPage);
  695:     if ($env{'browser.interface'} eq 'textual' ||
  696:         $env{'environment.remote'} eq 'off' ) {
  697:         $stayOnPage=1;
  698:     }
  699:     $width = 620 if (not defined $width);
  700:     $height = 600 if (not defined $height);
  701:     my $link='';
  702:     my $title = &mt('Get help');
  703:     my $origurl = $ENV{'REQUEST_URI'};
  704:     $origurl=~s|^/~|/priv/|;
  705:     my $timestamp = time;
  706:     foreach (\$color,\$function,\$topic,\$component_help,\$faq,\$bug,\$origurl) {
  707:         $$_ = &Apache::lonnet::escape($$_);
  708:     }
  709:     if (!$stayOnPage) {
  710:          $link = "javascript:helpMenu('open')";
  711:     } else {
  712:         $link = "javascript:helpMenu('display')";
  713:     }
  714:     my $banner_link = "/adm/helpmenu?page=banner&color=$color&function=$function&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
  715:     my $details_link = "/adm/helpmenu?page=body&color=$color&function=$function&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp";
  716:     my $template;
  717:     if ($text ne "") {
  718: 	$template .= 
  719:   "<table bgcolor='#CC3300' cellspacing='1' cellpadding='1' border='0'><tr>".
  720:   "<td bgcolor='#CC6600'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  721:     }
  722:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  723:     my $html=&Apache::lonxml::xmlbegin();
  724:     my $helpicon=&lonhttpdurl("/adm/lonIcons/helpgateway.gif");
  725:     $template .= <<"ENDTEMPLATE";
  726:  <script type="text/javascript">
  727: // <!-- BEGIN LON-CAPA Internal
  728: // <![CDATA[
  729: function helpMenu(target) {
  730:     var caller = this;
  731:     if (target == 'open') {
  732:         var newWindow = null;
  733:         try {
  734:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  735:         }
  736:         catch(error) {
  737:             writeHelp(caller);
  738:             return;
  739:         }
  740:         if (newWindow) {
  741:             caller = newWindow;
  742:         }
  743:     }
  744:     writeHelp(caller);
  745:     return;
  746: }
  747: function writeHelp(caller) {
  748:     caller.document.writeln('$html<head><title>LON-CAPA Help Menu</title><meta http-equiv="pragma" content="no-cache"></head>')
  749:     caller.document.writeln("<frameset rows='105,*' border='0'><frame name='bannerframe'  src='$banner_link'><frame name='bodyframe' src='$details_link'></frameset>")
  750:     caller.document.writeln("</html>")
  751:     caller.document.close()
  752:     caller.focus()
  753: }
  754: // ]]>
  755: // END LON-CAPA Internal -->
  756:  </script>
  757:  <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help Menu)" /></a>
  758: ENDTEMPLATE
  759:     if ($component_help) {
  760: 	if (!$text) {
  761: 	    $template=&help_open_topic($component_help,undef,$stayOnPage,
  762: 				       $width,$height).' '.$template;
  763: 	} else {
  764: 	    my $help_text;
  765: 	    $help_text=&Apache::lonnet::unescape($topic);
  766: 	    $template='<table><tr><td>'.
  767: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  768: 				 $width,$height).'</td><td>'.$template.
  769: 				 '</td></tr></table>';
  770: 	}
  771:     }
  772:     if ($text ne '') { $template.='</td></tr></table>' };
  773:     return $template;
  774: }
  775: 
  776: sub help_open_bug {
  777:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  778:     unless ($env{'user.adv'}) { return ''; }
  779:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  780:     $text = "" if (not defined $text);
  781:     $stayOnPage = 0 if (not defined $stayOnPage);
  782:     if ($env{'browser.interface'} eq 'textual' ||
  783: 	$env{'environment.remote'} eq 'off' ) {
  784: 	$stayOnPage=1;
  785:     }
  786:     $width = 600 if (not defined $width);
  787:     $height = 600 if (not defined $height);
  788: 
  789:     $topic=~s/\W+/\+/g;
  790:     my $link='';
  791:     my $template='';
  792:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
  793: 	&Apache::lonnet::escape($ENV{'REQUEST_URI'}).'&component='.$topic;
  794:     if (!$stayOnPage)
  795:     {
  796: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  797:     }
  798:     else
  799:     {
  800: 	$link = $url;
  801:     }
  802:     # Add the text
  803:     if ($text ne "")
  804:     {
  805: 	$template .= 
  806:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  807:   "<td bgcolor='#FF5555'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  808:     }
  809: 
  810:     # Add the graphic
  811:     my $title = &mt('Report a Bug');
  812:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
  813:     $template .= <<"ENDTEMPLATE";
  814:  <a href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
  815: ENDTEMPLATE
  816:     if ($text ne '') { $template.='</td></tr></table>' };
  817:     return $template;
  818: 
  819: }
  820: 
  821: sub help_open_faq {
  822:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  823:     unless ($env{'user.adv'}) { return ''; }
  824:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  825:     $text = "" if (not defined $text);
  826:     $stayOnPage = 0 if (not defined $stayOnPage);
  827:     if ($env{'browser.interface'} eq 'textual' ||
  828: 	$env{'environment.remote'} eq 'off' ) {
  829: 	$stayOnPage=1;
  830:     }
  831:     $width = 350 if (not defined $width);
  832:     $height = 400 if (not defined $height);
  833: 
  834:     $topic=~s/\W+/\+/g;
  835:     my $link='';
  836:     my $template='';
  837:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  838:     if (!$stayOnPage)
  839:     {
  840: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  841:     }
  842:     else
  843:     {
  844: 	$link = $url;
  845:     }
  846: 
  847:     # Add the text
  848:     if ($text ne "")
  849:     {
  850: 	$template .= 
  851:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
  852:   "<td bgcolor='#448844'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  853:     }
  854: 
  855:     # Add the graphic
  856:     my $title = &mt('View the FAQ');
  857:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
  858:     $template .= <<"ENDTEMPLATE";
  859:  <a href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
  860: ENDTEMPLATE
  861:     if ($text ne '') { $template.='</td></tr></table>' };
  862:     return $template;
  863: 
  864: }
  865: 
  866: ###############################################################
  867: ###############################################################
  868: 
  869: =pod
  870: 
  871: =item * change_content_javascript():
  872: 
  873: This and the next function allow you to create small sections of an
  874: otherwise static HTML page that you can update on the fly with
  875: Javascript, even in Netscape 4.
  876: 
  877: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
  878: must be written to the HTML page once. It will prove the Javascript
  879: function "change(name, content)". Calling the change function with the
  880: name of the section 
  881: you want to update, matching the name passed to C<changable_area>, and
  882: the new content you want to put in there, will put the content into
  883: that area.
  884: 
  885: B<Note>: Netscape 4 only reserves enough space for the changable area
  886: to contain room for the original contents. You need to "make space"
  887: for whatever changes you wish to make, and be B<sure> to check your
  888: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
  889: it's adequate for updating a one-line status display, but little more.
  890: This script will set the space to 100% width, so you only need to
  891: worry about height in Netscape 4.
  892: 
  893: Modern browsers are much less limiting, and if you can commit to the
  894: user not using Netscape 4, this feature may be used freely with
  895: pretty much any HTML.
  896: 
  897: =cut
  898: 
  899: sub change_content_javascript {
  900:     # If we're on Netscape 4, we need to use Layer-based code
  901:     if ($env{'browser.type'} eq 'netscape' &&
  902: 	$env{'browser.version'} =~ /^4\./) {
  903: 	return (<<NETSCAPE4);
  904: 	function change(name, content) {
  905: 	    doc = document.layers[name+"___escape"].layers[0].document;
  906: 	    doc.open();
  907: 	    doc.write(content);
  908: 	    doc.close();
  909: 	}
  910: NETSCAPE4
  911:     } else {
  912: 	# Otherwise, we need to use semi-standards-compliant code
  913: 	# (technically, "innerHTML" isn't standard but the equivalent
  914: 	# is really scary, and every useful browser supports it
  915: 	return (<<DOMBASED);
  916: 	function change(name, content) {
  917: 	    element = document.getElementById(name);
  918: 	    element.innerHTML = content;
  919: 	}
  920: DOMBASED
  921:     }
  922: }
  923: 
  924: =pod
  925: 
  926: =item * changable_area($name, $origContent):
  927: 
  928: This provides a "changable area" that can be modified on the fly via
  929: the Javascript code provided in C<change_content_javascript>. $name is
  930: the name you will use to reference the area later; do not repeat the
  931: same name on a given HTML page more then once. $origContent is what
  932: the area will originally contain, which can be left blank.
  933: 
  934: =cut
  935: 
  936: sub changable_area {
  937:     my ($name, $origContent) = @_;
  938: 
  939:     if ($env{'browser.type'} eq 'netscape' &&
  940: 	$env{'browser.version'} =~ /^4\./) {
  941: 	# If this is netscape 4, we need to use the Layer tag
  942: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
  943:     } else {
  944: 	return "<span id='$name'>$origContent</span>";
  945:     }
  946: }
  947: 
  948: =pod
  949: 
  950: =back
  951: 
  952: =head1 Excel and CSV file utility routines
  953: 
  954: =over 4
  955: 
  956: =cut
  957: 
  958: ###############################################################
  959: ###############################################################
  960: 
  961: =pod
  962: 
  963: =item * csv_translate($text) 
  964: 
  965: Translate $text to allow it to be output as a 'comma separated values' 
  966: format.
  967: 
  968: =cut
  969: 
  970: ###############################################################
  971: ###############################################################
  972: sub csv_translate {
  973:     my $text = shift;
  974:     $text =~ s/\"/\"\"/g;
  975:     $text =~ s/\n/ /g;
  976:     return $text;
  977: }
  978: 
  979: ###############################################################
  980: ###############################################################
  981: 
  982: =pod
  983: 
  984: =item * define_excel_formats
  985: 
  986: Define some commonly used Excel cell formats.
  987: 
  988: Currently supported formats:
  989: 
  990: =over 4
  991: 
  992: =item header
  993: 
  994: =item bold
  995: 
  996: =item h1
  997: 
  998: =item h2
  999: 
 1000: =item h3
 1001: 
 1002: =item h4
 1003: 
 1004: =item i
 1005: 
 1006: =item date
 1007: 
 1008: =back
 1009: 
 1010: Inputs: $workbook
 1011: 
 1012: Returns: $format, a hash reference.
 1013: 
 1014: =cut
 1015: 
 1016: ###############################################################
 1017: ###############################################################
 1018: sub define_excel_formats {
 1019:     my ($workbook) = @_;
 1020:     my $format;
 1021:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1022:                                                 bottom    => 1,
 1023:                                                 align     => 'center');
 1024:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1025:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1026:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1027:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1028:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1029:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1030:     $format->{'date'} = $workbook->add_format(num_format=>
 1031:                                             'mm/dd/yyyy hh:mm:ss');
 1032:     return $format;
 1033: }
 1034: 
 1035: ###############################################################
 1036: ###############################################################
 1037: 
 1038: =pod
 1039: 
 1040: =item * create_workbook
 1041: 
 1042: Create an Excel worksheet.  If it fails, output message on the
 1043: request object and return undefs.
 1044: 
 1045: Inputs: Apache request object
 1046: 
 1047: Returns (undef) on failure, 
 1048:     Excel worksheet object, scalar with filename, and formats 
 1049:     from &Apache::loncommon::define_excel_formats on success
 1050: 
 1051: =cut
 1052: 
 1053: ###############################################################
 1054: ###############################################################
 1055: sub create_workbook {
 1056:     my ($r) = @_;
 1057:         #
 1058:     # Create the excel spreadsheet
 1059:     my $filename = '/prtspool/'.
 1060:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1061:         time.'_'.rand(1000000000).'.xls';
 1062:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1063:     if (! defined($workbook)) {
 1064:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1065:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1066:                             "This error has been logged.  ".
 1067:                             "Please alert your LON-CAPA administrator").
 1068:                   '</p>');
 1069:         return (undef);
 1070:     }
 1071:     #
 1072:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1073:     #
 1074:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1075:     return ($workbook,$filename,$format);
 1076: }
 1077: 
 1078: ###############################################################
 1079: ###############################################################
 1080: 
 1081: =pod
 1082: 
 1083: =item * create_text_file
 1084: 
 1085: Create a file to write to and eventually make available to the usre.
 1086: If file creation fails, outputs an error message on the request object and 
 1087: return undefs.
 1088: 
 1089: Inputs: Apache request object, and file suffix
 1090: 
 1091: Returns (undef) on failure, 
 1092:     Filehandle and filename on success.
 1093: 
 1094: =cut
 1095: 
 1096: ###############################################################
 1097: ###############################################################
 1098: sub create_text_file {
 1099:     my ($r,$suffix) = @_;
 1100:     if (! defined($suffix)) { $suffix = 'txt'; };
 1101:     my $fh;
 1102:     my $filename = '/prtspool/'.
 1103:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1104:         time.'_'.rand(1000000000).'.'.$suffix;
 1105:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1106:     if (! defined($fh)) {
 1107:         $r->log_error("Couldn't open $filename for output $!");
 1108:         $r->print("Problems occured in creating the output file.  ".
 1109:                   "This error has been logged.  ".
 1110:                   "Please alert your LON-CAPA administrator.");
 1111:     }
 1112:     return ($fh,$filename)
 1113: }
 1114: 
 1115: 
 1116: =pod 
 1117: 
 1118: =back
 1119: 
 1120: =cut
 1121: 
 1122: ###############################################################
 1123: ##        Home server <option> list generating code          ##
 1124: ###############################################################
 1125: 
 1126: =pod
 1127: 
 1128: =head1 Home Server option list generating code
 1129: 
 1130: =over 4
 1131: 
 1132: =item * get_domains()
 1133: 
 1134: Returns an array containing each of the domains listed in the hosts.tab
 1135: file.
 1136: 
 1137: =cut
 1138: 
 1139: #-------------------------------------------
 1140: sub get_domains {
 1141:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
 1142:     my @domains;
 1143:     my %seen;
 1144:     foreach (sort values(%Apache::lonnet::hostdom)) {
 1145: 	push (@domains,$_) unless $seen{$_}++;
 1146:     }
 1147:     return @domains;
 1148: }
 1149: 
 1150: # ------------------------------------------
 1151: 
 1152: sub domain_select {
 1153:     my ($name,$value,$multiple)=@_;
 1154:     my %domains=map { 
 1155: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
 1156:     } &get_domains;
 1157:     if ($multiple) {
 1158: 	$domains{''}=&mt('Any domain');
 1159: 	return &multiple_select_form($name,$value,4,\%domains);
 1160:     } else {
 1161: 	return &select_form($name,$value,%domains);
 1162:     }
 1163: }
 1164: 
 1165: #-------------------------------------------
 1166: 
 1167: =pod
 1168: 
 1169: =item * multiple_select_form($name,$value,$size,$hash,$order)
 1170: 
 1171: Returns a string containing a <select> element int multiple mode
 1172: 
 1173: 
 1174: Args:
 1175:   $name - name of the <select> element
 1176:   $value - sclara or array ref of values that should already be selected
 1177:   $size - number of rows long the select element is
 1178:   $hash - the elements should be 'option' => 'shown text'
 1179:           (shown text should already have been &mt())
 1180:   $order - (optional) array ref of the order to show the elments in
 1181: 
 1182: =cut
 1183: 
 1184: #-------------------------------------------
 1185: sub multiple_select_form {
 1186:     my ($name,$value,$size,$hash,$order)=@_;
 1187:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1188:     my $output='';
 1189:     if (! defined($size)) {
 1190:         $size = 4;
 1191:         if (scalar(keys(%$hash))<4) {
 1192:             $size = scalar(keys(%$hash));
 1193:         }
 1194:     }
 1195:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1196:     my @order = ref($order) ? @$order
 1197:                             : sort(keys(%$hash));
 1198:     foreach my $key (@order) {
 1199:         $output.='<option value="'.$key.'" ';
 1200:         $output.='selected="selected" ' if ($selected{$key});
 1201:         $output.='>'.$hash->{$key}."</option>\n";
 1202:     }
 1203:     $output.="</select>\n";
 1204:     return $output;
 1205: }
 1206: 
 1207: #-------------------------------------------
 1208: 
 1209: =pod
 1210: 
 1211: =item * select_form($defdom,$name,%hash)
 1212: 
 1213: Returns a string containing a <select name='$name' size='1'> form to 
 1214: allow a user to select options from a hash option_name => displayed text.  
 1215: See lonrights.pm for an example invocation and use.
 1216: 
 1217: =cut
 1218: 
 1219: #-------------------------------------------
 1220: sub select_form {
 1221:     my ($def,$name,%hash) = @_;
 1222:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1223:     my @keys;
 1224:     if (exists($hash{'select_form_order'})) {
 1225: 	@keys=@{$hash{'select_form_order'}};
 1226:     } else {
 1227: 	@keys=sort(keys(%hash));
 1228:     }
 1229:     foreach (@keys) {
 1230:         $selectform.="<option value=\"$_\" ".
 1231:             ($_ eq $def ? 'selected="selected" ' : '').
 1232:                 ">".&mt($hash{$_})."</option>\n";
 1233:     }
 1234:     $selectform.="</select>";
 1235:     return $selectform;
 1236: }
 1237: 
 1238: sub gradeleveldescription {
 1239:     my $gradelevel=shift;
 1240:     my %gradelevels=(0 => 'Not specified',
 1241: 		     1 => 'Grade 1',
 1242: 		     2 => 'Grade 2',
 1243: 		     3 => 'Grade 3',
 1244: 		     4 => 'Grade 4',
 1245: 		     5 => 'Grade 5',
 1246: 		     6 => 'Grade 6',
 1247: 		     7 => 'Grade 7',
 1248: 		     8 => 'Grade 8',
 1249: 		     9 => 'Grade 9',
 1250: 		     10 => 'Grade 10',
 1251: 		     11 => 'Grade 11',
 1252: 		     12 => 'Grade 12',
 1253: 		     13 => 'Grade 13',
 1254: 		     14 => '100 Level',
 1255: 		     15 => '200 Level',
 1256: 		     16 => '300 Level',
 1257: 		     17 => '400 Level',
 1258: 		     18 => 'Graduate Level');
 1259:     return &mt($gradelevels{$gradelevel});
 1260: }
 1261: 
 1262: sub select_level_form {
 1263:     my ($deflevel,$name)=@_;
 1264:     unless ($deflevel) { $deflevel=0; }
 1265:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1266:     for (my $i=0; $i<=18; $i++) {
 1267:         $selectform.="<option value=\"$i\" ".
 1268:             ($i==$deflevel ? 'selected="selected" ' : '').
 1269:                 ">".&gradeleveldescription($i)."</option>\n";
 1270:     }
 1271:     $selectform.="</select>";
 1272:     return $selectform;
 1273: }
 1274: 
 1275: #-------------------------------------------
 1276: 
 1277: =pod
 1278: 
 1279: =item * select_dom_form($defdom,$name,$includeempty)
 1280: 
 1281: Returns a string containing a <select name='$name' size='1'> form to 
 1282: allow a user to select the domain to preform an operation in.  
 1283: See loncreateuser.pm for an example invocation and use.
 1284: 
 1285: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1286: selected");
 1287: 
 1288: =cut
 1289: 
 1290: #-------------------------------------------
 1291: sub select_dom_form {
 1292:     my ($defdom,$name,$includeempty) = @_;
 1293:     my @domains = get_domains();
 1294:     if ($includeempty) { @domains=('',@domains); }
 1295:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1296:     foreach (@domains) {
 1297:         $selectdomain.="<option value=\"$_\" ".
 1298:             ($_ eq $defdom ? 'selected="selected" ' : '').
 1299:                 ">$_</option>\n";
 1300:     }
 1301:     $selectdomain.="</select>";
 1302:     return $selectdomain;
 1303: }
 1304: 
 1305: #-------------------------------------------
 1306: 
 1307: =pod
 1308: 
 1309: =item * get_library_servers($domain)
 1310: 
 1311: Returns a hash which contains keys like '103l3' and values like 
 1312: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
 1313: given $domain.
 1314: 
 1315: =cut
 1316: 
 1317: #-------------------------------------------
 1318: sub get_library_servers {
 1319:     my $domain = shift;
 1320:     my %library_servers;
 1321:     foreach (keys(%Apache::lonnet::libserv)) {
 1322:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
 1323:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
 1324:         }
 1325:     }
 1326:     return %library_servers;
 1327: }
 1328: 
 1329: #-------------------------------------------
 1330: 
 1331: =pod
 1332: 
 1333: =item * home_server_option_list($domain)
 1334: 
 1335: returns a string which contains an <option> list to be used in a 
 1336: <select> form input.  See loncreateuser.pm for an example.
 1337: 
 1338: =cut
 1339: 
 1340: #-------------------------------------------
 1341: sub home_server_option_list {
 1342:     my $domain = shift;
 1343:     my %servers = &get_library_servers($domain);
 1344:     my $result = '';
 1345:     foreach (sort keys(%servers)) {
 1346:         $result.=
 1347:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
 1348:     }
 1349:     return $result;
 1350: }
 1351: 
 1352: =pod
 1353: 
 1354: =back
 1355: 
 1356: =cut
 1357: 
 1358: ###############################################################
 1359: ##                  Decoding User Agent                      ##
 1360: ###############################################################
 1361: 
 1362: =pod
 1363: 
 1364: =head1 Decoding the User Agent
 1365: 
 1366: =over 4
 1367: 
 1368: =item * &decode_user_agent()
 1369: 
 1370: Inputs: $r
 1371: 
 1372: Outputs:
 1373: 
 1374: =over 4
 1375: 
 1376: =item * $httpbrowser
 1377: 
 1378: =item * $clientbrowser
 1379: 
 1380: =item * $clientversion
 1381: 
 1382: =item * $clientmathml
 1383: 
 1384: =item * $clientunicode
 1385: 
 1386: =item * $clientos
 1387: 
 1388: =back
 1389: 
 1390: =back 
 1391: 
 1392: =cut
 1393: 
 1394: ###############################################################
 1395: ###############################################################
 1396: sub decode_user_agent {
 1397:     my ($r)=@_;
 1398:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1399:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1400:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1401:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1402:     my $clientbrowser='unknown';
 1403:     my $clientversion='0';
 1404:     my $clientmathml='';
 1405:     my $clientunicode='0';
 1406:     for (my $i=0;$i<=$#browsertype;$i++) {
 1407:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1408: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1409: 	    $clientbrowser=$bname;
 1410:             $httpbrowser=~/$vreg/i;
 1411: 	    $clientversion=$1;
 1412:             $clientmathml=($clientversion>=$minv);
 1413:             $clientunicode=($clientversion>=$univ);
 1414: 	}
 1415:     }
 1416:     my $clientos='unknown';
 1417:     if (($httpbrowser=~/linux/i) ||
 1418:         ($httpbrowser=~/unix/i) ||
 1419:         ($httpbrowser=~/ux/i) ||
 1420:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1421:     if (($httpbrowser=~/vax/i) ||
 1422:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1423:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1424:     if (($httpbrowser=~/mac/i) ||
 1425:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1426:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1427:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1428:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1429:             $clientunicode,$clientos,);
 1430: }
 1431: 
 1432: ###############################################################
 1433: ##    Authentication changing form generation subroutines    ##
 1434: ###############################################################
 1435: ##
 1436: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1437: ## hash, and have reasonable default values.
 1438: ##
 1439: ##    formname = the name given in the <form> tag.
 1440: #-------------------------------------------
 1441: 
 1442: =pod
 1443: 
 1444: =head1 Authentication Routines
 1445: 
 1446: =over 4
 1447: 
 1448: =item * authform_xxxxxx
 1449: 
 1450: The authform_xxxxxx subroutines provide javascript and html forms which 
 1451: handle some of the conveniences required for authentication forms.  
 1452: This is not an optimal method, but it works.  
 1453: 
 1454: See loncreateuser.pm for invocation and use examples.
 1455: 
 1456: =over 4
 1457: 
 1458: =item * authform_header
 1459: 
 1460: =item * authform_authorwarning
 1461: 
 1462: =item * authform_nochange
 1463: 
 1464: =item * authform_kerberos
 1465: 
 1466: =item * authform_internal
 1467: 
 1468: =item * authform_filesystem
 1469: 
 1470: =back
 1471: 
 1472: =back 
 1473: 
 1474: =cut
 1475: 
 1476: #-------------------------------------------
 1477: sub authform_header{  
 1478:     my %in = (
 1479:         formname => 'cu',
 1480:         kerb_def_dom => '',
 1481:         @_,
 1482:     );
 1483:     $in{'formname'} = 'document.' . $in{'formname'};
 1484:     my $result='';
 1485: 
 1486: #---------------------------------------------- Code for upper case translation
 1487:     my $Javascript_toUpperCase;
 1488:     unless ($in{kerb_def_dom}) {
 1489:         $Javascript_toUpperCase =<<"END";
 1490:         switch (choice) {
 1491:            case 'krb': currentform.elements[choicearg].value =
 1492:                currentform.elements[choicearg].value.toUpperCase();
 1493:                break;
 1494:            default:
 1495:         }
 1496: END
 1497:     } else {
 1498:         $Javascript_toUpperCase = "";
 1499:     }
 1500: 
 1501:     my $radioval = "'nochange'";
 1502:     if (exists($in{'curr_authtype'}) &&
 1503:         defined($in{'curr_authtype'}) &&
 1504:         $in{'curr_authtype'} ne '') {
 1505:         $radioval = "'$in{'curr_authtype'}arg'";
 1506:     }
 1507:     my $argfield = 'null';
 1508:     if ( grep/^mode$/,(keys %in) ) {
 1509:         if ($in{'mode'} eq 'modifycourse')  {
 1510:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1511:                 $radioval = "'$in{'curr_authtype'}'";
 1512:             }
 1513:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1514:                 unless ($in{'curr_autharg'} eq '') {
 1515:                     $argfield = "'$in{'curr_autharg'}'";
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520: 
 1521:     $result.=<<"END";
 1522: var current = new Object();
 1523: current.radiovalue = $radioval;
 1524: current.argfield = $argfield;
 1525: 
 1526: function changed_radio(choice,currentform) {
 1527:     var choicearg = choice + 'arg';
 1528:     // If a radio button in changed, we need to change the argfield
 1529:     if (current.radiovalue != choice) {
 1530:         current.radiovalue = choice;
 1531:         if (current.argfield != null) {
 1532:             currentform.elements[current.argfield].value = '';
 1533:         }
 1534:         if (choice == 'nochange') {
 1535:             current.argfield = null;
 1536:         } else {
 1537:             current.argfield = choicearg;
 1538:             switch(choice) {
 1539:                 case 'krb': 
 1540:                     currentform.elements[current.argfield].value = 
 1541:                         "$in{'kerb_def_dom'}";
 1542:                 break;
 1543:               default:
 1544:                 break;
 1545:             }
 1546:         }
 1547:     }
 1548:     return;
 1549: }
 1550: 
 1551: function changed_text(choice,currentform) {
 1552:     var choicearg = choice + 'arg';
 1553:     if (currentform.elements[choicearg].value !='') {
 1554:         $Javascript_toUpperCase
 1555:         // clear old field
 1556:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1557:             currentform.elements[current.argfield].value = '';
 1558:         }
 1559:         current.argfield = choicearg;
 1560:     }
 1561:     set_auth_radio_buttons(choice,currentform);
 1562:     return;
 1563: }
 1564: 
 1565: function set_auth_radio_buttons(newvalue,currentform) {
 1566:     var i=0;
 1567:     while (i < currentform.login.length) {
 1568:         if (currentform.login[i].value == newvalue) { break; }
 1569:         i++;
 1570:     }
 1571:     if (i == currentform.login.length) {
 1572:         return;
 1573:     }
 1574:     current.radiovalue = newvalue;
 1575:     currentform.login[i].checked = true;
 1576:     return;
 1577: }
 1578: END
 1579:     return $result;
 1580: }
 1581: 
 1582: sub authform_authorwarning{
 1583:     my $result='';
 1584:     $result='<i>'.
 1585:         &mt('As a general rule, only authors or co-authors should be '.
 1586:             'filesystem authenticated '.
 1587:             '(which allows access to the server filesystem).')."</i>\n";
 1588:     return $result;
 1589: }
 1590: 
 1591: sub authform_nochange{  
 1592:     my %in = (
 1593:               formname => 'document.cu',
 1594:               kerb_def_dom => 'MSU.EDU',
 1595:               @_,
 1596:           );
 1597:     my $result = '<label>'.&mt('[_1] Do not change login data',
 1598:                      '<input type="radio" name="login" value="nochange" '.
 1599:                      'checked="checked" onclick="'.
 1600:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1601: 	    '</label>';
 1602:     return $result;
 1603: }
 1604: 
 1605: sub authform_kerberos{  
 1606:     my %in = (
 1607:               formname => 'document.cu',
 1608:               kerb_def_dom => 'MSU.EDU',
 1609:               kerb_def_auth => 'krb4',
 1610:               @_,
 1611:               );
 1612:     my ($check4,$check5,$krbarg);
 1613:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1614:        $check5 = " checked=\"on\"";
 1615:     } else {
 1616:        $check4 = " checked=\"on\"";
 1617:     }
 1618:     $krbarg = $in{'kerb_def_dom'};
 1619: 
 1620:     my $krbcheck = "";
 1621:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1622:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1623:             $krbcheck = " checked=\"on\"";
 1624:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1625:                 $krbarg = $in{'curr_autharg'};
 1626:             }
 1627:         }
 1628:     }
 1629: 
 1630:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1631:     my $result .= &mt
 1632:         ('[_1] Kerberos authenticated with domain [_2] '.
 1633:          '[_3] Version 4 [_4] Version 5 [_5]',
 1634:          '<label><input type="radio" name="login" value="krb" '.
 1635:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1636:          '</label><input type="text" size="10" name="krbarg" '.
 1637:              'value="'.$krbarg.'" '.
 1638:              'onchange="'.$jscall.'" />',
 1639:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 1640:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 1641: 	 '</label>');
 1642:     return $result;
 1643: }
 1644: 
 1645: sub authform_internal{  
 1646:     my %args = (
 1647:                 formname => 'document.cu',
 1648:                 kerb_def_dom => 'MSU.EDU',
 1649:                 @_,
 1650:                 );
 1651: 
 1652:     my $intcheck = "";
 1653:     my $intarg = 'value=""';
 1654:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1655:         if ($args{'curr_authtype'} eq 'int') {
 1656:             $intcheck = " checked=\"on\"";
 1657:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1658:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1659:             }
 1660:         }
 1661:     }
 1662: 
 1663:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1664:     my $result.=&mt
 1665:         ('[_1] Internally authenticated (with initial password [_2])',
 1666:          '<label><input type="radio" name="login" value="int" '.$intcheck.
 1667:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1668:          '</label><input type="text" size="10" name="intarg" '.$intarg.
 1669:              ' onchange="'.$jscall.'" />');
 1670:     return $result;
 1671: }
 1672: 
 1673: sub authform_local{  
 1674:     my %in = (
 1675:               formname => 'document.cu',
 1676:               kerb_def_dom => 'MSU.EDU',
 1677:               @_,
 1678:               );
 1679: 
 1680:     my $loccheck = "";
 1681:     my $locarg = 'value=""';
 1682:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1683:         if ($in{'curr_authtype'} eq 'loc') {
 1684:             $loccheck = " checked=\"on\"";
 1685:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1686:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1687:             }
 1688:         }
 1689:     }
 1690: 
 1691:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1692:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1693:                     '<label><input type="radio" name="login" value="loc" '.$loccheck.
 1694:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1695:                     '</label><input type="text" size="10" name="locarg" '.$locarg.
 1696:                         ' onchange="'.$jscall.'" />');
 1697:     return $result;
 1698: }
 1699: 
 1700: sub authform_filesystem{  
 1701:     my %in = (
 1702:               formname => 'document.cu',
 1703:               kerb_def_dom => 'MSU.EDU',
 1704:               @_,
 1705:               );
 1706:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1707:     my $result.= &mt
 1708:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1709:          '<label><input type="radio" name="login" value="fsys" '.
 1710:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1711:          '</label><input type="text" size="10" name="fsysarg" value="" '.
 1712:                   'onchange="'.$jscall.'" />');
 1713:     return $result;
 1714: }
 1715: 
 1716: ###############################################################
 1717: ##    Get Authentication Defaults for Domain                 ##
 1718: ###############################################################
 1719: 
 1720: =pod
 1721: 
 1722: =head1 Domains and Authentication
 1723: 
 1724: Returns default authentication type and an associated argument as
 1725: listed in file 'domain.tab'.
 1726: 
 1727: =over 4
 1728: 
 1729: =item * get_auth_defaults
 1730: 
 1731: get_auth_defaults($target_domain) returns the default authentication
 1732: type and an associated argument (initial password or a kerberos domain).
 1733: These values are stored in lonTabs/domain.tab
 1734: 
 1735: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1736: 
 1737: If target_domain is not found in domain.tab, returns nothing ('').
 1738: 
 1739: =cut
 1740: 
 1741: #-------------------------------------------
 1742: sub get_auth_defaults {
 1743:     my $domain=shift;
 1744:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1745: }
 1746: ###############################################################
 1747: ##   End Get Authentication Defaults for Domain              ##
 1748: ###############################################################
 1749: 
 1750: ###############################################################
 1751: ##    Get Kerberos Defaults for Domain                 ##
 1752: ###############################################################
 1753: ##
 1754: ## Returns default kerberos version and an associated argument
 1755: ## as listed in file domain.tab. If not listed, provides
 1756: ## appropriate default domain and kerberos version.
 1757: ##
 1758: #-------------------------------------------
 1759: 
 1760: =pod
 1761: 
 1762: =item * get_kerberos_defaults
 1763: 
 1764: get_kerberos_defaults($target_domain) returns the default kerberos
 1765: version and domain. If not found in domain.tabs, it defaults to
 1766: version 4 and the domain of the server.
 1767: 
 1768: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1769: 
 1770: =cut
 1771: 
 1772: #-------------------------------------------
 1773: sub get_kerberos_defaults {
 1774:     my $domain=shift;
 1775:     my ($krbdef,$krbdefdom) =
 1776:         &Apache::loncommon::get_auth_defaults($domain);
 1777:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1778:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1779:         my $krbdefdom=$1;
 1780:         $krbdefdom=~tr/a-z/A-Z/;
 1781:         $krbdef = "krb4";
 1782:     }
 1783:     return ($krbdef,$krbdefdom);
 1784: }
 1785: 
 1786: =pod
 1787: 
 1788: =back
 1789: 
 1790: =cut
 1791: 
 1792: ###############################################################
 1793: ##                Thesaurus Functions                        ##
 1794: ###############################################################
 1795: 
 1796: =pod
 1797: 
 1798: =head1 Thesaurus Functions
 1799: 
 1800: =over 4
 1801: 
 1802: =item * initialize_keywords
 1803: 
 1804: Initializes the package variable %Keywords if it is empty.  Uses the
 1805: package variable $thesaurus_db_file.
 1806: 
 1807: =cut
 1808: 
 1809: ###################################################
 1810: 
 1811: sub initialize_keywords {
 1812:     return 1 if (scalar keys(%Keywords));
 1813:     # If we are here, %Keywords is empty, so fill it up
 1814:     #   Make sure the file we need exists...
 1815:     if (! -e $thesaurus_db_file) {
 1816:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1817:                                  " failed because it does not exist");
 1818:         return 0;
 1819:     }
 1820:     #   Set up the hash as a database
 1821:     my %thesaurus_db;
 1822:     if (! tie(%thesaurus_db,'GDBM_File',
 1823:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1824:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1825:                                  $thesaurus_db_file);
 1826:         return 0;
 1827:     } 
 1828:     #  Get the average number of appearances of a word.
 1829:     my $avecount = $thesaurus_db{'average.count'};
 1830:     #  Put keywords (those that appear > average) into %Keywords
 1831:     while (my ($word,$data)=each (%thesaurus_db)) {
 1832:         my ($count,undef) = split /:/,$data;
 1833:         $Keywords{$word}++ if ($count > $avecount);
 1834:     }
 1835:     untie %thesaurus_db;
 1836:     # Remove special values from %Keywords.
 1837:     foreach ('total.count','average.count') {
 1838:         delete($Keywords{$_}) if (exists($Keywords{$_}));
 1839:     }
 1840:     return 1;
 1841: }
 1842: 
 1843: ###################################################
 1844: 
 1845: =pod
 1846: 
 1847: =item * keyword($word)
 1848: 
 1849: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1850: than the average number of times in the thesaurus database.  Calls 
 1851: &initialize_keywords
 1852: 
 1853: =cut
 1854: 
 1855: ###################################################
 1856: 
 1857: sub keyword {
 1858:     return if (!&initialize_keywords());
 1859:     my $word=lc(shift());
 1860:     $word=~s/\W//g;
 1861:     return exists($Keywords{$word});
 1862: }
 1863: 
 1864: ###############################################################
 1865: 
 1866: =pod 
 1867: 
 1868: =item * get_related_words
 1869: 
 1870: Look up a word in the thesaurus.  Takes a scalar argument and returns
 1871: an array of words.  If the keyword is not in the thesaurus, an empty array
 1872: will be returned.  The order of the words returned is determined by the
 1873: database which holds them.
 1874: 
 1875: Uses global $thesaurus_db_file.
 1876: 
 1877: =cut
 1878: 
 1879: ###############################################################
 1880: sub get_related_words {
 1881:     my $keyword = shift;
 1882:     my %thesaurus_db;
 1883:     if (! -e $thesaurus_db_file) {
 1884:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1885:                                  "failed because the file does not exist");
 1886:         return ();
 1887:     }
 1888:     if (! tie(%thesaurus_db,'GDBM_File',
 1889:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1890:         return ();
 1891:     } 
 1892:     my @Words=();
 1893:     if (exists($thesaurus_db{$keyword})) {
 1894:         $_ = $thesaurus_db{$keyword};
 1895:         (undef,@Words) = split/:/;  # The first element is the number of times
 1896:                                     # the word appears.  We do not need it now.
 1897:         for (my $i=0;$i<=$#Words;$i++) {
 1898:             ($Words[$i],undef)= split/\,/,$Words[$i];
 1899:         }
 1900:     }
 1901:     untie %thesaurus_db;
 1902:     return @Words;
 1903: }
 1904: 
 1905: =pod
 1906: 
 1907: =back
 1908: 
 1909: =cut
 1910: 
 1911: # -------------------------------------------------------------- Plaintext name
 1912: =pod
 1913: 
 1914: =head1 User Name Functions
 1915: 
 1916: =over 4
 1917: 
 1918: =item * plainname($uname,$udom,$first)
 1919: 
 1920: Takes a users logon name and returns it as a string in
 1921: "first middle last generation" form 
 1922: if $first is set to 'lastname' then it returns it as
 1923: 'lastname generation, firstname middlename' if their is a lastname
 1924: 
 1925: =cut
 1926: 
 1927: 
 1928: ###############################################################
 1929: sub plainname {
 1930:     my ($uname,$udom,$first)=@_;
 1931:     my %names=&getnames($uname,$udom);
 1932:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 1933: 					  $names{'middlename'},
 1934: 					  $names{'lastname'},
 1935: 					  $names{'generation'},$first);
 1936:     $name=~s/^\s+//;
 1937:     $name=~s/\s+$//;
 1938:     $name=~s/\s+/ /g;
 1939:     if ($name !~ /\S/) { $name=$uname.'@'.$udom; }
 1940:     return $name;
 1941: }
 1942: 
 1943: # -------------------------------------------------------------------- Nickname
 1944: =pod
 1945: 
 1946: =item * nickname($uname,$udom)
 1947: 
 1948: Gets a users name and returns it as a string as
 1949: 
 1950: "&quot;nickname&quot;"
 1951: 
 1952: if the user has a nickname or
 1953: 
 1954: "first middle last generation"
 1955: 
 1956: if the user does not
 1957: 
 1958: =cut
 1959: 
 1960: sub nickname {
 1961:     my ($uname,$udom)=@_;
 1962:     my %names=&getnames($uname,$udom);
 1963:     my $name=$names{'nickname'};
 1964:     if ($name) {
 1965:        $name='&quot;'.$name.'&quot;'; 
 1966:     } else {
 1967:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1968: 	     $names{'lastname'}.' '.$names{'generation'};
 1969:        $name=~s/\s+$//;
 1970:        $name=~s/\s+/ /g;
 1971:     }
 1972:     return $name;
 1973: }
 1974: 
 1975: sub getnames {
 1976:     my ($uname,$udom)=@_;
 1977:     my $id=$uname.':'.$udom;
 1978:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 1979:     if ($cached) {
 1980: 	return %{$names};
 1981:     } else {
 1982: 	my %loadnames=&Apache::lonnet::get('environment',
 1983:                     ['firstname','middlename','lastname','generation','nickname'],
 1984: 					 $udom,$uname);
 1985: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 1986: 	return %loadnames;
 1987:     }
 1988: }
 1989: 
 1990: # ------------------------------------------------------------------ Screenname
 1991: 
 1992: =pod
 1993: 
 1994: =item * screenname($uname,$udom)
 1995: 
 1996: Gets a users screenname and returns it as a string
 1997: 
 1998: =cut
 1999: 
 2000: sub screenname {
 2001:     my ($uname,$udom)=@_;
 2002:     if ($uname eq $env{'user.name'} &&
 2003: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2004:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2005:     return $names{'screenname'};
 2006: }
 2007: 
 2008: 
 2009: # ------------------------------------------------------------- Message Wrapper
 2010: 
 2011: sub messagewrapper {
 2012:     my ($link,$username,$domain)=@_;
 2013:     return 
 2014:         '<a href="/adm/email?compose=individual&'.
 2015:         'recname='.$username.'&recdom='.$domain.'" '.
 2016:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2017: }
 2018: # --------------------------------------------------------------- Notes Wrapper
 2019: 
 2020: sub noteswrapper {
 2021:     my ($link,$un,$do)=@_;
 2022:     return 
 2023: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2024: }
 2025: # ------------------------------------------------------------- Aboutme Wrapper
 2026: 
 2027: sub aboutmewrapper {
 2028:     my ($link,$username,$domain,$target)=@_;
 2029:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2030: 	($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
 2031: }
 2032: 
 2033: # ------------------------------------------------------------ Syllabus Wrapper
 2034: 
 2035: 
 2036: sub syllabuswrapper {
 2037:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2038:     if ($fontcolor) { 
 2039:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2040:     }
 2041:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2042: }
 2043: 
 2044: sub track_student_link {
 2045:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2046:     my $link ="/adm/trackstudent?";
 2047:     my $title = 'View recent activity';
 2048:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2049:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2050:         $link .= "selected_student=$sname:$sdom";
 2051:         $title .= ' of this student';
 2052:     } 
 2053:     if (defined($target) && $target !~ /^\s*$/) {
 2054:         $target = qq{target="$target"};
 2055:     } else {
 2056:         $target = '';
 2057:     }
 2058:     if ($start) { $link.='&amp;start='.$start; }
 2059:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2060: }
 2061: 
 2062: =pod
 2063: 
 2064: =back
 2065: 
 2066: =head1 Access .tab File Data
 2067: 
 2068: =over 4
 2069: 
 2070: =item * languageids() 
 2071: 
 2072: returns list of all language ids
 2073: 
 2074: =cut
 2075: 
 2076: sub languageids {
 2077:     return sort(keys(%language));
 2078: }
 2079: 
 2080: =pod
 2081: 
 2082: =item * languagedescription() 
 2083: 
 2084: returns description of a specified language id
 2085: 
 2086: =cut
 2087: 
 2088: sub languagedescription {
 2089:     my $code=shift;
 2090:     return  ($supported_language{$code}?'* ':'').
 2091:             $language{$code}.
 2092: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2093: }
 2094: 
 2095: sub plainlanguagedescription {
 2096:     my $code=shift;
 2097:     return $language{$code};
 2098: }
 2099: 
 2100: sub supportedlanguagecode {
 2101:     my $code=shift;
 2102:     return $supported_language{$code};
 2103: }
 2104: 
 2105: =pod
 2106: 
 2107: =item * copyrightids() 
 2108: 
 2109: returns list of all copyrights
 2110: 
 2111: =cut
 2112: 
 2113: sub copyrightids {
 2114:     return sort(keys(%cprtag));
 2115: }
 2116: 
 2117: =pod
 2118: 
 2119: =item * copyrightdescription() 
 2120: 
 2121: returns description of a specified copyright id
 2122: 
 2123: =cut
 2124: 
 2125: sub copyrightdescription {
 2126:     return &mt($cprtag{shift(@_)});
 2127: }
 2128: 
 2129: =pod
 2130: 
 2131: =item * source_copyrightids() 
 2132: 
 2133: returns list of all source copyrights
 2134: 
 2135: =cut
 2136: 
 2137: sub source_copyrightids {
 2138:     return sort(keys(%scprtag));
 2139: }
 2140: 
 2141: =pod
 2142: 
 2143: =item * source_copyrightdescription() 
 2144: 
 2145: returns description of a specified source copyright id
 2146: 
 2147: =cut
 2148: 
 2149: sub source_copyrightdescription {
 2150:     return &mt($scprtag{shift(@_)});
 2151: }
 2152: 
 2153: =pod
 2154: 
 2155: =item * filecategories() 
 2156: 
 2157: returns list of all file categories
 2158: 
 2159: =cut
 2160: 
 2161: sub filecategories {
 2162:     return sort(keys(%category_extensions));
 2163: }
 2164: 
 2165: =pod
 2166: 
 2167: =item * filecategorytypes() 
 2168: 
 2169: returns list of file types belonging to a given file
 2170: category
 2171: 
 2172: =cut
 2173: 
 2174: sub filecategorytypes {
 2175:     return @{$category_extensions{lc($_[0])}};
 2176: }
 2177: 
 2178: =pod
 2179: 
 2180: =item * fileembstyle() 
 2181: 
 2182: returns embedding style for a specified file type
 2183: 
 2184: =cut
 2185: 
 2186: sub fileembstyle {
 2187:     return $fe{lc(shift(@_))};
 2188: }
 2189: 
 2190: 
 2191: sub filecategoryselect {
 2192:     my ($name,$value)=@_;
 2193:     return &select_form($value,$name,
 2194: 			'' => &mt('Any category'),
 2195: 			map { $_,$_ } sort(keys(%category_extensions)));
 2196: }
 2197: 
 2198: =pod
 2199: 
 2200: =item * filedescription() 
 2201: 
 2202: returns description for a specified file type
 2203: 
 2204: =cut
 2205: 
 2206: sub filedescription {
 2207:     my $file_description = $fd{lc(shift())};
 2208:     $file_description =~ s:([\[\]]):~$1:g;
 2209:     return &mt($file_description);
 2210: }
 2211: 
 2212: =pod
 2213: 
 2214: =item * filedescriptionex() 
 2215: 
 2216: returns description for a specified file type with
 2217: extra formatting
 2218: 
 2219: =cut
 2220: 
 2221: sub filedescriptionex {
 2222:     my $ex=shift;
 2223:     my $file_description = $fd{lc($ex)};
 2224:     $file_description =~ s:([\[\]]):~$1:g;
 2225:     return '.'.$ex.' '.&mt($file_description);
 2226: }
 2227: 
 2228: # End of .tab access
 2229: =pod
 2230: 
 2231: =back
 2232: 
 2233: =cut
 2234: 
 2235: # ------------------------------------------------------------------ File Types
 2236: sub fileextensions {
 2237:     return sort(keys(%fe));
 2238: }
 2239: 
 2240: # ----------------------------------------------------------- Display Languages
 2241: # returns a hash with all desired display languages
 2242: #
 2243: 
 2244: sub display_languages {
 2245:     my %languages=();
 2246:     foreach (&preferred_languages()) {
 2247: 	$languages{$_}=1;
 2248:     }
 2249:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2250:     if ($env{'form.displaylanguage'}) {
 2251: 	foreach (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2252: 	    $languages{$_}=1;
 2253:         }
 2254:     }
 2255:     return %languages;
 2256: }
 2257: 
 2258: sub preferred_languages {
 2259:     my @languages=();
 2260:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2261: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2262: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2263:     }
 2264:     if ($env{'environment.languages'}) {
 2265: 	@languages=split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'});
 2266:     }
 2267:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 2268:     if ($browser) {
 2269: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 2270:     }
 2271:     if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
 2272: 	@languages=(@languages,
 2273: 		$Apache::lonnet::domain_lang_def{$env{'user.domain'}});
 2274:     }
 2275:     if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
 2276: 	@languages=(@languages,
 2277: 		$Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
 2278:     }
 2279:     if ($Apache::lonnet::domain_lang_def{
 2280: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 2281: 	@languages=(@languages,
 2282: 		$Apache::lonnet::domain_lang_def{
 2283:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 2284:     }
 2285: # turn "en-ca" into "en-ca,en"
 2286:     my @genlanguages;
 2287:     foreach (@languages) {
 2288: 	unless ($_=~/\w/) { next; }
 2289: 	push (@genlanguages,$_);
 2290: 	if ($_=~/(\-|\_)/) {
 2291: 	    push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
 2292: 	}
 2293:     }
 2294:     return @genlanguages;
 2295: }
 2296: 
 2297: ###############################################################
 2298: ##               Student Answer Attempts                     ##
 2299: ###############################################################
 2300: 
 2301: =pod
 2302: 
 2303: =head1 Alternate Problem Views
 2304: 
 2305: =over 4
 2306: 
 2307: =item * get_previous_attempt($symb, $username, $domain, $course,
 2308:     $getattempt, $regexp, $gradesub)
 2309: 
 2310: Return string with previous attempt on problem. Arguments:
 2311: 
 2312: =over 4
 2313: 
 2314: =item * $symb: Problem, including path
 2315: 
 2316: =item * $username: username of the desired student
 2317: 
 2318: =item * $domain: domain of the desired student
 2319: 
 2320: =item * $course: Course ID
 2321: 
 2322: =item * $getattempt: Leave blank for all attempts, otherwise put
 2323:     something
 2324: 
 2325: =item * $regexp: if string matches this regexp, the string will be
 2326:     sent to $gradesub
 2327: 
 2328: =item * $gradesub: routine that processes the string if it matches $regexp
 2329: 
 2330: =back
 2331: 
 2332: The output string is a table containing all desired attempts, if any.
 2333: 
 2334: =cut
 2335: 
 2336: sub get_previous_attempt {
 2337:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2338:   my $prevattempts='';
 2339:   no strict 'refs';
 2340:   if ($symb) {
 2341:     my (%returnhash)=
 2342:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2343:     if ($returnhash{'version'}) {
 2344:       my %lasthash=();
 2345:       my $version;
 2346:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2347:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2348: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 2349:         }
 2350:       }
 2351:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2352:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2353:       foreach (sort(keys %lasthash)) {
 2354: 	my ($ign,@parts) = split(/\./,$_);
 2355: 	if ($#parts > 0) {
 2356: 	  my $data=$parts[-1];
 2357: 	  pop(@parts);
 2358: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2359: 	} else {
 2360: 	  if ($#parts == 0) {
 2361: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2362: 	  } else {
 2363: 	    $prevattempts.='<th>'.$ign.'</th>';
 2364: 	  }
 2365: 	}
 2366:       }
 2367:       if ($getattempt eq '') {
 2368: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2369: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2370: 	    foreach (sort(keys %lasthash)) {
 2371: 	       my $value;
 2372: 	       if ($_ =~ /timestamp/) {
 2373: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 2374: 	       } else {
 2375: 		  $value=$returnhash{$version.':'.$_};
 2376: 	       }
 2377: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
 2378: 	    }
 2379: 	 }
 2380:       }
 2381:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2382:       foreach (sort(keys %lasthash)) {
 2383: 	my $value;
 2384: 	if ($_ =~ /timestamp/) {
 2385: 	  $value=scalar(localtime($lasthash{$_}));
 2386: 	} else {
 2387: 	  $value=$lasthash{$_};
 2388: 	}
 2389: 	$value=&Apache::lonnet::unescape($value);
 2390: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2391: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2392:       }
 2393:       $prevattempts.='</tr></table></td></tr></table>';
 2394:     } else {
 2395:       $prevattempts='Nothing submitted - no attempts.';
 2396:     }
 2397:   } else {
 2398:     $prevattempts='No data.';
 2399:   }
 2400: }
 2401: 
 2402: sub relative_to_absolute {
 2403:     my ($url,$output)=@_;
 2404:     my $parser=HTML::TokeParser->new(\$output);
 2405:     my $token;
 2406:     my $thisdir=$url;
 2407:     my @rlinks=();
 2408:     while ($token=$parser->get_token) {
 2409: 	if ($token->[0] eq 'S') {
 2410: 	    if ($token->[1] eq 'a') {
 2411: 		if ($token->[2]->{'href'}) {
 2412: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 2413: 		}
 2414: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 2415: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2416: 	    } elsif ($token->[1] eq 'base') {
 2417: 		$thisdir=$token->[2]->{'href'};
 2418: 	    }
 2419: 	}
 2420:     }
 2421:     $thisdir=~s-/[^/]*$--;
 2422:     foreach (@rlinks) {
 2423: 	unless (($_=~/^http:\/\//i) ||
 2424: 		($_=~/^\//) ||
 2425: 		($_=~/^javascript:/i) ||
 2426: 		($_=~/^mailto:/i) ||
 2427: 		($_=~/^\#/)) {
 2428: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
 2429: 	    $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
 2430: 	}
 2431:     }
 2432: # -------------------------------------------------- Deal with Applet codebases
 2433:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2434:     return $output;
 2435: }
 2436: 
 2437: =pod
 2438: 
 2439: =item * get_student_view
 2440: 
 2441: show a snapshot of what student was looking at
 2442: 
 2443: =cut
 2444: 
 2445: sub get_student_view {
 2446:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 2447:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2448:   my (%form);
 2449:   my @elements=('symb','courseid','domain','username');
 2450:   foreach my $element (@elements) {
 2451:       $form{'grade_'.$element}=eval '$'.$element #'
 2452:   }
 2453:   if (defined($moreenv)) {
 2454:       %form=(%form,%{$moreenv});
 2455:   }
 2456:   if (defined($target)) { $form{'grade_target'} = $target; }
 2457:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2458:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 2459:   $userview=~s/\<body[^\>]*\>//gi;
 2460:   $userview=~s/\<\/body\>//gi;
 2461:   $userview=~s/\<html\>//gi;
 2462:   $userview=~s/\<\/html\>//gi;
 2463:   $userview=~s/\<head\>//gi;
 2464:   $userview=~s/\<\/head\>//gi;
 2465:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2466:   $userview=&relative_to_absolute($feedurl,$userview);
 2467:   return $userview;
 2468: }
 2469: 
 2470: =pod
 2471: 
 2472: =item * get_student_answers() 
 2473: 
 2474: show a snapshot of how student was answering problem
 2475: 
 2476: =cut
 2477: 
 2478: sub get_student_answers {
 2479:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2480:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2481:   my (%moreenv);
 2482:   my @elements=('symb','courseid','domain','username');
 2483:   foreach my $element (@elements) {
 2484:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 2485:   }
 2486:   $moreenv{'grade_target'}='answer';
 2487:   %moreenv=(%form,%moreenv);
 2488:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
 2489:   return $userview;
 2490: }
 2491: 
 2492: =pod
 2493: 
 2494: =item * &submlink()
 2495: 
 2496: Inputs: $text $uname $udom $symb $target
 2497: 
 2498: Returns: A link to grades.pm such as to see the SUBM view of a student
 2499: 
 2500: =cut
 2501: 
 2502: ###############################################
 2503: sub submlink {
 2504:     my ($text,$uname,$udom,$symb,$target)=@_;
 2505:     if (!($uname && $udom)) {
 2506: 	(my $cursymb, my $courseid,$udom,$uname)=
 2507: 	    &Apache::lonxml::whichuser($symb);
 2508: 	if (!$symb) { $symb=$cursymb; }
 2509:     }
 2510:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2511:     $symb=&Apache::lonnet::escape($symb);
 2512:     if ($target) { $target="target=\"$target\""; }
 2513:     return '<a href="/adm/grades?&command=submission&'.
 2514: 	'symb='.$symb.'&student='.$uname.
 2515: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 2516: }
 2517: ##############################################
 2518: 
 2519: =pod
 2520: 
 2521: =item * &pgrdlink()
 2522: 
 2523: Inputs: $text $uname $udom $symb $target
 2524: 
 2525: Returns: A link to grades.pm such as to see the PGRD view of a student
 2526: 
 2527: =cut
 2528: 
 2529: ###############################################
 2530: sub pgrdlink {
 2531:     my $link=&submlink(@_);
 2532:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 2533:     return $link;
 2534: }
 2535: ##############################################
 2536: 
 2537: =pod
 2538: 
 2539: =item * &pprmlink()
 2540: 
 2541: Inputs: $text $uname $udom $symb $target
 2542: 
 2543: Returns: A link to parmset.pm such as to see the PPRM view of a
 2544: student and a specific resource
 2545: 
 2546: =cut
 2547: 
 2548: ###############################################
 2549: sub pprmlink {
 2550:     my ($text,$uname,$udom,$symb,$target)=@_;
 2551:     if (!($uname && $udom)) {
 2552: 	(my $cursymb, my $courseid,$udom,$uname)=
 2553: 	    &Apache::lonxml::whichuser($symb);
 2554: 	if (!$symb) { $symb=$cursymb; }
 2555:     }
 2556:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2557:     $symb=&Apache::lonnet::escape($symb);
 2558:     if ($target) { $target="target=\"$target\""; }
 2559:     return '<a href="/adm/parmset?&command=set&'.
 2560: 	'symb='.$symb.'&uname='.$uname.
 2561: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
 2562: }
 2563: ##############################################
 2564: 
 2565: =pod
 2566: 
 2567: =back
 2568: 
 2569: =cut
 2570: 
 2571: ###############################################
 2572: 
 2573: 
 2574: sub timehash {
 2575:     my @ltime=localtime(shift);
 2576:     return ( 'seconds' => $ltime[0],
 2577:              'minutes' => $ltime[1],
 2578:              'hours'   => $ltime[2],
 2579:              'day'     => $ltime[3],
 2580:              'month'   => $ltime[4]+1,
 2581:              'year'    => $ltime[5]+1900,
 2582:              'weekday' => $ltime[6],
 2583:              'dayyear' => $ltime[7]+1,
 2584:              'dlsav'   => $ltime[8] );
 2585: }
 2586: 
 2587: sub maketime {
 2588:     my %th=@_;
 2589:     return POSIX::mktime(
 2590:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2591:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 2592: }
 2593: 
 2594: #########################################
 2595: 
 2596: sub findallcourses {
 2597:     my %courses=();
 2598:     my $now=time;
 2599:     foreach (keys %env) {
 2600: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 2601: 	    my ($starttime,$endtime)=$env{$_};
 2602:             my $active=1;
 2603:             if ($starttime) {
 2604: 		if ($now<$starttime) { $active=0; }
 2605:             }
 2606:             if ($endtime) {
 2607:                 if ($now>$endtime) { $active=0; }
 2608:             }
 2609:             if ($active) { $courses{$1.'_'.$2}=1; }
 2610:         }
 2611:     }
 2612:     return keys %courses;
 2613: }
 2614: 
 2615: ###############################################
 2616: ###############################################
 2617: 
 2618: =pod
 2619: 
 2620: =head1 Domain Template Functions
 2621: 
 2622: =over 4
 2623: 
 2624: =item * &determinedomain()
 2625: 
 2626: Inputs: $domain (usually will be undef)
 2627: 
 2628: Returns: Determines which domain should be used for designs
 2629: 
 2630: =cut
 2631: 
 2632: ###############################################
 2633: sub determinedomain {
 2634:     my $domain=shift;
 2635:    if (! $domain) {
 2636:         # Determine domain if we have not been given one
 2637:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2638:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 2639:         if ($env{'request.role.domain'}) { 
 2640:             $domain=$env{'request.role.domain'}; 
 2641:         }
 2642:     }
 2643:     return $domain;
 2644: }
 2645: ###############################################
 2646: =pod
 2647: 
 2648: =item * &domainlogo()
 2649: 
 2650: Inputs: $domain (usually will be undef)
 2651: 
 2652: Returns: A link to a domain logo, if the domain logo exists.
 2653: If the domain logo does not exist, a description of the domain.
 2654: 
 2655: =cut
 2656: 
 2657: ###############################################
 2658: sub domainlogo {
 2659:     my $domain = &determinedomain(shift);    
 2660:      # See if there is a logo
 2661:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2662: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
 2663:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
 2664:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2665:         return $Apache::lonnet::domaindescription{$domain};
 2666:     } else {
 2667:         return '';
 2668:     }
 2669: }
 2670: ##############################################
 2671: 
 2672: =pod
 2673: 
 2674: =item * &designparm()
 2675: 
 2676: Inputs: $which parameter; $domain (usually will be undef)
 2677: 
 2678: Returns: value of designparamter $which
 2679: 
 2680: =cut
 2681: 
 2682: ##############################################
 2683: sub designparm {
 2684:     my ($which,$domain)=@_;
 2685:     if ($env{'browser.blackwhite'} eq 'on') {
 2686: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 2687: 	    return '#000000';
 2688: 	}
 2689: 	if ($which=~/\.(pgbg|sidebg)$/) {
 2690: 	    return '#FFFFFF';
 2691: 	}
 2692: 	if ($which=~/\.tabbg$/) {
 2693: 	    return '#CCCCCC';
 2694: 	}
 2695:     }
 2696:     if ($env{'environment.color.'.$which}) {
 2697: 	return $env{'environment.color.'.$which};
 2698:     }
 2699:     $domain=&determinedomain($domain);
 2700:     if ($designhash{$domain.'.'.$which}) {
 2701: 	return $designhash{$domain.'.'.$which};
 2702:     } else {
 2703:         return $designhash{'default.'.$which};
 2704:     }
 2705: }
 2706: 
 2707: ###############################################
 2708: ###############################################
 2709: 
 2710: =pod
 2711: 
 2712: =back
 2713: 
 2714: =head1 HTTP Helpers
 2715: 
 2716: =over 4
 2717: 
 2718: =item * &bodytag()
 2719: 
 2720: Returns a uniform header for LON-CAPA web pages.
 2721: 
 2722: Inputs: 
 2723: 
 2724: =over 4
 2725: 
 2726: =item * $title, A title to be displayed on the page.
 2727: 
 2728: =item * $function, the current role (can be undef).
 2729: 
 2730: =item * $addentries, extra parameters for the <body> tag.
 2731: 
 2732: =item * $bodyonly, if defined, only return the <body> tag.
 2733: 
 2734: =item * $domain, if defined, force a given domain.
 2735: 
 2736: =item * $forcereg, if page should register as content page (relevant for 
 2737:             text interface only)
 2738: 
 2739: =item * $customtitle, alternate text to use instead of $title
 2740:                       in the title box that appears, this text
 2741:                       is not auto translated like the $title is
 2742: 
 2743: =item * $notopbar, if true, keep the 'what is this' info but remove the
 2744:                    navigational links
 2745: 
 2746: =item * $bgcolor, used to override the bg coor on a webpage to a specific value
 2747: 
 2748: =back
 2749: 
 2750: Returns: A uniform header for LON-CAPA web pages.  
 2751: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2752: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2753: other decorations will be returned.
 2754: 
 2755: =cut
 2756: 
 2757: sub bodytag {
 2758:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 2759: 	$notopbar,$bgcolor)=@_;
 2760:     $title=&mt($title);
 2761:     $function = &get_users_function() if (!$function);
 2762:     my $img=&designparm($function.'.img',$domain);
 2763:     my $pgbg= $bgcolor || &designparm($function.'.pgbg',$domain);
 2764:     my $tabbg=&designparm($function.'.tabbg',$domain);
 2765:     my $font=&designparm($function.'.font',$domain);
 2766:     my $link=&designparm($function.'.link',$domain);
 2767:     my $alink=&designparm($function.'.alink',$domain);
 2768:     my $vlink=&designparm($function.'.vlink',$domain);
 2769:     my $sidebg=&designparm($function.'.sidebg',$domain);
 2770: # Accessibility font enhance
 2771:     my $addstyle='';
 2772:     if ($env{'browser.fontenhance'} eq 'on') {
 2773: 	$addstyle=' font-size: x-large;';
 2774:     }
 2775:  # role and realm
 2776:     my ($role,$realm)
 2777:        =&Apache::lonnet::plaintext((split(/\./,$env{'request.role'}))[0]);
 2778: # realm
 2779:     if ($env{'request.course.id'}) {
 2780: 	$realm=
 2781:          $env{'course.'.$env{'request.course.id'}.'.description'};
 2782:     }
 2783:     unless ($realm) { $realm='&nbsp;'; }
 2784: # Set messages
 2785:     my $messages=&domainlogo($domain);
 2786: # Port for miniserver
 2787:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2788:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2789: 
 2790:     my $extra_body_attr = &make_attr_string($forcereg,$addentries);
 2791: 
 2792: # construct main body tag
 2793:     my $bodytag = <<END;
 2794: <style type="text/css">
 2795: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
 2796: a:focus { color: red; background: yellow } 
 2797: table.thinborder { border-collapse: collapse; }
 2798: table.thinborder tr th, table.thinborder tr td { border-style: solid; border-width: 1px}
 2799: form, .inline { display: inline; }
 2800: .center { text-align: center; }
 2801: .filename {font-family: monospace;}
 2802: </style>
 2803: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 2804: style="margin-top: 0px;$addstyle" $extra_body_attr>
 2805: END
 2806: 
 2807:     $bodytag .= &Apache::lontexconvert::init_math_support();
 2808: 
 2809:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 2810:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
 2811:     if ($bodyonly) {
 2812:         return $bodytag;
 2813:     } elsif ($env{'browser.interface'} eq 'textual') {
 2814: # Accessibility
 2815:           
 2816:         return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
 2817:                                                       $forcereg).
 2818:                '<h1>LON-CAPA: '.$title.'</h1>';
 2819:     } elsif ($env{'environment.remote'} eq 'off') {
 2820: # No Remote
 2821: 	my $roleinfo=(<<ENDROLE);
 2822: <td bgcolor="$tabbg" align="right">
 2823: <font size="2" face="Arial, Helvetica, sans-serif">
 2824:     $env{'environment.firstname'}
 2825:     $env{'environment.middlename'}
 2826:     $env{'environment.lastname'}
 2827:     $env{'environment.generation'}
 2828:     </font>&nbsp;
 2829: <br />
 2830: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2831: <br />
 2832: <font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;
 2833: </td>
 2834: ENDROLE
 2835:         my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
 2836: 		$font.'"><b>'.$title.'</b></font>';
 2837:         if ($customtitle) {
 2838:             $titleinfo = $customtitle;
 2839:         }
 2840: 
 2841: 	if ($env{'request.state'} eq 'construct') {
 2842: 	    my ($uname,$thisdisfn)=
 2843: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 2844: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 2845: 	    $formaction=~s/\/+/\//g;
 2846:             unless ($customtitle) {  #this is for resources; directories have customtitle, and crumbs and select recent are created in lonpubdir.pm  
 2847:                 my $parentpath = '';
 2848:                 my $lastitem = '';
 2849:                 if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 2850:                     $parentpath = $1;
 2851:                     $lastitem = $2;
 2852:                 } else {
 2853:                     $lastitem = $thisdisfn;
 2854:                 }
 2855: 	        $titleinfo = &Apache::loncommon::help_open_menu('','','','',3,'Authoring').
 2856:                       '<font face="Arial, Helvetica, sans-serif"><b>Construction Space</b>:</font>&nbsp;'. 
 2857:                       '<form name="dirs" method="post" action="'.$formaction
 2858: 		    .'" target="_top"><tt><b>'
 2859: 		    .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 2860: 		    .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 2861: 		    .'</form>'
 2862: 		    .&Apache::lonmenu::constspaceform();
 2863: 
 2864:             }
 2865: 	    $forcereg=1;
 2866:         }
 2867:         my $titletable = '<table bgcolor="'.$pgbg.'" width="100%" border="0" '.
 2868:                          'cellspacing="3" cellpadding="3">'.
 2869:                          '<tr><td bgcolor="'.$tabbg.'">'.
 2870:                          $titleinfo.'</td>'.$roleinfo.'</tr></table>';
 2871:         if ($env{'request.state'} eq 'construct') {
 2872:             if ($notopbar) {
 2873:                 $bodytag .= $titletable;
 2874:             } else {
 2875:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg,$titletable);
 2876:             }
 2877: 	} else {
 2878:             if ($notopbar) {
 2879:                 $bodytag .= $titletable;
 2880:             } else {
 2881:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg).
 2882:                         $titletable;
 2883:             }
 2884:         }
 2885:         return $bodytag;
 2886:     }
 2887: 
 2888: #
 2889: # Top frame rendering, Remote is up
 2890: #
 2891:     my $titleinfo = '&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
 2892:     if ($customtitle) {
 2893:         $titleinfo = $customtitle;
 2894:     }
 2895:     #
 2896:     # Extra info if you are the DC
 2897:     my $dc_info = '';
 2898:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 2899:                         $env{'course.'.$env{'request.course.id'}.
 2900:                                  '.domain'}.'/'})) {
 2901:         my $cid = $env{'request.course.id'};
 2902:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 2903:         $dc_info = '('.$dc_info.')';
 2904:     }
 2905:     # Explicit link to get inline menu
 2906:     my $menu='<br /><font size="2" face="Arial, Helvetica, sans-serif">&nbsp;<a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a></font>';
 2907:     #
 2908:     return(<<ENDBODY);
 2909: $bodytag
 2910: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 2911: <tr><td bgcolor="$sidebg">
 2912: $upperleft</td>
 2913: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
 2914: </tr>
 2915: <tr>
 2916: <td rowspan="3" bgcolor="$tabbg">
 2917: $titleinfo $dc_info $menu
 2918: </td><td bgcolor="$tabbg" align="right">
 2919: <font size="2" face="Arial, Helvetica, sans-serif">
 2920:     $env{'environment.firstname'}
 2921:     $env{'environment.middlename'}
 2922:     $env{'environment.lastname'}
 2923:     $env{'environment.generation'}
 2924:     </font>&nbsp;
 2925: </td>
 2926: </tr>
 2927: <tr><td bgcolor="$tabbg" align="right">
 2928: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2929: </td></tr>
 2930: <tr>
 2931: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
 2932: </table><br />
 2933: ENDBODY
 2934: }
 2935: 
 2936: sub make_attr_string {
 2937:     my ($register,$attr_ref) = @_;
 2938: 
 2939:     if ($attr_ref && !ref($attr_ref)) {
 2940: 	die("addentries Must be a hash ref ".
 2941: 	    join(':',caller(1))." ".
 2942: 	    join(':',caller(0))." ");
 2943:     }
 2944: 
 2945:     if ($register) {
 2946: 	$attr_ref->{'onload'}   = &Apache::lonmenu::loadevents().
 2947: 	    $attr_ref->{'onload'};
 2948: 	$attr_ref->{'onunload'} = &Apache::lonmenu::unloadevents().
 2949: 	    $attr_ref->{'onunload'};
 2950:     }
 2951:     my $attr_string;
 2952:     foreach my $attr (keys(%$attr_ref)) {
 2953: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 2954:     }
 2955:     return $attr_string;
 2956: }
 2957: 
 2958: 
 2959: ###############################################
 2960: ###############################################
 2961: 
 2962: =pod
 2963: 
 2964: =back
 2965: 
 2966: =head1 HTML Helpers
 2967: 
 2968: =over 4
 2969: 
 2970: =item * &endbodytag()
 2971: 
 2972: Returns a uniform footer for LON-CAPA web pages.
 2973: 
 2974: Inputs: none
 2975: 
 2976: =back
 2977: 
 2978: =cut
 2979: 
 2980: sub endbodytag {
 2981:     my $endbodytag='</body>';
 2982:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 2983:     if ( exists( $env{'internal.head.redirect'} ) ) {
 2984: 	$endbodytag=
 2985: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
 2986: 	    &mt('Continue').'</a>'.
 2987: 	    $endbodytag;
 2988:     }
 2989:     return $endbodytag;
 2990: }
 2991: 
 2992: =pod
 2993: 
 2994: =over 4
 2995: 
 2996: =item * &headtag()
 2997: 
 2998: Returns a uniform footer for LON-CAPA web pages.
 2999: 
 3000: Inputs: $title - optional title for the head
 3001:         $head_extra - optional extra HTML to put inside the <head>
 3002:         $args - optional arguments
 3003:             force_register - if is true call registerurl so the remote is 
 3004:                              informed
 3005:                              
 3006:             redirect - array ref of seconds before redirect occurs
 3007:                                     url to redirect to
 3008:                            (side effect of setting 
 3009:                                $env{'internal.head.redirect'} to the url 
 3010:                                redirected too)
 3011: =back
 3012: 
 3013: =cut
 3014: 
 3015: sub headtag {
 3016:     my ($title,$head_extra,$args) = @_;
 3017:     
 3018:     my $result =
 3019: 	'<head>'.
 3020: 	&Apache::lonxml::fontsettings().
 3021: 	&Apache::lonhtmlcommon::htmlareaheaders();
 3022: 
 3023:     if ($args->{'force_register'}) {
 3024: 	$result .= &Apache::lonmenu::registerurl(1);
 3025:     }
 3026: 
 3027:     if (ref($args->{'redirect'})) {
 3028: 	my ($time,$url) = @{$args->{'redirect'}};
 3029: 	$url = &Apache::lonenc::check_encrypt($url);
 3030: 	$env{'internal.head.redirect'} = $url;
 3031: 	$result.=<<ADDMETA
 3032: <meta http-equiv="pragma" content="no-cache" />
 3033: <meta HTTP-EQUIV="Refresh" CONTENT="$time; url=$url" />
 3034: ADDMETA
 3035:     }
 3036:     if (!defined($title)) {
 3037: 	$title = 'The LearningOnline Network with CAPA';
 3038:     }
 3039:     
 3040:     $result .= '<title> LON-CAPA '.&mt($title).'</title>'.$head_extra;
 3041:     return $result;
 3042: }
 3043: 
 3044: =pod
 3045: 
 3046: =over 4
 3047: 
 3048: =item * &endheadtag()
 3049: 
 3050: Returns a uniform </head> for LON-CAPA web pages.
 3051: 
 3052: Inputs: none
 3053: 
 3054: =back
 3055: 
 3056: =cut
 3057: 
 3058: sub endheadtag {
 3059:     return '</head>';
 3060: }
 3061: 
 3062: =pod
 3063: 
 3064: =over 4
 3065: 
 3066: =item * &head()
 3067: 
 3068: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 3069: 
 3070: Inputs: $title - optional title for the page
 3071:         $head_extra - optional extra HTML to put inside the <head>
 3072: =back
 3073: 
 3074: =cut
 3075: 
 3076: sub head {
 3077:     my ($title,$head_extra,$args) = @_;
 3078:     return &headtag($title,$head_extra,$args).&endheadtag();
 3079: }
 3080: 
 3081: =pod
 3082: 
 3083: =over 4
 3084: 
 3085: =item * &start_page()
 3086: 
 3087: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 3088: 
 3089: Inputs: $title - optional title for the page
 3090:         $head_extra - optional extra HTML to incude inside the <head>
 3091:         $args - additional optional args supported are:
 3092:                   only_body      -> is true will set &bodytag() onlybodytag
 3093:                                     arg on
 3094:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
 3095:                   add_entries    -> additional attributes to add to the  <body>
 3096:                   domain         -> force to color decorate a page for a 
 3097:                                     specific domain
 3098:                   function       -> force usage of a specific rolish color
 3099:                                     scheme
 3100:                   redirect       -> see &headtag()
 3101:                   bgcolor        -> override the default page bg color
 3102:                   js_ready       -> return a string ready for being used in 
 3103:                                     a javascript writeln
 3104:                   html_encode    -> return a string ready for being used in 
 3105:                                     a html attribute
 3106:                   force_register -> if is true will turn on the &bodytag()
 3107:                                     $forcereg arg
 3108:                   body_title     -> alternate text to use instead of $title
 3109:                                     in the title box that appears, this text
 3110:                                     is not auto translated like the $title is
 3111:                   frameset       -> if true will start with a <frameset>
 3112:                                     rather than <body>
 3113: =back
 3114: 
 3115: =cut
 3116: 
 3117: sub start_page {
 3118:     my ($title,$head_extra,$args) = @_;
 3119:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 3120:     my %head_args;
 3121:     foreach my $arg ('redirect','force_register') {
 3122: 	if (defined($args->{$arg})) {
 3123: 	    $head_args{$arg} = $args->{$arg};
 3124: 	}
 3125:     }
 3126: 
 3127:     $env{'internal.start_page'}++;
 3128:     my $result = 
 3129: 	&Apache::lonxml::xmlbegin().
 3130: 	&headtag($title,$head_extra,\%head_args).&endheadtag();
 3131:     if ($args->{'frameset'}) {
 3132: 	my $attr_string = &make_attr_string($args->{'force_register'},
 3133: 					    $args->{'add_entries'});
 3134: 	$result .= "\n<frameset $attr_string>\n";
 3135:     } else {
 3136: 	$result .=
 3137: 	    &bodytag($title, 
 3138: 		     $args->{'function'},       $args->{'add_entries'},
 3139: 		     $args->{'only_body'},      $args->{'domain'},
 3140: 		     $args->{'force_register'}, $args->{'body_title'},
 3141: 		     $args->{'no_nav_bar'},     $args->{'bgcolor'});
 3142:     }
 3143:     if ($args->{'js_ready'}) {
 3144: 	$result = &js_ready($result);
 3145:     }
 3146:     if ($args->{'html_encode'}) {
 3147: 	$result = &html_encode($result);
 3148:     }
 3149:     return $result;
 3150: }
 3151: 
 3152: 
 3153: =pod
 3154: 
 3155: =over 4
 3156: 
 3157: =item * &head()
 3158: 
 3159: Returns a complete </body></html> section for LON-CAPA web pages.
 3160: 
 3161: Inputs:         $args - additional optional args supported are:
 3162:                  js_ready     -> return a string ready for being used in 
 3163:                                  a javascript writeln
 3164:                  html_encode  -> return a string ready for being used in 
 3165:                                  a html attribute
 3166:                  frameset     -> if true will start with a <frameset>
 3167:                                  rather than <body>
 3168: =back
 3169: 
 3170: =cut
 3171: 
 3172: sub end_page {
 3173:     my ($args) = @_;
 3174:     #&Apache::lonnet::logthis("end_page ".join(':',caller(0)));
 3175:     $env{'internal.end_page'}++;
 3176:     my $result;
 3177:     if ($args->{'frameset'}) {
 3178: 	$result .= '</frameset>';
 3179:     } else {
 3180: 	$result .= &endbodytag();
 3181:     }
 3182:     $result .= "\n</html>";
 3183: 
 3184:     if ($args->{'js_ready'}) {
 3185: 	$result = &js_ready($result);
 3186:     }
 3187:     if ($args->{'html_encode'}) {
 3188: 	$result = &html_encode($result);
 3189:     }
 3190:     return $result;
 3191: }
 3192: 
 3193: sub html_encode {
 3194:     my ($result) = @_;
 3195: 
 3196:     $result = &HTML::Entities::encode($result,'<>&"');
 3197:     
 3198:     return $result;
 3199: }
 3200: sub js_ready {
 3201:     my ($result) = @_;
 3202: 
 3203:     $result =~ s/[\n\r]/ /xmsg;
 3204:     $result =~ s/\\/\\\\/xmsg;
 3205:     $result =~ s/'/\\'/xmsg;
 3206:     $result =~ s{</script>}{</scrip'+'t>}xmsg;
 3207:     
 3208:     return $result;
 3209: }
 3210: 
 3211: sub validate_page {
 3212:     if (  exists($env{'internal.start_page'})
 3213: 	  &&     $env{'internal.start_page'} > 1) {
 3214: 	&Apache::lonnet::logthis('start_page called multiple times '.
 3215: 				 $env{'internal.start_page'}.' '.
 3216: 				 $ENV{'request.filename'});
 3217:     }
 3218:     if (  exists($env{'internal.end_page'})
 3219: 	  &&     $env{'internal.end_page'} > 1) {
 3220: 	&Apache::lonnet::logthis('end_page called multiple times '.
 3221: 				 $env{'internal.end_page'}.' '.
 3222: 				 $env{'request.filename'});
 3223:     }
 3224:     if (     exists($env{'internal.start_page'})
 3225: 	&& ! exists($env{'internal.end_page'})) {
 3226: 	&Apache::lonnet::logthis('start_page called without end_page '.
 3227: 				 $env{'request.filename'});
 3228:     }
 3229:     if (   ! exists($env{'internal.start_page'})
 3230: 	&&   exists($env{'internal.end_page'})) {
 3231: 	&Apache::lonnet::logthis('end_page called without start_page'.
 3232: 				 $env{'request.filename'});
 3233:     }
 3234: }
 3235: 
 3236: sub simple_error_page {
 3237:     my ($r,$title,$msg) = @_;
 3238:     my $page =
 3239: 	&Apache::loncommon::start_page($title).
 3240: 	&mt($msg).
 3241: 	&Apache::loncommon::end_page();
 3242:     if (ref($r)) {
 3243: 	$r->print($page);
 3244: 	return;
 3245:     }
 3246:     return $page;
 3247: }
 3248: ###############################################
 3249: 
 3250: =pod
 3251: 
 3252: =over 4
 3253: 
 3254: =item get_users_function
 3255: 
 3256: Used by &bodytag to determine the current users primary role.
 3257: Returns either 'student','coordinator','admin', or 'author'.
 3258: 
 3259: =cut
 3260: 
 3261: ###############################################
 3262: sub get_users_function {
 3263:     my $function = 'student';
 3264:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 3265:         $function='coordinator';
 3266:     }
 3267:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 3268:         $function='admin';
 3269:     }
 3270:     if (($env{'request.role'}=~/^(au|ca)/) ||
 3271:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 3272:         $function='author';
 3273:     }
 3274:     return $function;
 3275: }
 3276: 
 3277: ###############################################
 3278: 
 3279: =pod
 3280: 
 3281: =item check_user_status
 3282: 
 3283: Determines current status of supplied role for a
 3284: specific user. Roles can be active, previous or future.
 3285: 
 3286: Inputs: 
 3287: user's domain, user's username, course's domain,
 3288: course's number, optional section/group.
 3289: 
 3290: Outputs:
 3291: role status: active, previous or future. 
 3292: 
 3293: =cut
 3294: 
 3295: sub check_user_status {
 3296:     my ($udom,$uname,$cdom,$crs,$role,$secgrp) = @_;
 3297:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 3298:     my @uroles = keys %userinfo;
 3299:     my $srchstr;
 3300:     my $active_chk = 'none';
 3301:     if (@uroles > 0) {
 3302:         if (($role eq 'cc') || ($secgrp eq '') || (!defined($secgrp))) {
 3303:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 3304:         } else {
 3305:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$secgrp.'_'.$role;         }
 3306:         if (grep/^$srchstr$/,@uroles) {
 3307:             my $role_end = 0;
 3308:             my $role_start = 0;
 3309:             $active_chk = 'active';
 3310:             if ($userinfo{$srchstr} =~ m/^($role)_(\d+)/) {
 3311:                 $role_end = $2;
 3312:                 if ($userinfo{$srchstr} =~ m/^($role)_($role_end)_(\d+)$/) {
 3313:                     $role_start = $3;
 3314:                 }
 3315:             }
 3316:             if ($role_start > 0) {
 3317:                 if (time < $role_start) {
 3318:                     $active_chk = 'future';
 3319:                 }
 3320:             }
 3321:             if ($role_end > 0) {
 3322:                 if (time > $role_end) {
 3323:                     $active_chk = 'previous';
 3324:                 }
 3325:             }
 3326:         }
 3327:     }
 3328:     return $active_chk;
 3329: }
 3330: 
 3331: ###############################################
 3332: 
 3333: =pod
 3334: 
 3335: =item get_sections
 3336: 
 3337: Determines all the sections for a course including
 3338: sections with students and sections containing other roles.
 3339: Incoming parameters: domain, course number, reference to 
 3340: section hash (keys to be section/group IDs), reference to 
 3341: array containing roles for which sections should be gathered
 3342: (optional). If the fourth argument is undefined, sections
 3343: are gathered for any role.
 3344:  
 3345: Returns number of sections.
 3346: 
 3347: =cut
 3348: 
 3349: ###############################################
 3350: sub get_sections {
 3351:     my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
 3352:     if (!($cdom && $cnum)) { return 0; }
 3353:     my $numsections = 0;
 3354: 
 3355:     if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
 3356: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 3357: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 3358: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 3359: 	while (my ($student,$data) = each %$classlist) {
 3360: 	    my ($section,$status) = ($data->[$sec_index],
 3361: 				     $data->[$status_index]);
 3362: 	    unless ($section eq '-1' || $section =~ /^\s*$/) {
 3363: 		if (!defined($$sectioncount{$section})) { $numsections++; }
 3364: 		$$sectioncount{$section}++;
 3365: 	    }
 3366: 	}
 3367:     }
 3368:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 3369:     foreach my $user (sort(keys(%courseroles))) {
 3370: 	if ($user !~ /^(\w{2})/) { next; }
 3371: 	my ($role) = ($user =~ /^(\w{2})/);
 3372: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 3373: 	my $section;
 3374: 	if ($role eq 'cr' &&
 3375: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 3376: 	    $section=$1;
 3377: 	}
 3378: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 3379: 	if (!defined($section) || $section eq '-1') { next; }
 3380: 	if (!defined($$sectioncount{$section})) { $numsections++; } 
 3381: 	$$sectioncount{$section}++;
 3382:     }
 3383:     return $numsections;
 3384: }
 3385: 
 3386: ###############################################
 3387:                                                                                   
 3388: =pod
 3389:                                                                                   
 3390: =item coursegroups
 3391: 
 3392: Retrieve information about groups in a course,
 3393: 
 3394: Input:
 3395: 1. Reference to hash to populate with group information. 
 3396: 2. Optional course domain
 3397: 3. Optional course number
 3398: 4. Optional group name
 3399: 
 3400: Course domain and number will be taken from user's
 3401: environment if not supplied. Optional group name will'
 3402: be passed to lonnet::get_coursegroups() as a regexp to
 3403: use in the call to the dump function.
 3404: 
 3405: Output
 3406: Returns number of groups in the course (subject to the
 3407: optional group name filter).
 3408: 
 3409: Side effects:
 3410: Populates the referenced curr_groups hash, with key,
 3411: value pairs. Keys are group names, corresponding values
 3412: are scalars containing group information in XML. This
 3413: can be sent to &get_group_settings() to be parsed.     
 3414: 
 3415: =cut 
 3416: 
 3417: ###############################################
 3418: 
 3419: sub coursegroups {
 3420:     my ($curr_groups,$cdom,$cnum,$group) = @_;
 3421:     my $numgroups;
 3422:     if (!defined($cdom) || !defined($cnum)) {
 3423:         my $cid =  $env{'request.course.id'};
 3424:         $cdom = $env{'course.'.$cid.'.domain'};
 3425:         $cnum = $env{'course.'.$cid.'.num'};
 3426:     }
 3427:     %{$curr_groups} = &Apache::lonnet::get_coursegroups($cdom,$cnum,$group);
 3428:     my ($tmp) = keys(%{$curr_groups});
 3429:     if ($tmp=~/^error:/) {
 3430:         unless ($tmp eq 'error: 2 tie(GDBM) Failed while attempting dump') {
 3431:             &logthis('Error retrieving groups: '.$tmp.' in '.$cnum.':'.
 3432:                                                                    $cdom);
 3433:         }
 3434:         $numgroups = 0;
 3435:     } else {
 3436:         $numgroups = keys(%{$curr_groups});
 3437:     }
 3438:     return $numgroups;
 3439: }
 3440: 
 3441: ###############################################
 3442: 
 3443: =pod
 3444: 
 3445: =item get_group_settings
 3446: 
 3447: Uses TokeParser to extract group information from the
 3448: XML used to describe course groups.
 3449: 
 3450: Input:
 3451: Scalar containing XML  - as retrieved from &coursegroups().
 3452: 
 3453: Output:
 3454: Hash containing group information as key=values for (a), and
 3455: hash of hashes for (b)
 3456: 
 3457: Keys (in two categories):
 3458: (a) groupname, creator, creation, modified, startdate,enddate.
 3459: Corresponding values are name of the group, creator of the group
 3460: (username:domain), UNIX time for date group was created, and
 3461: settings were last modified, and default start and end access
 3462: times for group members.
 3463: 
 3464: (b) functions returned in hash of hashes.
 3465: Outer hash key is functions.
 3466: Inner hash keys are chat,discussion,email,files,homepage,roster.
 3467: Corresponding values are either on or off, depending on
 3468: whether this type of functionality is available for the group.
 3469: 
 3470: =cut
 3471:                                                                                  
 3472: ###############################################
 3473: 
 3474: sub get_group_settings {
 3475:     my ($groupinfo)=@_;
 3476:     my $parser=HTML::TokeParser->new(\$groupinfo);
 3477:     my $token;
 3478:     my $tool = '';
 3479:     my $role = '';
 3480:     my %content=();
 3481:     while ($token=$parser->get_token) {
 3482:         if ($token->[0] eq 'S')  {
 3483:             my $entry=$token->[1];
 3484:             if ($entry eq 'functions' || $entry eq 'autosec') {
 3485:                 %{$content{$entry}} = ();
 3486:                 $tool = $entry;
 3487:             } elsif ($entry eq 'role') {
 3488:                 if ($tool eq 'autosec') {
 3489:                     $role = $token->[2]{id};
 3490:                 }
 3491:             } else {
 3492:                 my $value=$parser->get_text('/'.$entry);
 3493:                 if ($entry eq 'name') {
 3494:                     if ($tool eq 'functions') {
 3495:                         my $function = $token->[2]{id};
 3496:                         $content{$tool}{$function} = $value;
 3497:                     }
 3498:                 } elsif ($entry eq 'groupname') {
 3499:                     $content{$entry}=&Apache::lonnet::unescape($value);
 3500:                 } elsif (($entry eq 'roles') || ($entry eq 'types') ||
 3501:                          ($entry eq 'sectionpick') || ($entry eq 'defpriv')) {
 3502:                     push(@{$content{$entry}},$value);
 3503:                 } elsif ($entry eq 'section') {
 3504:                     if ($tool eq 'autosec'  && $role ne '') {
 3505:                         push(@{$content{$tool}{$role}},$value);
 3506:                     }
 3507:                 } else {
 3508:                     $content{$entry}=$value;
 3509:                 }
 3510:             }
 3511:         } elsif ($token->[0] eq 'E') {
 3512:             if ($token->[1] eq 'functions' || $token->[1] eq 'autosec') {
 3513:                 $tool = '';
 3514:             } elsif ($token->[1] eq 'role') {
 3515:                 $role = '';
 3516:             }
 3517: 
 3518:         }
 3519:     }
 3520:     return %content;
 3521: }
 3522: 
 3523: sub check_group_access {
 3524:     my ($group) = @_;
 3525:     my $access = 1;
 3526:     my $now = time;
 3527:     my ($start,$end) = split(/\./,$env{'user.role.gr/'.$env{'request.course,id'}.'/'.$group});
 3528:     if (($end!=0) && ($end<$now)) { $access = 0; }
 3529:     if (($start!=0) && ($start>$now)) { $access=0; }
 3530:     return $access;
 3531: }
 3532: 
 3533: ###############################################
 3534: 
 3535: =pod
 3536:                                                                                 
 3537: =item get_course_users
 3538:                                                                                 
 3539: Retrieves usernames:domains for users in the specified course
 3540: with specific role(s), and access status. 
 3541: 
 3542: Incoming parameters:
 3543: 1. course domain
 3544: 2. course number
 3545: 3. access status: users must have - either active, 
 3546: previous, future, or all.
 3547: 4. reference to array of permissible roles
 3548: 5. reference to array of section restrictions (optional)
 3549: 6. reference to results object (hash of hashes).
 3550: 7. reference to optional userdata hash
 3551: Keys of top level hash are roles.
 3552: Keys of inner hashes are username:domain, with 
 3553: values set to access type.
 3554: Optional userdata hash returns an array with arguments in the 
 3555: same order as loncoursedata::get_classlist() for student data.
 3556: 
 3557: Entries for end, start, section and status are blank because
 3558: of the possibility of multiple values for non-student roles.
 3559: 
 3560: =cut
 3561:                                                                                 
 3562: ###############################################
 3563:                                                                                 
 3564: sub get_course_users {
 3565:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
 3566:     my %idx = ();
 3567: 
 3568:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 3569:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 3570:     $idx{end} = &Apache::loncoursedata::CL_END();
 3571:     $idx{start} = &Apache::loncoursedata::CL_START();
 3572:     $idx{id} = &Apache::loncoursedata::CL_ID();
 3573:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 3574:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 3575:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 3576: 
 3577:     if (grep(/^st$/,@{$roles})) {
 3578:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 3579:         my $now = time;
 3580:         foreach my $student (keys(%{$classlist})) {
 3581:             my $match = 0;
 3582:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 3583: 		unless(grep(/^\Q$$classlist{$student}[$idx{section}]\E$/,
 3584: 			    @{$sections})) {
 3585: 		    next;
 3586: 		}
 3587:             } 
 3588:             if (defined($$types{'active'})) {
 3589:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 3590:                     push(@{$$users{st}{$student}},'active');
 3591:                     $match = 1;
 3592:                 }
 3593:             }
 3594:             if (defined($$types{'previous'})) {
 3595:                 if ($$classlist{$student}[$idx{end}] <= $now) {
 3596:                     push(@{$$users{st}{$student}},'previous');
 3597:                     $match = 1;
 3598:                 }
 3599:             }
 3600:             if (defined($$types{'future'})) {
 3601:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
 3602:                     push(@{$$users{st}{$student}},'future');
 3603:                     $match = 1;
 3604:                 }
 3605:             }
 3606:             if ($match && defined($userdata)) {
 3607:                 $$userdata{$student} = $$classlist{$student};
 3608:             }
 3609:         }
 3610:     }
 3611:     if ((@{$roles} > 0) && (@{$roles} ne "st")) {
 3612:         my @coursepersonnel = &Apache::lonnet::getkeys('nohist_userroles',$cdom,$cnum);
 3613:         foreach my $person (@coursepersonnel) {
 3614:             my $match = 0;
 3615:             my ($role,$user) = ($person =~ /^([^:]*):([^:]+:[^:]+)/);
 3616:             $user =~ s/:$//;
 3617:             if (($role) && (grep(/^\Q$role\E$/,@{$roles}))) {
 3618:                 my ($uname,$udom,$usec) = split(/:/,$user);
 3619:                 if ($usec ne '' && (ref($sections) eq 'ARRAY') && 
 3620: 		    @{$sections} > 0) {
 3621: 		    unless(grep(/^\Q$usec\E$/,@{$sections})) {
 3622: 			next;
 3623: 		    }
 3624:                 }
 3625:                 if ($uname ne '' && $udom ne '') {
 3626:                     my $status = &check_user_status($udom,$uname,$cdom,$cnum,$role);
 3627:                     foreach my $type (keys(%{$types})) { 
 3628:                         if ($status eq $type) {
 3629:                             @{$$users{$role}{$user}} = $type;
 3630:                             $match = 1;
 3631:                         }
 3632:                     }
 3633:                     if ($match && defined($userdata) &&
 3634:                         !exists($$userdata{$uname.':'.$udom})) {
 3635: 			&get_user_info($udom,$uname,\%idx,$userdata);
 3636:                     }
 3637:                 }
 3638:             }
 3639:         }
 3640:         if (grep(/^ow$/,@{$roles})) {
 3641:             if ((defined($cdom)) && (defined($cnum))) {
 3642:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 3643:                 if ( defined($csettings{'internal.courseowner'}) ) {
 3644:                     my $owner = $csettings{'internal.courseowner'};
 3645:                     @{$$users{'ow'}{$owner.':'.$cdom}} = 'any';
 3646:                     if (defined($userdata) && 
 3647: 			!exists($$userdata{$owner.':'.$cdom})) {
 3648: 			&get_user_info($cdom,$owner,\%idx,$userdata);
 3649: 		    }
 3650:                 }
 3651:             }
 3652:         }
 3653:     }
 3654:     return;
 3655: }
 3656: 
 3657: sub get_user_info {
 3658:     my ($udom,$uname,$idx,$userdata) = @_;
 3659:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 3660: 	&plainname($uname,$udom,'lastname');
 3661:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 3662:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 3663:     return;
 3664: }
 3665: 
 3666: ###############################################
 3667: 
 3668: sub get_posted_cgi {
 3669:     my $r=shift;
 3670: 
 3671:     my $buffer;
 3672:     if ($r->header_in('Content-length')) {
 3673: 	$r->read($buffer,$r->header_in('Content-length'),0);
 3674:     }
 3675:     unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
 3676: 	my @pairs=split(/&/,$buffer);
 3677: 	my $pair;
 3678: 	foreach $pair (@pairs) {
 3679: 	    my ($name,$value) = split(/=/,$pair);
 3680: 	    $value =~ tr/+/ /;
 3681: 	    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3682: 	    $name  =~ tr/+/ /;
 3683: 	    $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3684: 	    &add_to_env("form.$name",$value);
 3685: 	}
 3686:     } else {
 3687: 	my $contentsep=$1;
 3688: 	my @lines = split (/\n/,$buffer);
 3689: 	my $name='';
 3690: 	my $value='';
 3691: 	my $fname='';
 3692: 	my $fmime='';
 3693: 	my $i;
 3694: 	for ($i=0;$i<=$#lines;$i++) {
 3695: 	    if ($lines[$i]=~/^$contentsep/) {
 3696: 		if ($name) {
 3697: 		    chomp($value);
 3698: 		    if ($fname) {
 3699: 			$env{"form.$name.filename"}=$fname;
 3700: 			$env{"form.$name.mimetype"}=$fmime;
 3701: 		    } else {
 3702: 			$value=~s/\s+$//s;
 3703: 		    }
 3704: 		    &add_to_env("form.$name",$value);
 3705: 		}
 3706: 		if ($i<$#lines) {
 3707: 		    $i++;
 3708: 		    $lines[$i]=~
 3709: 		/Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
 3710: 		    $name=$1;
 3711: 		    $value='';
 3712: 		    if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
 3713: 			$fname=$1;
 3714: 			if 
 3715:                             ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
 3716: 				$fmime=$1;
 3717: 				$i++;
 3718: 			    } else {
 3719: 				$fmime='';
 3720: 			    }
 3721: 		    } else {
 3722: 			$fname='';
 3723: 			$fmime='';
 3724: 		    }
 3725: 		    $i++;
 3726: 		}
 3727: 	    } else {
 3728: 		$value.=$lines[$i]."\n";
 3729: 	    }
 3730: 	}
 3731:     }
 3732: #
 3733: # Digested POSTed values
 3734: #
 3735: # Remember the way this was originally done (GET or POST)
 3736: #
 3737:     $env{'request.method'}=$ENV{'REQUEST_METHOD'};
 3738: #
 3739: # There may also be stuff in the query string
 3740: # Tell subsequent handlers that this was GET, not POST, so they can access query string.
 3741: # Also, unset POSTed content length to cover all tracks.
 3742: #
 3743: 
 3744: # This does not work, because M_GET is not defined (if it's defined, it is just 0). 
 3745: # Commenting out for now ... not sure if harm is done.
 3746: #    $r->method_number(M_GET);
 3747: 
 3748:     $r->method('GET');
 3749:     $r->headers_in->unset('Content-length');
 3750: }
 3751: 
 3752: =pod
 3753: 
 3754: =item * get_unprocessed_cgi($query,$possible_names)
 3755: 
 3756: Modify the %env hash to contain unprocessed CGI form parameters held in
 3757: $query.  The parameters listed in $possible_names (an array reference),
 3758: will be set in $env{'form.name'} if they do not already exist.
 3759: 
 3760: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 3761: $possible_names is an ref to an array of form element names.  As an example:
 3762: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 3763: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 3764: 
 3765: =cut
 3766: 
 3767: sub get_unprocessed_cgi {
 3768:   my ($query,$possible_names)= @_;
 3769:   # $Apache::lonxml::debug=1;
 3770:   foreach (split(/&/,$query)) {
 3771:     my ($name, $value) = split(/=/,$_);
 3772:     $name = &Apache::lonnet::unescape($name);
 3773:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 3774:       $value =~ tr/+/ /;
 3775:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3776:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 3777:     }
 3778:   }
 3779: }
 3780: 
 3781: =pod
 3782: 
 3783: =item * cacheheader() 
 3784: 
 3785: returns cache-controlling header code
 3786: 
 3787: =cut
 3788: 
 3789: sub cacheheader {
 3790:     unless ($env{'request.method'} eq 'GET') { return ''; }
 3791:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 3792:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 3793:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 3794:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 3795:     return $output;
 3796: }
 3797: 
 3798: =pod
 3799: 
 3800: =item * no_cache($r) 
 3801: 
 3802: specifies header code to not have cache
 3803: 
 3804: =cut
 3805: 
 3806: sub no_cache {
 3807:     my ($r) = @_;
 3808:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 3809: 	$env{'request.method'} ne 'GET') { return ''; }
 3810:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 3811:     $r->no_cache(1);
 3812:     $r->header_out("Expires" => $date);
 3813:     $r->header_out("Pragma" => "no-cache");
 3814: }
 3815: 
 3816: sub content_type {
 3817:     my ($r,$type,$charset) = @_;
 3818:     if ($r) {
 3819: 	#  Note that printout.pl calls this with undef for $r.
 3820: 	&no_cache($r);
 3821:     }
 3822:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 3823:     unless ($charset) {
 3824: 	$charset=&Apache::lonlocal::current_encoding;
 3825:     }
 3826:     if ($charset) { $type.='; charset='.$charset; }
 3827:     if ($r) {
 3828: 	$r->content_type($type);
 3829:     } else {
 3830: 	print("Content-type: $type\n\n");
 3831:     }
 3832: }
 3833: 
 3834: =pod
 3835: 
 3836: =item * add_to_env($name,$value) 
 3837: 
 3838: adds $name to the %env hash with value
 3839: $value, if $name already exists, the entry is converted to an array
 3840: reference and $value is added to the array.
 3841: 
 3842: =cut
 3843: 
 3844: sub add_to_env {
 3845:   my ($name,$value)=@_;
 3846:   if (defined($env{$name})) {
 3847:     if (ref($env{$name})) {
 3848:       #already have multiple values
 3849:       push(@{ $env{$name} },$value);
 3850:     } else {
 3851:       #first time seeing multiple values, convert hash entry to an arrayref
 3852:       my $first=$env{$name};
 3853:       undef($env{$name});
 3854:       push(@{ $env{$name} },$first,$value);
 3855:     }
 3856:   } else {
 3857:     $env{$name}=$value;
 3858:   }
 3859: }
 3860: 
 3861: =pod
 3862: 
 3863: =item * get_env_multiple($name) 
 3864: 
 3865: gets $name from the %env hash, it seemlessly handles the cases where multiple
 3866: values may be defined and end up as an array ref.
 3867: 
 3868: returns an array of values
 3869: 
 3870: =cut
 3871: 
 3872: sub get_env_multiple {
 3873:     my ($name) = @_;
 3874:     my @values;
 3875:     if (defined($env{$name})) {
 3876:         # exists is it an array
 3877:         if (ref($env{$name})) {
 3878:             @values=@{ $env{$name} };
 3879:         } else {
 3880:             $values[0]=$env{$name};
 3881:         }
 3882:     }
 3883:     return(@values);
 3884: }
 3885: 
 3886: 
 3887: =pod
 3888: 
 3889: =back 
 3890: 
 3891: =head1 CSV Upload/Handling functions
 3892: 
 3893: =over 4
 3894: 
 3895: =item * upfile_store($r)
 3896: 
 3897: Store uploaded file, $r should be the HTTP Request object,
 3898: needs $env{'form.upfile'}
 3899: returns $datatoken to be put into hidden field
 3900: 
 3901: =cut
 3902: 
 3903: sub upfile_store {
 3904:     my $r=shift;
 3905:     $env{'form.upfile'}=~s/\r/\n/gs;
 3906:     $env{'form.upfile'}=~s/\f/\n/gs;
 3907:     $env{'form.upfile'}=~s/\n+/\n/gs;
 3908:     $env{'form.upfile'}=~s/\n+$//gs;
 3909: 
 3910:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 3911: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 3912:     {
 3913:         my $datafile = $r->dir_config('lonDaemons').
 3914:                            '/tmp/'.$datatoken.'.tmp';
 3915:         if ( open(my $fh,">$datafile") ) {
 3916:             print $fh $env{'form.upfile'};
 3917:             close($fh);
 3918:         }
 3919:     }
 3920:     return $datatoken;
 3921: }
 3922: 
 3923: =pod
 3924: 
 3925: =item * load_tmp_file($r)
 3926: 
 3927: Load uploaded file from tmp, $r should be the HTTP Request object,
 3928: needs $env{'form.datatoken'},
 3929: sets $env{'form.upfile'} to the contents of the file
 3930: 
 3931: =cut
 3932: 
 3933: sub load_tmp_file {
 3934:     my $r=shift;
 3935:     my @studentdata=();
 3936:     {
 3937:         my $studentfile = $r->dir_config('lonDaemons').
 3938:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 3939:         if ( open(my $fh,"<$studentfile") ) {
 3940:             @studentdata=<$fh>;
 3941:             close($fh);
 3942:         }
 3943:     }
 3944:     $env{'form.upfile'}=join('',@studentdata);
 3945: }
 3946: 
 3947: =pod
 3948: 
 3949: =item * upfile_record_sep()
 3950: 
 3951: Separate uploaded file into records
 3952: returns array of records,
 3953: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 3954: 
 3955: =cut
 3956: 
 3957: sub upfile_record_sep {
 3958:     if ($env{'form.upfiletype'} eq 'xml') {
 3959:     } else {
 3960: 	my @records;
 3961: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 3962: 	    if ($line=~/^\s*$/) { next; }
 3963: 	    push(@records,$line);
 3964: 	}
 3965: 	return @records;
 3966:     }
 3967: }
 3968: 
 3969: =pod
 3970: 
 3971: =item * record_sep($record)
 3972: 
 3973: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 3974: 
 3975: =cut
 3976: 
 3977: sub takeleft {
 3978:     my $index=shift;
 3979:     return substr('0000'.$index,-4,4);
 3980: }
 3981: 
 3982: sub record_sep {
 3983:     my $record=shift;
 3984:     my %components=();
 3985:     if ($env{'form.upfiletype'} eq 'xml') {
 3986:     } elsif ($env{'form.upfiletype'} eq 'space') {
 3987:         my $i=0;
 3988:         foreach (split(/\s+/,$record)) {
 3989:             my $field=$_;
 3990:             $field=~s/^(\"|\')//;
 3991:             $field=~s/(\"|\')$//;
 3992:             $components{&takeleft($i)}=$field;
 3993:             $i++;
 3994:         }
 3995:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 3996:         my $i=0;
 3997:         foreach (split(/\t/,$record)) {
 3998:             my $field=$_;
 3999:             $field=~s/^(\"|\')//;
 4000:             $field=~s/(\"|\')$//;
 4001:             $components{&takeleft($i)}=$field;
 4002:             $i++;
 4003:         }
 4004:     } else {
 4005:         my @allfields=split(/\,/,$record);
 4006:         my $i=0;
 4007:         my $j;
 4008:         for ($j=0;$j<=$#allfields;$j++) {
 4009:             my $field=$allfields[$j];
 4010:             if ($field=~/^\s*(\"|\')/) {
 4011: 		my $delimiter=$1;
 4012:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 4013: 		    $j++;
 4014: 		    $field.=','.$allfields[$j];
 4015: 		}
 4016:                 $field=~s/^\s*$delimiter//;
 4017:                 $field=~s/$delimiter\s*$//;
 4018:             }
 4019:             $components{&takeleft($i)}=$field;
 4020: 	    $i++;
 4021:         }
 4022:     }
 4023:     return %components;
 4024: }
 4025: 
 4026: ######################################################
 4027: ######################################################
 4028: 
 4029: =pod
 4030: 
 4031: =item * upfile_select_html()
 4032: 
 4033: Return HTML code to select a file from the users machine and specify 
 4034: the file type.
 4035: 
 4036: =cut
 4037: 
 4038: ######################################################
 4039: ######################################################
 4040: sub upfile_select_html {
 4041:     my %Types = (
 4042:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 4043:                  space => &mt('Space separated'),
 4044:                  tab   => &mt('Tabulator separated'),
 4045: #                 xml   => &mt('HTML/XML'),
 4046:                  );
 4047:     my $Str = '<input type="file" name="upfile" size="50" />'.
 4048:         '<br />Type: <select name="upfiletype">';
 4049:     foreach my $type (sort(keys(%Types))) {
 4050:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 4051:     }
 4052:     $Str .= "</select>\n";
 4053:     return $Str;
 4054: }
 4055: 
 4056: sub get_samples {
 4057:     my ($records,$toget) = @_;
 4058:     my @samples=({});
 4059:     my $got=0;
 4060:     foreach my $rec (@$records) {
 4061: 	my %temp = &record_sep($rec);
 4062: 	if (! grep(/\S/, values(%temp))) { next; }
 4063: 	if (%temp) {
 4064: 	    $samples[$got]=\%temp;
 4065: 	    $got++;
 4066: 	    if ($got == $toget) { last; }
 4067: 	}
 4068:     }
 4069:     return \@samples;
 4070: }
 4071: 
 4072: ######################################################
 4073: ######################################################
 4074: 
 4075: =pod
 4076: 
 4077: =item * csv_print_samples($r,$records)
 4078: 
 4079: Prints a table of sample values from each column uploaded $r is an
 4080: Apache Request ref, $records is an arrayref from
 4081: &Apache::loncommon::upfile_record_sep
 4082: 
 4083: =cut
 4084: 
 4085: ######################################################
 4086: ######################################################
 4087: sub csv_print_samples {
 4088:     my ($r,$records) = @_;
 4089:     my $samples = &get_samples($records,3);
 4090: 
 4091:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 4092:     foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 4093:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($_+1)).'</th>'); }
 4094:     $r->print('</tr>');
 4095:     foreach my $hash (@$samples) {
 4096: 	$r->print('<tr>');
 4097: 	foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4098: 	    $r->print('<td>');
 4099: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 4100: 	    $r->print('</td>');
 4101: 	}
 4102: 	$r->print('</tr>');
 4103:     }
 4104:     $r->print('</tr></table><br />'."\n");
 4105: }
 4106: 
 4107: ######################################################
 4108: ######################################################
 4109: 
 4110: =pod
 4111: 
 4112: =item * csv_print_select_table($r,$records,$d)
 4113: 
 4114: Prints a table to create associations between values and table columns.
 4115: 
 4116: $r is an Apache Request ref,
 4117: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4118: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 4119: 
 4120: =cut
 4121: 
 4122: ######################################################
 4123: ######################################################
 4124: sub csv_print_select_table {
 4125:     my ($r,$records,$d) = @_;
 4126:     my $i=0;
 4127:     my $samples = &get_samples($records,1);
 4128:     $r->print(&mt('Associate columns with student attributes.')."\n".
 4129: 	     '<table border="2"><tr>'.
 4130:               '<th>'.&mt('Attribute').'</th>'.
 4131:               '<th>'.&mt('Column').'</th></tr>'."\n");
 4132:     foreach (@$d) {
 4133: 	my ($value,$display,$defaultcol)=@{ $_ };
 4134: 	$r->print('<tr><td>'.$display.'</td>');
 4135: 
 4136: 	$r->print('<td><select name=f'.$i.
 4137: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4138: 	$r->print('<option value="none"></option>');
 4139: 	foreach (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4140: 	    $r->print('<option value="'.$_.'"'.
 4141:                       ($_ eq $defaultcol ? ' selected="selected" ' : '').
 4142:                       '>Column '.($_+1).'</option>');
 4143: 	}
 4144: 	$r->print('</select></td></tr>'."\n");
 4145: 	$i++;
 4146:     }
 4147:     $i--;
 4148:     return $i;
 4149: }
 4150: 
 4151: ######################################################
 4152: ######################################################
 4153: 
 4154: =pod
 4155: 
 4156: =item * csv_samples_select_table($r,$records,$d)
 4157: 
 4158: Prints a table of sample values from the upload and can make associate samples to internal names.
 4159: 
 4160: $r is an Apache Request ref,
 4161: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4162: $d is an array of 2 element arrays (internal name, displayed name)
 4163: 
 4164: =cut
 4165: 
 4166: ######################################################
 4167: ######################################################
 4168: sub csv_samples_select_table {
 4169:     my ($r,$records,$d) = @_;
 4170:     my $i=0;
 4171:     #
 4172:     my $samples = &get_samples($records,3);
 4173:     $r->print('<table border=2><tr><th>'.
 4174:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 4175: 
 4176:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 4177: 	$r->print('<tr><td><select name="f'.$i.'"'.
 4178: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4179: 	foreach my $option (@$d) {
 4180: 	    my ($value,$display,$defaultcol)=@{ $option };
 4181: 	    $r->print('<option value="'.$value.'"'.
 4182:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 4183:                       $display.'</option>');
 4184: 	}
 4185: 	$r->print('</select></td><td>');
 4186: 	foreach my $line (0..2) {
 4187: 	    if (defined($samples->[$line]{$key})) { 
 4188: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 4189: 	    }
 4190: 	}
 4191: 	$r->print('</td></tr>');
 4192: 	$i++;
 4193:     }
 4194:     $i--;
 4195:     return($i);
 4196: }
 4197: 
 4198: ######################################################
 4199: ######################################################
 4200: 
 4201: =pod
 4202: 
 4203: =item clean_excel_name($name)
 4204: 
 4205: Returns a replacement for $name which does not contain any illegal characters.
 4206: 
 4207: =cut
 4208: 
 4209: ######################################################
 4210: ######################################################
 4211: sub clean_excel_name {
 4212:     my ($name) = @_;
 4213:     $name =~ s/[:\*\?\/\\]//g;
 4214:     if (length($name) > 31) {
 4215:         $name = substr($name,0,31);
 4216:     }
 4217:     return $name;
 4218: }
 4219: 
 4220: =pod
 4221: 
 4222: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 4223: 
 4224: Returns either 1 or undef
 4225: 
 4226: 1 if the part is to be hidden, undef if it is to be shown
 4227: 
 4228: Arguments are:
 4229: 
 4230: $id the id of the part to be checked
 4231: $symb, optional the symb of the resource to check
 4232: $udom, optional the domain of the user to check for
 4233: $uname, optional the username of the user to check for
 4234: 
 4235: =cut
 4236: 
 4237: sub check_if_partid_hidden {
 4238:     my ($id,$symb,$udom,$uname) = @_;
 4239:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 4240: 					 $symb,$udom,$uname);
 4241:     my $truth=1;
 4242:     #if the string starts with !, then the list is the list to show not hide
 4243:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 4244:     my @hiddenlist=split(/,/,$hiddenparts);
 4245:     foreach my $checkid (@hiddenlist) {
 4246: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 4247:     }
 4248:     return !$truth;
 4249: }
 4250: 
 4251: 
 4252: ############################################################
 4253: ############################################################
 4254: 
 4255: =pod
 4256: 
 4257: =back 
 4258: 
 4259: =head1 cgi-bin script and graphing routines
 4260: 
 4261: =over 4
 4262: 
 4263: =item get_cgi_id
 4264: 
 4265: Inputs: none
 4266: 
 4267: Returns an id which can be used to pass environment variables
 4268: to various cgi-bin scripts.  These environment variables will
 4269: be removed from the users environment after a given time by
 4270: the routine &Apache::lonnet::transfer_profile_to_env.
 4271: 
 4272: =cut
 4273: 
 4274: ############################################################
 4275: ############################################################
 4276: my $uniq=0;
 4277: sub get_cgi_id {
 4278:     $uniq=($uniq+1)%100000;
 4279:     return (time.'_'.$$.'_'.$uniq);
 4280: }
 4281: 
 4282: ############################################################
 4283: ############################################################
 4284: 
 4285: =pod
 4286: 
 4287: =item DrawBarGraph
 4288: 
 4289: Facilitates the plotting of data in a (stacked) bar graph.
 4290: Puts plot definition data into the users environment in order for 
 4291: graph.png to plot it.  Returns an <img> tag for the plot.
 4292: The bars on the plot are labeled '1','2',...,'n'.
 4293: 
 4294: Inputs:
 4295: 
 4296: =over 4
 4297: 
 4298: =item $Title: string, the title of the plot
 4299: 
 4300: =item $xlabel: string, text describing the X-axis of the plot
 4301: 
 4302: =item $ylabel: string, text describing the Y-axis of the plot
 4303: 
 4304: =item $Max: scalar, the maximum Y value to use in the plot
 4305: If $Max is < any data point, the graph will not be rendered.
 4306: 
 4307: =item $colors: array ref holding the colors to be used for the data sets when
 4308: they are plotted.  If undefined, default values will be used.
 4309: 
 4310: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 4311: 
 4312: =item @Values: An array of array references.  Each array reference holds data
 4313: to be plotted in a stacked bar chart.
 4314: 
 4315: =item If the final element of @Values is a hash reference the key/value
 4316: pairs will be added to the graph definition.
 4317: 
 4318: =back
 4319: 
 4320: Returns:
 4321: 
 4322: An <img> tag which references graph.png and the appropriate identifying
 4323: information for the plot.
 4324: 
 4325: =cut
 4326: 
 4327: ############################################################
 4328: ############################################################
 4329: sub DrawBarGraph {
 4330:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 4331:     #
 4332:     if (! defined($colors)) {
 4333:         $colors = ['#33ff00', 
 4334:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 4335:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 4336:                   ]; 
 4337:     }
 4338:     my $extra_settings = {};
 4339:     if (ref($Values[-1]) eq 'HASH') {
 4340:         $extra_settings = pop(@Values);
 4341:     }
 4342:     #
 4343:     my $identifier = &get_cgi_id();
 4344:     my $id = 'cgi.'.$identifier;        
 4345:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 4346:         return '';
 4347:     }
 4348:     #
 4349:     my @Labels;
 4350:     if (defined($labels)) {
 4351:         @Labels = @$labels;
 4352:     } else {
 4353:         for (my $i=0;$i<@{$Values[0]};$i++) {
 4354:             push (@Labels,$i+1);
 4355:         }
 4356:     }
 4357:     #
 4358:     my $NumBars = scalar(@{$Values[0]});
 4359:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 4360:     my %ValuesHash;
 4361:     my $NumSets=1;
 4362:     foreach my $array (@Values) {
 4363:         next if (! ref($array));
 4364:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 4365:             join(',',@$array);
 4366:     }
 4367:     #
 4368:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 4369:     if ($NumBars < 3) {
 4370:         $width = 120+$NumBars*32;
 4371:         $xskip = 1;
 4372:         $bar_width = 30;
 4373:     } elsif ($NumBars < 5) {
 4374:         $width = 120+$NumBars*20;
 4375:         $xskip = 1;
 4376:         $bar_width = 20;
 4377:     } elsif ($NumBars < 10) {
 4378:         $width = 120+$NumBars*15;
 4379:         $xskip = 1;
 4380:         $bar_width = 15;
 4381:     } elsif ($NumBars <= 25) {
 4382:         $width = 120+$NumBars*11;
 4383:         $xskip = 5;
 4384:         $bar_width = 8;
 4385:     } elsif ($NumBars <= 50) {
 4386:         $width = 120+$NumBars*8;
 4387:         $xskip = 5;
 4388:         $bar_width = 4;
 4389:     } else {
 4390:         $width = 120+$NumBars*8;
 4391:         $xskip = 5;
 4392:         $bar_width = 4;
 4393:     }
 4394:     #
 4395:     $Max = 1 if ($Max < 1);
 4396:     if ( int($Max) < $Max ) {
 4397:         $Max++;
 4398:         $Max = int($Max);
 4399:     }
 4400:     $Title  = '' if (! defined($Title));
 4401:     $xlabel = '' if (! defined($xlabel));
 4402:     $ylabel = '' if (! defined($ylabel));
 4403:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
 4404:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
 4405:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
 4406:     $ValuesHash{$id.'.y_max_value'} = $Max;
 4407:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 4408:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 4409:     $ValuesHash{$id.'.PlotType'} = 'bar';
 4410:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4411:     $ValuesHash{$id.'.height'}   = $height;
 4412:     $ValuesHash{$id.'.width'}    = $width;
 4413:     $ValuesHash{$id.'.xskip'}    = $xskip;
 4414:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 4415:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 4416:     #
 4417:     # Deal with other parameters
 4418:     while (my ($key,$value) = each(%$extra_settings)) {
 4419:         $ValuesHash{$id.'.'.$key} = $value;
 4420:     }
 4421:     #
 4422:     &Apache::lonnet::appenv(%ValuesHash);
 4423:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4424: }
 4425: 
 4426: ############################################################
 4427: ############################################################
 4428: 
 4429: =pod
 4430: 
 4431: =item DrawXYGraph
 4432: 
 4433: Facilitates the plotting of data in an XY graph.
 4434: Puts plot definition data into the users environment in order for 
 4435: graph.png to plot it.  Returns an <img> tag for the plot.
 4436: 
 4437: Inputs:
 4438: 
 4439: =over 4
 4440: 
 4441: =item $Title: string, the title of the plot
 4442: 
 4443: =item $xlabel: string, text describing the X-axis of the plot
 4444: 
 4445: =item $ylabel: string, text describing the Y-axis of the plot
 4446: 
 4447: =item $Max: scalar, the maximum Y value to use in the plot
 4448: If $Max is < any data point, the graph will not be rendered.
 4449: 
 4450: =item $colors: Array ref containing the hex color codes for the data to be 
 4451: plotted in.  If undefined, default values will be used.
 4452: 
 4453: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 4454: 
 4455: =item $Ydata: Array ref containing Array refs.  
 4456: Each of the contained arrays will be plotted as a separate curve.
 4457: 
 4458: =item %Values: hash indicating or overriding any default values which are 
 4459: passed to graph.png.  
 4460: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 4461: 
 4462: =back
 4463: 
 4464: Returns:
 4465: 
 4466: An <img> tag which references graph.png and the appropriate identifying
 4467: information for the plot.
 4468: 
 4469: =cut
 4470: 
 4471: ############################################################
 4472: ############################################################
 4473: sub DrawXYGraph {
 4474:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 4475:     #
 4476:     # Create the identifier for the graph
 4477:     my $identifier = &get_cgi_id();
 4478:     my $id = 'cgi.'.$identifier;
 4479:     #
 4480:     $Title  = '' if (! defined($Title));
 4481:     $xlabel = '' if (! defined($xlabel));
 4482:     $ylabel = '' if (! defined($ylabel));
 4483:     my %ValuesHash = 
 4484:         (
 4485:          $id.'.title'  => &Apache::lonnet::escape($Title),
 4486:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 4487:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 4488:          $id.'.y_max_value'=> $Max,
 4489:          $id.'.labels'     => join(',',@$Xlabels),
 4490:          $id.'.PlotType'   => 'XY',
 4491:          );
 4492:     #
 4493:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 4494:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4495:     }
 4496:     #
 4497:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 4498:         return '';
 4499:     }
 4500:     my $NumSets=1;
 4501:     foreach my $array (@{$Ydata}){
 4502:         next if (! ref($array));
 4503:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 4504:     }
 4505:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 4506:     #
 4507:     # Deal with other parameters
 4508:     while (my ($key,$value) = each(%Values)) {
 4509:         $ValuesHash{$id.'.'.$key} = $value;
 4510:     }
 4511:     #
 4512:     &Apache::lonnet::appenv(%ValuesHash);
 4513:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4514: }
 4515: 
 4516: ############################################################
 4517: ############################################################
 4518: 
 4519: =pod
 4520: 
 4521: =item DrawXYYGraph
 4522: 
 4523: Facilitates the plotting of data in an XY graph with two Y axes.
 4524: Puts plot definition data into the users environment in order for 
 4525: graph.png to plot it.  Returns an <img> tag for the plot.
 4526: 
 4527: Inputs:
 4528: 
 4529: =over 4
 4530: 
 4531: =item $Title: string, the title of the plot
 4532: 
 4533: =item $xlabel: string, text describing the X-axis of the plot
 4534: 
 4535: =item $ylabel: string, text describing the Y-axis of the plot
 4536: 
 4537: =item $colors: Array ref containing the hex color codes for the data to be 
 4538: plotted in.  If undefined, default values will be used.
 4539: 
 4540: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 4541: 
 4542: =item $Ydata1: The first data set
 4543: 
 4544: =item $Min1: The minimum value of the left Y-axis
 4545: 
 4546: =item $Max1: The maximum value of the left Y-axis
 4547: 
 4548: =item $Ydata2: The second data set
 4549: 
 4550: =item $Min2: The minimum value of the right Y-axis
 4551: 
 4552: =item $Max2: The maximum value of the left Y-axis
 4553: 
 4554: =item %Values: hash indicating or overriding any default values which are 
 4555: passed to graph.png.  
 4556: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 4557: 
 4558: =back
 4559: 
 4560: Returns:
 4561: 
 4562: An <img> tag which references graph.png and the appropriate identifying
 4563: information for the plot.
 4564: 
 4565: =cut
 4566: 
 4567: ############################################################
 4568: ############################################################
 4569: sub DrawXYYGraph {
 4570:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 4571:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 4572:     #
 4573:     # Create the identifier for the graph
 4574:     my $identifier = &get_cgi_id();
 4575:     my $id = 'cgi.'.$identifier;
 4576:     #
 4577:     $Title  = '' if (! defined($Title));
 4578:     $xlabel = '' if (! defined($xlabel));
 4579:     $ylabel = '' if (! defined($ylabel));
 4580:     my %ValuesHash = 
 4581:         (
 4582:          $id.'.title'  => &Apache::lonnet::escape($Title),
 4583:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 4584:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 4585:          $id.'.labels' => join(',',@$Xlabels),
 4586:          $id.'.PlotType' => 'XY',
 4587:          $id.'.NumSets' => 2,
 4588:          $id.'.two_axes' => 1,
 4589:          $id.'.y1_max_value' => $Max1,
 4590:          $id.'.y1_min_value' => $Min1,
 4591:          $id.'.y2_max_value' => $Max2,
 4592:          $id.'.y2_min_value' => $Min2,
 4593:          );
 4594:     #
 4595:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 4596:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4597:     }
 4598:     #
 4599:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 4600:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 4601:         return '';
 4602:     }
 4603:     my $NumSets=1;
 4604:     foreach my $array ($Ydata1,$Ydata2){
 4605:         next if (! ref($array));
 4606:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 4607:     }
 4608:     #
 4609:     # Deal with other parameters
 4610:     while (my ($key,$value) = each(%Values)) {
 4611:         $ValuesHash{$id.'.'.$key} = $value;
 4612:     }
 4613:     #
 4614:     &Apache::lonnet::appenv(%ValuesHash);
 4615:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4616: }
 4617: 
 4618: ############################################################
 4619: ############################################################
 4620: 
 4621: =pod
 4622: 
 4623: =back 
 4624: 
 4625: =head1 Statistics helper routines?  
 4626: 
 4627: Bad place for them but what the hell.
 4628: 
 4629: =over 4
 4630: 
 4631: =item &chartlink
 4632: 
 4633: Returns a link to the chart for a specific student.  
 4634: 
 4635: Inputs:
 4636: 
 4637: =over 4
 4638: 
 4639: =item $linktext: The text of the link
 4640: 
 4641: =item $sname: The students username
 4642: 
 4643: =item $sdomain: The students domain
 4644: 
 4645: =back
 4646: 
 4647: =back
 4648: 
 4649: =cut
 4650: 
 4651: ############################################################
 4652: ############################################################
 4653: sub chartlink {
 4654:     my ($linktext, $sname, $sdomain) = @_;
 4655:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 4656:         '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
 4657:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 4658:        '">'.$linktext.'</a>';
 4659: }
 4660: 
 4661: #######################################################
 4662: #######################################################
 4663: 
 4664: =pod
 4665: 
 4666: =head1 Course Environment Routines
 4667: 
 4668: =over 4
 4669: 
 4670: =item &restore_course_settings 
 4671: 
 4672: =item &store_course_settings
 4673: 
 4674: Restores/Store indicated form parameters from the course environment.
 4675: Will not overwrite existing values of the form parameters.
 4676: 
 4677: Inputs: 
 4678: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 4679: 
 4680: a hash ref describing the data to be stored.  For example:
 4681:    
 4682: %Save_Parameters = ('Status' => 'scalar',
 4683:     'chartoutputmode' => 'scalar',
 4684:     'chartoutputdata' => 'scalar',
 4685:     'Section' => 'array',
 4686:     'StudentData' => 'array',
 4687:     'Maps' => 'array');
 4688: 
 4689: Returns: both routines return nothing
 4690: 
 4691: =cut
 4692: 
 4693: #######################################################
 4694: #######################################################
 4695: sub store_course_settings {
 4696:     # save to the environment
 4697:     # appenv the same items, just to be safe
 4698:     my $courseid = $env{'request.course.id'};
 4699:     my $udom  = $env{'user.domain'};
 4700:     my $uname = $env{'user.name'};
 4701:     my ($prefix,$Settings) = @_;
 4702:     my %SaveHash;
 4703:     my %AppHash;
 4704:     while (my ($setting,$type) = each(%$Settings)) {
 4705:         my $basename = join('.','internal',$courseid,$prefix,$setting);
 4706:         my $envname = 'environment.'.$basename;
 4707:         if (exists($env{'form.'.$setting})) {
 4708:             # Save this value away
 4709:             if ($type eq 'scalar' &&
 4710:                 (! exists($env{$envname}) || 
 4711:                  $env{$envname} ne $env{'form.'.$setting})) {
 4712:                 $SaveHash{$basename} = $env{'form.'.$setting};
 4713:                 $AppHash{$envname}   = $env{'form.'.$setting};
 4714:             } elsif ($type eq 'array') {
 4715:                 my $stored_form;
 4716:                 if (ref($env{'form.'.$setting})) {
 4717:                     $stored_form = join(',',
 4718:                                         map {
 4719:                                             &Apache::lonnet::escape($_);
 4720:                                         } sort(@{$env{'form.'.$setting}}));
 4721:                 } else {
 4722:                     $stored_form = 
 4723:                         &Apache::lonnet::escape($env{'form.'.$setting});
 4724:                 }
 4725:                 # Determine if the array contents are the same.
 4726:                 if ($stored_form ne $env{$envname}) {
 4727:                     $SaveHash{$basename} = $stored_form;
 4728:                     $AppHash{$envname}   = $stored_form;
 4729:                 }
 4730:             }
 4731:         }
 4732:     }
 4733:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 4734:                                           $udom,$uname);
 4735:     if ($put_result !~ /^(ok|delayed)/) {
 4736:         &Apache::lonnet::logthis('unable to save form parameters, '.
 4737:                                  'got error:'.$put_result);
 4738:     }
 4739:     # Make sure these settings stick around in this session, too
 4740:     &Apache::lonnet::appenv(%AppHash);
 4741:     return;
 4742: }
 4743: 
 4744: sub restore_course_settings {
 4745:     my $courseid = $env{'request.course.id'};
 4746:     my ($prefix,$Settings) = @_;
 4747:     while (my ($setting,$type) = each(%$Settings)) {
 4748:         next if (exists($env{'form.'.$setting}));
 4749:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
 4750:             '.'.$setting;
 4751:         if (exists($env{$envname})) {
 4752:             if ($type eq 'scalar') {
 4753:                 $env{'form.'.$setting} = $env{$envname};
 4754:             } elsif ($type eq 'array') {
 4755:                 $env{'form.'.$setting} = [ 
 4756:                                            map { 
 4757:                                                &Apache::lonnet::unescape($_); 
 4758:                                            } split(',',$env{$envname})
 4759:                                            ];
 4760:             }
 4761:         }
 4762:     }
 4763: }
 4764: 
 4765: ############################################################
 4766: ############################################################
 4767: 
 4768: sub propath {
 4769:     my ($udom,$uname)=@_;
 4770:     $udom=~s/\W//g;
 4771:     $uname=~s/\W//g;
 4772:     my $subdir=$uname.'__';
 4773:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4774:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 4775:     return $proname;
 4776: } 
 4777: 
 4778: sub icon {
 4779:     my ($file)=@_;
 4780:     my $curfext = (split(/\./,$file))[-1];
 4781:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 4782:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 4783:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 4784: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 4785: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 4786: 	            $curfext.".gif") {
 4787: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 4788: 		$curfext.".gif";
 4789: 	}
 4790:     }
 4791:     return &lonhttpdurl($iconname);
 4792: } 
 4793: 
 4794: sub lonhttpdurl {
 4795:     my ($url)=@_;
 4796:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 4797:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 4798:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 4799: }
 4800: 
 4801: sub connection_aborted {
 4802:     my ($r)=@_;
 4803:     $r->print(" ");$r->rflush();
 4804:     my $c = $r->connection;
 4805:     return $c->aborted();
 4806: }
 4807: 
 4808: #    Escapes strings that may have embedded 's that will be put into
 4809: #    strings as 'strings'.
 4810: sub escape_single {
 4811:     my ($input) = @_;
 4812:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 4813:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 4814:     return $input;
 4815: }
 4816: 
 4817: #  Same as escape_single, but escape's "'s  This 
 4818: #  can be used for  "strings"
 4819: sub escape_double {
 4820:     my ($input) = @_;
 4821:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 4822:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 4823:     return $input;
 4824: }
 4825:  
 4826: #   Escapes the last element of a full URL.
 4827: sub escape_url {
 4828:     my ($url)   = @_;
 4829:     my @urlslices = split(/\//, $url,-1);
 4830:     my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
 4831:     return join('/',@urlslices).'/'.$lastitem;
 4832: }
 4833: =pod
 4834: 
 4835: =back
 4836: 
 4837: =cut
 4838: 
 4839: 1;
 4840: __END__;
 4841: 

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