File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.193: download - view: text, annotated - select for diffs
Sat Jul 3 18:49:42 2004 UTC (20 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Integration of help icons in breadcrumb trail into a single icon. Click on icon to open new window with gateway to help options within frameset (or within main window if pop-ups blocked).  Help options include inline topic help, support request form, FAQ-o-matic, and bug reporting (all contextualized).  Option to collect form parameter information from page displaying help icon currently disabled.

Some work required:
lonsupportreq.pm - replace call to Mail::Send with more sophisticated CPAN module (e.g., Mail::Sender that allows specification of from: address and attachments.

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

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