File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.356: download - view: text, annotated - select for diffs
Wed Apr 26 15:29:51 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- death to $_
- select_form need to esacpe the $key from having bad values

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.356 2006/04/26 15:29:51 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::lonmenu();
   62: use Apache::lonlocal;
   63: use HTML::Entities;
   64: use Apache::lonhtmlcommon();
   65: use Apache::loncoursedata();
   66: use Apache::lontexconvert();
   67: 
   68: my $readit;
   69: 
   70: ##
   71: ## Global Variables
   72: ##
   73: 
   74: # ----------------------------------------------- Filetypes/Languages/Copyright
   75: my %language;
   76: my %supported_language;
   77: my %cprtag;
   78: my %scprtag;
   79: my %fe; my %fd; my %fm;
   80: my %category_extensions;
   81: 
   82: # ---------------------------------------------- Designs
   83: 
   84: my %designhash;
   85: 
   86: # ---------------------------------------------- Thesaurus variables
   87: #
   88: # %Keywords:
   89: #      A hash used by &keyword to determine if a word is considered a keyword.
   90: # $thesaurus_db_file 
   91: #      Scalar containing the full path to the thesaurus database.
   92: 
   93: my %Keywords;
   94: my $thesaurus_db_file;
   95: 
   96: #
   97: # Initialize values from language.tab, copyright.tab, filetypes.tab,
   98: # thesaurus.tab, and filecategories.tab.
   99: #
  100: BEGIN {
  101:     # Variable initialization
  102:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  103:     #
  104:     unless ($readit) {
  105: # ------------------------------------------------------------------- languages
  106:     {
  107:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  108:                                    '/language.tab';
  109:         if ( open(my $fh,"<$langtabfile") ) {
  110:             while (my $line = <$fh>) {
  111:                 next if ($line=~/^\#/);
  112:                 chomp($line);
  113:                 my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
  114:                 $language{$key}=$val.' - '.$enc;
  115:                 if ($sup) {
  116:                     $supported_language{$key}=$sup;
  117:                 }
  118:             }
  119:             close($fh);
  120:         }
  121:     }
  122: # ------------------------------------------------------------------ copyrights
  123:     {
  124:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  125:                                   '/copyright.tab';
  126:         if ( open (my $fh,"<$copyrightfile") ) {
  127:             while (my $line = <$fh>) {
  128:                 next if ($line=~/^\#/);
  129:                 chomp($line);
  130:                 my ($key,$val)=(split(/\s+/,$line,2));
  131:                 $cprtag{$key}=$val;
  132:             }
  133:             close($fh);
  134:         }
  135:     }
  136: # ----------------------------------------------------------- source copyrights
  137:     {
  138:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  139:                                   '/source_copyright.tab';
  140:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  141:             while (my $line = <$fh>) {
  142:                 next if ($line =~ /^\#/);
  143:                 chomp($line);
  144:                 my ($key,$val)=(split(/\s+/,$line,2));
  145:                 $scprtag{$key}=$val;
  146:             }
  147:             close($fh);
  148:         }
  149:     }
  150: 
  151: # -------------------------------------------------------------- domain designs
  152: 
  153:     my $filename;
  154:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  155:     opendir(DIR,$designdir);
  156:     while ($filename=readdir(DIR)) {
  157: 	if ($filename!~/\.tab$/) { next; }
  158: 	my ($domain)=($filename=~/^(\w+)\./);
  159: 	{
  160: 	    my $designfile = $designdir.'/'.$filename;
  161: 	    if ( open (my $fh,"<$designfile") ) {
  162: 		while (my $line = <$fh>) {
  163: 		    next if ($line =~ /^\#/);
  164: 		    chomp($line);
  165: 		    my ($key,$val)=(split(/\=/,$line));
  166: 		    if ($val) { $designhash{$domain.'.'.$key}=$val; }
  167: 		}
  168: 		close($fh);
  169: 	    }
  170: 	}
  171: 
  172:     }
  173:     closedir(DIR);
  174: 
  175: 
  176: # ------------------------------------------------------------- file categories
  177:     {
  178:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  179:                                   '/filecategories.tab';
  180:         if ( open (my $fh,"<$categoryfile") ) {
  181: 	    while (my $line = <$fh>) {
  182: 		next if ($line =~ /^\#/);
  183: 		chomp($line);
  184:                 my ($extension,$category)=(split(/\s+/,$line,2));
  185:                 push @{$category_extensions{lc($category)}},$extension;
  186:             }
  187:             close($fh);
  188:         }
  189: 
  190:     }
  191: # ------------------------------------------------------------------ file types
  192:     {
  193:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  194:                '/filetypes.tab';
  195:         if ( open (my $fh,"<$typesfile") ) {
  196:             while (my $line = <$fh>) {
  197: 		next if ($line =~ /^\#/);
  198: 		chomp($line);
  199:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  200:                 if ($descr ne '') {
  201:                     $fe{$ending}=lc($emb);
  202:                     $fd{$ending}=$descr;
  203:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  204:                 }
  205:             }
  206:             close($fh);
  207:         }
  208:     }
  209:     &Apache::lonnet::logthis(
  210:               "<font color=yellow>INFO: Read file types</font>");
  211:     $readit=1;
  212:     }  # end of unless($readit) 
  213:     
  214: }
  215: 
  216: ###############################################################
  217: ##           HTML and Javascript Helper Functions            ##
  218: ###############################################################
  219: 
  220: =pod 
  221: 
  222: =head1 HTML and Javascript Functions
  223: 
  224: =over 4
  225: 
  226: =item * browser_and_searcher_javascript ()
  227: 
  228: X<browsing, javascript>X<searching, javascript>Returns a string
  229: containing javascript with two functions, C<openbrowser> and
  230: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  231: tags.
  232: 
  233: =item * openbrowser(formname,elementname,only,omit) [javascript]
  234: 
  235: inputs: formname, elementname, only, omit
  236: 
  237: formname and elementname indicate the name of the html form and name of
  238: the element that the results of the browsing selection are to be placed in. 
  239: 
  240: Specifying 'only' will restrict the browser to displaying only files
  241: with the given extension.  Can be a comma separated list.
  242: 
  243: Specifying 'omit' will restrict the browser to NOT displaying files
  244: with the given extension.  Can be a comma separated list.
  245: 
  246: =item * opensearcher(formname, elementname) [javascript]
  247: 
  248: Inputs: formname, elementname
  249: 
  250: formname and elementname specify the name of the html form and the name
  251: of the element the selection from the search results will be placed in.
  252: 
  253: =cut
  254: 
  255: sub browser_and_searcher_javascript {
  256:     my ($mode)=@_;
  257:     if (!defined($mode)) { $mode='edit'; }
  258:     my $resurl=&lastresurl();
  259:     return <<END;
  260: // <!-- BEGIN LON-CAPA Internal
  261:     var editbrowser = null;
  262:     function openbrowser(formname,elementname,only,omit,titleelement) {
  263:         var url = '$resurl/?';
  264:         if (editbrowser == null) {
  265:             url += 'launch=1&';
  266:         }
  267:         url += 'catalogmode=interactive&';
  268:         url += 'mode=$mode&';
  269:         url += 'form=' + formname + '&';
  270:         if (only != null) {
  271:             url += 'only=' + only + '&';
  272:         } else {
  273:             url += 'only=&';
  274: 	}
  275:         if (omit != null) {
  276:             url += 'omit=' + omit + '&';
  277:         } else {
  278:             url += 'omit=&';
  279: 	}
  280:         if (titleelement != null) {
  281:             url += 'titleelement=' + titleelement + '&';
  282:         } else {
  283: 	    url += 'titleelement=&';
  284: 	}
  285:         url += 'element=' + elementname + '';
  286:         var title = 'Browser';
  287:         var options = 'scrollbars=1,resizable=1,menubar=1,location=1';
  288:         options += ',width=700,height=600';
  289:         editbrowser = open(url,title,options,'1');
  290:         editbrowser.focus();
  291:     }
  292:     var editsearcher;
  293:     function opensearcher(formname,elementname,titleelement) {
  294:         var url = '/adm/searchcat?';
  295:         if (editsearcher == null) {
  296:             url += 'launch=1&';
  297:         }
  298:         url += 'catalogmode=interactive&';
  299:         url += 'mode=$mode&';
  300:         url += 'form=' + formname + '&';
  301:         if (titleelement != null) {
  302:             url += 'titleelement=' + titleelement + '&';
  303:         } else {
  304: 	    url += 'titleelement=&';
  305: 	}
  306:         url += 'element=' + elementname + '';
  307:         var title = 'Search';
  308:         var options = 'scrollbars=1,resizable=1,menubar=0';
  309:         options += ',width=700,height=600';
  310:         editsearcher = open(url,title,options,'1');
  311:         editsearcher.focus();
  312:     }
  313: // END LON-CAPA Internal -->
  314: END
  315: }
  316: 
  317: sub lastresurl {
  318:     if ($env{'environment.lastresurl'}) {
  319: 	return $env{'environment.lastresurl'}
  320:     } else {
  321: 	return '/res';
  322:     }
  323: }
  324: 
  325: sub storeresurl {
  326:     my $resurl=&Apache::lonnet::clutter(shift);
  327:     unless ($resurl=~/^\/res/) { return 0; }
  328:     $resurl=~s/\/$//;
  329:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  330:     &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
  331:     return 1;
  332: }
  333: 
  334: sub studentbrowser_javascript {
  335:    unless (
  336:             (($env{'request.course.id'}) && 
  337:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  338: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  339: 					  '/'.$env{'request.course.sec'})
  340: 	      ))
  341:          || ($env{'request.role'}=~/^(au|dc|su)/)
  342:           ) { return ''; }  
  343:    return (<<'ENDSTDBRW');
  344: <script type="text/javascript" language="Javascript" >
  345:     var stdeditbrowser;
  346:     function openstdbrowser(formname,uname,udom,roleflag) {
  347:         var url = '/adm/pickstudent?';
  348:         var filter;
  349:         eval('filter=document.'+formname+'.'+uname+'.value;');
  350:         if (filter != null) {
  351:            if (filter != '') {
  352:                url += 'filter='+filter+'&';
  353: 	   }
  354:         }
  355:         url += 'form=' + formname + '&unameelement='+uname+
  356:                                     '&udomelement='+udom;
  357: 	if (roleflag) { url+="&roles=1"; }
  358:         var title = 'Student_Browser';
  359:         var options = 'scrollbars=1,resizable=1,menubar=0';
  360:         options += ',width=700,height=600';
  361:         stdeditbrowser = open(url,title,options,'1');
  362:         stdeditbrowser.focus();
  363:     }
  364: </script>
  365: ENDSTDBRW
  366: }
  367: 
  368: sub selectstudent_link {
  369:    my ($form,$unameele,$udomele)=@_;
  370:    if ($env{'request.course.id'}) {  
  371:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  372: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  373: 					'/'.$env{'request.course.sec'})) {
  374: 	   return '';
  375:        }
  376:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  377:         '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
  378:    }
  379:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  380:        return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  381:         '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
  382:    }
  383:    return '';
  384: }
  385: 
  386: sub coursebrowser_javascript {
  387:     my ($domainfilter)=@_;
  388:    return (<<ENDSTDBRW);
  389: <script type="text/javascript" language="Javascript" >
  390:     var stdeditbrowser;
  391:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag) {
  392:         var url = '/adm/pickcourse?';
  393:         var filter;
  394:         if (filter != null) {
  395:            if (filter != '') {
  396:                url += 'filter='+filter+'&';
  397: 	   }
  398:         }
  399:         var domainfilter='$domainfilter';
  400:         if (domainfilter != null) {
  401:            if (domainfilter != '') {
  402:                url += 'domainfilter='+domainfilter+'&';
  403: 	   }
  404:         }
  405:         url += 'form=' + formname + '&cnumelement='+uname+
  406: 	                            '&cdomelement='+udom+
  407:                                     '&cnameelement='+desc;
  408:         if (extra_element !=null && extra_element != '' && formname == 'rolechoice') {
  409:             url += '&roleelement='+extra_element;
  410:             if (domainfilter == null || domainfilter == '') {
  411:                 url += '&domainfilter='+extra_element;
  412:             }
  413:         }
  414:         if (multflag !=null && multflag != '') {
  415:             url += '&multiple='+multflag;
  416:         }
  417:         var title = 'Course_Browser';
  418:         var options = 'scrollbars=1,resizable=1,menubar=0';
  419:         options += ',width=700,height=600';
  420:         stdeditbrowser = open(url,title,options,'1');
  421:         stdeditbrowser.focus();
  422:     }
  423: </script>
  424: ENDSTDBRW
  425: }
  426: 
  427: sub selectcourse_link {
  428:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag)=@_;
  429:     return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
  430:         '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'");'."'>".&mt('Select Course')."</a>";
  431: }
  432: 
  433: sub check_uncheck_jscript {
  434:     my $jscript = <<"ENDSCRT";
  435: function checkAll(field) {
  436:     if (field.length > 0) {
  437:         for (i = 0; i < field.length; i++) {
  438:             field[i].checked = true ;
  439:         }
  440:     } else {
  441:         field.checked = true
  442:     }
  443: }
  444:  
  445: function uncheckAll(field) {
  446:     if (field.length > 0) {
  447:         for (i = 0; i < field.length; i++) {
  448:             field[i].checked = false ;
  449:         }     } else {
  450:         field.checked = false ;
  451:     }
  452: }
  453: ENDSCRT
  454:     return $jscript;
  455: }
  456: 
  457: 
  458: =pod
  459: 
  460: =item * linked_select_forms(...)
  461: 
  462: linked_select_forms returns a string containing a <script></script> block
  463: and html for two <select> menus.  The select menus will be linked in that
  464: changing the value of the first menu will result in new values being placed
  465: in the second menu.  The values in the select menu will appear in alphabetical
  466: order.
  467: 
  468: linked_select_forms takes the following ordered inputs:
  469: 
  470: =over 4
  471: 
  472: =item * $formname, the name of the <form> tag
  473: 
  474: =item * $middletext, the text which appears between the <select> tags
  475: 
  476: =item * $firstdefault, the default value for the first menu
  477: 
  478: =item * $firstselectname, the name of the first <select> tag
  479: 
  480: =item * $secondselectname, the name of the second <select> tag
  481: 
  482: =item * $hashref, a reference to a hash containing the data for the menus.
  483: 
  484: =back 
  485: 
  486: Below is an example of such a hash.  Only the 'text', 'default', and 
  487: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  488: values for the first select menu.  The text that coincides with the 
  489: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  490: and text for the second menu are given in the hash pointed to by 
  491: $menu{$choice1}->{'select2'}.  
  492: 
  493:  my %menu = ( A1 => { text =>"Choice A1" ,
  494:                        default => "B3",
  495:                        select2 => { 
  496:                            B1 => "Choice B1",
  497:                            B2 => "Choice B2",
  498:                            B3 => "Choice B3",
  499:                            B4 => "Choice B4"
  500:                            }
  501:                    },
  502:                A2 => { text =>"Choice A2" ,
  503:                        default => "C2",
  504:                        select2 => { 
  505:                            C1 => "Choice C1",
  506:                            C2 => "Choice C2",
  507:                            C3 => "Choice C3"
  508:                            }
  509:                    },
  510:                A3 => { text =>"Choice A3" ,
  511:                        default => "D6",
  512:                        select2 => { 
  513:                            D1 => "Choice D1",
  514:                            D2 => "Choice D2",
  515:                            D3 => "Choice D3",
  516:                            D4 => "Choice D4",
  517:                            D5 => "Choice D5",
  518:                            D6 => "Choice D6",
  519:                            D7 => "Choice D7"
  520:                            }
  521:                    }
  522:                );
  523: 
  524: =cut
  525: 
  526: sub linked_select_forms {
  527:     my ($formname,
  528:         $middletext,
  529:         $firstdefault,
  530:         $firstselectname,
  531:         $secondselectname, 
  532:         $hashref
  533:         ) = @_;
  534:     my $second = "document.$formname.$secondselectname";
  535:     my $first = "document.$formname.$firstselectname";
  536:     # output the javascript to do the changing
  537:     my $result = '';
  538:     $result.="<script type=\"text/javascript\">\n";
  539:     $result.="var select2data = new Object();\n";
  540:     $" = '","';
  541:     my $debug = '';
  542:     foreach my $s1 (sort(keys(%$hashref))) {
  543:         $result.="select2data.d_$s1 = new Object();\n";        
  544:         $result.="select2data.d_$s1.def = new String('".
  545:             $hashref->{$s1}->{'default'}."');\n";
  546:         $result.="select2data.d_$s1.values = new Array(";        
  547:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  548:         $result.="\"@s2values\");\n";
  549:         $result.="select2data.d_$s1.texts = new Array(";        
  550:         my @s2texts;
  551:         foreach my $value (@s2values) {
  552:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  553:         }
  554:         $result.="\"@s2texts\");\n";
  555:     }
  556:     $"=' ';
  557:     $result.= <<"END";
  558: 
  559: function select1_changed() {
  560:     // Determine new choice
  561:     var newvalue = "d_" + $first.value;
  562:     // update select2
  563:     var values     = select2data[newvalue].values;
  564:     var texts      = select2data[newvalue].texts;
  565:     var select2def = select2data[newvalue].def;
  566:     var i;
  567:     // out with the old
  568:     for (i = 0; i < $second.options.length; i++) {
  569:         $second.options[i] = null;
  570:     }
  571:     // in with the nuclear
  572:     for (i=0;i<values.length; i++) {
  573:         $second.options[i] = new Option(values[i]);
  574:         $second.options[i].value = values[i];
  575:         $second.options[i].text = texts[i];
  576:         if (values[i] == select2def) {
  577:             $second.options[i].selected = true;
  578:         }
  579:     }
  580: }
  581: </script>
  582: END
  583:     # output the initial values for the selection lists
  584:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  585:     foreach my $value (sort(keys(%$hashref))) {
  586:         $result.="    <option value=\"$value\" ";
  587:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
  588:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
  589:     }
  590:     $result .= "</select>\n";
  591:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  592:     $result .= $middletext;
  593:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  594:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  595:     foreach my $value (sort(keys(%select2))) {
  596:         $result.="    <option value=\"$value\" ";        
  597:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
  598:         $result.=">".&mt($select2{$value})."</option>\n";
  599:     }
  600:     $result .= "</select>\n";
  601:     #    return $debug;
  602:     return $result;
  603: }   #  end of sub linked_select_forms {
  604: 
  605: =pod
  606: 
  607: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
  608: 
  609: Returns a string corresponding to an HTML link to the given help
  610: $topic, where $topic corresponds to the name of a .tex file in
  611: /home/httpd/html/adm/help/tex, with underscores replaced by
  612: spaces. 
  613: 
  614: $text will optionally be linked to the same topic, allowing you to
  615: link text in addition to the graphic. If you do not want to link
  616: text, but wish to specify one of the later parameters, pass an
  617: empty string. 
  618: 
  619: $stayOnPage is a value that will be interpreted as a boolean. If true,
  620: the link will not open a new window. If false, the link will open
  621: a new window using Javascript. (Default is false.) 
  622: 
  623: $width and $height are optional numerical parameters that will
  624: override the width and height of the popped up window, which may
  625: be useful for certain help topics with big pictures included. 
  626: 
  627: =cut
  628: 
  629: sub help_open_topic {
  630:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  631:     $text = "" if (not defined $text);
  632:     $stayOnPage = 0 if (not defined $stayOnPage);
  633:     if ($env{'browser.interface'} eq 'textual' ||
  634: 	$env{'environment.remote'} eq 'off' ) {
  635: 	$stayOnPage=1;
  636:     }
  637:     $width = 350 if (not defined $width);
  638:     $height = 400 if (not defined $height);
  639:     my $filename = $topic;
  640:     $filename =~ s/ /_/g;
  641: 
  642:     my $template = "";
  643:     my $link;
  644: 
  645:     $topic=~s/\W/\_/g;
  646: 
  647:     if (!$stayOnPage)
  648:     {
  649: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  650:     }
  651:     else
  652:     {
  653: 	$link = "/adm/help/${filename}.hlp";
  654:     }
  655: 
  656:     # Add the text
  657:     if ($text ne "")
  658:     {
  659: 	$template .= 
  660:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  661:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  662:     }
  663: 
  664:     # Add the graphic
  665:     my $title = &mt('Online Help');
  666:     my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
  667:     $template .= <<"ENDTEMPLATE";
  668:  <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
  669: ENDTEMPLATE
  670:     if ($text ne '') { $template.='</td></tr></table>' };
  671:     return $template;
  672: 
  673: }
  674: 
  675: # This is a quicky function for Latex cheatsheet editing, since it 
  676: # appears in at least four places
  677: sub helpLatexCheatsheet {
  678:     my $other = shift;
  679:     my $addOther = '';
  680:     if ($other) {
  681: 	$addOther = Apache::loncommon::help_open_topic($other, shift,
  682: 						       undef, undef, 600) .
  683: 							   '</td><td>';
  684:     }
  685:     return '<table><tr><td>'.
  686: 	$addOther .
  687: 	&Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
  688: 					    undef,undef,600)
  689: 	.'</td><td>'.
  690: 	&Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
  691: 					    undef,undef,600)
  692: 	.'</td></tr></table>';
  693: }
  694: 
  695: sub help_open_menu {
  696:     my ($color,$topic,$component_help,$function,$faq,$bug,$stayOnPage,$width,$height,$text) = @_;
  697:     $text = "" if (not defined $text);
  698:     $stayOnPage = 0 if (not defined $stayOnPage);
  699:     if ($env{'browser.interface'} eq 'textual' ||
  700:         $env{'environment.remote'} eq 'off' ) {
  701:         $stayOnPage=1;
  702:     }
  703:     $width = 620 if (not defined $width);
  704:     $height = 600 if (not defined $height);
  705:     my $link='';
  706:     my $title = &mt('Get help');
  707:     my $origurl = $ENV{'REQUEST_URI'};
  708:     $origurl=~s|^/~|/priv/|;
  709:     my $timestamp = time;
  710:     foreach my $datum (\$color,\$function,\$topic,\$component_help,\$faq,
  711: 		       \$bug,\$origurl) {
  712:         $$datum = &Apache::lonnet::escape($$datum);
  713:     }
  714:     if (!$stayOnPage) {
  715:          $link = "javascript:helpMenu('open')";
  716:     } else {
  717:         $link = "javascript:helpMenu('display')";
  718:     }
  719:     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";
  720:     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";
  721:     my $template;
  722:     if ($text ne "") {
  723: 	$template .= 
  724:   "<table bgcolor='#CC3300' cellspacing='1' cellpadding='1' border='0'><tr>".
  725:   "<td bgcolor='#CC6600'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  726:     }
  727:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
  728:     my $helpicon=&lonhttpdurl("/adm/lonIcons/helpgateway.gif");
  729:     my $start_page =
  730:         &Apache::loncommon::start_page('Help Menu', undef,
  731: 				       {'frameset'    => 1,
  732: 					'js_ready'    => 1,
  733: 					'add_entries' => {
  734: 					    'border' => '0',
  735: 					    'rows'   => "105,*",},});
  736:     my $end_page =
  737:         &Apache::loncommon::end_page({'frameset' => 1,
  738: 				      'js_ready' => 1,});
  739: 
  740:     $template .= <<"ENDTEMPLATE";
  741:  <script type="text/javascript">
  742: // <!-- BEGIN LON-CAPA Internal
  743: // <![CDATA[
  744: function helpMenu(target) {
  745:     var caller = this;
  746:     if (target == 'open') {
  747:         var newWindow = null;
  748:         try {
  749:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
  750:         }
  751:         catch(error) {
  752:             writeHelp(caller);
  753:             return;
  754:         }
  755:         if (newWindow) {
  756:             caller = newWindow;
  757:         }
  758:     }
  759:     writeHelp(caller);
  760:     return;
  761: }
  762: function writeHelp(caller) {
  763:     caller.document.writeln('$start_page<frame name="bannerframe"  src="$banner_link" /><frame name="bodyframe" src="$details_link" /> $end_page')
  764:     caller.document.close()
  765:     caller.focus()
  766: }
  767: // ]]>
  768: // END LON-CAPA Internal -->
  769:  </script>
  770:  <a href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help Menu)" /></a>
  771: ENDTEMPLATE
  772:     if ($component_help) {
  773: 	if (!$text) {
  774: 	    $template=&help_open_topic($component_help,undef,$stayOnPage,
  775: 				       $width,$height).' '.$template;
  776: 	} else {
  777: 	    my $help_text;
  778: 	    $help_text=&Apache::lonnet::unescape($topic);
  779: 	    $template='<table><tr><td>'.
  780: 		&help_open_topic($component_help,$help_text,$stayOnPage,
  781: 				 $width,$height).'</td><td>'.$template.
  782: 				 '</td></tr></table>';
  783: 	}
  784:     }
  785:     if ($text ne '') { $template.='</td></tr></table>' };
  786:     return $template;
  787: }
  788: 
  789: sub help_open_bug {
  790:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  791:     unless ($env{'user.adv'}) { return ''; }
  792:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
  793:     $text = "" if (not defined $text);
  794:     $stayOnPage = 0 if (not defined $stayOnPage);
  795:     if ($env{'browser.interface'} eq 'textual' ||
  796: 	$env{'environment.remote'} eq 'off' ) {
  797: 	$stayOnPage=1;
  798:     }
  799:     $width = 600 if (not defined $width);
  800:     $height = 600 if (not defined $height);
  801: 
  802:     $topic=~s/\W+/\+/g;
  803:     my $link='';
  804:     my $template='';
  805:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
  806: 	&Apache::lonnet::escape($ENV{'REQUEST_URI'}).'&component='.$topic;
  807:     if (!$stayOnPage)
  808:     {
  809: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  810:     }
  811:     else
  812:     {
  813: 	$link = $url;
  814:     }
  815:     # Add the text
  816:     if ($text ne "")
  817:     {
  818: 	$template .= 
  819:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
  820:   "<td bgcolor='#FF5555'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  821:     }
  822: 
  823:     # Add the graphic
  824:     my $title = &mt('Report a Bug');
  825:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
  826:     $template .= <<"ENDTEMPLATE";
  827:  <a href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
  828: ENDTEMPLATE
  829:     if ($text ne '') { $template.='</td></tr></table>' };
  830:     return $template;
  831: 
  832: }
  833: 
  834: sub help_open_faq {
  835:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  836:     unless ($env{'user.adv'}) { return ''; }
  837:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
  838:     $text = "" if (not defined $text);
  839:     $stayOnPage = 0 if (not defined $stayOnPage);
  840:     if ($env{'browser.interface'} eq 'textual' ||
  841: 	$env{'environment.remote'} eq 'off' ) {
  842: 	$stayOnPage=1;
  843:     }
  844:     $width = 350 if (not defined $width);
  845:     $height = 400 if (not defined $height);
  846: 
  847:     $topic=~s/\W+/\+/g;
  848:     my $link='';
  849:     my $template='';
  850:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
  851:     if (!$stayOnPage)
  852:     {
  853: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  854:     }
  855:     else
  856:     {
  857: 	$link = $url;
  858:     }
  859: 
  860:     # Add the text
  861:     if ($text ne "")
  862:     {
  863: 	$template .= 
  864:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
  865:   "<td bgcolor='#448844'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  866:     }
  867: 
  868:     # Add the graphic
  869:     my $title = &mt('View the FAQ');
  870:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
  871:     $template .= <<"ENDTEMPLATE";
  872:  <a href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
  873: ENDTEMPLATE
  874:     if ($text ne '') { $template.='</td></tr></table>' };
  875:     return $template;
  876: 
  877: }
  878: 
  879: ###############################################################
  880: ###############################################################
  881: 
  882: =pod
  883: 
  884: =item * change_content_javascript():
  885: 
  886: This and the next function allow you to create small sections of an
  887: otherwise static HTML page that you can update on the fly with
  888: Javascript, even in Netscape 4.
  889: 
  890: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
  891: must be written to the HTML page once. It will prove the Javascript
  892: function "change(name, content)". Calling the change function with the
  893: name of the section 
  894: you want to update, matching the name passed to C<changable_area>, and
  895: the new content you want to put in there, will put the content into
  896: that area.
  897: 
  898: B<Note>: Netscape 4 only reserves enough space for the changable area
  899: to contain room for the original contents. You need to "make space"
  900: for whatever changes you wish to make, and be B<sure> to check your
  901: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
  902: it's adequate for updating a one-line status display, but little more.
  903: This script will set the space to 100% width, so you only need to
  904: worry about height in Netscape 4.
  905: 
  906: Modern browsers are much less limiting, and if you can commit to the
  907: user not using Netscape 4, this feature may be used freely with
  908: pretty much any HTML.
  909: 
  910: =cut
  911: 
  912: sub change_content_javascript {
  913:     # If we're on Netscape 4, we need to use Layer-based code
  914:     if ($env{'browser.type'} eq 'netscape' &&
  915: 	$env{'browser.version'} =~ /^4\./) {
  916: 	return (<<NETSCAPE4);
  917: 	function change(name, content) {
  918: 	    doc = document.layers[name+"___escape"].layers[0].document;
  919: 	    doc.open();
  920: 	    doc.write(content);
  921: 	    doc.close();
  922: 	}
  923: NETSCAPE4
  924:     } else {
  925: 	# Otherwise, we need to use semi-standards-compliant code
  926: 	# (technically, "innerHTML" isn't standard but the equivalent
  927: 	# is really scary, and every useful browser supports it
  928: 	return (<<DOMBASED);
  929: 	function change(name, content) {
  930: 	    element = document.getElementById(name);
  931: 	    element.innerHTML = content;
  932: 	}
  933: DOMBASED
  934:     }
  935: }
  936: 
  937: =pod
  938: 
  939: =item * changable_area($name, $origContent):
  940: 
  941: This provides a "changable area" that can be modified on the fly via
  942: the Javascript code provided in C<change_content_javascript>. $name is
  943: the name you will use to reference the area later; do not repeat the
  944: same name on a given HTML page more then once. $origContent is what
  945: the area will originally contain, which can be left blank.
  946: 
  947: =cut
  948: 
  949: sub changable_area {
  950:     my ($name, $origContent) = @_;
  951: 
  952:     if ($env{'browser.type'} eq 'netscape' &&
  953: 	$env{'browser.version'} =~ /^4\./) {
  954: 	# If this is netscape 4, we need to use the Layer tag
  955: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
  956:     } else {
  957: 	return "<span id='$name'>$origContent</span>";
  958:     }
  959: }
  960: 
  961: =pod
  962: 
  963: =back
  964: 
  965: =head1 Excel and CSV file utility routines
  966: 
  967: =over 4
  968: 
  969: =cut
  970: 
  971: ###############################################################
  972: ###############################################################
  973: 
  974: =pod
  975: 
  976: =item * csv_translate($text) 
  977: 
  978: Translate $text to allow it to be output as a 'comma separated values' 
  979: format.
  980: 
  981: =cut
  982: 
  983: ###############################################################
  984: ###############################################################
  985: sub csv_translate {
  986:     my $text = shift;
  987:     $text =~ s/\"/\"\"/g;
  988:     $text =~ s/\n/ /g;
  989:     return $text;
  990: }
  991: 
  992: ###############################################################
  993: ###############################################################
  994: 
  995: =pod
  996: 
  997: =item * define_excel_formats
  998: 
  999: Define some commonly used Excel cell formats.
 1000: 
 1001: Currently supported formats:
 1002: 
 1003: =over 4
 1004: 
 1005: =item header
 1006: 
 1007: =item bold
 1008: 
 1009: =item h1
 1010: 
 1011: =item h2
 1012: 
 1013: =item h3
 1014: 
 1015: =item h4
 1016: 
 1017: =item i
 1018: 
 1019: =item date
 1020: 
 1021: =back
 1022: 
 1023: Inputs: $workbook
 1024: 
 1025: Returns: $format, a hash reference.
 1026: 
 1027: =cut
 1028: 
 1029: ###############################################################
 1030: ###############################################################
 1031: sub define_excel_formats {
 1032:     my ($workbook) = @_;
 1033:     my $format;
 1034:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1035:                                                 bottom    => 1,
 1036:                                                 align     => 'center');
 1037:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1038:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1039:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1040:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1041:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1042:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1043:     $format->{'date'} = $workbook->add_format(num_format=>
 1044:                                             'mm/dd/yyyy hh:mm:ss');
 1045:     return $format;
 1046: }
 1047: 
 1048: ###############################################################
 1049: ###############################################################
 1050: 
 1051: =pod
 1052: 
 1053: =item * create_workbook
 1054: 
 1055: Create an Excel worksheet.  If it fails, output message on the
 1056: request object and return undefs.
 1057: 
 1058: Inputs: Apache request object
 1059: 
 1060: Returns (undef) on failure, 
 1061:     Excel worksheet object, scalar with filename, and formats 
 1062:     from &Apache::loncommon::define_excel_formats on success
 1063: 
 1064: =cut
 1065: 
 1066: ###############################################################
 1067: ###############################################################
 1068: sub create_workbook {
 1069:     my ($r) = @_;
 1070:         #
 1071:     # Create the excel spreadsheet
 1072:     my $filename = '/prtspool/'.
 1073:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1074:         time.'_'.rand(1000000000).'.xls';
 1075:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1076:     if (! defined($workbook)) {
 1077:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1078:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
 1079:                             "This error has been logged.  ".
 1080:                             "Please alert your LON-CAPA administrator").
 1081:                   '</p>');
 1082:         return (undef);
 1083:     }
 1084:     #
 1085:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1086:     #
 1087:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1088:     return ($workbook,$filename,$format);
 1089: }
 1090: 
 1091: ###############################################################
 1092: ###############################################################
 1093: 
 1094: =pod
 1095: 
 1096: =item * create_text_file
 1097: 
 1098: Create a file to write to and eventually make available to the usre.
 1099: If file creation fails, outputs an error message on the request object and 
 1100: return undefs.
 1101: 
 1102: Inputs: Apache request object, and file suffix
 1103: 
 1104: Returns (undef) on failure, 
 1105:     Filehandle and filename on success.
 1106: 
 1107: =cut
 1108: 
 1109: ###############################################################
 1110: ###############################################################
 1111: sub create_text_file {
 1112:     my ($r,$suffix) = @_;
 1113:     if (! defined($suffix)) { $suffix = 'txt'; };
 1114:     my $fh;
 1115:     my $filename = '/prtspool/'.
 1116:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1117:         time.'_'.rand(1000000000).'.'.$suffix;
 1118:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1119:     if (! defined($fh)) {
 1120:         $r->log_error("Couldn't open $filename for output $!");
 1121:         $r->print("Problems occured in creating the output file.  ".
 1122:                   "This error has been logged.  ".
 1123:                   "Please alert your LON-CAPA administrator.");
 1124:     }
 1125:     return ($fh,$filename)
 1126: }
 1127: 
 1128: 
 1129: =pod 
 1130: 
 1131: =back
 1132: 
 1133: =cut
 1134: 
 1135: ###############################################################
 1136: ##        Home server <option> list generating code          ##
 1137: ###############################################################
 1138: 
 1139: =pod
 1140: 
 1141: =head1 Home Server option list generating code
 1142: 
 1143: =over 4
 1144: 
 1145: =item * get_domains()
 1146: 
 1147: Returns an array containing each of the domains listed in the hosts.tab
 1148: file.
 1149: 
 1150: =cut
 1151: 
 1152: #-------------------------------------------
 1153: sub get_domains {
 1154:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
 1155:     my @domains;
 1156:     my %seen;
 1157:     foreach my $dom (sort(values(%Apache::lonnet::hostdom))) {
 1158: 	push(@domains,$dom) unless $seen{$dom}++;
 1159:     }
 1160:     return @domains;
 1161: }
 1162: 
 1163: # ------------------------------------------
 1164: 
 1165: sub domain_select {
 1166:     my ($name,$value,$multiple)=@_;
 1167:     my %domains=map { 
 1168: 	$_ => $_.' '.$Apache::lonnet::domaindescription{$_} 
 1169:     } &get_domains;
 1170:     if ($multiple) {
 1171: 	$domains{''}=&mt('Any domain');
 1172: 	return &multiple_select_form($name,$value,4,\%domains);
 1173:     } else {
 1174: 	return &select_form($name,$value,%domains);
 1175:     }
 1176: }
 1177: 
 1178: #-------------------------------------------
 1179: 
 1180: =pod
 1181: 
 1182: =item * multiple_select_form($name,$value,$size,$hash,$order)
 1183: 
 1184: Returns a string containing a <select> element int multiple mode
 1185: 
 1186: 
 1187: Args:
 1188:   $name - name of the <select> element
 1189:   $value - sclara or array ref of values that should already be selected
 1190:   $size - number of rows long the select element is
 1191:   $hash - the elements should be 'option' => 'shown text'
 1192:           (shown text should already have been &mt())
 1193:   $order - (optional) array ref of the order to show the elments in
 1194: 
 1195: =cut
 1196: 
 1197: #-------------------------------------------
 1198: sub multiple_select_form {
 1199:     my ($name,$value,$size,$hash,$order)=@_;
 1200:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1201:     my $output='';
 1202:     if (! defined($size)) {
 1203:         $size = 4;
 1204:         if (scalar(keys(%$hash))<4) {
 1205:             $size = scalar(keys(%$hash));
 1206:         }
 1207:     }
 1208:     $output.="\n<select name='$name' size='$size' multiple='1'>";
 1209:     my @order = ref($order) ? @$order
 1210:                             : sort(keys(%$hash));
 1211:     foreach my $key (@order) {
 1212:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1213:         $output.='selected="selected" ' if ($selected{$key});
 1214:         $output.='>'.$hash->{$key}."</option>\n";
 1215:     }
 1216:     $output.="</select>\n";
 1217:     return $output;
 1218: }
 1219: 
 1220: #-------------------------------------------
 1221: 
 1222: =pod
 1223: 
 1224: =item * select_form($defdom,$name,%hash)
 1225: 
 1226: Returns a string containing a <select name='$name' size='1'> form to 
 1227: allow a user to select options from a hash option_name => displayed text.  
 1228: See lonrights.pm for an example invocation and use.
 1229: 
 1230: =cut
 1231: 
 1232: #-------------------------------------------
 1233: sub select_form {
 1234:     my ($def,$name,%hash) = @_;
 1235:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1236:     my @keys;
 1237:     if (exists($hash{'select_form_order'})) {
 1238: 	@keys=@{$hash{'select_form_order'}};
 1239:     } else {
 1240: 	@keys=sort(keys(%hash));
 1241:     }
 1242:     foreach my $key (@keys) {
 1243:         $selectform.=
 1244: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 1245:             ($key eq $def ? 'selected="selected" ' : '').
 1246:                 ">".&mt($hash{$key})."</option>\n";
 1247:     }
 1248:     $selectform.="</select>";
 1249:     return $selectform;
 1250: }
 1251: 
 1252: sub gradeleveldescription {
 1253:     my $gradelevel=shift;
 1254:     my %gradelevels=(0 => 'Not specified',
 1255: 		     1 => 'Grade 1',
 1256: 		     2 => 'Grade 2',
 1257: 		     3 => 'Grade 3',
 1258: 		     4 => 'Grade 4',
 1259: 		     5 => 'Grade 5',
 1260: 		     6 => 'Grade 6',
 1261: 		     7 => 'Grade 7',
 1262: 		     8 => 'Grade 8',
 1263: 		     9 => 'Grade 9',
 1264: 		     10 => 'Grade 10',
 1265: 		     11 => 'Grade 11',
 1266: 		     12 => 'Grade 12',
 1267: 		     13 => 'Grade 13',
 1268: 		     14 => '100 Level',
 1269: 		     15 => '200 Level',
 1270: 		     16 => '300 Level',
 1271: 		     17 => '400 Level',
 1272: 		     18 => 'Graduate Level');
 1273:     return &mt($gradelevels{$gradelevel});
 1274: }
 1275: 
 1276: sub select_level_form {
 1277:     my ($deflevel,$name)=@_;
 1278:     unless ($deflevel) { $deflevel=0; }
 1279:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 1280:     for (my $i=0; $i<=18; $i++) {
 1281:         $selectform.="<option value=\"$i\" ".
 1282:             ($i==$deflevel ? 'selected="selected" ' : '').
 1283:                 ">".&gradeleveldescription($i)."</option>\n";
 1284:     }
 1285:     $selectform.="</select>";
 1286:     return $selectform;
 1287: }
 1288: 
 1289: #-------------------------------------------
 1290: 
 1291: =pod
 1292: 
 1293: =item * select_dom_form($defdom,$name,$includeempty)
 1294: 
 1295: Returns a string containing a <select name='$name' size='1'> form to 
 1296: allow a user to select the domain to preform an operation in.  
 1297: See loncreateuser.pm for an example invocation and use.
 1298: 
 1299: If the $includeempty flag is set, it also includes an empty choice ("no domain
 1300: selected");
 1301: 
 1302: =cut
 1303: 
 1304: #-------------------------------------------
 1305: sub select_dom_form {
 1306:     my ($defdom,$name,$includeempty) = @_;
 1307:     my @domains = get_domains();
 1308:     if ($includeempty) { @domains=('',@domains); }
 1309:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
 1310:     foreach my $dom (@domains) {
 1311:         $selectdomain.="<option value=\"$dom\" ".
 1312:             ($dom eq $defdom ? 'selected="selected" ' : '').
 1313:                 ">$dom</option>\n";
 1314:     }
 1315:     $selectdomain.="</select>";
 1316:     return $selectdomain;
 1317: }
 1318: 
 1319: #-------------------------------------------
 1320: 
 1321: =pod
 1322: 
 1323: =item * get_library_servers($domain)
 1324: 
 1325: Returns a hash which contains keys like '103l3' and values like 
 1326: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
 1327: given $domain.
 1328: 
 1329: =cut
 1330: 
 1331: #-------------------------------------------
 1332: sub get_library_servers {
 1333:     my $domain = shift;
 1334:     my %library_servers;
 1335:     foreach my $hostid (keys(%Apache::lonnet::libserv)) {
 1336:         if ($Apache::lonnet::hostdom{$hostid} eq $domain) {
 1337:             $library_servers{$hostid} = $Apache::lonnet::hostname{$hostid};
 1338:         }
 1339:     }
 1340:     return %library_servers;
 1341: }
 1342: 
 1343: #-------------------------------------------
 1344: 
 1345: =pod
 1346: 
 1347: =item * home_server_option_list($domain)
 1348: 
 1349: returns a string which contains an <option> list to be used in a 
 1350: <select> form input.  See loncreateuser.pm for an example.
 1351: 
 1352: =cut
 1353: 
 1354: #-------------------------------------------
 1355: sub home_server_option_list {
 1356:     my $domain = shift;
 1357:     my %servers = &get_library_servers($domain);
 1358:     my $result = '';
 1359:     foreach my $hostid (sort(keys(%servers))) {
 1360:         $result.=
 1361:             '<option value="'.$hostid.'">'.
 1362: 	    $hostid.' '.$servers{$hostid}."</option>\n";
 1363:     }
 1364:     return $result;
 1365: }
 1366: 
 1367: =pod
 1368: 
 1369: =back
 1370: 
 1371: =cut
 1372: 
 1373: ###############################################################
 1374: ##                  Decoding User Agent                      ##
 1375: ###############################################################
 1376: 
 1377: =pod
 1378: 
 1379: =head1 Decoding the User Agent
 1380: 
 1381: =over 4
 1382: 
 1383: =item * &decode_user_agent()
 1384: 
 1385: Inputs: $r
 1386: 
 1387: Outputs:
 1388: 
 1389: =over 4
 1390: 
 1391: =item * $httpbrowser
 1392: 
 1393: =item * $clientbrowser
 1394: 
 1395: =item * $clientversion
 1396: 
 1397: =item * $clientmathml
 1398: 
 1399: =item * $clientunicode
 1400: 
 1401: =item * $clientos
 1402: 
 1403: =back
 1404: 
 1405: =back 
 1406: 
 1407: =cut
 1408: 
 1409: ###############################################################
 1410: ###############################################################
 1411: sub decode_user_agent {
 1412:     my ($r)=@_;
 1413:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 1414:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 1415:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 1416:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 1417:     my $clientbrowser='unknown';
 1418:     my $clientversion='0';
 1419:     my $clientmathml='';
 1420:     my $clientunicode='0';
 1421:     for (my $i=0;$i<=$#browsertype;$i++) {
 1422:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 1423: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 1424: 	    $clientbrowser=$bname;
 1425:             $httpbrowser=~/$vreg/i;
 1426: 	    $clientversion=$1;
 1427:             $clientmathml=($clientversion>=$minv);
 1428:             $clientunicode=($clientversion>=$univ);
 1429: 	}
 1430:     }
 1431:     my $clientos='unknown';
 1432:     if (($httpbrowser=~/linux/i) ||
 1433:         ($httpbrowser=~/unix/i) ||
 1434:         ($httpbrowser=~/ux/i) ||
 1435:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 1436:     if (($httpbrowser=~/vax/i) ||
 1437:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 1438:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 1439:     if (($httpbrowser=~/mac/i) ||
 1440:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 1441:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 1442:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 1443:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 1444:             $clientunicode,$clientos,);
 1445: }
 1446: 
 1447: ###############################################################
 1448: ##    Authentication changing form generation subroutines    ##
 1449: ###############################################################
 1450: ##
 1451: ## All of the authform_xxxxxxx subroutines take their inputs in a
 1452: ## hash, and have reasonable default values.
 1453: ##
 1454: ##    formname = the name given in the <form> tag.
 1455: #-------------------------------------------
 1456: 
 1457: =pod
 1458: 
 1459: =head1 Authentication Routines
 1460: 
 1461: =over 4
 1462: 
 1463: =item * authform_xxxxxx
 1464: 
 1465: The authform_xxxxxx subroutines provide javascript and html forms which 
 1466: handle some of the conveniences required for authentication forms.  
 1467: This is not an optimal method, but it works.  
 1468: 
 1469: See loncreateuser.pm for invocation and use examples.
 1470: 
 1471: =over 4
 1472: 
 1473: =item * authform_header
 1474: 
 1475: =item * authform_authorwarning
 1476: 
 1477: =item * authform_nochange
 1478: 
 1479: =item * authform_kerberos
 1480: 
 1481: =item * authform_internal
 1482: 
 1483: =item * authform_filesystem
 1484: 
 1485: =back
 1486: 
 1487: =back 
 1488: 
 1489: =cut
 1490: 
 1491: #-------------------------------------------
 1492: sub authform_header{  
 1493:     my %in = (
 1494:         formname => 'cu',
 1495:         kerb_def_dom => '',
 1496:         @_,
 1497:     );
 1498:     $in{'formname'} = 'document.' . $in{'formname'};
 1499:     my $result='';
 1500: 
 1501: #---------------------------------------------- Code for upper case translation
 1502:     my $Javascript_toUpperCase;
 1503:     unless ($in{kerb_def_dom}) {
 1504:         $Javascript_toUpperCase =<<"END";
 1505:         switch (choice) {
 1506:            case 'krb': currentform.elements[choicearg].value =
 1507:                currentform.elements[choicearg].value.toUpperCase();
 1508:                break;
 1509:            default:
 1510:         }
 1511: END
 1512:     } else {
 1513:         $Javascript_toUpperCase = "";
 1514:     }
 1515: 
 1516:     my $radioval = "'nochange'";
 1517:     if (exists($in{'curr_authtype'}) &&
 1518:         defined($in{'curr_authtype'}) &&
 1519:         $in{'curr_authtype'} ne '') {
 1520:         $radioval = "'$in{'curr_authtype'}arg'";
 1521:     }
 1522:     my $argfield = 'null';
 1523:     if ( grep/^mode$/,(keys %in) ) {
 1524:         if ($in{'mode'} eq 'modifycourse')  {
 1525:             if ( grep/^curr_authtype$/,(keys %in) ) {
 1526:                 $radioval = "'$in{'curr_authtype'}'";
 1527:             }
 1528:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1529:                 unless ($in{'curr_autharg'} eq '') {
 1530:                     $argfield = "'$in{'curr_autharg'}'";
 1531:                 }
 1532:             }
 1533:         }
 1534:     }
 1535: 
 1536:     $result.=<<"END";
 1537: var current = new Object();
 1538: current.radiovalue = $radioval;
 1539: current.argfield = $argfield;
 1540: 
 1541: function changed_radio(choice,currentform) {
 1542:     var choicearg = choice + 'arg';
 1543:     // If a radio button in changed, we need to change the argfield
 1544:     if (current.radiovalue != choice) {
 1545:         current.radiovalue = choice;
 1546:         if (current.argfield != null) {
 1547:             currentform.elements[current.argfield].value = '';
 1548:         }
 1549:         if (choice == 'nochange') {
 1550:             current.argfield = null;
 1551:         } else {
 1552:             current.argfield = choicearg;
 1553:             switch(choice) {
 1554:                 case 'krb': 
 1555:                     currentform.elements[current.argfield].value = 
 1556:                         "$in{'kerb_def_dom'}";
 1557:                 break;
 1558:               default:
 1559:                 break;
 1560:             }
 1561:         }
 1562:     }
 1563:     return;
 1564: }
 1565: 
 1566: function changed_text(choice,currentform) {
 1567:     var choicearg = choice + 'arg';
 1568:     if (currentform.elements[choicearg].value !='') {
 1569:         $Javascript_toUpperCase
 1570:         // clear old field
 1571:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 1572:             currentform.elements[current.argfield].value = '';
 1573:         }
 1574:         current.argfield = choicearg;
 1575:     }
 1576:     set_auth_radio_buttons(choice,currentform);
 1577:     return;
 1578: }
 1579: 
 1580: function set_auth_radio_buttons(newvalue,currentform) {
 1581:     var i=0;
 1582:     while (i < currentform.login.length) {
 1583:         if (currentform.login[i].value == newvalue) { break; }
 1584:         i++;
 1585:     }
 1586:     if (i == currentform.login.length) {
 1587:         return;
 1588:     }
 1589:     current.radiovalue = newvalue;
 1590:     currentform.login[i].checked = true;
 1591:     return;
 1592: }
 1593: END
 1594:     return $result;
 1595: }
 1596: 
 1597: sub authform_authorwarning{
 1598:     my $result='';
 1599:     $result='<i>'.
 1600:         &mt('As a general rule, only authors or co-authors should be '.
 1601:             'filesystem authenticated '.
 1602:             '(which allows access to the server filesystem).')."</i>\n";
 1603:     return $result;
 1604: }
 1605: 
 1606: sub authform_nochange{  
 1607:     my %in = (
 1608:               formname => 'document.cu',
 1609:               kerb_def_dom => 'MSU.EDU',
 1610:               @_,
 1611:           );
 1612:     my $result = '<label>'.&mt('[_1] Do not change login data',
 1613:                      '<input type="radio" name="login" value="nochange" '.
 1614:                      'checked="checked" onclick="'.
 1615:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 1616: 	    '</label>';
 1617:     return $result;
 1618: }
 1619: 
 1620: sub authform_kerberos{  
 1621:     my %in = (
 1622:               formname => 'document.cu',
 1623:               kerb_def_dom => 'MSU.EDU',
 1624:               kerb_def_auth => 'krb4',
 1625:               @_,
 1626:               );
 1627:     my ($check4,$check5,$krbarg);
 1628:     if ($in{'kerb_def_auth'} eq 'krb5') {
 1629:        $check5 = " checked=\"on\"";
 1630:     } else {
 1631:        $check4 = " checked=\"on\"";
 1632:     }
 1633:     $krbarg = $in{'kerb_def_dom'};
 1634: 
 1635:     my $krbcheck = "";
 1636:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1637:         if ($in{'curr_authtype'} =~ m/^krb/) {
 1638:             $krbcheck = " checked=\"on\"";
 1639:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1640:                 $krbarg = $in{'curr_autharg'};
 1641:             }
 1642:         }
 1643:     }
 1644: 
 1645:     my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 1646:     my $result .= &mt
 1647:         ('[_1] Kerberos authenticated with domain [_2] '.
 1648:          '[_3] Version 4 [_4] Version 5 [_5]',
 1649:          '<label><input type="radio" name="login" value="krb" '.
 1650:              'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
 1651:          '</label><input type="text" size="10" name="krbarg" '.
 1652:              'value="'.$krbarg.'" '.
 1653:              'onchange="'.$jscall.'" />',
 1654:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 1655:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 1656: 	 '</label>');
 1657:     return $result;
 1658: }
 1659: 
 1660: sub authform_internal{  
 1661:     my %args = (
 1662:                 formname => 'document.cu',
 1663:                 kerb_def_dom => 'MSU.EDU',
 1664:                 @_,
 1665:                 );
 1666: 
 1667:     my $intcheck = "";
 1668:     my $intarg = 'value=""';
 1669:     if ( grep/^curr_authtype$/,(keys %args) ) {
 1670:         if ($args{'curr_authtype'} eq 'int') {
 1671:             $intcheck = " checked=\"on\"";
 1672:             if ( grep/^curr_autharg$/,(keys %args) ) {
 1673:                 $intarg = "value=\"$args{'curr_autharg'}\"";
 1674:             }
 1675:         }
 1676:     }
 1677: 
 1678:     my $jscall = "javascript:changed_radio('int',$args{'formname'});";
 1679:     my $result.=&mt
 1680:         ('[_1] Internally authenticated (with initial password [_2])',
 1681:          '<label><input type="radio" name="login" value="int" '.$intcheck.
 1682:              ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1683:          '</label><input type="text" size="10" name="intarg" '.$intarg.
 1684:              ' onchange="'.$jscall.'" />');
 1685:     return $result;
 1686: }
 1687: 
 1688: sub authform_local{  
 1689:     my %in = (
 1690:               formname => 'document.cu',
 1691:               kerb_def_dom => 'MSU.EDU',
 1692:               @_,
 1693:               );
 1694: 
 1695:     my $loccheck = "";
 1696:     my $locarg = 'value=""';
 1697:     if ( grep/^curr_authtype$/,(keys %in) ) {
 1698:         if ($in{'curr_authtype'} eq 'loc') {
 1699:             $loccheck = " checked=\"on\"";
 1700:             if ( grep/^curr_autharg$/,(keys %in) ) {
 1701:                 $locarg = "value=\"$in{'curr_autharg'}\"";
 1702:             }
 1703:         }
 1704:     }
 1705: 
 1706:     my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 1707:     my $result.=&mt('[_1] Local Authentication with argument [_2]',
 1708:                     '<label><input type="radio" name="login" value="loc" '.$loccheck.
 1709:                         ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1710:                     '</label><input type="text" size="10" name="locarg" '.$locarg.
 1711:                         ' onchange="'.$jscall.'" />');
 1712:     return $result;
 1713: }
 1714: 
 1715: sub authform_filesystem{  
 1716:     my %in = (
 1717:               formname => 'document.cu',
 1718:               kerb_def_dom => 'MSU.EDU',
 1719:               @_,
 1720:               );
 1721:     my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 1722:     my $result.= &mt
 1723:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 1724:          '<label><input type="radio" name="login" value="fsys" '.
 1725:          'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 1726:          '</label><input type="text" size="10" name="fsysarg" value="" '.
 1727:                   'onchange="'.$jscall.'" />');
 1728:     return $result;
 1729: }
 1730: 
 1731: ###############################################################
 1732: ##    Get Authentication Defaults for Domain                 ##
 1733: ###############################################################
 1734: 
 1735: =pod
 1736: 
 1737: =head1 Domains and Authentication
 1738: 
 1739: Returns default authentication type and an associated argument as
 1740: listed in file 'domain.tab'.
 1741: 
 1742: =over 4
 1743: 
 1744: =item * get_auth_defaults
 1745: 
 1746: get_auth_defaults($target_domain) returns the default authentication
 1747: type and an associated argument (initial password or a kerberos domain).
 1748: These values are stored in lonTabs/domain.tab
 1749: 
 1750: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
 1751: 
 1752: If target_domain is not found in domain.tab, returns nothing ('').
 1753: 
 1754: =cut
 1755: 
 1756: #-------------------------------------------
 1757: sub get_auth_defaults {
 1758:     my $domain=shift;
 1759:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
 1760: }
 1761: ###############################################################
 1762: ##   End Get Authentication Defaults for Domain              ##
 1763: ###############################################################
 1764: 
 1765: ###############################################################
 1766: ##    Get Kerberos Defaults for Domain                 ##
 1767: ###############################################################
 1768: ##
 1769: ## Returns default kerberos version and an associated argument
 1770: ## as listed in file domain.tab. If not listed, provides
 1771: ## appropriate default domain and kerberos version.
 1772: ##
 1773: #-------------------------------------------
 1774: 
 1775: =pod
 1776: 
 1777: =item * get_kerberos_defaults
 1778: 
 1779: get_kerberos_defaults($target_domain) returns the default kerberos
 1780: version and domain. If not found in domain.tabs, it defaults to
 1781: version 4 and the domain of the server.
 1782: 
 1783: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 1784: 
 1785: =cut
 1786: 
 1787: #-------------------------------------------
 1788: sub get_kerberos_defaults {
 1789:     my $domain=shift;
 1790:     my ($krbdef,$krbdefdom) =
 1791:         &Apache::loncommon::get_auth_defaults($domain);
 1792:     unless ($krbdef =~/^krb/ && $krbdefdom) {
 1793:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 1794:         my $krbdefdom=$1;
 1795:         $krbdefdom=~tr/a-z/A-Z/;
 1796:         $krbdef = "krb4";
 1797:     }
 1798:     return ($krbdef,$krbdefdom);
 1799: }
 1800: 
 1801: =pod
 1802: 
 1803: =back
 1804: 
 1805: =cut
 1806: 
 1807: ###############################################################
 1808: ##                Thesaurus Functions                        ##
 1809: ###############################################################
 1810: 
 1811: =pod
 1812: 
 1813: =head1 Thesaurus Functions
 1814: 
 1815: =over 4
 1816: 
 1817: =item * initialize_keywords
 1818: 
 1819: Initializes the package variable %Keywords if it is empty.  Uses the
 1820: package variable $thesaurus_db_file.
 1821: 
 1822: =cut
 1823: 
 1824: ###################################################
 1825: 
 1826: sub initialize_keywords {
 1827:     return 1 if (scalar keys(%Keywords));
 1828:     # If we are here, %Keywords is empty, so fill it up
 1829:     #   Make sure the file we need exists...
 1830:     if (! -e $thesaurus_db_file) {
 1831:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 1832:                                  " failed because it does not exist");
 1833:         return 0;
 1834:     }
 1835:     #   Set up the hash as a database
 1836:     my %thesaurus_db;
 1837:     if (! tie(%thesaurus_db,'GDBM_File',
 1838:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1839:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 1840:                                  $thesaurus_db_file);
 1841:         return 0;
 1842:     } 
 1843:     #  Get the average number of appearances of a word.
 1844:     my $avecount = $thesaurus_db{'average.count'};
 1845:     #  Put keywords (those that appear > average) into %Keywords
 1846:     while (my ($word,$data)=each (%thesaurus_db)) {
 1847:         my ($count,undef) = split /:/,$data;
 1848:         $Keywords{$word}++ if ($count > $avecount);
 1849:     }
 1850:     untie %thesaurus_db;
 1851:     # Remove special values from %Keywords.
 1852:     foreach my $value ('total.count','average.count') {
 1853:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 1854:     }
 1855:     return 1;
 1856: }
 1857: 
 1858: ###################################################
 1859: 
 1860: =pod
 1861: 
 1862: =item * keyword($word)
 1863: 
 1864: Returns true if $word is a keyword.  A keyword is a word that appears more 
 1865: than the average number of times in the thesaurus database.  Calls 
 1866: &initialize_keywords
 1867: 
 1868: =cut
 1869: 
 1870: ###################################################
 1871: 
 1872: sub keyword {
 1873:     return if (!&initialize_keywords());
 1874:     my $word=lc(shift());
 1875:     $word=~s/\W//g;
 1876:     return exists($Keywords{$word});
 1877: }
 1878: 
 1879: ###############################################################
 1880: 
 1881: =pod 
 1882: 
 1883: =item * get_related_words
 1884: 
 1885: Look up a word in the thesaurus.  Takes a scalar argument and returns
 1886: an array of words.  If the keyword is not in the thesaurus, an empty array
 1887: will be returned.  The order of the words returned is determined by the
 1888: database which holds them.
 1889: 
 1890: Uses global $thesaurus_db_file.
 1891: 
 1892: =cut
 1893: 
 1894: ###############################################################
 1895: sub get_related_words {
 1896:     my $keyword = shift;
 1897:     my %thesaurus_db;
 1898:     if (! -e $thesaurus_db_file) {
 1899:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 1900:                                  "failed because the file does not exist");
 1901:         return ();
 1902:     }
 1903:     if (! tie(%thesaurus_db,'GDBM_File',
 1904:               $thesaurus_db_file,&GDBM_READER(),0640)){
 1905:         return ();
 1906:     } 
 1907:     my @Words=();
 1908:     if (exists($thesaurus_db{$keyword})) {
 1909: 	# The first element is the number of times
 1910: 	# the word appears.  We do not need it now.
 1911: 	(undef,@Words) = (split(/:/,$thesaurus_db{$keyword}));
 1912:         for (my $i=0;$i<=$#Words;$i++) {
 1913:             ($Words[$i],undef)= split(/\,/,$Words[$i]);
 1914:         }
 1915:     }
 1916:     untie %thesaurus_db;
 1917:     return @Words;
 1918: }
 1919: 
 1920: =pod
 1921: 
 1922: =back
 1923: 
 1924: =cut
 1925: 
 1926: # -------------------------------------------------------------- Plaintext name
 1927: =pod
 1928: 
 1929: =head1 User Name Functions
 1930: 
 1931: =over 4
 1932: 
 1933: =item * plainname($uname,$udom,$first)
 1934: 
 1935: Takes a users logon name and returns it as a string in
 1936: "first middle last generation" form 
 1937: if $first is set to 'lastname' then it returns it as
 1938: 'lastname generation, firstname middlename' if their is a lastname
 1939: 
 1940: =cut
 1941: 
 1942: 
 1943: ###############################################################
 1944: sub plainname {
 1945:     my ($uname,$udom,$first)=@_;
 1946:     my %names=&getnames($uname,$udom);
 1947:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 1948: 					  $names{'middlename'},
 1949: 					  $names{'lastname'},
 1950: 					  $names{'generation'},$first);
 1951:     $name=~s/^\s+//;
 1952:     $name=~s/\s+$//;
 1953:     $name=~s/\s+/ /g;
 1954:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 1955:     return $name;
 1956: }
 1957: 
 1958: # -------------------------------------------------------------------- Nickname
 1959: =pod
 1960: 
 1961: =item * nickname($uname,$udom)
 1962: 
 1963: Gets a users name and returns it as a string as
 1964: 
 1965: "&quot;nickname&quot;"
 1966: 
 1967: if the user has a nickname or
 1968: 
 1969: "first middle last generation"
 1970: 
 1971: if the user does not
 1972: 
 1973: =cut
 1974: 
 1975: sub nickname {
 1976:     my ($uname,$udom)=@_;
 1977:     my %names=&getnames($uname,$udom);
 1978:     my $name=$names{'nickname'};
 1979:     if ($name) {
 1980:        $name='&quot;'.$name.'&quot;'; 
 1981:     } else {
 1982:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1983: 	     $names{'lastname'}.' '.$names{'generation'};
 1984:        $name=~s/\s+$//;
 1985:        $name=~s/\s+/ /g;
 1986:     }
 1987:     return $name;
 1988: }
 1989: 
 1990: sub getnames {
 1991:     my ($uname,$udom)=@_;
 1992:     my $id=$uname.':'.$udom;
 1993:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 1994:     if ($cached) {
 1995: 	return %{$names};
 1996:     } else {
 1997: 	my %loadnames=&Apache::lonnet::get('environment',
 1998:                     ['firstname','middlename','lastname','generation','nickname'],
 1999: 					 $udom,$uname);
 2000: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 2001: 	return %loadnames;
 2002:     }
 2003: }
 2004: 
 2005: # ------------------------------------------------------------------ Screenname
 2006: 
 2007: =pod
 2008: 
 2009: =item * screenname($uname,$udom)
 2010: 
 2011: Gets a users screenname and returns it as a string
 2012: 
 2013: =cut
 2014: 
 2015: sub screenname {
 2016:     my ($uname,$udom)=@_;
 2017:     if ($uname eq $env{'user.name'} &&
 2018: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 2019:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 2020:     return $names{'screenname'};
 2021: }
 2022: 
 2023: 
 2024: # ------------------------------------------------------------- Message Wrapper
 2025: 
 2026: sub messagewrapper {
 2027:     my ($link,$username,$domain)=@_;
 2028:     return 
 2029:         '<a href="/adm/email?compose=individual&'.
 2030:         'recname='.$username.'&recdom='.$domain.'" '.
 2031:         'title="'.&mt('Send message').'">'.$link.'</a>';
 2032: }
 2033: # --------------------------------------------------------------- Notes Wrapper
 2034: 
 2035: sub noteswrapper {
 2036:     my ($link,$un,$do)=@_;
 2037:     return 
 2038: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 2039: }
 2040: # ------------------------------------------------------------- Aboutme Wrapper
 2041: 
 2042: sub aboutmewrapper {
 2043:     my ($link,$username,$domain,$target)=@_;
 2044:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 2045: 	($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
 2046: }
 2047: 
 2048: # ------------------------------------------------------------ Syllabus Wrapper
 2049: 
 2050: 
 2051: sub syllabuswrapper {
 2052:     my ($linktext,$coursedir,$domain,$fontcolor)=@_;
 2053:     if ($fontcolor) { 
 2054:         $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>'; 
 2055:     }
 2056:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 2057: }
 2058: 
 2059: sub track_student_link {
 2060:     my ($linktext,$sname,$sdom,$target,$start) = @_;
 2061:     my $link ="/adm/trackstudent?";
 2062:     my $title = 'View recent activity';
 2063:     if (defined($sname) && $sname !~ /^\s*$/ &&
 2064:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 2065:         $link .= "selected_student=$sname:$sdom";
 2066:         $title .= ' of this student';
 2067:     } 
 2068:     if (defined($target) && $target !~ /^\s*$/) {
 2069:         $target = qq{target="$target"};
 2070:     } else {
 2071:         $target = '';
 2072:     }
 2073:     if ($start) { $link.='&amp;start='.$start; }
 2074:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 2075: }
 2076: 
 2077: =pod
 2078: 
 2079: =back
 2080: 
 2081: =head1 Access .tab File Data
 2082: 
 2083: =over 4
 2084: 
 2085: =item * languageids() 
 2086: 
 2087: returns list of all language ids
 2088: 
 2089: =cut
 2090: 
 2091: sub languageids {
 2092:     return sort(keys(%language));
 2093: }
 2094: 
 2095: =pod
 2096: 
 2097: =item * languagedescription() 
 2098: 
 2099: returns description of a specified language id
 2100: 
 2101: =cut
 2102: 
 2103: sub languagedescription {
 2104:     my $code=shift;
 2105:     return  ($supported_language{$code}?'* ':'').
 2106:             $language{$code}.
 2107: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 2108: }
 2109: 
 2110: sub plainlanguagedescription {
 2111:     my $code=shift;
 2112:     return $language{$code};
 2113: }
 2114: 
 2115: sub supportedlanguagecode {
 2116:     my $code=shift;
 2117:     return $supported_language{$code};
 2118: }
 2119: 
 2120: =pod
 2121: 
 2122: =item * copyrightids() 
 2123: 
 2124: returns list of all copyrights
 2125: 
 2126: =cut
 2127: 
 2128: sub copyrightids {
 2129:     return sort(keys(%cprtag));
 2130: }
 2131: 
 2132: =pod
 2133: 
 2134: =item * copyrightdescription() 
 2135: 
 2136: returns description of a specified copyright id
 2137: 
 2138: =cut
 2139: 
 2140: sub copyrightdescription {
 2141:     return &mt($cprtag{shift(@_)});
 2142: }
 2143: 
 2144: =pod
 2145: 
 2146: =item * source_copyrightids() 
 2147: 
 2148: returns list of all source copyrights
 2149: 
 2150: =cut
 2151: 
 2152: sub source_copyrightids {
 2153:     return sort(keys(%scprtag));
 2154: }
 2155: 
 2156: =pod
 2157: 
 2158: =item * source_copyrightdescription() 
 2159: 
 2160: returns description of a specified source copyright id
 2161: 
 2162: =cut
 2163: 
 2164: sub source_copyrightdescription {
 2165:     return &mt($scprtag{shift(@_)});
 2166: }
 2167: 
 2168: =pod
 2169: 
 2170: =item * filecategories() 
 2171: 
 2172: returns list of all file categories
 2173: 
 2174: =cut
 2175: 
 2176: sub filecategories {
 2177:     return sort(keys(%category_extensions));
 2178: }
 2179: 
 2180: =pod
 2181: 
 2182: =item * filecategorytypes() 
 2183: 
 2184: returns list of file types belonging to a given file
 2185: category
 2186: 
 2187: =cut
 2188: 
 2189: sub filecategorytypes {
 2190:     my ($cat) = @_;
 2191:     return @{$category_extensions{lc($cat)}};
 2192: }
 2193: 
 2194: =pod
 2195: 
 2196: =item * fileembstyle() 
 2197: 
 2198: returns embedding style for a specified file type
 2199: 
 2200: =cut
 2201: 
 2202: sub fileembstyle {
 2203:     return $fe{lc(shift(@_))};
 2204: }
 2205: 
 2206: sub filemimetype {
 2207:     return $fm{lc(shift(@_))};
 2208: }
 2209: 
 2210: 
 2211: sub filecategoryselect {
 2212:     my ($name,$value)=@_;
 2213:     return &select_form($value,$name,
 2214: 			'' => &mt('Any category'),
 2215: 			map { $_,$_ } sort(keys(%category_extensions)));
 2216: }
 2217: 
 2218: =pod
 2219: 
 2220: =item * filedescription() 
 2221: 
 2222: returns description for a specified file type
 2223: 
 2224: =cut
 2225: 
 2226: sub filedescription {
 2227:     my $file_description = $fd{lc(shift())};
 2228:     $file_description =~ s:([\[\]]):~$1:g;
 2229:     return &mt($file_description);
 2230: }
 2231: 
 2232: =pod
 2233: 
 2234: =item * filedescriptionex() 
 2235: 
 2236: returns description for a specified file type with
 2237: extra formatting
 2238: 
 2239: =cut
 2240: 
 2241: sub filedescriptionex {
 2242:     my $ex=shift;
 2243:     my $file_description = $fd{lc($ex)};
 2244:     $file_description =~ s:([\[\]]):~$1:g;
 2245:     return '.'.$ex.' '.&mt($file_description);
 2246: }
 2247: 
 2248: # End of .tab access
 2249: =pod
 2250: 
 2251: =back
 2252: 
 2253: =cut
 2254: 
 2255: # ------------------------------------------------------------------ File Types
 2256: sub fileextensions {
 2257:     return sort(keys(%fe));
 2258: }
 2259: 
 2260: # ----------------------------------------------------------- Display Languages
 2261: # returns a hash with all desired display languages
 2262: #
 2263: 
 2264: sub display_languages {
 2265:     my %languages=();
 2266:     foreach my $lang (&preferred_languages()) {
 2267: 	$languages{$lang}=1;
 2268:     }
 2269:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 2270:     if ($env{'form.displaylanguage'}) {
 2271: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 2272: 	    $languages{$lang}=1;
 2273:         }
 2274:     }
 2275:     return %languages;
 2276: }
 2277: 
 2278: sub preferred_languages {
 2279:     my @languages=();
 2280:     if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
 2281: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
 2282: 	         $env{'course.'.$env{'request.course.id'}.'.languages'}));
 2283:     }
 2284:     if ($env{'environment.languages'}) {
 2285: 	@languages=split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'});
 2286:     }
 2287:     my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
 2288:     if ($browser) {
 2289: 	@languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
 2290:     }
 2291:     if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
 2292: 	@languages=(@languages,
 2293: 		$Apache::lonnet::domain_lang_def{$env{'user.domain'}});
 2294:     }
 2295:     if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
 2296: 	@languages=(@languages,
 2297: 		$Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
 2298:     }
 2299:     if ($Apache::lonnet::domain_lang_def{
 2300: 	                          $Apache::lonnet::perlvar{'lonDefDomain'}}) {
 2301: 	@languages=(@languages,
 2302: 		$Apache::lonnet::domain_lang_def{
 2303:                                   $Apache::lonnet::perlvar{'lonDefDomain'}});
 2304:     }
 2305: # turn "en-ca" into "en-ca,en"
 2306:     my @genlanguages;
 2307:     foreach my $lang (@languages) {
 2308: 	unless ($lang=~/\w/) { next; }
 2309: 	push (@genlanguages,$lang);
 2310: 	if ($lang=~/(\-|\_)/) {
 2311: 	    push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
 2312: 	}
 2313:     }
 2314:     return @genlanguages;
 2315: }
 2316: 
 2317: ###############################################################
 2318: ##               Student Answer Attempts                     ##
 2319: ###############################################################
 2320: 
 2321: =pod
 2322: 
 2323: =head1 Alternate Problem Views
 2324: 
 2325: =over 4
 2326: 
 2327: =item * get_previous_attempt($symb, $username, $domain, $course,
 2328:     $getattempt, $regexp, $gradesub)
 2329: 
 2330: Return string with previous attempt on problem. Arguments:
 2331: 
 2332: =over 4
 2333: 
 2334: =item * $symb: Problem, including path
 2335: 
 2336: =item * $username: username of the desired student
 2337: 
 2338: =item * $domain: domain of the desired student
 2339: 
 2340: =item * $course: Course ID
 2341: 
 2342: =item * $getattempt: Leave blank for all attempts, otherwise put
 2343:     something
 2344: 
 2345: =item * $regexp: if string matches this regexp, the string will be
 2346:     sent to $gradesub
 2347: 
 2348: =item * $gradesub: routine that processes the string if it matches $regexp
 2349: 
 2350: =back
 2351: 
 2352: The output string is a table containing all desired attempts, if any.
 2353: 
 2354: =cut
 2355: 
 2356: sub get_previous_attempt {
 2357:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 2358:   my $prevattempts='';
 2359:   no strict 'refs';
 2360:   if ($symb) {
 2361:     my (%returnhash)=
 2362:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 2363:     if ($returnhash{'version'}) {
 2364:       my %lasthash=();
 2365:       my $version;
 2366:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 2367:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 2368: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 2369:         }
 2370:       }
 2371:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 2372:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 2373:       foreach my $key (sort(keys(%lasthash))) {
 2374: 	my ($ign,@parts) = split(/\./,$key);
 2375: 	if ($#parts > 0) {
 2376: 	  my $data=$parts[-1];
 2377: 	  pop(@parts);
 2378: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 2379: 	} else {
 2380: 	  if ($#parts == 0) {
 2381: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 2382: 	  } else {
 2383: 	    $prevattempts.='<th>'.$ign.'</th>';
 2384: 	  }
 2385: 	}
 2386:       }
 2387:       if ($getattempt eq '') {
 2388: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 2389: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 2390: 	    foreach my $key (sort(keys(%lasthash))) {
 2391: 	       my $value;
 2392: 	       if ($key =~ /timestamp/) {
 2393: 		  $value=scalar(localtime($returnhash{$version.':'.$key}));
 2394: 	       } else {
 2395: 		  $value=$returnhash{$version.':'.$key};
 2396: 	       }
 2397: 	       $prevattempts.='<td>'.&Apache::lonnet::unescape($value).'&nbsp;</td>';   
 2398: 	    }
 2399: 	 }
 2400:       }
 2401:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 2402:       foreach my $key (sort(keys(%lasthash))) {
 2403: 	my $value;
 2404: 	if ($key =~ /timestamp/) {
 2405: 	  $value=scalar(localtime($lasthash{$key}));
 2406: 	} else {
 2407: 	  $value=$lasthash{$key};
 2408: 	}
 2409: 	$value=&Apache::lonnet::unescape($value);
 2410: 	if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 2411: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 2412:       }
 2413:       $prevattempts.='</tr></table></td></tr></table>';
 2414:     } else {
 2415:       $prevattempts='Nothing submitted - no attempts.';
 2416:     }
 2417:   } else {
 2418:     $prevattempts='No data.';
 2419:   }
 2420: }
 2421: 
 2422: sub relative_to_absolute {
 2423:     my ($url,$output)=@_;
 2424:     my $parser=HTML::TokeParser->new(\$output);
 2425:     my $token;
 2426:     my $thisdir=$url;
 2427:     my @rlinks=();
 2428:     while ($token=$parser->get_token) {
 2429: 	if ($token->[0] eq 'S') {
 2430: 	    if ($token->[1] eq 'a') {
 2431: 		if ($token->[2]->{'href'}) {
 2432: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 2433: 		}
 2434: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 2435: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 2436: 	    } elsif ($token->[1] eq 'base') {
 2437: 		$thisdir=$token->[2]->{'href'};
 2438: 	    }
 2439: 	}
 2440:     }
 2441:     $thisdir=~s-/[^/]*$--;
 2442:     foreach my $link (@rlinks) {
 2443: 	unless (($link=~/^http:\/\//i) ||
 2444: 		($link=~/^\//) ||
 2445: 		($link=~/^javascript:/i) ||
 2446: 		($link=~/^mailto:/i) ||
 2447: 		($link=~/^\#/)) {
 2448: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 2449: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 2450: 	}
 2451:     }
 2452: # -------------------------------------------------- Deal with Applet codebases
 2453:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 2454:     return $output;
 2455: }
 2456: 
 2457: =pod
 2458: 
 2459: =item * get_student_view
 2460: 
 2461: show a snapshot of what student was looking at
 2462: 
 2463: =cut
 2464: 
 2465: sub get_student_view {
 2466:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 2467:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2468:   my (%form);
 2469:   my @elements=('symb','courseid','domain','username');
 2470:   foreach my $element (@elements) {
 2471:       $form{'grade_'.$element}=eval '$'.$element #'
 2472:   }
 2473:   if (defined($moreenv)) {
 2474:       %form=(%form,%{$moreenv});
 2475:   }
 2476:   if (defined($target)) { $form{'grade_target'} = $target; }
 2477:   $feedurl=&Apache::lonnet::clutter($feedurl);
 2478:   my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
 2479:   $userview=~s/\<body[^\>]*\>//gi;
 2480:   $userview=~s/\<\/body\>//gi;
 2481:   $userview=~s/\<html\>//gi;
 2482:   $userview=~s/\<\/html\>//gi;
 2483:   $userview=~s/\<head\>//gi;
 2484:   $userview=~s/\<\/head\>//gi;
 2485:   $userview=~s/action\s*\=/would_be_action\=/gi;
 2486:   $userview=&relative_to_absolute($feedurl,$userview);
 2487:   return $userview;
 2488: }
 2489: 
 2490: =pod
 2491: 
 2492: =item * get_student_answers() 
 2493: 
 2494: show a snapshot of how student was answering problem
 2495: 
 2496: =cut
 2497: 
 2498: sub get_student_answers {
 2499:   my ($symb,$username,$domain,$courseid,%form) = @_;
 2500:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 2501:   my (%moreenv);
 2502:   my @elements=('symb','courseid','domain','username');
 2503:   foreach my $element (@elements) {
 2504:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 2505:   }
 2506:   $moreenv{'grade_target'}='answer';
 2507:   %moreenv=(%form,%moreenv);
 2508:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
 2509:   return $userview;
 2510: }
 2511: 
 2512: =pod
 2513: 
 2514: =item * &submlink()
 2515: 
 2516: Inputs: $text $uname $udom $symb $target
 2517: 
 2518: Returns: A link to grades.pm such as to see the SUBM view of a student
 2519: 
 2520: =cut
 2521: 
 2522: ###############################################
 2523: sub submlink {
 2524:     my ($text,$uname,$udom,$symb,$target)=@_;
 2525:     if (!($uname && $udom)) {
 2526: 	(my $cursymb, my $courseid,$udom,$uname)=
 2527: 	    &Apache::lonxml::whichuser($symb);
 2528: 	if (!$symb) { $symb=$cursymb; }
 2529:     }
 2530:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2531:     $symb=&Apache::lonnet::escape($symb);
 2532:     if ($target) { $target="target=\"$target\""; }
 2533:     return '<a href="/adm/grades?&command=submission&'.
 2534: 	'symb='.$symb.'&student='.$uname.
 2535: 	'&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
 2536: }
 2537: ##############################################
 2538: 
 2539: =pod
 2540: 
 2541: =item * &pgrdlink()
 2542: 
 2543: Inputs: $text $uname $udom $symb $target
 2544: 
 2545: Returns: A link to grades.pm such as to see the PGRD view of a student
 2546: 
 2547: =cut
 2548: 
 2549: ###############################################
 2550: sub pgrdlink {
 2551:     my $link=&submlink(@_);
 2552:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 2553:     return $link;
 2554: }
 2555: ##############################################
 2556: 
 2557: =pod
 2558: 
 2559: =item * &pprmlink()
 2560: 
 2561: Inputs: $text $uname $udom $symb $target
 2562: 
 2563: Returns: A link to parmset.pm such as to see the PPRM view of a
 2564: student and a specific resource
 2565: 
 2566: =cut
 2567: 
 2568: ###############################################
 2569: sub pprmlink {
 2570:     my ($text,$uname,$udom,$symb,$target)=@_;
 2571:     if (!($uname && $udom)) {
 2572: 	(my $cursymb, my $courseid,$udom,$uname)=
 2573: 	    &Apache::lonxml::whichuser($symb);
 2574: 	if (!$symb) { $symb=$cursymb; }
 2575:     }
 2576:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 2577:     $symb=&Apache::lonnet::escape($symb);
 2578:     if ($target) { $target="target=\"$target\""; }
 2579:     return '<a href="/adm/parmset?&command=set&'.
 2580: 	'symb='.$symb.'&uname='.$uname.
 2581: 	'&udom='.$udom.'" '.$target.'>'.$text.'</a>';
 2582: }
 2583: ##############################################
 2584: 
 2585: =pod
 2586: 
 2587: =back
 2588: 
 2589: =cut
 2590: 
 2591: ###############################################
 2592: 
 2593: 
 2594: sub timehash {
 2595:     my @ltime=localtime(shift);
 2596:     return ( 'seconds' => $ltime[0],
 2597:              'minutes' => $ltime[1],
 2598:              'hours'   => $ltime[2],
 2599:              'day'     => $ltime[3],
 2600:              'month'   => $ltime[4]+1,
 2601:              'year'    => $ltime[5]+1900,
 2602:              'weekday' => $ltime[6],
 2603:              'dayyear' => $ltime[7]+1,
 2604:              'dlsav'   => $ltime[8] );
 2605: }
 2606: 
 2607: sub maketime {
 2608:     my %th=@_;
 2609:     return POSIX::mktime(
 2610:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 2611:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 2612: }
 2613: 
 2614: #########################################
 2615: 
 2616: sub findallcourses {
 2617:     my ($roles) = @_;
 2618:     my %roles;
 2619:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 2620:     my %courses;
 2621:     my $now=time;
 2622:     foreach my $key (keys(%env)) {
 2623: 	if ( $key=~m{^user\.role\.(\w+)\./(\w+)/(\w+)} ) {
 2624: 	    my ($role,$domain,$id) = ($1,$2,$3);
 2625: 	    next if ($role eq 'ca' || $role eq 'aa');
 2626: 	    next if (%roles && !exists($roles{$role}));
 2627: 	    my ($starttime,$endtime)=split(/\./,$env{$key});
 2628:             my $active=1;
 2629:             if ($starttime) {
 2630: 		if ($now<$starttime) { $active=0; }
 2631:             }
 2632:             if ($endtime) {
 2633:                 if ($now>$endtime) { $active=0; }
 2634:             }
 2635:             if ($active) { $courses{$domain.'_'.$id}=1; }
 2636:         }
 2637:     }
 2638:     return keys(%courses);
 2639: }
 2640: 
 2641: ###############################################
 2642: ###############################################
 2643: 
 2644: =pod
 2645: 
 2646: =head1 Domain Template Functions
 2647: 
 2648: =over 4
 2649: 
 2650: =item * &determinedomain()
 2651: 
 2652: Inputs: $domain (usually will be undef)
 2653: 
 2654: Returns: Determines which domain should be used for designs
 2655: 
 2656: =cut
 2657: 
 2658: ###############################################
 2659: sub determinedomain {
 2660:     my $domain=shift;
 2661:    if (! $domain) {
 2662:         # Determine domain if we have not been given one
 2663:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 2664:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 2665:         if ($env{'request.role.domain'}) { 
 2666:             $domain=$env{'request.role.domain'}; 
 2667:         }
 2668:     }
 2669:     return $domain;
 2670: }
 2671: ###############################################
 2672: =pod
 2673: 
 2674: =item * &domainlogo()
 2675: 
 2676: Inputs: $domain (usually will be undef)
 2677: 
 2678: Returns: A link to a domain logo, if the domain logo exists.
 2679: If the domain logo does not exist, a description of the domain.
 2680: 
 2681: =cut
 2682: 
 2683: ###############################################
 2684: sub domainlogo {
 2685:     my $domain = &determinedomain(shift);    
 2686:      # See if there is a logo
 2687:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 2688: 	my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
 2689:         return '<img src="'.$logo.'" alt="'.$domain.'" />';
 2690:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 2691:         return $Apache::lonnet::domaindescription{$domain};
 2692:     } else {
 2693:         return '';
 2694:     }
 2695: }
 2696: ##############################################
 2697: 
 2698: =pod
 2699: 
 2700: =item * &designparm()
 2701: 
 2702: Inputs: $which parameter; $domain (usually will be undef)
 2703: 
 2704: Returns: value of designparamter $which
 2705: 
 2706: =cut
 2707: 
 2708: ##############################################
 2709: sub designparm {
 2710:     my ($which,$domain)=@_;
 2711:     if ($env{'browser.blackwhite'} eq 'on') {
 2712: 	if ($which=~/\.(font|alink|vlink|link)$/) {
 2713: 	    return '#000000';
 2714: 	}
 2715: 	if ($which=~/\.(pgbg|sidebg)$/) {
 2716: 	    return '#FFFFFF';
 2717: 	}
 2718: 	if ($which=~/\.tabbg$/) {
 2719: 	    return '#CCCCCC';
 2720: 	}
 2721:     }
 2722:     if ($env{'environment.color.'.$which}) {
 2723: 	return $env{'environment.color.'.$which};
 2724:     }
 2725:     $domain=&determinedomain($domain);
 2726:     if ($designhash{$domain.'.'.$which}) {
 2727: 	return $designhash{$domain.'.'.$which};
 2728:     } else {
 2729:         return $designhash{'default.'.$which};
 2730:     }
 2731: }
 2732: 
 2733: ###############################################
 2734: ###############################################
 2735: 
 2736: =pod
 2737: 
 2738: =back
 2739: 
 2740: =head1 HTTP Helpers
 2741: 
 2742: =over 4
 2743: 
 2744: =item * &bodytag()
 2745: 
 2746: Returns a uniform header for LON-CAPA web pages.
 2747: 
 2748: Inputs: 
 2749: 
 2750: =over 4
 2751: 
 2752: =item * $title, A title to be displayed on the page.
 2753: 
 2754: =item * $function, the current role (can be undef).
 2755: 
 2756: =item * $addentries, extra parameters for the <body> tag.
 2757: 
 2758: =item * $bodyonly, if defined, only return the <body> tag.
 2759: 
 2760: =item * $domain, if defined, force a given domain.
 2761: 
 2762: =item * $forcereg, if page should register as content page (relevant for 
 2763:             text interface only)
 2764: 
 2765: =item * $customtitle, alternate text to use instead of $title
 2766:                       in the title box that appears, this text
 2767:                       is not auto translated like the $title is
 2768: 
 2769: =item * $notopbar, if true, keep the 'what is this' info but remove the
 2770:                    navigational links
 2771: 
 2772: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 2773: 
 2774: =item * $notitle, if true keep the nav controls, but remove the title bar
 2775: 
 2776: 
 2777: =back
 2778: 
 2779: Returns: A uniform header for LON-CAPA web pages.  
 2780: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 2781: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 2782: other decorations will be returned.
 2783: 
 2784: =cut
 2785: 
 2786: sub bodytag {
 2787:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
 2788: 	$notopbar,$bgcolor,$notitle)=@_;
 2789: 
 2790:     $title=&mt($title);
 2791: 
 2792:     $function = &get_users_function() if (!$function);
 2793:     my $img =    &designparm($function.'.img',$domain);
 2794:     my $tabbg =  &designparm($function.'.tabbg',$domain);
 2795:     my $font =   &designparm($function.'.font',$domain);
 2796:     my $sidebg = &designparm($function.'.sidebg',$domain);
 2797:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 2798: 
 2799:     my %design = ( 'style'   => 'margin-top: 0px',
 2800: 		   'bgcolor' => $pgbg,
 2801: 		   'text'    => $font,
 2802:                    'alink'   => &designparm($function.'.alink',$domain),
 2803: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 2804: 		   'link'    => &designparm($function.'.link',$domain),);
 2805:     @$addentries{keys(%design)} = @design{keys(%design)};
 2806: 
 2807:  # role and realm
 2808:     my ($role,$realm)
 2809:        =&Apache::lonnet::plaintext((split(/\./,$env{'request.role'}))[0]);
 2810: # realm
 2811:     if ($env{'request.course.id'}) {
 2812: 	$realm=
 2813:          $env{'course.'.$env{'request.course.id'}.'.description'};
 2814:     }
 2815:     unless ($realm) { $realm='&nbsp;'; }
 2816: # Set messages
 2817:     my $messages=&domainlogo($domain);
 2818: # Port for miniserver
 2819:     my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
 2820:     if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
 2821: 
 2822:     my $extra_body_attr = &make_attr_string($forcereg,$addentries);
 2823: 
 2824: # construct main body tag
 2825:     my $bodytag = <<END;
 2826: <body $extra_body_attr>
 2827: END
 2828: 
 2829:     $bodytag .= &Apache::lontexconvert::init_math_support();
 2830: 
 2831:     my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
 2832:                    $lonhttpdPort.$img.'" alt="'.$function.'" />';
 2833:     if ($bodyonly 
 2834: 	|| ($env{'request.state'} eq 'construct' 
 2835: 	    && $env{'environment.remote'} ne 'off' )) {
 2836:         return $bodytag;
 2837:     } elsif ($env{'browser.interface'} eq 'textual') {
 2838: # Accessibility
 2839:           
 2840: 	$bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
 2841: 	if (!$notitle) {
 2842: 	    $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
 2843: 	}
 2844: 	return $bodytag;
 2845:     } elsif ($env{'environment.remote'} eq 'off') {
 2846: # No Remote
 2847: 	my $roleinfo=(<<ENDROLE);
 2848: <td bgcolor="$tabbg" align="right">
 2849: <font size="2" face="Arial, Helvetica, sans-serif">
 2850:     $env{'environment.firstname'}
 2851:     $env{'environment.middlename'}
 2852:     $env{'environment.lastname'}
 2853:     $env{'environment.generation'}
 2854:     </font>&nbsp;
 2855: <br />
 2856: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2857: <br />
 2858: <font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;
 2859: </td>
 2860: ENDROLE
 2861:         my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
 2862: 		$font.'"><b>'.$title.'</b></font>';
 2863:         if ($customtitle) {
 2864:             $titleinfo = $customtitle;
 2865:         }
 2866: 
 2867: 	if ($env{'request.state'} eq 'construct') {
 2868: 	    my ($uname,$thisdisfn)=
 2869: 		($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
 2870: 	    my $formaction='/priv/'.$uname.'/'.$thisdisfn;
 2871: 	    $formaction=~s/\/+/\//g;
 2872:             unless ($customtitle) {  #this is for resources; directories have customtitle, and crumbs and select recent are created in lonpubdir.pm  
 2873:                 my $parentpath = '';
 2874:                 my $lastitem = '';
 2875:                 if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 2876:                     $parentpath = $1;
 2877:                     $lastitem = $2;
 2878:                 } else {
 2879:                     $lastitem = $thisdisfn;
 2880:                 }
 2881: 	        $titleinfo = &Apache::loncommon::help_open_menu('','','','',3,'Authoring').
 2882:                       '<font face="Arial, Helvetica, sans-serif"><b>Construction Space</b>:</font>&nbsp;'. 
 2883:                       '<form name="dirs" method="post" action="'.$formaction
 2884: 		    .'" target="_top"><tt><b>'
 2885: 		    .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
 2886: 		    .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 2887: 		    .'</form>'
 2888: 		    .&Apache::lonmenu::constspaceform();
 2889: 
 2890:             }
 2891: 	    $forcereg=1;
 2892:         }
 2893:         my $titletable;
 2894: 	if (!$notitle) {
 2895: 	    $titletable =
 2896: 		'<table bgcolor="'.$pgbg.'" width="100%" border="0" '.
 2897:                          'cellspacing="3" cellpadding="3">'.
 2898:                          '<tr><td bgcolor="'.$tabbg.'">'.
 2899:                          $titleinfo.'</td>'.$roleinfo.'</tr></table>';
 2900: 	}
 2901: 	if ($env{'request.state'} eq 'construct') {
 2902:             if ($notopbar) {
 2903:                 $bodytag .= $titletable;
 2904:             } else {
 2905:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
 2906: 							  $titletable);
 2907:             }
 2908: 	} else {
 2909:             if ($notopbar) {
 2910:                 $bodytag .= $titletable;
 2911:             } else {
 2912:                 $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
 2913:                         $titletable;
 2914:             }
 2915:         }
 2916:         return $bodytag;
 2917:     }
 2918: 
 2919: #
 2920: # Top frame rendering, Remote is up
 2921: #
 2922:     my $titleinfo = '&nbsp;<font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
 2923:     if ($customtitle) {
 2924:         $titleinfo = $customtitle;
 2925:     }
 2926:     #
 2927:     # Extra info if you are the DC
 2928:     my $dc_info = '';
 2929:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 2930:                         $env{'course.'.$env{'request.course.id'}.
 2931:                                  '.domain'}.'/'})) {
 2932:         my $cid = $env{'request.course.id'};
 2933:         $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 2934:         $dc_info = '('.$dc_info.')';
 2935:     }
 2936:     # Explicit link to get inline menu
 2937:     my $menu='<br /><font size="2" face="Arial, Helvetica, sans-serif">&nbsp;<a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a></font>';
 2938:     #
 2939:     if ($notitle) {
 2940: 	return $bodytag;
 2941:     }
 2942:     return(<<ENDBODY);
 2943: $bodytag
 2944: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 2945: <tr><td bgcolor="$sidebg">
 2946: $upperleft</td>
 2947: <td bgcolor="$sidebg" align="right">$messages&nbsp;</td>
 2948: </tr>
 2949: <tr>
 2950: <td rowspan="3" bgcolor="$tabbg">
 2951: $titleinfo $dc_info $menu
 2952: </td><td bgcolor="$tabbg" align="right">
 2953: <font size="2" face="Arial, Helvetica, sans-serif">
 2954:     $env{'environment.firstname'}
 2955:     $env{'environment.middlename'}
 2956:     $env{'environment.lastname'}
 2957:     $env{'environment.generation'}
 2958:     </font>&nbsp;
 2959: </td>
 2960: </tr>
 2961: <tr><td bgcolor="$tabbg" align="right">
 2962: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>&nbsp;
 2963: </td></tr>
 2964: <tr>
 2965: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font>&nbsp;</td></tr>
 2966: </table>
 2967: ENDBODY
 2968: }
 2969: 
 2970: sub make_attr_string {
 2971:     my ($register,$attr_ref) = @_;
 2972: 
 2973:     if ($attr_ref && !ref($attr_ref)) {
 2974: 	die("addentries Must be a hash ref ".
 2975: 	    join(':',caller(1))." ".
 2976: 	    join(':',caller(0))." ");
 2977:     }
 2978: 
 2979:     if ($register) {
 2980: 	my ($on_load,$on_unload);
 2981: 	foreach my $key (keys(%{$attr_ref})) {
 2982: 	    if      (lc($key) eq 'onload') {
 2983: 		$on_load.=$attr_ref->{$key}.';';
 2984: 		delete($attr_ref->{$key});
 2985: 
 2986: 	    } elsif (lc($key) eq 'onunload') {
 2987: 		$on_unload.=$attr_ref->{$key}.';';
 2988: 		delete($attr_ref->{$key});
 2989: 	    }
 2990: 	}
 2991: 	$attr_ref->{'onload'}  =
 2992: 	    &Apache::lonmenu::loadevents().  $on_load;
 2993: 	$attr_ref->{'onunload'}=
 2994: 	    &Apache::lonmenu::unloadevents().$on_unload;
 2995:     }
 2996: 
 2997: # Accessibility font enhance
 2998:     if ($env{'browser.fontenhance'} eq 'on') {
 2999: 	my $style;
 3000: 	foreach my $key (keys(%{$attr_ref})) {
 3001: 	    if (lc($key) eq 'style') {
 3002: 		$style.=$attr_ref->{$key}.';';
 3003: 		delete($attr_ref->{$key});
 3004: 	    }
 3005: 	}
 3006: 	$attr_ref->{'style'}=$style.'; font-size: x-large;';
 3007:     }
 3008: 
 3009:     if ($env{'browser.blackwhite'} eq 'on') {
 3010: 	delete($attr_ref->{'font'});
 3011: 	delete($attr_ref->{'link'});
 3012: 	delete($attr_ref->{'alink'});
 3013: 	delete($attr_ref->{'vlink'});
 3014: 	delete($attr_ref->{'bgcolor'});
 3015: 	delete($attr_ref->{'background'});
 3016:     }
 3017: 
 3018:     my $attr_string;
 3019:     foreach my $attr (keys(%$attr_ref)) {
 3020: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 3021:     }
 3022:     return $attr_string;
 3023: }
 3024: 
 3025: 
 3026: ###############################################
 3027: ###############################################
 3028: 
 3029: =pod
 3030: 
 3031: =back
 3032: 
 3033: =head1 HTML Helpers
 3034: 
 3035: =over 4
 3036: 
 3037: =item * &endbodytag()
 3038: 
 3039: Returns a uniform footer for LON-CAPA web pages.
 3040: 
 3041: Inputs: none
 3042: 
 3043: =back
 3044: 
 3045: =cut
 3046: 
 3047: sub endbodytag {
 3048:     my $endbodytag='</body>';
 3049:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 3050:     if ( exists( $env{'internal.head.redirect'} ) ) {
 3051: 	$endbodytag=
 3052: 	    "<br /><a href=\"$env{'internal.head.redirect'}\">".
 3053: 	    &mt('Continue').'</a>'.
 3054: 	    $endbodytag;
 3055:     }
 3056:     return $endbodytag;
 3057: }
 3058: 
 3059: =pod
 3060: 
 3061: =over 4
 3062: 
 3063: =item * &standard_css()
 3064: 
 3065: Returns a style sheet
 3066: 
 3067: Inputs: (all optional)
 3068:             domain         -> force to color decorate a page for a specific
 3069:                                domain
 3070:             function       -> force usage of a specific rolish color scheme
 3071:             bgcolor        -> override the default page bgcolor
 3072: 
 3073: =back
 3074: 
 3075: =cut
 3076: 
 3077: sub standard_css {
 3078:     my ($function,$domain,$bgcolor) = @_;
 3079:     $function  = &get_users_function() if (!$function);
 3080:     my $img    = &designparm($function.'.img',   $domain);
 3081:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 3082:     my $font   = &designparm($function.'.font',  $domain);
 3083:     my $sidebg = &designparm($function.'.sidebg',$domain);
 3084:     my $pgbg   = $bgcolor ||
 3085: 	         &designparm($function.'.pgbg',  $domain);
 3086:     my $alink  = &designparm($function.'.alink', $domain);
 3087:     my $vlink  = &designparm($function.'.vlink', $domain);
 3088:     my $link   = &designparm($function.'.link',  $domain);
 3089: 
 3090:     my $sans                 = 'Arial,Helvetica,sans-serif';
 3091:     my $data_table_head      = $tabbg;
 3092:     my $data_table_light     = '#EEEEEE';
 3093:     my $data_table_dark      = '#DDD';
 3094:     my $data_table_highlight = '#FFFF00';
 3095:     my $mail_new             = '#FFBB77';
 3096:     my $mail_new_hover       = '#DD9955';
 3097:     my $mail_read            = '#BBBB77';
 3098:     my $mail_read_hover      = '#999944';
 3099:     my $mail_replied         = '#AAAA88';
 3100:     my $mail_replied_hover   = '#888855';
 3101:     my $mail_other           = '#99BBBB';
 3102:     my $mail_other_hover     = '#669999';
 3103: 
 3104:     return <<END;
 3105: <style type="text/css">
 3106: h1, h2, h3, th { font-family: $sans }
 3107: a:focus { color: red; background: yellow } 
 3108: table.thinborder { border-collapse: collapse; }
 3109: table.thinborder tr th, table.thinborder tr td { border-style: solid; border-width: 1px}
 3110: form, .inline { display: inline; }
 3111: .center { text-align: center; }
 3112: .filename {font-family: monospace;}
 3113: .LC_error {
 3114:   color: red;
 3115:   font-size: larger;
 3116: }
 3117: .LC_success {
 3118:   color: green;
 3119: }
 3120: 
 3121: table#LC_top_nav, table#LC_menubuttons, table#LC_nav_location {
 3122:   width: 100%;
 3123:   background: $pgbg;
 3124:   border: 0px;
 3125:   border-spacing: 1px;
 3126:   padding: 0px;
 3127:   margin: 0px;
 3128:   border-collapse: separate;
 3129: }
 3130: table#LC_menubuttons_mainmenu {
 3131:   background: $pgbg;
 3132:   border: 0px;
 3133:   border-spacing: 1px;
 3134:   padding: 0px;
 3135:   margin: 0px;
 3136:   border-collapse: separate;
 3137: }
 3138: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
 3139:   border: 0px;
 3140: }
 3141: table#LC_top_nav td {
 3142:   background: $tabbg;
 3143: }
 3144: table#LC_top_nav td a, div#LC_top_nav a {
 3145:   color: $font;
 3146:   font-family: $sans;
 3147: }
 3148: .LC_menubuttons_inline_text {
 3149:   color: $font;
 3150:   font-family: $sans;
 3151:   font-size: smaller;
 3152: }
 3153: 
 3154: td.LC_menubuttons_text {
 3155:   color: $font;
 3156:   font-family: $sans;
 3157: }
 3158: td.LC_menubuttons_img {
 3159:   background: $tabbg;
 3160: }
 3161: .LC_current_location {
 3162:   font-family: $sans;
 3163:   background: $tabbg;
 3164: }
 3165: .LC_new_mail {
 3166:   font-family: $sans;
 3167:   font-weight: bold;
 3168: }
 3169: 
 3170: table.LC_data_table, table.LC_mail_list {
 3171:   border: 1px solid #000000;
 3172:   border-collapse: seperate;
 3173: }
 3174: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th {
 3175:   font-weight: bold;
 3176:   background-color: $data_table_head;
 3177: }
 3178: table.LC_data_table tr td {
 3179:   background-color: $data_table_light;
 3180: }
 3181: table.LC_data_table tr.LC_even_row td {
 3182:   background-color: $data_table_dark;
 3183: }
 3184: table.LC_data_table tr.LC_empty td {
 3185:   background-color: #FFFFFF;
 3186: }
 3187: 
 3188: table.LC_calendar {
 3189:   border: 1px solid #000000;
 3190:   border-collapse: collapse;
 3191: }
 3192: table.LC_calendar_pickdate {
 3193:   font-size: xx-small;
 3194: }
 3195: table.LC_calendar tr td {
 3196:   border: 1px solid #000000;
 3197:   vertical-align: top;
 3198: }
 3199: table.LC_calendar tr td.LC_calendar_day_empty {
 3200:   background-color: $data_table_dark;
 3201: }
 3202: table.LC_calendar tr td.LC_calendar_day_current {
 3203:   background-color: $data_table_highlight;
 3204: }
 3205: 
 3206: table.LC_mail_list tr.LC_mail_new {
 3207:   background-color: $mail_new;
 3208: }
 3209: table.LC_mail_list tr.LC_mail_new:hover {
 3210:   background-color: $mail_new_hover;
 3211: }
 3212: table.LC_mail_list tr.LC_mail_read {
 3213:   background-color: $mail_read;
 3214: }
 3215: table.LC_mail_list tr.LC_mail_read:hover {
 3216:   background-color: $mail_read_hover;
 3217: }
 3218: table.LC_mail_list tr.LC_mail_replied {
 3219:   background-color: $mail_replied;
 3220: }
 3221: table.LC_mail_list tr.LC_mail_replied:hover {
 3222:   background-color: $mail_replied_hover;
 3223: }
 3224: table.LC_mail_list tr.LC_mail_other {
 3225:   background-color: $mail_other;
 3226: }
 3227: table.LC_mail_list tr.LC_mail_other:hover {
 3228:   background-color: $mail_other_hover;
 3229: }
 3230: </style>
 3231: END
 3232: }
 3233: 
 3234: =pod
 3235: 
 3236: =over 4
 3237: 
 3238: =item * &headtag()
 3239: 
 3240: Returns a uniform footer for LON-CAPA web pages.
 3241: 
 3242: Inputs: $title - optional title for the head
 3243:         $head_extra - optional extra HTML to put inside the <head>
 3244:         $args - optional arguments
 3245:             force_register - if is true call registerurl so the remote is 
 3246:                              informed
 3247:             redirect       -> array ref of seconds before redirect occurs
 3248:                                     url to redirect to
 3249:                            (side effect of setting 
 3250:                                $env{'internal.head.redirect'} to the url 
 3251:                                redirected too)
 3252:             domain         -> force to color decorate a page for a specific
 3253:                                domain
 3254:             function       -> force usage of a specific rolish color scheme
 3255:             bgcolor        -> override the default page bgcolor
 3256: 
 3257: =back
 3258: 
 3259: =cut
 3260: 
 3261: sub headtag {
 3262:     my ($title,$head_extra,$args) = @_;
 3263:     
 3264:     my $result =
 3265: 	'<head>'.
 3266: 	&standard_css($args->{'function'},$args->{'domain'},
 3267: 		      $args->{'bgcolor'}).
 3268: 	&font_settings().
 3269: 	&Apache::lonhtmlcommon::htmlareaheaders();
 3270: 
 3271:     if ($args->{'force_register'}) {
 3272: 	$result .= &Apache::lonmenu::registerurl(1);
 3273:     }
 3274: 
 3275:     if (ref($args->{'redirect'})) {
 3276: 	my ($time,$url) = @{$args->{'redirect'}};
 3277: 	$url = &Apache::lonenc::check_encrypt($url);
 3278: 	$env{'internal.head.redirect'} = $url;
 3279: 	$result.=<<ADDMETA
 3280: <meta http-equiv="pragma" content="no-cache" />
 3281: <meta http-equiv="Refresh" content="$time; url=$url" />
 3282: ADDMETA
 3283:     }
 3284:     if (!defined($title)) {
 3285: 	$title = 'The LearningOnline Network with CAPA';
 3286:     }
 3287:     
 3288:     $result .= '<title> LON-CAPA '.&mt($title).'</title>'.$head_extra;
 3289:     return $result;
 3290: }
 3291: 
 3292: =pod
 3293: 
 3294: =over 4
 3295: 
 3296: =item * &font_settings()
 3297: 
 3298: Returns neccessary <meta> to set the proper encoding
 3299: 
 3300: Inputs: none
 3301: 
 3302: =back
 3303: 
 3304: =cut
 3305: 
 3306: sub font_settings {
 3307:     my $headerstring='';
 3308:     if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) { 
 3309: 	$headerstring.=
 3310: 	    '<meta Content-Type="text/html; charset=x-mac-roman" />';
 3311:     } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 3312: 	$headerstring.=
 3313: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 3314:     }
 3315:     return $headerstring;
 3316: }
 3317: 
 3318: =pod
 3319: 
 3320: =over 4
 3321: 
 3322: =item * &xml_begin()
 3323: 
 3324: Returns the needed doctype and <html>
 3325: 
 3326: Inputs: none
 3327: 
 3328: =back
 3329: 
 3330: =cut
 3331: 
 3332: sub xml_begin {
 3333:     my $output='';
 3334: 
 3335:     &Apache::lonhtmlcommon::init_htmlareafields();
 3336: 
 3337:     if ($env{'browser.mathml'}) {
 3338: 	$output='<?xml version="1.0"?>'
 3339:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 3340: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 3341:             
 3342: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
 3343: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
 3344:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 3345: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 3346:     } else {
 3347: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
 3348:     }
 3349:     return $output;
 3350: }
 3351: 
 3352: =pod
 3353: 
 3354: =over 4
 3355: 
 3356: =item * &endheadtag()
 3357: 
 3358: Returns a uniform </head> for LON-CAPA web pages.
 3359: 
 3360: Inputs: none
 3361: 
 3362: =back
 3363: 
 3364: =cut
 3365: 
 3366: sub endheadtag {
 3367:     return '</head>';
 3368: }
 3369: 
 3370: =pod
 3371: 
 3372: =over 4
 3373: 
 3374: =item * &head()
 3375: 
 3376: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
 3377: 
 3378: Inputs: $title - optional title for the page
 3379:         $head_extra - optional extra HTML to put inside the <head>
 3380: =back
 3381: 
 3382: =cut
 3383: 
 3384: sub head {
 3385:     my ($title,$head_extra,$args) = @_;
 3386:     return &headtag($title,$head_extra,$args).&endheadtag();
 3387: }
 3388: 
 3389: =pod
 3390: 
 3391: =over 4
 3392: 
 3393: =item * &start_page()
 3394: 
 3395: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 3396: 
 3397: Inputs: $title - optional title for the page
 3398:         $head_extra - optional extra HTML to incude inside the <head>
 3399:         $args - additional optional args supported are:
 3400:                   only_body      -> is true will set &bodytag() onlybodytag
 3401:                                     arg on
 3402:                   no_nav_bar     -> is true will set &bodytag() notopbar arg on
 3403:                   add_entries    -> additional attributes to add to the  <body>
 3404:                   domain         -> force to color decorate a page for a 
 3405:                                     specific domain
 3406:                   function       -> force usage of a specific rolish color
 3407:                                     scheme
 3408:                   redirect       -> see &headtag()
 3409:                   bgcolor        -> override the default page bg color
 3410:                   js_ready       -> return a string ready for being used in 
 3411:                                     a javascript writeln
 3412:                   html_encode    -> return a string ready for being used in 
 3413:                                     a html attribute
 3414:                   force_register -> if is true will turn on the &bodytag()
 3415:                                     $forcereg arg
 3416:                   body_title     -> alternate text to use instead of $title
 3417:                                     in the title box that appears, this text
 3418:                                     is not auto translated like the $title is
 3419:                   frameset       -> if true will start with a <frameset>
 3420:                                     rather than <body>
 3421:                   no_title       -> if true the title bar won't be shown
 3422:                   skip_phases    -> hash ref of 
 3423:                                     head -> skip the <html><head> generation
 3424:                                     body -> skip all <body> generation
 3425: 
 3426: =back
 3427: 
 3428: =cut
 3429: 
 3430: sub start_page {
 3431:     my ($title,$head_extra,$args) = @_;
 3432:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 3433:     my %head_args;
 3434:     foreach my $arg ('redirect','force_register','domain','function',
 3435: 		     'bgcolor') {
 3436: 	if (defined($args->{$arg})) {
 3437: 	    $head_args{$arg} = $args->{$arg};
 3438: 	}
 3439:     }
 3440: 
 3441:     $env{'internal.start_page'}++;
 3442:     my $result;
 3443:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 3444: 	$result.=
 3445: 	    &xml_begin().
 3446: 	    &headtag($title,$head_extra,\%head_args).&endheadtag();
 3447:     }
 3448:     
 3449:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 3450: 	if ($args->{'frameset'}) {
 3451: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 3452: 						$args->{'add_entries'});
 3453: 	    $result .= "\n<frameset $attr_string>\n";
 3454: 	} else {
 3455: 	    $result .=
 3456: 		&bodytag($title, 
 3457: 			 $args->{'function'},       $args->{'add_entries'},
 3458: 			 $args->{'only_body'},      $args->{'domain'},
 3459: 			 $args->{'force_register'}, $args->{'body_title'},
 3460: 			 $args->{'no_nav_bar'},     $args->{'bgcolor'},
 3461: 			 $args->{'no_title'});
 3462: 	}
 3463:     }
 3464: 
 3465:     if ($args->{'js_ready'}) {
 3466: 	$result = &js_ready($result);
 3467:     }
 3468:     if ($args->{'html_encode'}) {
 3469: 	$result = &html_encode($result);
 3470:     }
 3471:     return $result;
 3472: }
 3473: 
 3474: 
 3475: =pod
 3476: 
 3477: =over 4
 3478: 
 3479: =item * &head()
 3480: 
 3481: Returns a complete </body></html> section for LON-CAPA web pages.
 3482: 
 3483: Inputs:         $args - additional optional args supported are:
 3484:                  js_ready     -> return a string ready for being used in 
 3485:                                  a javascript writeln
 3486:                  html_encode  -> return a string ready for being used in 
 3487:                                  a html attribute
 3488:                  frameset     -> if true will start with a <frameset>
 3489:                                  rather than <body>
 3490: =back
 3491: 
 3492: =cut
 3493: 
 3494: sub end_page {
 3495:     my ($args) = @_;
 3496:     #&Apache::lonnet::logthis("end_page ".join(':',caller(0)));
 3497:     $env{'internal.end_page'}++;
 3498:     my $result;
 3499:     if ($args->{'discussion'}) {
 3500: 	my ($target,$parser);
 3501: 	if (ref($args->{'discussion'})) {
 3502: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 3503: 				$args->{'discussion'}{'parser'});
 3504: 	}
 3505: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 3506:     }
 3507: 
 3508:     if ($args->{'frameset'}) {
 3509: 	$result .= '</frameset>';
 3510:     } else {
 3511: 	$result .= &endbodytag();
 3512:     }
 3513:     $result .= "\n</html>";
 3514: 
 3515:     if ($args->{'js_ready'}) {
 3516: 	$result = &js_ready($result);
 3517:     }
 3518: 
 3519:     if ($args->{'html_encode'}) {
 3520: 	$result = &html_encode($result);
 3521:     }
 3522: 
 3523:     return $result;
 3524: }
 3525: 
 3526: sub html_encode {
 3527:     my ($result) = @_;
 3528: 
 3529:     $result = &HTML::Entities::encode($result,'<>&"');
 3530:     
 3531:     return $result;
 3532: }
 3533: sub js_ready {
 3534:     my ($result) = @_;
 3535: 
 3536:     $result =~ s/[\n\r]/ /xmsg;
 3537:     $result =~ s/\\/\\\\/xmsg;
 3538:     $result =~ s/'/\\'/xmsg;
 3539:     $result =~ s{</script>}{</scrip'+'t>}xmsg;
 3540:     
 3541:     return $result;
 3542: }
 3543: 
 3544: sub validate_page {
 3545:     if (  exists($env{'internal.start_page'})
 3546: 	  &&     $env{'internal.start_page'} > 1) {
 3547: 	&Apache::lonnet::logthis('start_page called multiple times '.
 3548: 				 $env{'internal.start_page'}.' '.
 3549: 				 $ENV{'request.filename'});
 3550:     }
 3551:     if (  exists($env{'internal.end_page'})
 3552: 	  &&     $env{'internal.end_page'} > 1) {
 3553: 	&Apache::lonnet::logthis('end_page called multiple times '.
 3554: 				 $env{'internal.end_page'}.' '.
 3555: 				 $env{'request.filename'});
 3556:     }
 3557:     if (     exists($env{'internal.start_page'})
 3558: 	&& ! exists($env{'internal.end_page'})) {
 3559: 	&Apache::lonnet::logthis('start_page called without end_page '.
 3560: 				 $env{'request.filename'});
 3561:     }
 3562:     if (   ! exists($env{'internal.start_page'})
 3563: 	&&   exists($env{'internal.end_page'})) {
 3564: 	&Apache::lonnet::logthis('end_page called without start_page'.
 3565: 				 $env{'request.filename'});
 3566:     }
 3567: }
 3568: 
 3569: sub simple_error_page {
 3570:     my ($r,$title,$msg) = @_;
 3571:     my $page =
 3572: 	&Apache::loncommon::start_page($title).
 3573: 	&mt($msg).
 3574: 	&Apache::loncommon::end_page();
 3575:     if (ref($r)) {
 3576: 	$r->print($page);
 3577: 	return;
 3578:     }
 3579:     return $page;
 3580: }
 3581: 
 3582: {
 3583:     my $row_count;
 3584:     sub start_data_table {
 3585: 	undef($row_count);
 3586: 	return '<table class="LC_data_table">';
 3587:     }
 3588: 
 3589:     sub end_data_table {
 3590: 	undef($row_count);
 3591: 	return '</table>';
 3592:     }
 3593: 
 3594:     sub start_data_table_row {
 3595: 	$row_count++;
 3596: 	return  '<tr '.(($row_count % 2)?'':'class="LC_even_row"').'>';
 3597:     }
 3598: 
 3599:     sub end_data_table_row {
 3600: 	return '</tr>';
 3601:     }
 3602: }
 3603: 
 3604: ###############################################
 3605: 
 3606: =pod
 3607: 
 3608: =over 4
 3609: 
 3610: =item get_users_function
 3611: 
 3612: Used by &bodytag to determine the current users primary role.
 3613: Returns either 'student','coordinator','admin', or 'author'.
 3614: 
 3615: =cut
 3616: 
 3617: ###############################################
 3618: sub get_users_function {
 3619:     my $function = 'student';
 3620:     if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
 3621:         $function='coordinator';
 3622:     }
 3623:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 3624:         $function='admin';
 3625:     }
 3626:     if (($env{'request.role'}=~/^(au|ca)/) ||
 3627:         ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 3628:         $function='author';
 3629:     }
 3630:     return $function;
 3631: }
 3632: 
 3633: ###############################################
 3634: 
 3635: =pod
 3636: 
 3637: =item check_user_status
 3638: 
 3639: Determines current status of supplied role for a
 3640: specific user. Roles can be active, previous or future.
 3641: 
 3642: Inputs: 
 3643: user's domain, user's username, course's domain,
 3644: course's number, optional section/group.
 3645: 
 3646: Outputs:
 3647: role status: active, previous or future. 
 3648: 
 3649: =cut
 3650: 
 3651: sub check_user_status {
 3652:     my ($udom,$uname,$cdom,$crs,$role,$secgrp) = @_;
 3653:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 3654:     my @uroles = keys %userinfo;
 3655:     my $srchstr;
 3656:     my $active_chk = 'none';
 3657:     if (@uroles > 0) {
 3658:         if (($role eq 'cc') || ($secgrp eq '') || (!defined($secgrp))) {
 3659:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 3660:         } else {
 3661:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$secgrp.'_'.$role;         }
 3662:         if (grep/^$srchstr$/,@uroles) {
 3663:             my $role_end = 0;
 3664:             my $role_start = 0;
 3665:             $active_chk = 'active';
 3666:             if ($userinfo{$srchstr} =~ m/^($role)_(\d+)/) {
 3667:                 $role_end = $2;
 3668:                 if ($userinfo{$srchstr} =~ m/^($role)_($role_end)_(\d+)$/) {
 3669:                     $role_start = $3;
 3670:                 }
 3671:             }
 3672:             if ($role_start > 0) {
 3673:                 if (time < $role_start) {
 3674:                     $active_chk = 'future';
 3675:                 }
 3676:             }
 3677:             if ($role_end > 0) {
 3678:                 if (time > $role_end) {
 3679:                     $active_chk = 'previous';
 3680:                 }
 3681:             }
 3682:         }
 3683:     }
 3684:     return $active_chk;
 3685: }
 3686: 
 3687: ###############################################
 3688: 
 3689: =pod
 3690: 
 3691: =item get_sections
 3692: 
 3693: Determines all the sections for a course including
 3694: sections with students and sections containing other roles.
 3695: Incoming parameters: domain, course number, reference to 
 3696: section hash (keys to be section/group IDs), reference to 
 3697: array containing roles for which sections should be gathered
 3698: (optional). If the fourth argument is undefined, sections
 3699: are gathered for any role.
 3700:  
 3701: Returns number of sections.
 3702: 
 3703: =cut
 3704: 
 3705: ###############################################
 3706: sub get_sections {
 3707:     my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
 3708:     if (!($cdom && $cnum)) { return 0; }
 3709:     my $numsections = 0;
 3710: 
 3711:     if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
 3712: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 3713: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 3714: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 3715: 	while (my ($student,$data) = each %$classlist) {
 3716: 	    my ($section,$status) = ($data->[$sec_index],
 3717: 				     $data->[$status_index]);
 3718: 	    unless ($section eq '-1' || $section =~ /^\s*$/) {
 3719: 		if (!defined($$sectioncount{$section})) { $numsections++; }
 3720: 		$$sectioncount{$section}++;
 3721: 	    }
 3722: 	}
 3723:     }
 3724:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 3725:     foreach my $user (sort(keys(%courseroles))) {
 3726: 	if ($user !~ /^(\w{2})/) { next; }
 3727: 	my ($role) = ($user =~ /^(\w{2})/);
 3728: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 3729: 	my $section;
 3730: 	if ($role eq 'cr' &&
 3731: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 3732: 	    $section=$1;
 3733: 	}
 3734: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 3735: 	if (!defined($section) || $section eq '-1') { next; }
 3736: 	if (!defined($$sectioncount{$section})) { $numsections++; } 
 3737: 	$$sectioncount{$section}++;
 3738:     }
 3739:     return $numsections;
 3740: }
 3741: 
 3742: ###############################################
 3743:                                                                                   
 3744: =pod
 3745:                                                                                   
 3746: =item coursegroups
 3747: 
 3748: Retrieve information about groups in a course,
 3749: 
 3750: Input:
 3751: 1. Reference to hash to populate with group information. 
 3752: 2. Optional course domain
 3753: 3. Optional course number
 3754: 4. Optional group name
 3755: 
 3756: Course domain and number will be taken from user's
 3757: environment if not supplied. Optional group name will'
 3758: be passed to lonnet::get_coursegroups() as a regexp to
 3759: use in the call to the dump function.
 3760: 
 3761: Output
 3762: Returns number of groups in the course (subject to the
 3763: optional group name filter).
 3764: 
 3765: Side effects:
 3766: Populates the referenced curr_groups hash, with key,
 3767: value pairs. Keys are group names, corresponding values
 3768: are scalars containing group information in XML. This
 3769: can be sent to &get_group_settings() to be parsed.     
 3770: 
 3771: =cut 
 3772: 
 3773: ###############################################
 3774: 
 3775: sub coursegroups {
 3776:     my ($curr_groups,$cdom,$cnum,$group) = @_;
 3777:     my $numgroups;
 3778:     if (!defined($cdom) || !defined($cnum)) {
 3779:         my $cid =  $env{'request.course.id'};
 3780:         $cdom = $env{'course.'.$cid.'.domain'};
 3781:         $cnum = $env{'course.'.$cid.'.num'};
 3782:     }
 3783:     %{$curr_groups} = &Apache::lonnet::get_coursegroups($cdom,$cnum,$group);
 3784:     my ($tmp) = keys(%{$curr_groups});
 3785:     if ($tmp=~/^error:/) {
 3786:         unless ($tmp eq 'error: 2 tie(GDBM) Failed while attempting dump') {
 3787:             &logthis('Error retrieving groups: '.$tmp.' in '.$cnum.':'.
 3788:                                                                    $cdom);
 3789:         }
 3790:         $numgroups = 0;
 3791:     } else {
 3792:         $numgroups = keys(%{$curr_groups});
 3793:     }
 3794:     return $numgroups;
 3795: }
 3796: 
 3797: ###############################################
 3798: 
 3799: =pod
 3800: 
 3801: =item get_group_settings
 3802: 
 3803: Uses TokeParser to extract group information from the
 3804: XML used to describe course groups.
 3805: 
 3806: Input:
 3807: Scalar containing XML  - as retrieved from &coursegroups().
 3808: 
 3809: Output:
 3810: Hash containing group information as key=values for (a), and
 3811: hash of hashes for (b)
 3812: 
 3813: Keys (in two categories):
 3814: (a) groupname, creator, creation, modified, startdate,enddate.
 3815: Corresponding values are name of the group, creator of the group
 3816: (username:domain), UNIX time for date group was created, and
 3817: settings were last modified, and default start and end access
 3818: times for group members.
 3819: 
 3820: (b) functions returned in hash of hashes.
 3821: Outer hash key is functions.
 3822: Inner hash keys are chat,discussion,email,files,homepage,roster.
 3823: Corresponding values are either on or off, depending on
 3824: whether this type of functionality is available for the group.
 3825: 
 3826: =cut
 3827:                                                                                  
 3828: ###############################################
 3829: 
 3830: sub get_group_settings {
 3831:     my ($groupinfo)=@_;
 3832:     my $parser=HTML::TokeParser->new(\$groupinfo);
 3833:     my $token;
 3834:     my $tool = '';
 3835:     my $role = '';
 3836:     my %content=();
 3837:     while ($token=$parser->get_token) {
 3838:         if ($token->[0] eq 'S')  {
 3839:             my $entry=$token->[1];
 3840:             if ($entry eq 'functions' || $entry eq 'autosec') {
 3841:                 %{$content{$entry}} = ();
 3842:                 $tool = $entry;
 3843:             } elsif ($entry eq 'role') {
 3844:                 if ($tool eq 'autosec') {
 3845:                     $role = $token->[2]{id};
 3846:                 }
 3847:             } else {
 3848:                 my $value=$parser->get_text('/'.$entry);
 3849:                 if ($entry eq 'name') {
 3850:                     if ($tool eq 'functions') {
 3851:                         my $function = $token->[2]{id};
 3852:                         $content{$tool}{$function} = $value;
 3853:                     }
 3854:                 } elsif ($entry eq 'groupname') {
 3855:                     $content{$entry}=&Apache::lonnet::unescape($value);
 3856:                 } elsif (($entry eq 'roles') || ($entry eq 'types') ||
 3857:                          ($entry eq 'sectionpick') || ($entry eq 'defpriv')) {
 3858:                     push(@{$content{$entry}},$value);
 3859:                 } elsif ($entry eq 'section') {
 3860:                     if ($tool eq 'autosec'  && $role ne '') {
 3861:                         push(@{$content{$tool}{$role}},$value);
 3862:                     }
 3863:                 } else {
 3864:                     $content{$entry}=$value;
 3865:                 }
 3866:             }
 3867:         } elsif ($token->[0] eq 'E') {
 3868:             if ($token->[1] eq 'functions' || $token->[1] eq 'autosec') {
 3869:                 $tool = '';
 3870:             } elsif ($token->[1] eq 'role') {
 3871:                 $role = '';
 3872:             }
 3873: 
 3874:         }
 3875:     }
 3876:     return %content;
 3877: }
 3878: 
 3879: sub check_group_access {
 3880:     my ($group) = @_;
 3881:     my $access = 1;
 3882:     my $now = time;
 3883:     my ($start,$end) = split(/\./,$env{'user.role.gr/'.$env{'request.course,id'}.'/'.$group});
 3884:     if (($end!=0) && ($end<$now)) { $access = 0; }
 3885:     if (($start!=0) && ($start>$now)) { $access=0; }
 3886:     return $access;
 3887: }
 3888: 
 3889: ###############################################
 3890: 
 3891: =pod
 3892:                                                                                 
 3893: =item get_course_users
 3894:                                                                                 
 3895: Retrieves usernames:domains for users in the specified course
 3896: with specific role(s), and access status. 
 3897: 
 3898: Incoming parameters:
 3899: 1. course domain
 3900: 2. course number
 3901: 3. access status: users must have - either active, 
 3902: previous, future, or all.
 3903: 4. reference to array of permissible roles
 3904: 5. reference to array of section restrictions (optional)
 3905: 6. reference to results object (hash of hashes).
 3906: 7. reference to optional userdata hash
 3907: Keys of top level hash are roles.
 3908: Keys of inner hashes are username:domain, with 
 3909: values set to access type.
 3910: Optional userdata hash returns an array with arguments in the 
 3911: same order as loncoursedata::get_classlist() for student data.
 3912: 
 3913: Entries for end, start, section and status are blank because
 3914: of the possibility of multiple values for non-student roles.
 3915: 
 3916: =cut
 3917:                                                                                 
 3918: ###############################################
 3919:                                                                                 
 3920: sub get_course_users {
 3921:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
 3922:     my %idx = ();
 3923: 
 3924:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 3925:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 3926:     $idx{end} = &Apache::loncoursedata::CL_END();
 3927:     $idx{start} = &Apache::loncoursedata::CL_START();
 3928:     $idx{id} = &Apache::loncoursedata::CL_ID();
 3929:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 3930:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 3931:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 3932: 
 3933:     if (grep(/^st$/,@{$roles})) {
 3934:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 3935:         my $now = time;
 3936:         foreach my $student (keys(%{$classlist})) {
 3937:             my $match = 0;
 3938:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 3939: 		unless(grep(/^\Q$$classlist{$student}[$idx{section}]\E$/,
 3940: 			    @{$sections})) {
 3941: 		    next;
 3942: 		}
 3943:             } 
 3944:             if (defined($$types{'active'})) {
 3945:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 3946:                     push(@{$$users{st}{$student}},'active');
 3947:                     $match = 1;
 3948:                 }
 3949:             }
 3950:             if (defined($$types{'previous'})) {
 3951:                 if ($$classlist{$student}[$idx{end}] <= $now) {
 3952:                     push(@{$$users{st}{$student}},'previous');
 3953:                     $match = 1;
 3954:                 }
 3955:             }
 3956:             if (defined($$types{'future'})) {
 3957:                 if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
 3958:                     push(@{$$users{st}{$student}},'future');
 3959:                     $match = 1;
 3960:                 }
 3961:             }
 3962:             if ($match && defined($userdata)) {
 3963:                 $$userdata{$student} = $$classlist{$student};
 3964:             }
 3965:         }
 3966:     }
 3967:     if ((@{$roles} > 0) && (@{$roles} ne "st")) {
 3968:         my @coursepersonnel = &Apache::lonnet::getkeys('nohist_userroles',$cdom,$cnum);
 3969:         foreach my $person (@coursepersonnel) {
 3970:             my $match = 0;
 3971:             my ($role,$user) = ($person =~ /^([^:]*):([^:]+:[^:]+)/);
 3972:             $user =~ s/:$//;
 3973:             if (($role) && (grep(/^\Q$role\E$/,@{$roles}))) {
 3974:                 my ($uname,$udom,$usec) = split(/:/,$user);
 3975:                 if ($usec ne '' && (ref($sections) eq 'ARRAY') && 
 3976: 		    @{$sections} > 0) {
 3977: 		    unless(grep(/^\Q$usec\E$/,@{$sections})) {
 3978: 			next;
 3979: 		    }
 3980:                 }
 3981:                 if ($uname ne '' && $udom ne '') {
 3982:                     my $status = &check_user_status($udom,$uname,$cdom,$cnum,$role);
 3983:                     foreach my $type (keys(%{$types})) { 
 3984:                         if ($status eq $type) {
 3985:                             @{$$users{$role}{$user}} = $type;
 3986:                             $match = 1;
 3987:                         }
 3988:                     }
 3989:                     if ($match && defined($userdata) &&
 3990:                         !exists($$userdata{$uname.':'.$udom})) {
 3991: 			&get_user_info($udom,$uname,\%idx,$userdata);
 3992:                     }
 3993:                 }
 3994:             }
 3995:         }
 3996:         if (grep(/^ow$/,@{$roles})) {
 3997:             if ((defined($cdom)) && (defined($cnum))) {
 3998:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 3999:                 if ( defined($csettings{'internal.courseowner'}) ) {
 4000:                     my $owner = $csettings{'internal.courseowner'};
 4001:                     @{$$users{'ow'}{$owner.':'.$cdom}} = 'any';
 4002:                     if (defined($userdata) && 
 4003: 			!exists($$userdata{$owner.':'.$cdom})) {
 4004: 			&get_user_info($cdom,$owner,\%idx,$userdata);
 4005: 		    }
 4006:                 }
 4007:             }
 4008:         }
 4009:     }
 4010:     return;
 4011: }
 4012: 
 4013: sub get_user_info {
 4014:     my ($udom,$uname,$idx,$userdata) = @_;
 4015:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 4016: 	&plainname($uname,$udom,'lastname');
 4017:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 4018:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 4019:     return;
 4020: }
 4021: 
 4022: =pod
 4023: 
 4024: =item * get_unprocessed_cgi($query,$possible_names)
 4025: 
 4026: Modify the %env hash to contain unprocessed CGI form parameters held in
 4027: $query.  The parameters listed in $possible_names (an array reference),
 4028: will be set in $env{'form.name'} if they do not already exist.
 4029: 
 4030: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 4031: $possible_names is an ref to an array of form element names.  As an example:
 4032: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 4033: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 4034: 
 4035: =cut
 4036: 
 4037: sub get_unprocessed_cgi {
 4038:   my ($query,$possible_names)= @_;
 4039:   # $Apache::lonxml::debug=1;
 4040:   foreach my $pair (split(/&/,$query)) {
 4041:     my ($name, $value) = split(/=/,$pair);
 4042:     $name = &Apache::lonnet::unescape($name);
 4043:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 4044:       $value =~ tr/+/ /;
 4045:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4046:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 4047:     }
 4048:   }
 4049: }
 4050: 
 4051: =pod
 4052: 
 4053: =item * cacheheader() 
 4054: 
 4055: returns cache-controlling header code
 4056: 
 4057: =cut
 4058: 
 4059: sub cacheheader {
 4060:     unless ($env{'request.method'} eq 'GET') { return ''; }
 4061:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 4062:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 4063:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 4064:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 4065:     return $output;
 4066: }
 4067: 
 4068: =pod
 4069: 
 4070: =item * no_cache($r) 
 4071: 
 4072: specifies header code to not have cache
 4073: 
 4074: =cut
 4075: 
 4076: sub no_cache {
 4077:     my ($r) = @_;
 4078:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 4079: 	$env{'request.method'} ne 'GET') { return ''; }
 4080:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 4081:     $r->no_cache(1);
 4082:     $r->header_out("Expires" => $date);
 4083:     $r->header_out("Pragma" => "no-cache");
 4084: }
 4085: 
 4086: sub content_type {
 4087:     my ($r,$type,$charset) = @_;
 4088:     if ($r) {
 4089: 	#  Note that printout.pl calls this with undef for $r.
 4090: 	&no_cache($r);
 4091:     }
 4092:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 4093:     unless ($charset) {
 4094: 	$charset=&Apache::lonlocal::current_encoding;
 4095:     }
 4096:     if ($charset) { $type.='; charset='.$charset; }
 4097:     if ($r) {
 4098: 	$r->content_type($type);
 4099:     } else {
 4100: 	print("Content-type: $type\n\n");
 4101:     }
 4102: }
 4103: 
 4104: =pod
 4105: 
 4106: =item * add_to_env($name,$value) 
 4107: 
 4108: adds $name to the %env hash with value
 4109: $value, if $name already exists, the entry is converted to an array
 4110: reference and $value is added to the array.
 4111: 
 4112: =cut
 4113: 
 4114: sub add_to_env {
 4115:   my ($name,$value)=@_;
 4116:   if (defined($env{$name})) {
 4117:     if (ref($env{$name})) {
 4118:       #already have multiple values
 4119:       push(@{ $env{$name} },$value);
 4120:     } else {
 4121:       #first time seeing multiple values, convert hash entry to an arrayref
 4122:       my $first=$env{$name};
 4123:       undef($env{$name});
 4124:       push(@{ $env{$name} },$first,$value);
 4125:     }
 4126:   } else {
 4127:     $env{$name}=$value;
 4128:   }
 4129: }
 4130: 
 4131: =pod
 4132: 
 4133: =item * get_env_multiple($name) 
 4134: 
 4135: gets $name from the %env hash, it seemlessly handles the cases where multiple
 4136: values may be defined and end up as an array ref.
 4137: 
 4138: returns an array of values
 4139: 
 4140: =cut
 4141: 
 4142: sub get_env_multiple {
 4143:     my ($name) = @_;
 4144:     my @values;
 4145:     if (defined($env{$name})) {
 4146:         # exists is it an array
 4147:         if (ref($env{$name})) {
 4148:             @values=@{ $env{$name} };
 4149:         } else {
 4150:             $values[0]=$env{$name};
 4151:         }
 4152:     }
 4153:     return(@values);
 4154: }
 4155: 
 4156: 
 4157: =pod
 4158: 
 4159: =back 
 4160: 
 4161: =head1 CSV Upload/Handling functions
 4162: 
 4163: =over 4
 4164: 
 4165: =item * upfile_store($r)
 4166: 
 4167: Store uploaded file, $r should be the HTTP Request object,
 4168: needs $env{'form.upfile'}
 4169: returns $datatoken to be put into hidden field
 4170: 
 4171: =cut
 4172: 
 4173: sub upfile_store {
 4174:     my $r=shift;
 4175:     $env{'form.upfile'}=~s/\r/\n/gs;
 4176:     $env{'form.upfile'}=~s/\f/\n/gs;
 4177:     $env{'form.upfile'}=~s/\n+/\n/gs;
 4178:     $env{'form.upfile'}=~s/\n+$//gs;
 4179: 
 4180:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
 4181: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
 4182:     {
 4183:         my $datafile = $r->dir_config('lonDaemons').
 4184:                            '/tmp/'.$datatoken.'.tmp';
 4185:         if ( open(my $fh,">$datafile") ) {
 4186:             print $fh $env{'form.upfile'};
 4187:             close($fh);
 4188:         }
 4189:     }
 4190:     return $datatoken;
 4191: }
 4192: 
 4193: =pod
 4194: 
 4195: =item * load_tmp_file($r)
 4196: 
 4197: Load uploaded file from tmp, $r should be the HTTP Request object,
 4198: needs $env{'form.datatoken'},
 4199: sets $env{'form.upfile'} to the contents of the file
 4200: 
 4201: =cut
 4202: 
 4203: sub load_tmp_file {
 4204:     my $r=shift;
 4205:     my @studentdata=();
 4206:     {
 4207:         my $studentfile = $r->dir_config('lonDaemons').
 4208:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
 4209:         if ( open(my $fh,"<$studentfile") ) {
 4210:             @studentdata=<$fh>;
 4211:             close($fh);
 4212:         }
 4213:     }
 4214:     $env{'form.upfile'}=join('',@studentdata);
 4215: }
 4216: 
 4217: =pod
 4218: 
 4219: =item * upfile_record_sep()
 4220: 
 4221: Separate uploaded file into records
 4222: returns array of records,
 4223: needs $env{'form.upfile'} and $env{'form.upfiletype'}
 4224: 
 4225: =cut
 4226: 
 4227: sub upfile_record_sep {
 4228:     if ($env{'form.upfiletype'} eq 'xml') {
 4229:     } else {
 4230: 	my @records;
 4231: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
 4232: 	    if ($line=~/^\s*$/) { next; }
 4233: 	    push(@records,$line);
 4234: 	}
 4235: 	return @records;
 4236:     }
 4237: }
 4238: 
 4239: =pod
 4240: 
 4241: =item * record_sep($record)
 4242: 
 4243: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
 4244: 
 4245: =cut
 4246: 
 4247: sub takeleft {
 4248:     my $index=shift;
 4249:     return substr('0000'.$index,-4,4);
 4250: }
 4251: 
 4252: sub record_sep {
 4253:     my $record=shift;
 4254:     my %components=();
 4255:     if ($env{'form.upfiletype'} eq 'xml') {
 4256:     } elsif ($env{'form.upfiletype'} eq 'space') {
 4257:         my $i=0;
 4258:         foreach my $field (split(/\s+/,$record)) {
 4259:             $field=~s/^(\"|\')//;
 4260:             $field=~s/(\"|\')$//;
 4261:             $components{&takeleft($i)}=$field;
 4262:             $i++;
 4263:         }
 4264:     } elsif ($env{'form.upfiletype'} eq 'tab') {
 4265:         my $i=0;
 4266:         foreach my $field (split(/\t/,$record)) {
 4267:             $field=~s/^(\"|\')//;
 4268:             $field=~s/(\"|\')$//;
 4269:             $components{&takeleft($i)}=$field;
 4270:             $i++;
 4271:         }
 4272:     } else {
 4273:         my @allfields=split(/\,/,$record);
 4274:         my $i=0;
 4275:         my $j;
 4276:         for ($j=0;$j<=$#allfields;$j++) {
 4277:             my $field=$allfields[$j];
 4278:             if ($field=~/^\s*(\"|\')/) {
 4279: 		my $delimiter=$1;
 4280:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 4281: 		    $j++;
 4282: 		    $field.=','.$allfields[$j];
 4283: 		}
 4284:                 $field=~s/^\s*$delimiter//;
 4285:                 $field=~s/$delimiter\s*$//;
 4286:             }
 4287:             $components{&takeleft($i)}=$field;
 4288: 	    $i++;
 4289:         }
 4290:     }
 4291:     return %components;
 4292: }
 4293: 
 4294: ######################################################
 4295: ######################################################
 4296: 
 4297: =pod
 4298: 
 4299: =item * upfile_select_html()
 4300: 
 4301: Return HTML code to select a file from the users machine and specify 
 4302: the file type.
 4303: 
 4304: =cut
 4305: 
 4306: ######################################################
 4307: ######################################################
 4308: sub upfile_select_html {
 4309:     my %Types = (
 4310:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
 4311:                  space => &mt('Space separated'),
 4312:                  tab   => &mt('Tabulator separated'),
 4313: #                 xml   => &mt('HTML/XML'),
 4314:                  );
 4315:     my $Str = '<input type="file" name="upfile" size="50" />'.
 4316:         '<br />Type: <select name="upfiletype">';
 4317:     foreach my $type (sort(keys(%Types))) {
 4318:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
 4319:     }
 4320:     $Str .= "</select>\n";
 4321:     return $Str;
 4322: }
 4323: 
 4324: sub get_samples {
 4325:     my ($records,$toget) = @_;
 4326:     my @samples=({});
 4327:     my $got=0;
 4328:     foreach my $rec (@$records) {
 4329: 	my %temp = &record_sep($rec);
 4330: 	if (! grep(/\S/, values(%temp))) { next; }
 4331: 	if (%temp) {
 4332: 	    $samples[$got]=\%temp;
 4333: 	    $got++;
 4334: 	    if ($got == $toget) { last; }
 4335: 	}
 4336:     }
 4337:     return \@samples;
 4338: }
 4339: 
 4340: ######################################################
 4341: ######################################################
 4342: 
 4343: =pod
 4344: 
 4345: =item * csv_print_samples($r,$records)
 4346: 
 4347: Prints a table of sample values from each column uploaded $r is an
 4348: Apache Request ref, $records is an arrayref from
 4349: &Apache::loncommon::upfile_record_sep
 4350: 
 4351: =cut
 4352: 
 4353: ######################################################
 4354: ######################################################
 4355: sub csv_print_samples {
 4356:     my ($r,$records) = @_;
 4357:     my $samples = &get_samples($records,3);
 4358: 
 4359:     $r->print(&mt('Samples').'<br /><table border="2"><tr>');
 4360:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
 4361:         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
 4362:     $r->print('</tr>');
 4363:     foreach my $hash (@$samples) {
 4364: 	$r->print('<tr>');
 4365: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4366: 	    $r->print('<td>');
 4367: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 4368: 	    $r->print('</td>');
 4369: 	}
 4370: 	$r->print('</tr>');
 4371:     }
 4372:     $r->print('</tr></table><br />'."\n");
 4373: }
 4374: 
 4375: ######################################################
 4376: ######################################################
 4377: 
 4378: =pod
 4379: 
 4380: =item * csv_print_select_table($r,$records,$d)
 4381: 
 4382: Prints a table to create associations between values and table columns.
 4383: 
 4384: $r is an Apache Request ref,
 4385: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4386: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
 4387: 
 4388: =cut
 4389: 
 4390: ######################################################
 4391: ######################################################
 4392: sub csv_print_select_table {
 4393:     my ($r,$records,$d) = @_;
 4394:     my $i=0;
 4395:     my $samples = &get_samples($records,1);
 4396:     $r->print(&mt('Associate columns with student attributes.')."\n".
 4397: 	     '<table border="2"><tr>'.
 4398:               '<th>'.&mt('Attribute').'</th>'.
 4399:               '<th>'.&mt('Column').'</th></tr>'."\n");
 4400:     foreach my $array_ref (@$d) {
 4401: 	my ($value,$display,$defaultcol)=@{ $array_ref };
 4402: 	$r->print('<tr><td>'.$display.'</td>');
 4403: 
 4404: 	$r->print('<td><select name=f'.$i.
 4405: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4406: 	$r->print('<option value="none"></option>');
 4407: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 4408: 	    $r->print('<option value="'.$sample.'"'.
 4409:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
 4410:                       '>Column '.($sample+1).'</option>');
 4411: 	}
 4412: 	$r->print('</select></td></tr>'."\n");
 4413: 	$i++;
 4414:     }
 4415:     $i--;
 4416:     return $i;
 4417: }
 4418: 
 4419: ######################################################
 4420: ######################################################
 4421: 
 4422: =pod
 4423: 
 4424: =item * csv_samples_select_table($r,$records,$d)
 4425: 
 4426: Prints a table of sample values from the upload and can make associate samples to internal names.
 4427: 
 4428: $r is an Apache Request ref,
 4429: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 4430: $d is an array of 2 element arrays (internal name, displayed name)
 4431: 
 4432: =cut
 4433: 
 4434: ######################################################
 4435: ######################################################
 4436: sub csv_samples_select_table {
 4437:     my ($r,$records,$d) = @_;
 4438:     my $i=0;
 4439:     #
 4440:     my $samples = &get_samples($records,3);
 4441:     $r->print('<table border=2><tr><th>'.
 4442:               &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
 4443: 
 4444:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
 4445: 	$r->print('<tr><td><select name="f'.$i.'"'.
 4446: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 4447: 	foreach my $option (@$d) {
 4448: 	    my ($value,$display,$defaultcol)=@{ $option };
 4449: 	    $r->print('<option value="'.$value.'"'.
 4450:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
 4451:                       $display.'</option>');
 4452: 	}
 4453: 	$r->print('</select></td><td>');
 4454: 	foreach my $line (0..2) {
 4455: 	    if (defined($samples->[$line]{$key})) { 
 4456: 		$r->print($samples->[$line]{$key}."<br />\n"); 
 4457: 	    }
 4458: 	}
 4459: 	$r->print('</td></tr>');
 4460: 	$i++;
 4461:     }
 4462:     $i--;
 4463:     return($i);
 4464: }
 4465: 
 4466: ######################################################
 4467: ######################################################
 4468: 
 4469: =pod
 4470: 
 4471: =item clean_excel_name($name)
 4472: 
 4473: Returns a replacement for $name which does not contain any illegal characters.
 4474: 
 4475: =cut
 4476: 
 4477: ######################################################
 4478: ######################################################
 4479: sub clean_excel_name {
 4480:     my ($name) = @_;
 4481:     $name =~ s/[:\*\?\/\\]//g;
 4482:     if (length($name) > 31) {
 4483:         $name = substr($name,0,31);
 4484:     }
 4485:     return $name;
 4486: }
 4487: 
 4488: =pod
 4489: 
 4490: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
 4491: 
 4492: Returns either 1 or undef
 4493: 
 4494: 1 if the part is to be hidden, undef if it is to be shown
 4495: 
 4496: Arguments are:
 4497: 
 4498: $id the id of the part to be checked
 4499: $symb, optional the symb of the resource to check
 4500: $udom, optional the domain of the user to check for
 4501: $uname, optional the username of the user to check for
 4502: 
 4503: =cut
 4504: 
 4505: sub check_if_partid_hidden {
 4506:     my ($id,$symb,$udom,$uname) = @_;
 4507:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
 4508: 					 $symb,$udom,$uname);
 4509:     my $truth=1;
 4510:     #if the string starts with !, then the list is the list to show not hide
 4511:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
 4512:     my @hiddenlist=split(/,/,$hiddenparts);
 4513:     foreach my $checkid (@hiddenlist) {
 4514: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
 4515:     }
 4516:     return !$truth;
 4517: }
 4518: 
 4519: 
 4520: ############################################################
 4521: ############################################################
 4522: 
 4523: =pod
 4524: 
 4525: =back 
 4526: 
 4527: =head1 cgi-bin script and graphing routines
 4528: 
 4529: =over 4
 4530: 
 4531: =item get_cgi_id
 4532: 
 4533: Inputs: none
 4534: 
 4535: Returns an id which can be used to pass environment variables
 4536: to various cgi-bin scripts.  These environment variables will
 4537: be removed from the users environment after a given time by
 4538: the routine &Apache::lonnet::transfer_profile_to_env.
 4539: 
 4540: =cut
 4541: 
 4542: ############################################################
 4543: ############################################################
 4544: my $uniq=0;
 4545: sub get_cgi_id {
 4546:     $uniq=($uniq+1)%100000;
 4547:     return (time.'_'.$$.'_'.$uniq);
 4548: }
 4549: 
 4550: ############################################################
 4551: ############################################################
 4552: 
 4553: =pod
 4554: 
 4555: =item DrawBarGraph
 4556: 
 4557: Facilitates the plotting of data in a (stacked) bar graph.
 4558: Puts plot definition data into the users environment in order for 
 4559: graph.png to plot it.  Returns an <img> tag for the plot.
 4560: The bars on the plot are labeled '1','2',...,'n'.
 4561: 
 4562: Inputs:
 4563: 
 4564: =over 4
 4565: 
 4566: =item $Title: string, the title of the plot
 4567: 
 4568: =item $xlabel: string, text describing the X-axis of the plot
 4569: 
 4570: =item $ylabel: string, text describing the Y-axis of the plot
 4571: 
 4572: =item $Max: scalar, the maximum Y value to use in the plot
 4573: If $Max is < any data point, the graph will not be rendered.
 4574: 
 4575: =item $colors: array ref holding the colors to be used for the data sets when
 4576: they are plotted.  If undefined, default values will be used.
 4577: 
 4578: =item $labels: array ref holding the labels to use on the x-axis for the bars.
 4579: 
 4580: =item @Values: An array of array references.  Each array reference holds data
 4581: to be plotted in a stacked bar chart.
 4582: 
 4583: =item If the final element of @Values is a hash reference the key/value
 4584: pairs will be added to the graph definition.
 4585: 
 4586: =back
 4587: 
 4588: Returns:
 4589: 
 4590: An <img> tag which references graph.png and the appropriate identifying
 4591: information for the plot.
 4592: 
 4593: =cut
 4594: 
 4595: ############################################################
 4596: ############################################################
 4597: sub DrawBarGraph {
 4598:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
 4599:     #
 4600:     if (! defined($colors)) {
 4601:         $colors = ['#33ff00', 
 4602:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
 4603:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
 4604:                   ]; 
 4605:     }
 4606:     my $extra_settings = {};
 4607:     if (ref($Values[-1]) eq 'HASH') {
 4608:         $extra_settings = pop(@Values);
 4609:     }
 4610:     #
 4611:     my $identifier = &get_cgi_id();
 4612:     my $id = 'cgi.'.$identifier;        
 4613:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
 4614:         return '';
 4615:     }
 4616:     #
 4617:     my @Labels;
 4618:     if (defined($labels)) {
 4619:         @Labels = @$labels;
 4620:     } else {
 4621:         for (my $i=0;$i<@{$Values[0]};$i++) {
 4622:             push (@Labels,$i+1);
 4623:         }
 4624:     }
 4625:     #
 4626:     my $NumBars = scalar(@{$Values[0]});
 4627:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
 4628:     my %ValuesHash;
 4629:     my $NumSets=1;
 4630:     foreach my $array (@Values) {
 4631:         next if (! ref($array));
 4632:         $ValuesHash{$id.'.data.'.$NumSets++} = 
 4633:             join(',',@$array);
 4634:     }
 4635:     #
 4636:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
 4637:     if ($NumBars < 3) {
 4638:         $width = 120+$NumBars*32;
 4639:         $xskip = 1;
 4640:         $bar_width = 30;
 4641:     } elsif ($NumBars < 5) {
 4642:         $width = 120+$NumBars*20;
 4643:         $xskip = 1;
 4644:         $bar_width = 20;
 4645:     } elsif ($NumBars < 10) {
 4646:         $width = 120+$NumBars*15;
 4647:         $xskip = 1;
 4648:         $bar_width = 15;
 4649:     } elsif ($NumBars <= 25) {
 4650:         $width = 120+$NumBars*11;
 4651:         $xskip = 5;
 4652:         $bar_width = 8;
 4653:     } elsif ($NumBars <= 50) {
 4654:         $width = 120+$NumBars*8;
 4655:         $xskip = 5;
 4656:         $bar_width = 4;
 4657:     } else {
 4658:         $width = 120+$NumBars*8;
 4659:         $xskip = 5;
 4660:         $bar_width = 4;
 4661:     }
 4662:     #
 4663:     $Max = 1 if ($Max < 1);
 4664:     if ( int($Max) < $Max ) {
 4665:         $Max++;
 4666:         $Max = int($Max);
 4667:     }
 4668:     $Title  = '' if (! defined($Title));
 4669:     $xlabel = '' if (! defined($xlabel));
 4670:     $ylabel = '' if (! defined($ylabel));
 4671:     $ValuesHash{$id.'.title'}    = &Apache::lonnet::escape($Title);
 4672:     $ValuesHash{$id.'.xlabel'}   = &Apache::lonnet::escape($xlabel);
 4673:     $ValuesHash{$id.'.ylabel'}   = &Apache::lonnet::escape($ylabel);
 4674:     $ValuesHash{$id.'.y_max_value'} = $Max;
 4675:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
 4676:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
 4677:     $ValuesHash{$id.'.PlotType'} = 'bar';
 4678:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4679:     $ValuesHash{$id.'.height'}   = $height;
 4680:     $ValuesHash{$id.'.width'}    = $width;
 4681:     $ValuesHash{$id.'.xskip'}    = $xskip;
 4682:     $ValuesHash{$id.'.bar_width'} = $bar_width;
 4683:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
 4684:     #
 4685:     # Deal with other parameters
 4686:     while (my ($key,$value) = each(%$extra_settings)) {
 4687:         $ValuesHash{$id.'.'.$key} = $value;
 4688:     }
 4689:     #
 4690:     &Apache::lonnet::appenv(%ValuesHash);
 4691:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4692: }
 4693: 
 4694: ############################################################
 4695: ############################################################
 4696: 
 4697: =pod
 4698: 
 4699: =item DrawXYGraph
 4700: 
 4701: Facilitates the plotting of data in an XY graph.
 4702: Puts plot definition data into the users environment in order for 
 4703: graph.png to plot it.  Returns an <img> tag for the plot.
 4704: 
 4705: Inputs:
 4706: 
 4707: =over 4
 4708: 
 4709: =item $Title: string, the title of the plot
 4710: 
 4711: =item $xlabel: string, text describing the X-axis of the plot
 4712: 
 4713: =item $ylabel: string, text describing the Y-axis of the plot
 4714: 
 4715: =item $Max: scalar, the maximum Y value to use in the plot
 4716: If $Max is < any data point, the graph will not be rendered.
 4717: 
 4718: =item $colors: Array ref containing the hex color codes for the data to be 
 4719: plotted in.  If undefined, default values will be used.
 4720: 
 4721: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 4722: 
 4723: =item $Ydata: Array ref containing Array refs.  
 4724: Each of the contained arrays will be plotted as a separate curve.
 4725: 
 4726: =item %Values: hash indicating or overriding any default values which are 
 4727: passed to graph.png.  
 4728: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 4729: 
 4730: =back
 4731: 
 4732: Returns:
 4733: 
 4734: An <img> tag which references graph.png and the appropriate identifying
 4735: information for the plot.
 4736: 
 4737: =cut
 4738: 
 4739: ############################################################
 4740: ############################################################
 4741: sub DrawXYGraph {
 4742:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
 4743:     #
 4744:     # Create the identifier for the graph
 4745:     my $identifier = &get_cgi_id();
 4746:     my $id = 'cgi.'.$identifier;
 4747:     #
 4748:     $Title  = '' if (! defined($Title));
 4749:     $xlabel = '' if (! defined($xlabel));
 4750:     $ylabel = '' if (! defined($ylabel));
 4751:     my %ValuesHash = 
 4752:         (
 4753:          $id.'.title'  => &Apache::lonnet::escape($Title),
 4754:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 4755:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 4756:          $id.'.y_max_value'=> $Max,
 4757:          $id.'.labels'     => join(',',@$Xlabels),
 4758:          $id.'.PlotType'   => 'XY',
 4759:          );
 4760:     #
 4761:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 4762:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4763:     }
 4764:     #
 4765:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
 4766:         return '';
 4767:     }
 4768:     my $NumSets=1;
 4769:     foreach my $array (@{$Ydata}){
 4770:         next if (! ref($array));
 4771:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 4772:     }
 4773:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
 4774:     #
 4775:     # Deal with other parameters
 4776:     while (my ($key,$value) = each(%Values)) {
 4777:         $ValuesHash{$id.'.'.$key} = $value;
 4778:     }
 4779:     #
 4780:     &Apache::lonnet::appenv(%ValuesHash);
 4781:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4782: }
 4783: 
 4784: ############################################################
 4785: ############################################################
 4786: 
 4787: =pod
 4788: 
 4789: =item DrawXYYGraph
 4790: 
 4791: Facilitates the plotting of data in an XY graph with two Y axes.
 4792: Puts plot definition data into the users environment in order for 
 4793: graph.png to plot it.  Returns an <img> tag for the plot.
 4794: 
 4795: Inputs:
 4796: 
 4797: =over 4
 4798: 
 4799: =item $Title: string, the title of the plot
 4800: 
 4801: =item $xlabel: string, text describing the X-axis of the plot
 4802: 
 4803: =item $ylabel: string, text describing the Y-axis of the plot
 4804: 
 4805: =item $colors: Array ref containing the hex color codes for the data to be 
 4806: plotted in.  If undefined, default values will be used.
 4807: 
 4808: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
 4809: 
 4810: =item $Ydata1: The first data set
 4811: 
 4812: =item $Min1: The minimum value of the left Y-axis
 4813: 
 4814: =item $Max1: The maximum value of the left Y-axis
 4815: 
 4816: =item $Ydata2: The second data set
 4817: 
 4818: =item $Min2: The minimum value of the right Y-axis
 4819: 
 4820: =item $Max2: The maximum value of the left Y-axis
 4821: 
 4822: =item %Values: hash indicating or overriding any default values which are 
 4823: passed to graph.png.  
 4824: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
 4825: 
 4826: =back
 4827: 
 4828: Returns:
 4829: 
 4830: An <img> tag which references graph.png and the appropriate identifying
 4831: information for the plot.
 4832: 
 4833: =cut
 4834: 
 4835: ############################################################
 4836: ############################################################
 4837: sub DrawXYYGraph {
 4838:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
 4839:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
 4840:     #
 4841:     # Create the identifier for the graph
 4842:     my $identifier = &get_cgi_id();
 4843:     my $id = 'cgi.'.$identifier;
 4844:     #
 4845:     $Title  = '' if (! defined($Title));
 4846:     $xlabel = '' if (! defined($xlabel));
 4847:     $ylabel = '' if (! defined($ylabel));
 4848:     my %ValuesHash = 
 4849:         (
 4850:          $id.'.title'  => &Apache::lonnet::escape($Title),
 4851:          $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
 4852:          $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
 4853:          $id.'.labels' => join(',',@$Xlabels),
 4854:          $id.'.PlotType' => 'XY',
 4855:          $id.'.NumSets' => 2,
 4856:          $id.'.two_axes' => 1,
 4857:          $id.'.y1_max_value' => $Max1,
 4858:          $id.'.y1_min_value' => $Min1,
 4859:          $id.'.y2_max_value' => $Max2,
 4860:          $id.'.y2_min_value' => $Min2,
 4861:          );
 4862:     #
 4863:     if (defined($colors) && ref($colors) eq 'ARRAY') {
 4864:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
 4865:     }
 4866:     #
 4867:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
 4868:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
 4869:         return '';
 4870:     }
 4871:     my $NumSets=1;
 4872:     foreach my $array ($Ydata1,$Ydata2){
 4873:         next if (! ref($array));
 4874:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
 4875:     }
 4876:     #
 4877:     # Deal with other parameters
 4878:     while (my ($key,$value) = each(%Values)) {
 4879:         $ValuesHash{$id.'.'.$key} = $value;
 4880:     }
 4881:     #
 4882:     &Apache::lonnet::appenv(%ValuesHash);
 4883:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
 4884: }
 4885: 
 4886: ############################################################
 4887: ############################################################
 4888: 
 4889: =pod
 4890: 
 4891: =back 
 4892: 
 4893: =head1 Statistics helper routines?  
 4894: 
 4895: Bad place for them but what the hell.
 4896: 
 4897: =over 4
 4898: 
 4899: =item &chartlink
 4900: 
 4901: Returns a link to the chart for a specific student.  
 4902: 
 4903: Inputs:
 4904: 
 4905: =over 4
 4906: 
 4907: =item $linktext: The text of the link
 4908: 
 4909: =item $sname: The students username
 4910: 
 4911: =item $sdomain: The students domain
 4912: 
 4913: =back
 4914: 
 4915: =back
 4916: 
 4917: =cut
 4918: 
 4919: ############################################################
 4920: ############################################################
 4921: sub chartlink {
 4922:     my ($linktext, $sname, $sdomain) = @_;
 4923:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
 4924:         '&amp;SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
 4925:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
 4926:        '">'.$linktext.'</a>';
 4927: }
 4928: 
 4929: #######################################################
 4930: #######################################################
 4931: 
 4932: =pod
 4933: 
 4934: =head1 Course Environment Routines
 4935: 
 4936: =over 4
 4937: 
 4938: =item &restore_course_settings 
 4939: 
 4940: =item &store_course_settings
 4941: 
 4942: Restores/Store indicated form parameters from the course environment.
 4943: Will not overwrite existing values of the form parameters.
 4944: 
 4945: Inputs: 
 4946: a scalar describing the data (e.g. 'chart', 'problem_analysis')
 4947: 
 4948: a hash ref describing the data to be stored.  For example:
 4949:    
 4950: %Save_Parameters = ('Status' => 'scalar',
 4951:     'chartoutputmode' => 'scalar',
 4952:     'chartoutputdata' => 'scalar',
 4953:     'Section' => 'array',
 4954:     'StudentData' => 'array',
 4955:     'Maps' => 'array');
 4956: 
 4957: Returns: both routines return nothing
 4958: 
 4959: =cut
 4960: 
 4961: #######################################################
 4962: #######################################################
 4963: sub store_course_settings {
 4964:     # save to the environment
 4965:     # appenv the same items, just to be safe
 4966:     my $courseid = $env{'request.course.id'};
 4967:     my $udom  = $env{'user.domain'};
 4968:     my $uname = $env{'user.name'};
 4969:     my ($prefix,$Settings) = @_;
 4970:     my %SaveHash;
 4971:     my %AppHash;
 4972:     while (my ($setting,$type) = each(%$Settings)) {
 4973:         my $basename = join('.','internal',$courseid,$prefix,$setting);
 4974:         my $envname = 'environment.'.$basename;
 4975:         if (exists($env{'form.'.$setting})) {
 4976:             # Save this value away
 4977:             if ($type eq 'scalar' &&
 4978:                 (! exists($env{$envname}) || 
 4979:                  $env{$envname} ne $env{'form.'.$setting})) {
 4980:                 $SaveHash{$basename} = $env{'form.'.$setting};
 4981:                 $AppHash{$envname}   = $env{'form.'.$setting};
 4982:             } elsif ($type eq 'array') {
 4983:                 my $stored_form;
 4984:                 if (ref($env{'form.'.$setting})) {
 4985:                     $stored_form = join(',',
 4986:                                         map {
 4987:                                             &Apache::lonnet::escape($_);
 4988:                                         } sort(@{$env{'form.'.$setting}}));
 4989:                 } else {
 4990:                     $stored_form = 
 4991:                         &Apache::lonnet::escape($env{'form.'.$setting});
 4992:                 }
 4993:                 # Determine if the array contents are the same.
 4994:                 if ($stored_form ne $env{$envname}) {
 4995:                     $SaveHash{$basename} = $stored_form;
 4996:                     $AppHash{$envname}   = $stored_form;
 4997:                 }
 4998:             }
 4999:         }
 5000:     }
 5001:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
 5002:                                           $udom,$uname);
 5003:     if ($put_result !~ /^(ok|delayed)/) {
 5004:         &Apache::lonnet::logthis('unable to save form parameters, '.
 5005:                                  'got error:'.$put_result);
 5006:     }
 5007:     # Make sure these settings stick around in this session, too
 5008:     &Apache::lonnet::appenv(%AppHash);
 5009:     return;
 5010: }
 5011: 
 5012: sub restore_course_settings {
 5013:     my $courseid = $env{'request.course.id'};
 5014:     my ($prefix,$Settings) = @_;
 5015:     while (my ($setting,$type) = each(%$Settings)) {
 5016:         next if (exists($env{'form.'.$setting}));
 5017:         my $envname = 'environment.internal.'.$courseid.'.'.$prefix.
 5018:             '.'.$setting;
 5019:         if (exists($env{$envname})) {
 5020:             if ($type eq 'scalar') {
 5021:                 $env{'form.'.$setting} = $env{$envname};
 5022:             } elsif ($type eq 'array') {
 5023:                 $env{'form.'.$setting} = [ 
 5024:                                            map { 
 5025:                                                &Apache::lonnet::unescape($_); 
 5026:                                            } split(',',$env{$envname})
 5027:                                            ];
 5028:             }
 5029:         }
 5030:     }
 5031: }
 5032: 
 5033: ############################################################
 5034: ############################################################
 5035: 
 5036: sub propath {
 5037:     my ($udom,$uname)=@_;
 5038:     $udom=~s/\W//g;
 5039:     $uname=~s/\W//g;
 5040:     my $subdir=$uname.'__';
 5041:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5042:     my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 5043:     return $proname;
 5044: } 
 5045: 
 5046: sub icon {
 5047:     my ($file)=@_;
 5048:     my $curfext = (split(/\./,$file))[-1];
 5049:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
 5050:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
 5051:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
 5052: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
 5053: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 5054: 	            $curfext.".gif") {
 5055: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
 5056: 		$curfext.".gif";
 5057: 	}
 5058:     }
 5059:     return &lonhttpdurl($iconname);
 5060: } 
 5061: 
 5062: sub lonhttpdurl {
 5063:     my ($url)=@_;
 5064:     my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
 5065:     if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
 5066:     return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
 5067: }
 5068: 
 5069: sub connection_aborted {
 5070:     my ($r)=@_;
 5071:     $r->print(" ");$r->rflush();
 5072:     my $c = $r->connection;
 5073:     return $c->aborted();
 5074: }
 5075: 
 5076: #    Escapes strings that may have embedded 's that will be put into
 5077: #    strings as 'strings'.
 5078: sub escape_single {
 5079:     my ($input) = @_;
 5080:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
 5081:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
 5082:     return $input;
 5083: }
 5084: 
 5085: #  Same as escape_single, but escape's "'s  This 
 5086: #  can be used for  "strings"
 5087: sub escape_double {
 5088:     my ($input) = @_;
 5089:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
 5090:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
 5091:     return $input;
 5092: }
 5093:  
 5094: #   Escapes the last element of a full URL.
 5095: sub escape_url {
 5096:     my ($url)   = @_;
 5097:     my @urlslices = split(/\//, $url,-1);
 5098:     my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
 5099:     return join('/',@urlslices).'/'.$lastitem;
 5100: }
 5101: =pod
 5102: 
 5103: =back
 5104: 
 5105: =cut
 5106: 
 5107: 1;
 5108: __END__;
 5109: 

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