File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.262: download - view: text, annotated - select for diffs
Thu May 26 20:49:23 2005 UTC (19 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- I'm an idiot

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

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