File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.260: download - view: text, annotated - select for diffs
Fri Apr 22 20:50:07 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: version_1_99_1_tmcc, HEAD
- check conten-length before trying to read it

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

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