File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.79: download - view: text, annotated - select for diffs
Thu Feb 13 18:11:26 2003 UTC (21 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Steps towards server side menu for handicapper access.
Get activated when logging in with "Accessibility Option"
If not using that entrance, Remote should remain exactly the same pain as it
always was.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.79 2003/02/13 18:11:26 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # YEAR=2001
   29: # 2/13-12/7 Guy Albertelli
   30: # 12/21 Gerd Kortemeyer
   31: # 12/25,12/28 Gerd Kortemeyer
   32: # YEAR=2002
   33: # 1/4 Gerd Kortemeyer
   34: # 6/24,7/2 H. K. Ng
   35: 
   36: # Makes a table out of the previous attempts
   37: # Inputs result_from_symbread, user, domain, course_id
   38: # Reads in non-network-related .tab files
   39: 
   40: # POD header:
   41: 
   42: =pod
   43: 
   44: =head1 NAME
   45: 
   46: Apache::loncommon - pile of common routines
   47: 
   48: =head1 SYNOPSIS
   49: 
   50: Referenced by other mod_perl Apache modules.
   51: 
   52: Invocation:
   53:  &Apache::loncommon::SUBROUTINENAME(ARGUMENTS);
   54: 
   55: =head1 INTRODUCTION
   56: 
   57: Common collection of used subroutines.  This collection helps remove
   58: redundancy from other modules and increase efficiency of memory usage.
   59: 
   60: Current things done:
   61: 
   62:  Makes a table out of the previous homework attempts
   63:  Inputs result_from_symbread, user, domain, course_id
   64:  Reads in non-network-related .tab files
   65: 
   66: This is part of the LearningOnline Network with CAPA project
   67: described at http://www.lon-capa.org.
   68: 
   69: =head2 General Subroutines
   70: 
   71: =over 4
   72: 
   73: =cut 
   74: 
   75: # End of POD header
   76: package Apache::loncommon;
   77: 
   78: use strict;
   79: use Apache::lonnet();
   80: use GDBM_File;
   81: use POSIX qw(strftime mktime);
   82: use Apache::Constants qw(:common);
   83: use Apache::lonmsg();
   84: my $readit;
   85: 
   86: =pod 
   87: 
   88: =item Global Variables
   89: 
   90: =over 4
   91: 
   92: =cut
   93: # ----------------------------------------------- Filetypes/Languages/Copyright
   94: my %language;
   95: my %cprtag;
   96: my %fe; my %fd;
   97: my %category_extensions;
   98: 
   99: # ---------------------------------------------- Designs
  100: 
  101: my %designhash;
  102: 
  103: # ---------------------------------------------- Thesaurus variables
  104: 
  105: =pod
  106: 
  107: =item %Keywords  
  108: 
  109: A hash used by &keyword to determine if a word is considered a keyword.
  110: 
  111: =item $thesaurus_db_file
  112: 
  113: Scalar containing the full path to the thesaurus database.                 
  114: 
  115: =cut
  116: 
  117: my %Keywords;
  118: my $thesaurus_db_file;
  119: 
  120: 
  121: =pod
  122: 
  123: =back
  124: 
  125: =cut
  126: 
  127: # ----------------------------------------------------------------------- BEGIN
  128: 
  129: =pod
  130: 
  131: =item BEGIN() 
  132: 
  133: Initialize values from language.tab, copyright.tab, filetypes.tab,
  134: thesaurus.tab, and filecategories.tab.
  135: 
  136: =cut
  137: 
  138: # ----------------------------------------------------------------------- BEGIN
  139: 
  140: BEGIN {
  141:     # Variable initialization
  142:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  143:     #
  144:     unless ($readit) {
  145: # ------------------------------------------------------------------- languages
  146:     {
  147: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  148: 				 '/language.tab');
  149: 	if ($fh) {
  150: 	    while (<$fh>) {
  151: 		next if /^\#/;
  152: 		chomp;
  153: 		my ($key,$val)=(split(/\s+/,$_,2));
  154: 		$language{$key}=$val;
  155: 	    }
  156: 	}
  157:     }
  158: # ------------------------------------------------------------------ copyrights
  159:     {
  160: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonIncludes'}.
  161: 				  '/copyright.tab');
  162: 	if ($fh) {
  163: 	    while (<$fh>) {
  164: 		next if /^\#/;
  165: 		chomp;
  166: 		my ($key,$val)=(split(/\s+/,$_,2));
  167: 		$cprtag{$key}=$val;
  168: 	    }
  169: 	}
  170:     }
  171: 
  172: # -------------------------------------------------------------- domain designs
  173: 
  174:     my $filename;
  175:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  176:     opendir(DIR,$designdir);
  177:     while ($filename=readdir(DIR)) {
  178: 	my ($domain)=($filename=~/^(\w+)\./);
  179:     {
  180: 	my $fh=Apache::File->new($designdir.'/'.$filename);
  181: 	if ($fh) {
  182: 	    while (<$fh>) {
  183: 		next if /^\#/;
  184: 		chomp;
  185: 		my ($key,$val)=(split(/\=/,$_));
  186: 		if ($val) { $designhash{$domain.'.'.$key}=$val; }
  187: 	    }
  188: 	}
  189:     }
  190: 
  191:     }
  192:     closedir(DIR);
  193: 
  194: 
  195: # ------------------------------------------------------------- file categories
  196:     {
  197: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  198: 				  '/filecategories.tab');
  199: 	if ($fh) {
  200: 	    while (<$fh>) {
  201: 		next if /^\#/;
  202: 		chomp;
  203: 		my ($extension,$category)=(split(/\s+/,$_,2));
  204: 		push @{$category_extensions{lc($category)}},$extension;
  205: 	    }
  206: 	}
  207:     }
  208: # ------------------------------------------------------------------ file types
  209:     {
  210: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
  211: 	       '/filetypes.tab');
  212: 	if ($fh) {
  213:             while (<$fh>) {
  214: 		next if (/^\#/);
  215: 		chomp;
  216: 		my ($ending,$emb,$descr)=split(/\s+/,$_,3);
  217: 		if ($descr ne '') { 
  218: 		    $fe{$ending}=lc($emb);
  219: 		    $fd{$ending}=$descr;
  220: 		}
  221: 	    }
  222: 	}
  223:     }
  224:     &Apache::lonnet::logthis(
  225:               "<font color=yellow>INFO: Read file types</font>");
  226:     $readit=1;
  227:     }  # end of unless($readit) 
  228:     
  229: }
  230: # ============================================================= END BEGIN BLOCK
  231: ###############################################################
  232: ##           HTML and Javascript Helper Functions            ##
  233: ###############################################################
  234: 
  235: =pod 
  236: 
  237: =item browser_and_searcher_javascript 
  238: 
  239: Returns scalar containing javascript to open a browser window
  240: or a searcher window.  Also creates 
  241: 
  242: =over 4
  243: 
  244: =item openbrowser(formname,elementname,only,omit) [javascript]
  245: 
  246: inputs: formname, elementname, only, omit
  247: 
  248: formname and elementname indicate the name of the html form and name of
  249: the element that the results of the browsing selection are to be placed in. 
  250: 
  251: Specifying 'only' will restrict the browser to displaying only files
  252: with the given extension.  Can be a comma seperated list.
  253: 
  254: Specifying 'omit' will restrict the browser to NOT displaying files
  255: with the given extension.  Can be a comma seperated list.
  256: 
  257: =item opensearcher(formname, elementname) [javascript]
  258: 
  259: Inputs: formname, elementname
  260: 
  261: formname and elementname specify the name of the html form and the name
  262: of the element the selection from the search results will be placed in.
  263: 
  264: =back
  265: 
  266: =cut
  267: 
  268: ###############################################################
  269: sub browser_and_searcher_javascript {
  270:     return <<END;
  271:     var editbrowser = null;
  272:     function openbrowser(formname,elementname,only,omit) {
  273:         var url = '/res/?';
  274:         if (editbrowser == null) {
  275:             url += 'launch=1&';
  276:         }
  277:         url += 'catalogmode=interactive&';
  278:         url += 'mode=edit&';
  279:         url += 'form=' + formname + '&';
  280:         if (only != null) {
  281:             url += 'only=' + only + '&';
  282:         } 
  283:         if (omit != null) {
  284:             url += 'omit=' + omit + '&';
  285:         }
  286:         url += 'element=' + elementname + '';
  287:         var title = 'Browser';
  288:         var options = 'scrollbars=1,resizable=1,menubar=0';
  289:         options += ',width=700,height=600';
  290:         editbrowser = open(url,title,options,'1');
  291:         editbrowser.focus();
  292:     }
  293:     var editsearcher;
  294:     function opensearcher(formname,elementname) {
  295:         var url = '/adm/searchcat?';
  296:         if (editsearcher == null) {
  297:             url += 'launch=1&';
  298:         }
  299:         url += 'catalogmode=interactive&';
  300:         url += 'mode=edit&';
  301:         url += 'form=' + formname + '&';
  302:         url += 'element=' + elementname + '';
  303:         var title = 'Search';
  304:         var options = 'scrollbars=1,resizable=1,menubar=0';
  305:         options += ',width=700,height=600';
  306:         editsearcher = open(url,title,options,'1');
  307:         editsearcher.focus();
  308:     }
  309: END
  310: }
  311: 
  312: sub studentbrowser_javascript {
  313:    unless ($ENV{'request.course.id'}) { return ''; }  
  314:    unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
  315:         return '';
  316:    }
  317:    return (<<'ENDSTDBRW');
  318: <script type="text/javascript" language="Javascript" >
  319:     var stdeditbrowser;
  320:     function openstdbrowser(formname,uname,udom) {
  321:         var url = '/adm/pickstudent?';
  322:         var filter;
  323:         eval('filter=document.'+formname+'.'+uname+'.value;');
  324:         if (filter != null) {
  325:            if (filter != '') {
  326:                url += 'filter='+filter+'&';
  327: 	   }
  328:         }
  329:         url += 'form=' + formname + '&unameelement='+uname+
  330:                                     '&udomelement='+udom;
  331:         var title = 'Student Browser';
  332:         var options = 'scrollbars=1,resizable=1,menubar=0';
  333:         options += ',width=700,height=600';
  334:         stdeditbrowser = open(url,title,options,'1');
  335:         stdeditbrowser.focus();
  336:     }
  337: </script>
  338: ENDSTDBRW
  339: }
  340: 
  341: sub selectstudent_link {
  342:     my ($form,$unameele,$udomele)=@_;
  343:    unless ($ENV{'request.course.id'}) { return ''; }  
  344:    unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
  345:         return '';
  346:    }
  347:     return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
  348:         '","'.$udomele.'");'."'>Select</a>";
  349: }
  350: 
  351: ###############################################################
  352: 
  353: =pod
  354: 
  355: =item linked_select_forms(...)
  356: 
  357: linked_select_forms returns a string containing a <script></script> block
  358: and html for two <select> menus.  The select menus will be linked in that
  359: changing the value of the first menu will result in new values being placed
  360: in the second menu.  The values in the select menu will appear in alphabetical
  361: order.
  362: 
  363: linked_select_forms takes the following ordered inputs:
  364: 
  365: =over 4
  366: 
  367: =item $formname, the name of the <form> tag
  368: 
  369: =item $middletext, the text which appears between the <select> tags
  370: 
  371: =item $firstdefault, the default value for the first menu
  372: 
  373: =item $firstselectname, the name of the first <select> tag
  374: 
  375: =item $secondselectname, the name of the second <select> tag
  376: 
  377: =item $hashref, a reference to a hash containing the data for the menus.
  378: 
  379: =back 
  380: 
  381: Below is an example of such a hash.  Only the 'text', 'default', and 
  382: 'select2' keys must appear as stated.  keys(%menu) are the possible 
  383: values for the first select menu.  The text that coincides with the 
  384: first menu value is given in $menu{$choice1}->{'text'}.  The values 
  385: and text for the second menu are given in the hash pointed to by 
  386: $menu{$choice1}->{'select2'}.  
  387: 
  388: my %menu = ( A1 => { text =>"Choice A1" ,
  389:                       default => "B3",
  390:                       select2 => { 
  391:                           B1 => "Choice B1",
  392:                           B2 => "Choice B2",
  393:                           B3 => "Choice B3",
  394:                           B4 => "Choice B4"
  395:                           }
  396:                   },
  397:               A2 => { text =>"Choice A2" ,
  398:                       default => "C2",
  399:                       select2 => { 
  400:                           C1 => "Choice C1",
  401:                           C2 => "Choice C2",
  402:                           C3 => "Choice C3"
  403:                           }
  404:                   },
  405:               A3 => { text =>"Choice A3" ,
  406:                       default => "D6",
  407:                       select2 => { 
  408:                           D1 => "Choice D1",
  409:                           D2 => "Choice D2",
  410:                           D3 => "Choice D3",
  411:                           D4 => "Choice D4",
  412:                           D5 => "Choice D5",
  413:                           D6 => "Choice D6",
  414:                           D7 => "Choice D7"
  415:                           }
  416:                   }
  417:               );
  418: 
  419: =cut
  420: 
  421: # ------------------------------------------------
  422: 
  423: sub linked_select_forms {
  424:     my ($formname,
  425:         $middletext,
  426:         $firstdefault,
  427:         $firstselectname,
  428:         $secondselectname, 
  429:         $hashref
  430:         ) = @_;
  431:     my $second = "document.$formname.$secondselectname";
  432:     my $first = "document.$formname.$firstselectname";
  433:     # output the javascript to do the changing
  434:     my $result = '';
  435:     $result.="<script>\n";
  436:     $result.="var select2data = new Object();\n";
  437:     $" = '","';
  438:     my $debug = '';
  439:     foreach my $s1 (sort(keys(%$hashref))) {
  440:         $result.="select2data.d_$s1 = new Object();\n";        
  441:         $result.="select2data.d_$s1.def = new String('".
  442:             $hashref->{$s1}->{'default'}."');\n";
  443:         $result.="select2data.d_$s1.values = new Array(";        
  444:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
  445:         $result.="\"@s2values\");\n";
  446:         $result.="select2data.d_$s1.texts = new Array(";        
  447:         my @s2texts;
  448:         foreach my $value (@s2values) {
  449:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
  450:         }
  451:         $result.="\"@s2texts\");\n";
  452:     }
  453:     $"=' ';
  454:     $result.= <<"END";
  455: 
  456: function select1_changed() {
  457:     // Determine new choice
  458:     var newvalue = "d_" + $first.value;
  459:     // update select2
  460:     var values     = select2data[newvalue].values;
  461:     var texts      = select2data[newvalue].texts;
  462:     var select2def = select2data[newvalue].def;
  463:     var i;
  464:     // out with the old
  465:     for (i = 0; i < $second.options.length; i++) {
  466:         $second.options[i] = null;
  467:     }
  468:     // in with the nuclear
  469:     for (i=0;i<values.length; i++) {
  470:         $second.options[i] = new Option(values[i]);
  471:         $second.options[i].text = texts[i];
  472:         if (values[i] == select2def) {
  473:             $second.options[i].selected = true;
  474:         }
  475:     }
  476: }
  477: </script>
  478: END
  479:     # output the initial values for the selection lists
  480:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
  481:     foreach my $value (sort(keys(%$hashref))) {
  482:         $result.="    <option value=\"$value\" ";
  483:         $result.=" selected=\"true\" " if ($value eq $firstdefault);
  484:         $result.=">$hashref->{$value}->{'text'}</option>\n";
  485:     }
  486:     $result .= "</select>\n";
  487:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
  488:     $result .= $middletext;
  489:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
  490:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
  491:     foreach my $value (sort(keys(%select2))) {
  492:         $result.="    <option value=\"$value\" ";        
  493:         $result.=" selected=\"true\" " if ($value eq $seconddefault);
  494:         $result.=">$select2{$value}</option>\n";
  495:     }
  496:     $result .= "</select>\n";
  497:     #    return $debug;
  498:     return $result;
  499: }   #  end of sub linked_select_forms {
  500: 
  501: ###############################################################
  502: 
  503: =pod
  504: 
  505: =item help_open_topic($topic, $text, $stayOnPage, $width, $height)
  506: 
  507: Returns a string corresponding to an HTML link to the given help $topic, where $topic corresponds to the name of a .tex file in /home/httpd/html/adm/help/tex, with underscores replaced by spaces.
  508: 
  509: $text will optionally be linked to the same topic, allowing you to link text in addition to the graphic. If you do not want to link text, but wish to specify one of the later parameters, pass an empty string.
  510: 
  511: $stayOnPage is a value that will be interpreted as a boolean. If true, the link will not open a new window. If false, the link will open a new window using Javascript. (Default is false.)
  512: 
  513: $width and $height are optional numerical parameters that will override the width and height of the popped up window, which may be useful for certain help topics with big pictures included.
  514: 
  515: =cut
  516: 
  517: sub help_open_topic {
  518:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
  519:     $text = "" if (not defined $text);
  520:     $stayOnPage = 0 if (not defined $stayOnPage);
  521:     if ($ENV{'browser.interface'} eq 'textual') {
  522: 	$stayOnPage=1;
  523:     }
  524:     $width = 350 if (not defined $width);
  525:     $height = 400 if (not defined $height);
  526:     my $filename = $topic;
  527:     $filename =~ s/ /_/g;
  528: 
  529:     my $template = "";
  530:     my $link;
  531: 
  532:     if (!$stayOnPage)
  533:     {
  534: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
  535:     }
  536:     else
  537:     {
  538: 	$link = "/adm/help/${filename}.hlp";
  539:     }
  540: 
  541:     # Add the text
  542:     if ($text ne "")
  543:     {
  544: 	$template .= 
  545:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
  546:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
  547:     }
  548: 
  549:     # Add the graphic
  550:     $template .= <<"ENDTEMPLATE";
  551:  <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
  552: ENDTEMPLATE
  553:     if ($text ne '') { $template.='</td></tr></table>' };
  554:     return $template;
  555: 
  556: }
  557: 
  558: =pod
  559: 
  560: =item csv_translate($text) 
  561: 
  562: Translate $text to allow it to be output as a 'comma seperated values' 
  563: format.
  564: 
  565: =cut
  566: 
  567: sub csv_translate {
  568:     my $text = shift;
  569:     $text =~ s/\"/\"\"/g;
  570:     $text =~ s/\n//g;
  571:     return $text;
  572: }
  573: 
  574: ###############################################################
  575: ##        Home server <option> list generating code          ##
  576: ###############################################################
  577: #-------------------------------------------
  578: 
  579: =pod
  580: 
  581: =item get_domains()
  582: 
  583: Returns an array containing each of the domains listed in the hosts.tab
  584: file.
  585: 
  586: =cut
  587: 
  588: #-------------------------------------------
  589: sub get_domains {
  590:     # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
  591:     my @domains;
  592:     my %seen;
  593:     foreach (sort values(%Apache::lonnet::hostdom)) {
  594:         push (@domains,$_) unless $seen{$_}++;
  595:     }
  596:     return @domains;
  597: }
  598: 
  599: #-------------------------------------------
  600: 
  601: =pod
  602: 
  603: =item select_dom_form($defdom,$name)
  604: 
  605: Returns a string containing a <select name='$name' size='1'> form to 
  606: allow a user to select the domain to preform an operation in.  
  607: See loncreateuser.pm for an example invocation and use.
  608: 
  609: =cut
  610: 
  611: #-------------------------------------------
  612: sub select_dom_form {
  613:     my ($defdom,$name) = @_;
  614:     my @domains = get_domains();
  615:     my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
  616:     foreach (@domains) {
  617:         $selectdomain.="<option value=\"$_\" ".
  618:             ($_ eq $defdom ? 'selected' : '').
  619:                 ">$_</option>\n";
  620:     }
  621:     $selectdomain.="</select>";
  622:     return $selectdomain;
  623: }
  624: 
  625: #-------------------------------------------
  626: 
  627: =pod
  628: 
  629: =item get_library_servers($domain)
  630: 
  631: Returns a hash which contains keys like '103l3' and values like 
  632: 'kirk.lite.msu.edu'.  All of the keys will be for machines in the
  633: given $domain.
  634: 
  635: =cut
  636: 
  637: #-------------------------------------------
  638: sub get_library_servers {
  639:     my $domain = shift;
  640:     my %library_servers;
  641:     foreach (keys(%Apache::lonnet::libserv)) {
  642:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
  643:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
  644:         }
  645:     }
  646:     return %library_servers;
  647: }
  648: 
  649: #-------------------------------------------
  650: 
  651: =pod
  652: 
  653: =item home_server_option_list($domain)
  654: 
  655: returns a string which contains an <option> list to be used in a 
  656: <select> form input.  See loncreateuser.pm for an example.
  657: 
  658: =cut
  659: 
  660: #-------------------------------------------
  661: sub home_server_option_list {
  662:     my $domain = shift;
  663:     my %servers = &get_library_servers($domain);
  664:     my $result = '';
  665:     foreach (sort keys(%servers)) {
  666:         $result.=
  667:             '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
  668:     }
  669:     return $result;
  670: }
  671: ###############################################################
  672: ##    End of home server <option> list generating code       ##
  673: ###############################################################
  674: 
  675: ###############################################################
  676: ##    Authentication changing form generation subroutines    ##
  677: ###############################################################
  678: ##
  679: ## All of the authform_xxxxxxx subroutines take their inputs in a
  680: ## hash, and have reasonable default values.
  681: ##
  682: ##    formname = the name given in the <form> tag.
  683: #-------------------------------------------
  684: 
  685: =pod
  686: 
  687: =item authform_xxxxxx
  688: 
  689: The authform_xxxxxx subroutines provide javascript and html forms which 
  690: handle some of the conveniences required for authentication forms.  
  691: This is not an optimal method, but it works.  
  692: 
  693: See loncreateuser.pm for invocation and use examples.
  694: 
  695: =over 4
  696: 
  697: =item authform_header
  698: 
  699: =item authform_authorwarning
  700: 
  701: =item authform_nochange
  702: 
  703: =item authform_kerberos
  704: 
  705: =item authform_internal
  706: 
  707: =item authform_filesystem
  708: 
  709: =back
  710: 
  711: =cut
  712: 
  713: #-------------------------------------------
  714: sub authform_header{  
  715:     my %in = (
  716:         formname => 'cu',
  717:         kerb_def_dom => 'MSU.EDU',
  718:         @_,
  719:     );
  720:     $in{'formname'} = 'document.' . $in{'formname'};
  721:     my $result='';
  722:     $result.=<<"END";
  723: var current = new Object();
  724: current.radiovalue = 'nochange';
  725: current.argfield = null;
  726: 
  727: function changed_radio(choice,currentform) {
  728:     var choicearg = choice + 'arg';
  729:     // If a radio button in changed, we need to change the argfield
  730:     if (current.radiovalue != choice) {
  731:         current.radiovalue = choice;
  732:         if (current.argfield != null) {
  733:             currentform.elements[current.argfield].value = '';
  734:         }
  735:         if (choice == 'nochange') {
  736:             current.argfield = null;
  737:         } else {
  738:             current.argfield = choicearg;
  739:             switch(choice) {
  740:                 case 'krb': 
  741:                     currentform.elements[current.argfield].value = 
  742:                         "$in{'kerb_def_dom'}";
  743:                 break;
  744:               default:
  745:                 break;
  746:             }
  747:         }
  748:     }
  749:     return;
  750: }
  751: 
  752: function changed_text(choice,currentform) {
  753:     var choicearg = choice + 'arg';
  754:     if (currentform.elements[choicearg].value !='') {
  755:         switch (choice) {
  756:             case 'krb': currentform.elements[choicearg].value =
  757:                 currentform.elements[choicearg].value.toUpperCase();
  758:                 break;
  759:             default:
  760:         }
  761:         // clear old field
  762:         if ((current.argfield != choicearg) && (current.argfield != null)) {
  763:             currentform.elements[current.argfield].value = '';
  764:         }
  765:         current.argfield = choicearg;
  766:     }
  767:     set_auth_radio_buttons(choice,currentform);
  768:     return;
  769: }
  770: 
  771: function set_auth_radio_buttons(newvalue,currentform) {
  772:     var i=0;
  773:     while (i < currentform.login.length) {
  774:         if (currentform.login[i].value == newvalue) { break; }
  775:         i++;
  776:     }
  777:     if (i == currentform.login.length) {
  778:         return;
  779:     }
  780:     current.radiovalue = newvalue;
  781:     currentform.login[i].checked = true;
  782:     return;
  783: }
  784: END
  785:     return $result;
  786: }
  787: 
  788: sub authform_authorwarning{
  789:     my $result='';
  790:     $result=<<"END";
  791: <i>As a general rule, only authors or co-authors should be filesystem
  792: authenticated (which allows access to the server filesystem).</i>
  793: END
  794:     return $result;
  795: }
  796: 
  797: sub authform_nochange{  
  798:     my %in = (
  799:               formname => 'document.cu',
  800:               kerb_def_dom => 'MSU.EDU',
  801:               @_,
  802:           );
  803:     my $result='';
  804:     $result.=<<"END";
  805: <input type="radio" name="login" value="nochange" checked="checked"
  806:        onclick="javascript:changed_radio('nochange',$in{'formname'});" />
  807: Do not change login data
  808: END
  809:     return $result;
  810: }
  811: 
  812: sub authform_kerberos{  
  813:     my %in = (
  814:               formname => 'document.cu',
  815:               kerb_def_dom => 'MSU.EDU',
  816:               @_,
  817:               );
  818:     my $result='';
  819:     $result.=<<"END";
  820: <input type="radio" name="login" value="krb" 
  821:        onclick="javascript:changed_radio('krb',$in{'formname'});"
  822:        onchange="javascript:changed_radio('krb',$in{'formname'});" />
  823: Kerberos authenticated with domain
  824: <input type="text" size="10" name="krbarg" value=""
  825:        onchange="javascript:changed_text('krb',$in{'formname'});" />
  826: <input type="radio" name="krbver" value="4" checked="on" />Version 4
  827: <input type="radio" name="krbver" value="5" />Version 5
  828: END
  829:     return $result;
  830: }
  831: 
  832: sub authform_internal{  
  833:     my %args = (
  834:                 formname => 'document.cu',
  835:                 kerb_def_dom => 'MSU.EDU',
  836:                 @_,
  837:                 );
  838:     my $result='';
  839:     $result.=<<"END";
  840: <input type="radio" name="login" value="int"
  841:        onchange="javascript:changed_radio('int',$args{'formname'});"
  842:        onclick="javascript:changed_radio('int',$args{'formname'});" />
  843: Internally authenticated (with initial password 
  844: <input type="text" size="10" name="intarg" value=""
  845:        onchange="javascript:changed_text('int',$args{'formname'});" />)
  846: END
  847:     return $result;
  848: }
  849: 
  850: sub authform_local{  
  851:     my %in = (
  852:               formname => 'document.cu',
  853:               kerb_def_dom => 'MSU.EDU',
  854:               @_,
  855:               );
  856:     my $result='';
  857:     $result.=<<"END";
  858: <input type="radio" name="login" value="loc"
  859:        onchange="javascript:changed_radio('loc',$in{'formname'});"
  860:        onclick="javascript:changed_radio('loc',$in{'formname'});" />
  861: Local Authentication with argument
  862: <input type="text" size="10" name="locarg" value=""
  863:        onchange="javascript:changed_text('loc',$in{'formname'});" />
  864: END
  865:     return $result;
  866: }
  867: 
  868: sub authform_filesystem{  
  869:     my %in = (
  870:               formname => 'document.cu',
  871:               kerb_def_dom => 'MSU.EDU',
  872:               @_,
  873:               );
  874:     my $result='';
  875:     $result.=<<"END";
  876: <input type="radio" name="login" value="fsys" 
  877:        onchange="javascript:changed_radio('fsys',$in{'formname'});"
  878:        onclick="javascript:changed_radio('fsys',$in{'formname'});" />
  879: Filesystem authenticated (with initial password 
  880: <input type="text" size="10" name="fsysarg" value=""
  881:        onchange="javascript:changed_text('fsys',$in{'formname'});">)
  882: END
  883:     return $result;
  884: }
  885: 
  886: ###############################################################
  887: ##   End Authentication changing form generation functions   ##
  888: ###############################################################
  889: 
  890: ###############################################################
  891: ##                Thesaurus Functions                        ##
  892: ###############################################################
  893: 
  894: =pod
  895: 
  896: =item initialize_keywords
  897: 
  898: Initializes the package variable %Keywords if it is empty.  Uses the
  899: package variable $thesaurus_db_file.
  900: 
  901: =cut
  902: 
  903: ###################################################
  904: 
  905: sub initialize_keywords {
  906:     return 1 if (scalar keys(%Keywords));
  907:     # If we are here, %Keywords is empty, so fill it up
  908:     #   Make sure the file we need exists...
  909:     if (! -e $thesaurus_db_file) {
  910:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
  911:                                  " failed because it does not exist");
  912:         return 0;
  913:     }
  914:     #   Set up the hash as a database
  915:     my %thesaurus_db;
  916:     if (! tie(%thesaurus_db,'GDBM_File',
  917:               $thesaurus_db_file,&GDBM_READER(),0640)){
  918:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
  919:                                  $thesaurus_db_file);
  920:         return 0;
  921:     } 
  922:     #  Get the average number of appearances of a word.
  923:     my $avecount = $thesaurus_db{'average.count'};
  924:     #  Put keywords (those that appear > average) into %Keywords
  925:     while (my ($word,$data)=each (%thesaurus_db)) {
  926:         my ($count,undef) = split /:/,$data;
  927:         $Keywords{$word}++ if ($count > $avecount);
  928:     }
  929:     untie %thesaurus_db;
  930:     # Remove special values from %Keywords.
  931:     foreach ('total.count','average.count') {
  932:         delete($Keywords{$_}) if (exists($Keywords{$_}));
  933:     }
  934:     return 1;
  935: }
  936: 
  937: ###################################################
  938: 
  939: =pod
  940: 
  941: =item keyword($word)
  942: 
  943: Returns true if $word is a keyword.  A keyword is a word that appears more 
  944: than the average number of times in the thesaurus database.  Calls 
  945: &initialize_keywords
  946: 
  947: =cut
  948: 
  949: ###################################################
  950: 
  951: sub keyword {
  952:     return if (!&initialize_keywords());
  953:     my $word=lc(shift());
  954:     $word=~s/\W//g;
  955:     return exists($Keywords{$word});
  956: }
  957: 
  958: ###############################################################
  959: 
  960: =pod 
  961: 
  962: =item get_related_words
  963: 
  964: Look up a word in the thesaurus.  Takes a scalar arguement and returns
  965: an array of words.  If the keyword is not in the thesaurus, an empty array
  966: will be returned.  The order of the words returned is determined by the
  967: database which holds them.
  968: 
  969: Uses global $thesaurus_db_file.
  970: 
  971: =cut
  972: 
  973: ###############################################################
  974: sub get_related_words {
  975:     my $keyword = shift;
  976:     my %thesaurus_db;
  977:     if (! -e $thesaurus_db_file) {
  978:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
  979:                                  "failed because the file does not exist");
  980:         return ();
  981:     }
  982:     if (! tie(%thesaurus_db,'GDBM_File',
  983:               $thesaurus_db_file,&GDBM_READER(),0640)){
  984:         return ();
  985:     } 
  986:     my @Words=();
  987:     if (exists($thesaurus_db{$keyword})) {
  988:         $_ = $thesaurus_db{$keyword};
  989:         (undef,@Words) = split/:/;  # The first element is the number of times
  990:                                     # the word appears.  We do not need it now.
  991:         for (my $i=0;$i<=$#Words;$i++) {
  992:             ($Words[$i],undef)= split/\,/,$Words[$i];
  993:         }
  994:     }
  995:     untie %thesaurus_db;
  996:     return @Words;
  997: }
  998: 
  999: ###############################################################
 1000: ##              End Thesaurus Functions                      ##
 1001: ###############################################################
 1002: 
 1003: # -------------------------------------------------------------- Plaintext name
 1004: 
 1005: sub plainname {
 1006:     my ($uname,$udom)=@_;
 1007:     my %names=&Apache::lonnet::get('environment',
 1008:                     ['firstname','middlename','lastname','generation'],
 1009: 					 $udom,$uname);
 1010:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1011: 	$names{'lastname'}.' '.$names{'generation'};
 1012:     $name=~s/\s+$//;
 1013:     $name=~s/\s+/ /g;
 1014:     return $name;
 1015: }
 1016: 
 1017: # -------------------------------------------------------------------- Nickname
 1018: 
 1019: 
 1020: sub nickname {
 1021:     my ($uname,$udom)=@_;
 1022:     my %names=&Apache::lonnet::get('environment',
 1023:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
 1024:     my $name=$names{'nickname'};
 1025:     if ($name) {
 1026:        $name='&quot;'.$name.'&quot;'; 
 1027:     } else {
 1028:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 1029: 	     $names{'lastname'}.' '.$names{'generation'};
 1030:        $name=~s/\s+$//;
 1031:        $name=~s/\s+/ /g;
 1032:     }
 1033:     return $name;
 1034: }
 1035: 
 1036: 
 1037: # ------------------------------------------------------------------ Screenname
 1038: 
 1039: sub screenname {
 1040:     my ($uname,$udom)=@_;
 1041:     my %names=
 1042:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 1043:     return $names{'screenname'};
 1044: }
 1045: 
 1046: # ------------------------------------------------------------- Message Wrapper
 1047: 
 1048: sub messagewrapper {
 1049:     my ($link,$un,$do)=@_;
 1050:     return 
 1051: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
 1052: }
 1053: # --------------------------------------------------------------- Notes Wrapper
 1054: 
 1055: sub noteswrapper {
 1056:     my ($link,$un,$do)=@_;
 1057:     return 
 1058: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
 1059: }
 1060: # ------------------------------------------------------------- Aboutme Wrapper
 1061: 
 1062: sub aboutmewrapper {
 1063:     my ($link,$username,$domain)=@_;
 1064:     return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
 1065: }
 1066: 
 1067: # ------------------------------------------------------------ Syllabus Wrapper
 1068: 
 1069: 
 1070: sub syllabuswrapper {
 1071:     my ($link,$un,$do,$tf)=@_;
 1072:     if ($tf) { $link='<font color="'.$tf.'">'.$link.'</font>'; }
 1073:     return "<a href='/public/$do/$un/syllabus'>$link</a>";
 1074: }
 1075: 
 1076: # ---------------------------------------------------------------- Language IDs
 1077: sub languageids {
 1078:     return sort(keys(%language));
 1079: }
 1080: 
 1081: # -------------------------------------------------------- Language Description
 1082: sub languagedescription {
 1083:     return $language{shift(@_)};
 1084: }
 1085: 
 1086: # --------------------------------------------------------------- Copyright IDs
 1087: sub copyrightids {
 1088:     return sort(keys(%cprtag));
 1089: }
 1090: 
 1091: # ------------------------------------------------------- Copyright Description
 1092: sub copyrightdescription {
 1093:     return $cprtag{shift(@_)};
 1094: }
 1095: 
 1096: # ------------------------------------------------------------- File Categories
 1097: sub filecategories {
 1098:     return sort(keys(%category_extensions));
 1099: }
 1100: 
 1101: # -------------------------------------- File Types within a specified category
 1102: sub filecategorytypes {
 1103:     return @{$category_extensions{lc($_[0])}};
 1104: }
 1105: 
 1106: # ------------------------------------------------------------------ File Types
 1107: sub fileextensions {
 1108:     return sort(keys(%fe));
 1109: }
 1110: 
 1111: # ------------------------------------------------------------- Embedding Style
 1112: sub fileembstyle {
 1113:     return $fe{lc(shift(@_))};
 1114: }
 1115: 
 1116: # ------------------------------------------------------------ Description Text
 1117: sub filedescription {
 1118:     return $fd{lc(shift(@_))};
 1119: }
 1120: 
 1121: # ------------------------------------------------------------ Description Text
 1122: sub filedescriptionex {
 1123:     my $ex=shift;
 1124:     return '.'.$ex.' '.$fd{lc($ex)};
 1125: }
 1126: 
 1127: # ---- Retrieve attempts by students
 1128: # input
 1129: # $symb             - problem including path
 1130: # $username,$domain - that of the student
 1131: # $course           - course name
 1132: # $getattempt       - leave blank if want all attempts, else put something.
 1133: # $regexp           - regular expression. If string matches regexp send to
 1134: # $gradesub         - routine that process the string if it matches regexp
 1135: # 
 1136: # output
 1137: # formatted as a table all the attempts, if any.
 1138: #
 1139: sub get_previous_attempt {
 1140:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 1141:   my $prevattempts='';
 1142:   no strict 'refs';
 1143:   if ($symb) {
 1144:     my (%returnhash)=
 1145:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 1146:     if ($returnhash{'version'}) {
 1147:       my %lasthash=();
 1148:       my $version;
 1149:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 1150:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 1151: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
 1152:         }
 1153:       }
 1154:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1155:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
 1156:       foreach (sort(keys %lasthash)) {
 1157: 	my ($ign,@parts) = split(/\./,$_);
 1158: 	if ($#parts > 0) {
 1159: 	  my $data=$parts[-1];
 1160: 	  pop(@parts);
 1161: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
 1162: 	} else {
 1163: 	  if ($#parts == 0) {
 1164: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 1165: 	  } else {
 1166: 	    $prevattempts.='<th>'.$ign.'</th>';
 1167: 	  }
 1168: 	}
 1169:       }
 1170:       if ($getattempt eq '') {
 1171: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 1172: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
 1173: 	    foreach (sort(keys %lasthash)) {
 1174: 	       my $value;
 1175: 	       if ($_ =~ /timestamp/) {
 1176: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
 1177: 	       } else {
 1178: 		  $value=$returnhash{$version.':'.$_};
 1179: 	       }
 1180: 	       $prevattempts.='<td>'.$value.'&nbsp;</td>';   
 1181: 	    }
 1182: 	 }
 1183:       }
 1184:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
 1185:       foreach (sort(keys %lasthash)) {
 1186: 	my $value;
 1187: 	if ($_ =~ /timestamp/) {
 1188: 	  $value=scalar(localtime($lasthash{$_}));
 1189: 	} else {
 1190: 	  $value=$lasthash{$_};
 1191: 	}
 1192: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
 1193: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
 1194:       }
 1195:       $prevattempts.='</tr></table></td></tr></table>';
 1196:     } else {
 1197:       $prevattempts='Nothing submitted - no attempts.';
 1198:     }
 1199:   } else {
 1200:     $prevattempts='No data.';
 1201:   }
 1202: }
 1203: 
 1204: sub get_student_view {
 1205:   my ($symb,$username,$domain,$courseid,$target) = @_;
 1206:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1207:   my (%old,%moreenv);
 1208:   my @elements=('symb','courseid','domain','username');
 1209:   foreach my $element (@elements) {
 1210:     $old{$element}=$ENV{'form.grade_'.$element};
 1211:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1212:   }
 1213:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
 1214:   &Apache::lonnet::appenv(%moreenv);
 1215:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
 1216:   &Apache::lonnet::delenv('form.grade_');
 1217:   foreach my $element (@elements) {
 1218:     $ENV{'form.grade_'.$element}=$old{$element};
 1219:   }
 1220:   $userview=~s/\<body[^\>]*\>//gi;
 1221:   $userview=~s/\<\/body\>//gi;
 1222:   $userview=~s/\<html\>//gi;
 1223:   $userview=~s/\<\/html\>//gi;
 1224:   $userview=~s/\<head\>//gi;
 1225:   $userview=~s/\<\/head\>//gi;
 1226:   $userview=~s/action\s*\=/would_be_action\=/gi;
 1227:   return $userview;
 1228: }
 1229: 
 1230: sub get_student_answers {
 1231:   my ($symb,$username,$domain,$courseid) = @_;
 1232:   my ($map,$id,$feedurl) = split(/___/,$symb);
 1233:   my (%old,%moreenv);
 1234:   my @elements=('symb','courseid','domain','username');
 1235:   foreach my $element (@elements) {
 1236:     $old{$element}=$ENV{'form.grade_'.$element};
 1237:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
 1238:   }
 1239:   $moreenv{'form.grade_target'}='answer';
 1240:   &Apache::lonnet::appenv(%moreenv);
 1241:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
 1242:   &Apache::lonnet::delenv('form.grade_');
 1243:   foreach my $element (@elements) {
 1244:     $ENV{'form.grade_'.$element}=$old{$element};
 1245:   }
 1246:   return $userview;
 1247: }
 1248: 
 1249: ###############################################
 1250: 
 1251: 
 1252: sub timehash {
 1253:     my @ltime=localtime(shift);
 1254:     return ( 'seconds' => $ltime[0],
 1255:              'minutes' => $ltime[1],
 1256:              'hours'   => $ltime[2],
 1257:              'day'     => $ltime[3],
 1258:              'month'   => $ltime[4]+1,
 1259:              'year'    => $ltime[5]+1900,
 1260:              'weekday' => $ltime[6],
 1261:              'dayyear' => $ltime[7]+1,
 1262:              'dlsav'   => $ltime[8] );
 1263: }
 1264: 
 1265: sub maketime {
 1266:     my %th=@_;
 1267:     return POSIX::mktime(
 1268:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 1269:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
 1270: }
 1271: 
 1272: 
 1273: #########################################
 1274: #
 1275: # Retro-fixing of un-backward-compatible time format
 1276: 
 1277: sub unsqltime {
 1278:     my $timestamp=shift;
 1279:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
 1280:        $timestamp=&maketime(
 1281: 	   'year'=>$1,'month'=>$2,'day'=>$3,
 1282:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
 1283:     }
 1284:     return $timestamp;
 1285: }
 1286: 
 1287: #########################################
 1288: 
 1289: sub findallcourses {
 1290:     my %courses=();
 1291:     my $now=time;
 1292:     foreach (keys %ENV) {
 1293: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
 1294: 	    my ($starttime,$endtime)=$ENV{$_};
 1295:             my $active=1;
 1296:             if ($starttime) {
 1297: 		if ($now<$starttime) { $active=0; }
 1298:             }
 1299:             if ($endtime) {
 1300:                 if ($now>$endtime) { $active=0; }
 1301:             }
 1302:             if ($active) { $courses{$1.'_'.$2}=1; }
 1303:         }
 1304:     }
 1305:     return keys %courses;
 1306: }
 1307: 
 1308: ###############################################
 1309: ###############################################
 1310: 
 1311: =pod
 1312: 
 1313: =item &determinedomain()
 1314: 
 1315: Inputs: $domain (usually will be undef)
 1316: 
 1317: Returns: Determines which domain should be used for designs
 1318: 
 1319: =cut
 1320: 
 1321: ###############################################
 1322: sub determinedomain {
 1323:     my $domain=shift;
 1324:    if (! $domain) {
 1325:         # Determine domain if we have not been given one
 1326:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
 1327:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
 1328:         if ($ENV{'request.role.domain'}) { 
 1329:             $domain=$ENV{'request.role.domain'}; 
 1330:         }
 1331:     }
 1332:     return $domain;
 1333: }
 1334: ###############################################
 1335: =pod
 1336: 
 1337: =item &domainlogo()
 1338: 
 1339: Inputs: $domain (usually will be undef)
 1340: 
 1341: Returns: A link to a domain logo, if the domain logo exists.
 1342: If the domain logo does not exist, a description of the domain.
 1343: 
 1344: =cut
 1345: ###############################################
 1346: sub domainlogo {
 1347:     my $domain = &determinedomain(shift);    
 1348:      # See if there is a logo
 1349:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
 1350:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':8080/adm/lonDomLogos/'.
 1351:                $domain.'.gif" />';
 1352:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
 1353:         return $Apache::lonnet::domaindescription{$domain};
 1354:     } else {
 1355:         return '';
 1356:     }
 1357: }
 1358: ##############################################
 1359: 
 1360: =pod
 1361: 
 1362: =item &designparm()
 1363: 
 1364: Inputs: $which parameter; $domain (usually will be undef)
 1365: 
 1366: Returns: value of designparamter $which
 1367: 
 1368: =cut
 1369: ##############################################
 1370: sub designparm {
 1371:     my ($which,$domain)=@_;
 1372:     $domain=&determinedomain($domain);
 1373:     if ($designhash{$domain.'.'.$which}) {
 1374: 	return $designhash{$domain.'.'.$which};
 1375:     } else {
 1376:         return $designhash{'default.'.$which};
 1377:     }
 1378: }
 1379: 
 1380: ###############################################
 1381: ###############################################
 1382: 
 1383: =pod
 1384: 
 1385: =item &bodytag()
 1386: 
 1387: Returns a uniform header for LON-CAPA web pages.
 1388: 
 1389: Inputs: 
 1390: 
 1391:  $title, A title to be displayed on the page.
 1392:  $function, the current role (can be undef).
 1393:  $addentries, extra parameters for the <body> tag.
 1394:  $bodyonly, if defined, only return the <body> tag.
 1395:  $domain, if defined, force a given domain.
 1396: 
 1397: Returns: A uniform header for LON-CAPA web pages.  
 1398: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 1399: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 1400: other decorations will be returned.
 1401: 
 1402: =cut
 1403: 
 1404: ###############################################
 1405: 
 1406: 
 1407: ###############################################
 1408: sub bodytag {
 1409:     my ($title,$function,$addentries,$bodyonly,$domain)=@_;
 1410:     unless ($function) {
 1411: 	$function='student';
 1412:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
 1413: 	    $function='coordinator';
 1414:         }
 1415: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
 1416:             $function='admin';
 1417:         }
 1418:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
 1419:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
 1420:             $function='author';
 1421:         }
 1422:     }
 1423:     my $img=&designparm($function.'.img',$domain);
 1424:     my $pgbg=&designparm($function.'.pgbg',$domain);
 1425:     my $tabbg=&designparm($function.'.tabbg',$domain);
 1426:     my $font=&designparm($function.'.font',$domain);
 1427:     my $link=&designparm($function.'.link',$domain);
 1428:     my $alink=&designparm($function.'.alink',$domain);
 1429:     my $vlink=&designparm($function.'.vlink',$domain);
 1430:     my $sidebg=&designparm($function.'.sidebg',$domain);
 1431: 
 1432:  # role and realm
 1433:     my ($role,$realm)
 1434:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
 1435: # realm
 1436:     if ($ENV{'request.course.id'}) {
 1437: 	$realm=
 1438:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1439:     }
 1440:     unless ($realm) { $realm='&nbsp;'; }
 1441: # Set messages
 1442:     my $messages=&domainlogo($domain);
 1443: # Output
 1444:     my $bodytag = <<END;
 1445: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
 1446: $addentries>
 1447: END
 1448:     if ($bodyonly) {
 1449:         return $bodytag;
 1450:     } elsif ($ENV{'browser.interface'} eq 'textual') {
 1451:         return $bodytag.'<h1>LON-CAPA: '.$title.
 1452:          '</h1><a href="/adm/menu">Main Menu</a><hr />';
 1453:     } else {
 1454:         return(<<ENDBODY);
 1455: $bodytag
 1456: <table width="100%" cellspacing="0" border="0" cellpadding="0">
 1457: <tr><td bgcolor="$font">
 1458: <img src="http://$ENV{'HTTP_HOST'}:8080/$img" /></td>
 1459: <td bgcolor="$font"><font color='$sidebg'>$messages</font></td>
 1460: </tr>
 1461: <tr>
 1462: <td rowspan="3" bgcolor="$tabbg">
 1463: &nbsp;<font size="5"><b>$title</b></font>
 1464: <td bgcolor="$tabbg"  align="right">
 1465: <font size="2">
 1466:     $ENV{'environment.firstname'}
 1467:     $ENV{'environment.middlename'}
 1468:     $ENV{'environment.lastname'}
 1469:     $ENV{'environment.generation'}
 1470:     </font>&nbsp;
 1471: </td>
 1472: </tr>
 1473: <tr><td bgcolor="$tabbg" align="right">
 1474: <font size="2">$role</font>&nbsp;
 1475: </td></tr>
 1476: <tr>
 1477: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font>&nbsp;</td></tr>
 1478: </table><br>
 1479: ENDBODY
 1480:     }
 1481: }
 1482: ###############################################
 1483: 
 1484: sub get_unprocessed_cgi {
 1485:   my ($query,$possible_names)= @_;
 1486:   # $Apache::lonxml::debug=1;
 1487:   foreach (split(/&/,$query)) {
 1488:     my ($name, $value) = split(/=/,$_);
 1489:     $name = &Apache::lonnet::unescape($name);
 1490:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 1491:       $value =~ tr/+/ /;
 1492:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 1493:       &Apache::lonxml::debug("Seting :$name: to :$value:");
 1494:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 1495:     }
 1496:   }
 1497: }
 1498: 
 1499: sub cacheheader {
 1500:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 1501:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 1502:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 1503:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 1504:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 1505:   return $output;
 1506: }
 1507: 
 1508: sub no_cache {
 1509:   my ($r) = @_;
 1510:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
 1511:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 1512:   $r->no_cache(1);
 1513:   $r->header_out("Pragma" => "no-cache");
 1514:   #$r->header_out("Expires" => $date);
 1515: }
 1516: 
 1517: sub add_to_env {
 1518:   my ($name,$value)=@_;
 1519:   if (defined($ENV{$name})) {
 1520:     if (ref($ENV{$name})) {
 1521:       #already have multiple values
 1522:       push(@{ $ENV{$name} },$value);
 1523:     } else {
 1524:       #first time seeing multiple values, convert hash entry to an arrayref
 1525:       my $first=$ENV{$name};
 1526:       undef($ENV{$name});
 1527:       push(@{ $ENV{$name} },$first,$value);
 1528:     }
 1529:   } else {
 1530:     $ENV{$name}=$value;
 1531:   }
 1532: }
 1533: 
 1534: =pod
 1535: 
 1536: =back 
 1537: 
 1538: =head2 CSV Upload/Handling functions
 1539: 
 1540: =over 4
 1541: 
 1542: =item  upfile_store($r)
 1543: 
 1544: Store uploaded file, $r should be the HTTP Request object,
 1545: needs $ENV{'form.upfile'}
 1546: returns $datatoken to be put into hidden field
 1547: 
 1548: =cut
 1549: 
 1550: sub upfile_store {
 1551:     my $r=shift;
 1552:     $ENV{'form.upfile'}=~s/\r/\n/gs;
 1553:     $ENV{'form.upfile'}=~s/\f/\n/gs;
 1554:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
 1555:     $ENV{'form.upfile'}=~s/\n+$//gs;
 1556: 
 1557:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
 1558: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
 1559:     {
 1560: 	my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
 1561: 				 '/tmp/'.$datatoken.'.tmp');
 1562: 	print $fh $ENV{'form.upfile'};
 1563:     }
 1564:     return $datatoken;
 1565: }
 1566: 
 1567: =pod
 1568: 
 1569: =item load_tmp_file($r)
 1570: 
 1571: Load uploaded file from tmp, $r should be the HTTP Request object,
 1572: needs $ENV{'form.datatoken'},
 1573: sets $ENV{'form.upfile'} to the contents of the file
 1574: 
 1575: =cut
 1576: 
 1577: sub load_tmp_file {
 1578:     my $r=shift;
 1579:     my @studentdata=();
 1580:     {
 1581: 	my $fh;
 1582: 	if ($fh=Apache::File->new($r->dir_config('lonDaemons').
 1583: 				  '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
 1584: 	    @studentdata=<$fh>;
 1585: 	}
 1586:     }
 1587:     $ENV{'form.upfile'}=join('',@studentdata);
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =item upfile_record_sep()
 1593: 
 1594: Separate uploaded file into records
 1595: returns array of records,
 1596: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
 1597: 
 1598: =cut
 1599: 
 1600: sub upfile_record_sep {
 1601:     if ($ENV{'form.upfiletype'} eq 'xml') {
 1602:     } else {
 1603: 	return split(/\n/,$ENV{'form.upfile'});
 1604:     }
 1605: }
 1606: 
 1607: =pod
 1608: 
 1609: =item record_sep($record)
 1610: 
 1611: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
 1612: 
 1613: =cut
 1614: 
 1615: sub record_sep {
 1616:     my $record=shift;
 1617:     my %components=();
 1618:     if ($ENV{'form.upfiletype'} eq 'xml') {
 1619:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
 1620:         my $i=0;
 1621:         foreach (split(/\s+/,$record)) {
 1622:             my $field=$_;
 1623:             $field=~s/^(\"|\')//;
 1624:             $field=~s/(\"|\')$//;
 1625:             $components{$i}=$field;
 1626:             $i++;
 1627:         }
 1628:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
 1629:         my $i=0;
 1630:         foreach (split(/\t+/,$record)) {
 1631:             my $field=$_;
 1632:             $field=~s/^(\"|\')//;
 1633:             $field=~s/(\"|\')$//;
 1634:             $components{$i}=$field;
 1635:             $i++;
 1636:         }
 1637:     } else {
 1638:         my @allfields=split(/\,/,$record);
 1639:         my $i=0;
 1640:         my $j;
 1641:         for ($j=0;$j<=$#allfields;$j++) {
 1642:             my $field=$allfields[$j];
 1643:             if ($field=~/^\s*(\"|\')/) {
 1644: 		my $delimiter=$1;
 1645:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
 1646: 		    $j++;
 1647: 		    $field.=','.$allfields[$j];
 1648: 		}
 1649:                 $field=~s/^\s*$delimiter//;
 1650:                 $field=~s/$delimiter\s*$//;
 1651:             }
 1652:             $components{$i}=$field;
 1653: 	    $i++;
 1654:         }
 1655:     }
 1656:     return %components;
 1657: }
 1658: 
 1659: =pod
 1660: 
 1661: =item upfile_select_html()
 1662: 
 1663: return HTML code to select file and specify its type
 1664: 
 1665: =cut
 1666: 
 1667: sub upfile_select_html {
 1668:     return (<<'ENDUPFORM');
 1669: <input type="file" name="upfile" size="50" />
 1670: <br />Type: <select name="upfiletype">
 1671: <option value="csv">CSV (comma separated values, spreadsheet)</option>
 1672: <option value="space">Space separated</option>
 1673: <option value="tab">Tabulator separated</option>
 1674: <option value="xml">HTML/XML</option>
 1675: </select>
 1676: ENDUPFORM
 1677: }
 1678: 
 1679: =pod
 1680: 
 1681: =item csv_print_samples($r,$records)
 1682: 
 1683: Prints a table of sample values from each column uploaded $r is an
 1684: Apache Request ref, $records is an arrayref from
 1685: &Apache::loncommon::upfile_record_sep
 1686: 
 1687: =cut
 1688: 
 1689: sub csv_print_samples {
 1690:     my ($r,$records) = @_;
 1691:     my (%sone,%stwo,%sthree);
 1692:     %sone=&record_sep($$records[0]);
 1693:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 1694:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 1695: 
 1696:     $r->print('Samples<br /><table border="2"><tr>');
 1697:     foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column&nbsp;'.($_+1).'</th>'); }
 1698:     $r->print('</tr>');
 1699:     foreach my $hash (\%sone,\%stwo,\%sthree) {
 1700: 	$r->print('<tr>');
 1701: 	foreach (sort({$a <=> $b} keys(%sone))) {
 1702: 	    $r->print('<td>');
 1703: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
 1704: 	    $r->print('</td>');
 1705: 	}
 1706: 	$r->print('</tr>');
 1707:     }
 1708:     $r->print('</tr></table><br />'."\n");
 1709: }
 1710: 
 1711: =pod
 1712: 
 1713: =item csv_print_select_table($r,$records,$d)
 1714: 
 1715: Prints a table to create associations between values and table columns.
 1716: $r is an Apache Request ref,
 1717: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 1718: $d is an array of 2 element arrays (internal name, displayed name)
 1719: 
 1720: =cut
 1721: 
 1722: sub csv_print_select_table {
 1723:     my ($r,$records,$d) = @_;
 1724:     my $i=0;my %sone;
 1725:     %sone=&record_sep($$records[0]);
 1726:     $r->print('Associate columns with student attributes.'."\n".
 1727: 	     '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
 1728:     foreach (@$d) {
 1729: 	my ($value,$display)=@{ $_ };
 1730: 	$r->print('<tr><td>'.$display.'</td>');
 1731: 
 1732: 	$r->print('<td><select name=f'.$i.
 1733: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 1734: 	$r->print('<option value="none"></option>');
 1735: 	foreach (sort({$a <=> $b} keys(%sone))) {
 1736: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
 1737: 	}
 1738: 	$r->print('</select></td></tr>'."\n");
 1739: 	$i++;
 1740:     }
 1741:     $i--;
 1742:     return $i;
 1743: }
 1744: 
 1745: =pod
 1746: 
 1747: =item csv_samples_select_table($r,$records,$d)
 1748: 
 1749: Prints a table of sample values from the upload and can make associate samples to internal names.
 1750: 
 1751: $r is an Apache Request ref,
 1752: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
 1753: $d is an array of 2 element arrays (internal name, displayed name)
 1754: 
 1755: =cut
 1756: 
 1757: sub csv_samples_select_table {
 1758:     my ($r,$records,$d) = @_;
 1759:     my %sone; my %stwo; my %sthree;
 1760:     my $i=0;
 1761: 
 1762:     $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
 1763:     %sone=&record_sep($$records[0]);
 1764:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
 1765:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
 1766: 
 1767:     foreach (sort keys %sone) {
 1768: 	$r->print('<tr><td><select name=f'.$i.
 1769: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 1770: 	foreach (@$d) {
 1771: 	    my ($value,$display)=@{ $_ };
 1772: 	    $r->print('<option value='.$value.'>'.$display.'</option>');
 1773: 	}
 1774: 	$r->print('</select></td><td>');
 1775: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
 1776: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
 1777: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
 1778: 	$r->print('</td></tr>');
 1779: 	$i++;
 1780:     }
 1781:     $i--;
 1782:     return($i);
 1783: }
 1784: 1;
 1785: __END__;
 1786: 
 1787: =pod
 1788: 
 1789: =back
 1790: 
 1791: =head2 Access .tab File Data
 1792: 
 1793: =over 4
 1794: 
 1795: =item languageids() 
 1796: 
 1797: returns list of all language ids
 1798: 
 1799: =item languagedescription() 
 1800: 
 1801: returns description of a specified language id
 1802: 
 1803: =item copyrightids() 
 1804: 
 1805: returns list of all copyrights
 1806: 
 1807: =item copyrightdescription() 
 1808: 
 1809: returns description of a specified copyright id
 1810: 
 1811: =item filecategories() 
 1812: 
 1813: returns list of all file categories
 1814: 
 1815: =item filecategorytypes() 
 1816: 
 1817: returns list of file types belonging to a given file
 1818: category
 1819: 
 1820: =item fileembstyle() 
 1821: 
 1822: returns embedding style for a specified file type
 1823: 
 1824: =item filedescription() 
 1825: 
 1826: returns description for a specified file type
 1827: 
 1828: =item filedescriptionex() 
 1829: 
 1830: returns description for a specified file type with
 1831: extra formatting
 1832: 
 1833: =back
 1834: 
 1835: =head2 Alternate Problem Views
 1836: 
 1837: =over 4
 1838: 
 1839: =item get_previous_attempt() 
 1840: 
 1841: return string with previous attempt on problem
 1842: 
 1843: =item get_student_view() 
 1844: 
 1845: show a snapshot of what student was looking at
 1846: 
 1847: =item get_student_answers() 
 1848: 
 1849: show a snapshot of how student was answering problem
 1850: 
 1851: =back
 1852: 
 1853: =head2 HTTP Helper
 1854: 
 1855: =over 4
 1856: 
 1857: =item get_unprocessed_cgi($query,$possible_names)
 1858: 
 1859: Modify the %ENV hash to contain unprocessed CGI form parameters held in
 1860: $query.  The parameters listed in $possible_names (an array reference),
 1861: will be set in $ENV{'form.name'} if they do not already exist.
 1862: 
 1863: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 1864: $possible_names is an ref to an array of form element names.  As an example:
 1865: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 1866: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
 1867: 
 1868: =item cacheheader() 
 1869: 
 1870: returns cache-controlling header code
 1871: 
 1872: =item no_cache($r) 
 1873: 
 1874: specifies header code to not have cache
 1875: 
 1876: =item add_to_env($name,$value) 
 1877: 
 1878: adds $name to the %ENV hash with value
 1879: $value, if $name already exists, the entry is converted to an array
 1880: reference and $value is added to the array.
 1881: 
 1882: =back
 1883: 
 1884: =cut

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