File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.226: download - view: text, annotated - select for diffs
Tue Nov 2 20:48:02 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
consolidate some of the multitude of functions out there that try to format and display the student's 'fullname'

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

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