File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.213: download - view: text, annotated - select for diffs
Fri Sep 24 20:32:02 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- when someone hits stop on the browser we need to stopp processing scantron records, and creating printouts, otherwise havoc ensues.

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

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