File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.337: download - view: text, annotated - select for diffs
Fri Apr 14 20:16:02 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- starting on getting homework problems to use start_page stuff

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

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