File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.301: download - view: text, annotated - select for diffs
Thu Dec 15 22:10:49 2005 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
- skip lines that have now values in the upload scores 'samples' display BUG#3936

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

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