File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.206: download - view: text, annotated - select for diffs
Tue Aug 24 22:47:58 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
 -BUG#3296, add role info to the top of the screen when in inline mode

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

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