File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.255: download - view: text, annotated - select for diffs
Thu Mar 10 00:21:48 2005 UTC (19 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
&define_excel_formats: Added 'h4' format
Added &create_workbook which takes care of the boring part of creating an
    Excel workbook.

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

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