File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.218: download - view: text, annotated - select for diffs
Tue Oct 12 22:37:37 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- <image> isn't an html tag <img> is

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

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