File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.432: download - view: text, annotated - select for diffs
Wed Jul 19 10:52:27 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixing up public access to look like logged in access
- making the exit and help links predictable in size and location

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

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