File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.347: download - view: text, annotated - select for diffs
Sat Apr 22 01:06:48 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
-adding a LC_data_table that has the CC color in the th row and alternates the row colors

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

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