File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.243: download - view: text, annotated - select for diffs
Mon Dec 20 19:57:14 2004 UTC (19 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Eliminate Javascript error messages when launching Help menu.

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

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