File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.351: download - view: text, annotated - select for diffs
Sat Apr 22 20:58:32 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
More work on RSS and Podcasts, now extra broken.

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

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