Annotation of loncom/interface/loncommon.pm, revision 1.81

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.81    ! albertel    4: # $Id: loncommon.pm,v 1.80 2003/02/13 21:35:50 albertel Exp $
1.10      albertel    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: #
1.12      harris41   28: # YEAR=2001
                     29: # 2/13-12/7 Guy Albertelli
1.18      www        30: # 12/21 Gerd Kortemeyer
1.22      www        31: # 12/25,12/28 Gerd Kortemeyer
1.23      www        32: # YEAR=2002
                     33: # 1/4 Gerd Kortemeyer
1.43      ng         34: # 6/24,7/2 H. K. Ng
1.1       albertel   35: 
                     36: # Makes a table out of the previous attempts
1.2       albertel   37: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   38: # Reads in non-network-related .tab files
1.1       albertel   39: 
1.35      matthew    40: # POD header:
                     41: 
1.45      matthew    42: =pod
                     43: 
1.35      matthew    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: 
1.41      ng         69: =head2 General Subroutines
1.35      matthew    70: 
                     71: =over 4
                     72: 
                     73: =cut 
                     74: 
                     75: # End of POD header
1.1       albertel   76: package Apache::loncommon;
                     77: 
                     78: use strict;
1.22      www        79: use Apache::lonnet();
1.46      matthew    80: use GDBM_File;
1.51      www        81: use POSIX qw(strftime mktime);
1.1       albertel   82: use Apache::Constants qw(:common);
                     83: use Apache::lonmsg();
1.22      www        84: my $readit;
                     85: 
1.46      matthew    86: =pod 
                     87: 
                     88: =item Global Variables
                     89: 
                     90: =over 4
                     91: 
                     92: =cut
1.20      www        93: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41   94: my %language;
                     95: my %cprtag;
                     96: my %fe; my %fd;
1.41      ng         97: my %category_extensions;
1.12      harris41   98: 
1.63      www        99: # ---------------------------------------------- Designs
                    100: 
                    101: my %designhash;
                    102: 
1.46      matthew   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
1.20      www       126: 
1.12      harris41  127: # ----------------------------------------------------------------------- BEGIN
1.41      ng        128: 
                    129: =pod
                    130: 
1.35      matthew   131: =item BEGIN() 
                    132: 
                    133: Initialize values from language.tab, copyright.tab, filetypes.tab,
1.45      matthew   134: thesaurus.tab, and filecategories.tab.
1.35      matthew   135: 
                    136: =cut
1.45      matthew   137: 
1.35      matthew   138: # ----------------------------------------------------------------------- BEGIN
                    139: 
1.18      www       140: BEGIN {
1.46      matthew   141:     # Variable initialization
                    142:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    143:     #
1.22      www       144:     unless ($readit) {
1.12      harris41  145: # ------------------------------------------------------------------- languages
                    146:     {
                    147: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
                    148: 				 '/language.tab');
1.16      harris41  149: 	if ($fh) {
                    150: 	    while (<$fh>) {
                    151: 		next if /^\#/;
                    152: 		chomp;
                    153: 		my ($key,$val)=(split(/\s+/,$_,2));
                    154: 		$language{$key}=$val;
                    155: 	    }
1.12      harris41  156: 	}
                    157:     }
                    158: # ------------------------------------------------------------------ copyrights
                    159:     {
1.16      harris41  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: 	    }
1.12      harris41  169: 	}
                    170:     }
1.63      www       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: 
1.15      harris41  195: # ------------------------------------------------------------- file categories
                    196:     {
                    197: 	my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
1.16      harris41  198: 				  '/filecategories.tab');
                    199: 	if ($fh) {
                    200: 	    while (<$fh>) {
                    201: 		next if /^\#/;
                    202: 		chomp;
1.41      ng        203: 		my ($extension,$category)=(split(/\s+/,$_,2));
                    204: 		push @{$category_extensions{lc($category)}},$extension;
1.16      harris41  205: 	    }
1.15      harris41  206: 	}
                    207:     }
1.12      harris41  208: # ------------------------------------------------------------------ file types
                    209:     {
1.16      harris41  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: 		}
1.12      harris41  221: 	    }
                    222: 	}
                    223:     }
1.22      www       224:     &Apache::lonnet::logthis(
1.46      matthew   225:               "<font color=yellow>INFO: Read file types</font>");
1.22      www       226:     $readit=1;
1.46      matthew   227:     }  # end of unless($readit) 
1.32      matthew   228:     
                    229: }
                    230: # ============================================================= END BEGIN BLOCK
1.42      matthew   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;
1.50      matthew   271:     var editbrowser = null;
1.42      matthew   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: 
1.74      www       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: }
1.42      matthew   340: 
1.74      www       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: }
1.42      matthew   350: 
                    351: ###############################################################
                    352: 
                    353: =pod
1.36      matthew   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: 
1.41      ng        379: =back 
                    380: 
1.36      matthew   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 
1.41      ng        384: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew   385: and text for the second menu are given in the hash pointed to by 
                    386: $menu{$choice1}->{'select2'}.  
                    387: 
1.41      ng        388: my %menu = ( A1 => { text =>"Choice A1" ,
1.36      matthew   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: 
1.33      matthew   501: ###############################################################
1.44      bowersj2  502: 
1.45      matthew   503: =pod
1.44      bowersj2  504: 
1.48      bowersj2  505: =item help_open_topic($topic, $text, $stayOnPage, $width, $height)
1.44      bowersj2  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: 
1.48      bowersj2  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: 
1.44      bowersj2  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 {
1.48      bowersj2  518:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
                    519:     $text = "" if (not defined $text);
1.44      bowersj2  520:     $stayOnPage = 0 if (not defined $stayOnPage);
1.79      www       521:     if ($ENV{'browser.interface'} eq 'textual') {
                    522: 	$stayOnPage=1;
                    523:     }
1.44      bowersj2  524:     $width = 350 if (not defined $width);
                    525:     $height = 400 if (not defined $height);
                    526:     my $filename = $topic;
                    527:     $filename =~ s/ /_/g;
                    528: 
1.48      bowersj2  529:     my $template = "";
                    530:     my $link;
1.44      bowersj2  531: 
                    532:     if (!$stayOnPage)
                    533:     {
1.72      bowersj2  534: 	$link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.44      bowersj2  535:     }
                    536:     else
                    537:     {
1.48      bowersj2  538: 	$link = "/adm/help/${filename}.hlp";
                    539:     }
                    540: 
                    541:     # Add the text
                    542:     if ($text ne "")
                    543:     {
1.77      www       544: 	$template .= 
                    545:   "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1.78      www       546:   "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1.48      bowersj2  547:     }
                    548: 
                    549:     # Add the graphic
                    550:     $template .= <<"ENDTEMPLATE";
1.77      www       551:  <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
1.44      bowersj2  552: ENDTEMPLATE
1.78      www       553:     if ($text ne '') { $template.='</td></tr></table>' };
1.44      bowersj2  554:     return $template;
                    555: 
                    556: }
1.37      matthew   557: 
1.45      matthew   558: =pod
                    559: 
1.37      matthew   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: ###############################################################
1.33      matthew   575: ##        Home server <option> list generating code          ##
                    576: ###############################################################
1.35      matthew   577: #-------------------------------------------
                    578: 
1.45      matthew   579: =pod
                    580: 
1.35      matthew   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: #-------------------------------------------
1.34      matthew   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: 
1.35      matthew   599: #-------------------------------------------
                    600: 
1.45      matthew   601: =pod
                    602: 
1.35      matthew   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: #-------------------------------------------
1.34      matthew   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: 
1.35      matthew   625: #-------------------------------------------
                    626: 
1.45      matthew   627: =pod
                    628: 
1.52      matthew   629: =item get_library_servers($domain)
1.35      matthew   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: #-------------------------------------------
1.52      matthew   638: sub get_library_servers {
1.33      matthew   639:     my $domain = shift;
1.52      matthew   640:     my %library_servers;
1.33      matthew   641:     foreach (keys(%Apache::lonnet::libserv)) {
                    642:         if ($Apache::lonnet::hostdom{$_} eq $domain) {
1.52      matthew   643:             $library_servers{$_} = $Apache::lonnet::hostname{$_};
1.33      matthew   644:         }
                    645:     }
1.52      matthew   646:     return %library_servers;
1.33      matthew   647: }
                    648: 
1.35      matthew   649: #-------------------------------------------
                    650: 
1.45      matthew   651: =pod
                    652: 
1.35      matthew   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: #-------------------------------------------
1.33      matthew   661: sub home_server_option_list {
                    662:     my $domain = shift;
1.52      matthew   663:     my %servers = &get_library_servers($domain);
1.33      matthew   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: ###############################################################
1.32      matthew   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.
1.35      matthew   683: #-------------------------------------------
                    684: 
1.45      matthew   685: =pod
                    686: 
1.35      matthew   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: #-------------------------------------------
1.32      matthew   714: sub authform_header{  
                    715:     my %in = (
                    716:         formname => 'cu',
1.80      albertel  717:         kerb_def_dom => '',
1.32      matthew   718:         @_,
                    719:     );
                    720:     $in{'formname'} = 'document.' . $in{'formname'};
                    721:     my $result='';
1.80      albertel  722: 
                    723: #---------------------------------------------- Code for upper case translation
                    724:     my $Javascript_toUpperCase;
                    725:     unless ($in{kerb_def_dom}) {
                    726:         $Javascript_toUpperCase =<<"END";
                    727:         switch (choice) {
                    728:            case 'krb': currentform.elements[choicearg].value =
                    729:                currentform.elements[choicearg].value.toUpperCase();
                    730:                break;
                    731:            default:
                    732:         }
                    733: END
                    734:     } else {
                    735:         $Javascript_toUpperCase = "";
                    736:     }
                    737: 
1.32      matthew   738:     $result.=<<"END";
                    739: var current = new Object();
                    740: current.radiovalue = 'nochange';
                    741: current.argfield = null;
                    742: 
                    743: function changed_radio(choice,currentform) {
                    744:     var choicearg = choice + 'arg';
                    745:     // If a radio button in changed, we need to change the argfield
                    746:     if (current.radiovalue != choice) {
                    747:         current.radiovalue = choice;
                    748:         if (current.argfield != null) {
                    749:             currentform.elements[current.argfield].value = '';
                    750:         }
                    751:         if (choice == 'nochange') {
                    752:             current.argfield = null;
                    753:         } else {
                    754:             current.argfield = choicearg;
                    755:             switch(choice) {
                    756:                 case 'krb': 
                    757:                     currentform.elements[current.argfield].value = 
                    758:                         "$in{'kerb_def_dom'}";
                    759:                 break;
                    760:               default:
                    761:                 break;
                    762:             }
                    763:         }
                    764:     }
                    765:     return;
                    766: }
1.22      www       767: 
1.32      matthew   768: function changed_text(choice,currentform) {
                    769:     var choicearg = choice + 'arg';
                    770:     if (currentform.elements[choicearg].value !='') {
1.80      albertel  771:         $Javascript_toUpperCase
1.32      matthew   772:         // clear old field
                    773:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                    774:             currentform.elements[current.argfield].value = '';
                    775:         }
                    776:         current.argfield = choicearg;
                    777:     }
                    778:     set_auth_radio_buttons(choice,currentform);
                    779:     return;
1.20      www       780: }
1.32      matthew   781: 
                    782: function set_auth_radio_buttons(newvalue,currentform) {
                    783:     var i=0;
                    784:     while (i < currentform.login.length) {
                    785:         if (currentform.login[i].value == newvalue) { break; }
                    786:         i++;
                    787:     }
                    788:     if (i == currentform.login.length) {
                    789:         return;
                    790:     }
                    791:     current.radiovalue = newvalue;
                    792:     currentform.login[i].checked = true;
                    793:     return;
                    794: }
                    795: END
                    796:     return $result;
                    797: }
                    798: 
                    799: sub authform_authorwarning{
                    800:     my $result='';
                    801:     $result=<<"END";
                    802: <i>As a general rule, only authors or co-authors should be filesystem
                    803: authenticated (which allows access to the server filesystem).</i>
                    804: END
                    805:     return $result;
                    806: }
                    807: 
                    808: sub authform_nochange{  
                    809:     my %in = (
                    810:               formname => 'document.cu',
                    811:               kerb_def_dom => 'MSU.EDU',
                    812:               @_,
                    813:           );
                    814:     my $result='';
                    815:     $result.=<<"END";
                    816: <input type="radio" name="login" value="nochange" checked="checked"
1.57      albertel  817:        onclick="javascript:changed_radio('nochange',$in{'formname'});" />
1.32      matthew   818: Do not change login data
                    819: END
                    820:     return $result;
                    821: }
                    822: 
                    823: sub authform_kerberos{  
                    824:     my %in = (
                    825:               formname => 'document.cu',
                    826:               kerb_def_dom => 'MSU.EDU',
1.80      albertel  827:               kerb_def_auth => 'krb4',
1.32      matthew   828:               @_,
                    829:               );
                    830:     my $result='';
1.80      albertel  831:     my $check4;
                    832:     my $check5;
                    833:     if ($in{'kerb_def_auth'} eq 'krb5') {
                    834:        $check5 = " checked=\"on\"";
                    835:     } else {
                    836:        $check4 = " checked=\"on\"";
                    837:     }
1.32      matthew   838:     $result.=<<"END";
                    839: <input type="radio" name="login" value="krb" 
                    840:        onclick="javascript:changed_radio('krb',$in{'formname'});"
1.57      albertel  841:        onchange="javascript:changed_radio('krb',$in{'formname'});" />
1.32      matthew   842: Kerberos authenticated with domain
1.80      albertel  843: <input type="text" size="10" name="krbarg" value="$in{'kerb_def_dom'}"
1.57      albertel  844:        onchange="javascript:changed_text('krb',$in{'formname'});" />
1.80      albertel  845: <input type="radio" name="krbver" value="4" $check4 />Version 4
                    846: <input type="radio" name="krbver" value="5" $check5 />Version 5
1.32      matthew   847: END
                    848:     return $result;
                    849: }
                    850: 
                    851: sub authform_internal{  
                    852:     my %args = (
                    853:                 formname => 'document.cu',
                    854:                 kerb_def_dom => 'MSU.EDU',
                    855:                 @_,
                    856:                 );
                    857:     my $result='';
                    858:     $result.=<<"END";
                    859: <input type="radio" name="login" value="int"
                    860:        onchange="javascript:changed_radio('int',$args{'formname'});"
1.57      albertel  861:        onclick="javascript:changed_radio('int',$args{'formname'});" />
1.32      matthew   862: Internally authenticated (with initial password 
                    863: <input type="text" size="10" name="intarg" value=""
1.75      www       864:        onchange="javascript:changed_text('int',$args{'formname'});" />)
1.32      matthew   865: END
                    866:     return $result;
                    867: }
                    868: 
                    869: sub authform_local{  
                    870:     my %in = (
                    871:               formname => 'document.cu',
                    872:               kerb_def_dom => 'MSU.EDU',
                    873:               @_,
                    874:               );
                    875:     my $result='';
                    876:     $result.=<<"END";
                    877: <input type="radio" name="login" value="loc"
                    878:        onchange="javascript:changed_radio('loc',$in{'formname'});"
1.57      albertel  879:        onclick="javascript:changed_radio('loc',$in{'formname'});" />
1.32      matthew   880: Local Authentication with argument
                    881: <input type="text" size="10" name="locarg" value=""
1.57      albertel  882:        onchange="javascript:changed_text('loc',$in{'formname'});" />
1.32      matthew   883: END
                    884:     return $result;
                    885: }
                    886: 
                    887: sub authform_filesystem{  
                    888:     my %in = (
                    889:               formname => 'document.cu',
                    890:               kerb_def_dom => 'MSU.EDU',
                    891:               @_,
                    892:               );
                    893:     my $result='';
                    894:     $result.=<<"END";
                    895: <input type="radio" name="login" value="fsys" 
                    896:        onchange="javascript:changed_radio('fsys',$in{'formname'});"
1.57      albertel  897:        onclick="javascript:changed_radio('fsys',$in{'formname'});" />
1.32      matthew   898: Filesystem authenticated (with initial password 
                    899: <input type="text" size="10" name="fsysarg" value=""
1.75      www       900:        onchange="javascript:changed_text('fsys',$in{'formname'});">)
1.32      matthew   901: END
                    902:     return $result;
                    903: }
                    904: 
                    905: ###############################################################
                    906: ##   End Authentication changing form generation functions   ##
1.80      albertel  907: ###############################################################
                    908: 
                    909: ###############################################################
                    910: ##    Get Authentication Defaults for Domain                 ##
                    911: ###############################################################
                    912: ##
                    913: ## Returns default authentication type and an associated argument
                    914: ## as listed in file domain.tab
                    915: ##
                    916: #-------------------------------------------
                    917: 
                    918: =pod
                    919: 
                    920: =item get_auth_defaults
                    921: 
                    922: get_auth_defaults($target_domain) returns the default authentication
                    923: type and an associated argument (initial password or a kerberos domain).
                    924: These values are stored in lonTabs/domain.tab
                    925: 
                    926: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
                    927: 
                    928: If target_domain is not found in domain.tab, returns nothing ('').
                    929: 
                    930: =over 4
                    931: 
                    932: =item get_auth_defaults
                    933: 
                    934: =back
                    935: 
                    936: =cut
                    937: 
                    938: #-------------------------------------------
                    939: sub get_auth_defaults {
                    940:     my $domain=shift;
                    941:     return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
                    942: }
                    943: ###############################################################
                    944: ##   End Get Authentication Defaults for Domain              ##
                    945: ###############################################################
                    946: 
                    947: ###############################################################
                    948: ##    Get Kerberos Defaults for Domain                 ##
                    949: ###############################################################
                    950: ##
                    951: ## Returns default kerberos version and an associated argument
                    952: ## as listed in file domain.tab. If not listed, provides
                    953: ## appropriate default domain and kerberos version.
                    954: ##
                    955: #-------------------------------------------
                    956: 
                    957: =pod
                    958: 
                    959: =item get_kerberos_defaults
                    960: 
                    961: get_kerberos_defaults($target_domain) returns the default kerberos
                    962: version and domain. If not found in domain.tabs, it defaults to
                    963: version 4 and the domain of the server.
                    964: 
                    965: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                    966: 
                    967: =over 4
                    968: 
                    969: =item get_kerberos_defaults
                    970: 
                    971: =back
                    972: 
                    973: =cut
                    974: 
                    975: #-------------------------------------------
                    976: sub get_kerberos_defaults {
                    977:     my $domain=shift;
                    978:     my ($krbdef,$krbdefdom) =
                    979:         &Apache::loncommon::get_auth_defaults($domain);
                    980:     unless ($krbdef =~/^krb/ && $krbdefdom) {
                    981:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                    982:         my $krbdefdom=$1;
                    983:         $krbdefdom=~tr/a-z/A-Z/;
                    984:         $krbdef = "krb4";
                    985:     }
                    986:     return ($krbdef,$krbdefdom);
                    987: }
                    988: ###############################################################
                    989: ##   End Get Kerberos Defaults for Domain              ##
1.32      matthew   990: ###############################################################
                    991: 
1.46      matthew   992: ###############################################################
                    993: ##                Thesaurus Functions                        ##
                    994: ###############################################################
1.20      www       995: 
1.46      matthew   996: =pod
1.20      www       997: 
1.46      matthew   998: =item initialize_keywords
                    999: 
                   1000: Initializes the package variable %Keywords if it is empty.  Uses the
                   1001: package variable $thesaurus_db_file.
                   1002: 
                   1003: =cut
                   1004: 
                   1005: ###################################################
                   1006: 
                   1007: sub initialize_keywords {
                   1008:     return 1 if (scalar keys(%Keywords));
                   1009:     # If we are here, %Keywords is empty, so fill it up
                   1010:     #   Make sure the file we need exists...
                   1011:     if (! -e $thesaurus_db_file) {
                   1012:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   1013:                                  " failed because it does not exist");
                   1014:         return 0;
                   1015:     }
                   1016:     #   Set up the hash as a database
                   1017:     my %thesaurus_db;
                   1018:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1019:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1020:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   1021:                                  $thesaurus_db_file);
                   1022:         return 0;
                   1023:     } 
                   1024:     #  Get the average number of appearances of a word.
                   1025:     my $avecount = $thesaurus_db{'average.count'};
                   1026:     #  Put keywords (those that appear > average) into %Keywords
                   1027:     while (my ($word,$data)=each (%thesaurus_db)) {
                   1028:         my ($count,undef) = split /:/,$data;
                   1029:         $Keywords{$word}++ if ($count > $avecount);
                   1030:     }
                   1031:     untie %thesaurus_db;
                   1032:     # Remove special values from %Keywords.
                   1033:     foreach ('total.count','average.count') {
                   1034:         delete($Keywords{$_}) if (exists($Keywords{$_}));
                   1035:     }
                   1036:     return 1;
                   1037: }
                   1038: 
                   1039: ###################################################
                   1040: 
                   1041: =pod
                   1042: 
                   1043: =item keyword($word)
                   1044: 
                   1045: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   1046: than the average number of times in the thesaurus database.  Calls 
                   1047: &initialize_keywords
                   1048: 
                   1049: =cut
                   1050: 
                   1051: ###################################################
1.20      www      1052: 
                   1053: sub keyword {
1.46      matthew  1054:     return if (!&initialize_keywords());
                   1055:     my $word=lc(shift());
                   1056:     $word=~s/\W//g;
                   1057:     return exists($Keywords{$word});
1.20      www      1058: }
1.46      matthew  1059: 
                   1060: ###############################################################
                   1061: 
                   1062: =pod 
1.20      www      1063: 
1.46      matthew  1064: =item get_related_words
                   1065: 
                   1066: Look up a word in the thesaurus.  Takes a scalar arguement and returns
                   1067: an array of words.  If the keyword is not in the thesaurus, an empty array
                   1068: will be returned.  The order of the words returned is determined by the
                   1069: database which holds them.
                   1070: 
                   1071: Uses global $thesaurus_db_file.
                   1072: 
                   1073: =cut
                   1074: 
                   1075: ###############################################################
                   1076: sub get_related_words {
                   1077:     my $keyword = shift;
                   1078:     my %thesaurus_db;
                   1079:     if (! -e $thesaurus_db_file) {
                   1080:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   1081:                                  "failed because the file does not exist");
                   1082:         return ();
                   1083:     }
                   1084:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 1085:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  1086:         return ();
                   1087:     } 
                   1088:     my @Words=();
                   1089:     if (exists($thesaurus_db{$keyword})) {
                   1090:         $_ = $thesaurus_db{$keyword};
                   1091:         (undef,@Words) = split/:/;  # The first element is the number of times
                   1092:                                     # the word appears.  We do not need it now.
                   1093:         for (my $i=0;$i<=$#Words;$i++) {
                   1094:             ($Words[$i],undef)= split/\,/,$Words[$i];
1.20      www      1095:         }
                   1096:     }
1.46      matthew  1097:     untie %thesaurus_db;
                   1098:     return @Words;
1.14      harris41 1099: }
1.46      matthew  1100: 
                   1101: ###############################################################
                   1102: ##              End Thesaurus Functions                      ##
                   1103: ###############################################################
1.61      www      1104: 
                   1105: # -------------------------------------------------------------- Plaintext name
1.81    ! albertel 1106: =pod
        !          1107: 
        !          1108: =item plainname($uname,$udom)
        !          1109: 
        !          1110: Gets a users name and returns it as a string in
        !          1111: "first middle last generation"
        !          1112: form
        !          1113: 
        !          1114: =cut
1.61      www      1115: 
1.81    ! albertel 1116: ###############################################################
1.61      www      1117: sub plainname {
                   1118:     my ($uname,$udom)=@_;
                   1119:     my %names=&Apache::lonnet::get('environment',
                   1120:                     ['firstname','middlename','lastname','generation'],
                   1121: 					 $udom,$uname);
1.62      www      1122:     my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1.61      www      1123: 	$names{'lastname'}.' '.$names{'generation'};
1.62      www      1124:     $name=~s/\s+$//;
                   1125:     $name=~s/\s+/ /g;
                   1126:     return $name;
1.61      www      1127: }
1.66      www      1128: 
                   1129: # -------------------------------------------------------------------- Nickname
1.81    ! albertel 1130: =pod
        !          1131: 
        !          1132: =item nickname($uname,$udom)
        !          1133: 
        !          1134: Gets a users name and returns it as a string as
        !          1135: 
        !          1136: "&quot;nickname&quot;"
1.66      www      1137: 
1.81    ! albertel 1138: if the user has a nickname or
        !          1139: 
        !          1140: "first middle last generation"
        !          1141: 
        !          1142: if the user does not
        !          1143: 
        !          1144: =cut
1.66      www      1145: 
                   1146: sub nickname {
                   1147:     my ($uname,$udom)=@_;
                   1148:     my %names=&Apache::lonnet::get('environment',
                   1149:   ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1.68      albertel 1150:     my $name=$names{'nickname'};
1.66      www      1151:     if ($name) {
                   1152:        $name='&quot;'.$name.'&quot;'; 
                   1153:     } else {
                   1154:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   1155: 	     $names{'lastname'}.' '.$names{'generation'};
                   1156:        $name=~s/\s+$//;
                   1157:        $name=~s/\s+/ /g;
                   1158:     }
                   1159:     return $name;
                   1160: }
                   1161: 
1.61      www      1162: 
                   1163: # ------------------------------------------------------------------ Screenname
1.81    ! albertel 1164: 
        !          1165: =pod
        !          1166: 
        !          1167: =item screenname($uname,$udom)
        !          1168: 
        !          1169: Gets a users screenname and returns it as a string
        !          1170: 
        !          1171: =cut
1.61      www      1172: 
                   1173: sub screenname {
                   1174:     my ($uname,$udom)=@_;
                   1175:     my %names=
                   1176:  &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 1177:     return $names{'screenname'};
1.62      www      1178: }
                   1179: 
                   1180: # ------------------------------------------------------------- Message Wrapper
                   1181: 
                   1182: sub messagewrapper {
                   1183:     my ($link,$un,$do)=@_;
                   1184:     return 
                   1185: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1.74      www      1186: }
                   1187: # --------------------------------------------------------------- Notes Wrapper
                   1188: 
                   1189: sub noteswrapper {
                   1190:     my ($link,$un,$do)=@_;
                   1191:     return 
                   1192: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1.62      www      1193: }
                   1194: # ------------------------------------------------------------- Aboutme Wrapper
                   1195: 
                   1196: sub aboutmewrapper {
1.69      matthew  1197:     my ($link,$username,$domain)=@_;
                   1198:     return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1.62      www      1199: }
                   1200: 
                   1201: # ------------------------------------------------------------ Syllabus Wrapper
                   1202: 
                   1203: 
                   1204: sub syllabuswrapper {
1.73      www      1205:     my ($link,$un,$do,$tf)=@_;
                   1206:     if ($tf) { $link='<font color="'.$tf.'">'.$link.'</font>'; }
1.62      www      1207:     return "<a href='/public/$do/$un/syllabus'>$link</a>";
1.61      www      1208: }
1.14      harris41 1209: 
                   1210: # ---------------------------------------------------------------- Language IDs
                   1211: sub languageids {
1.16      harris41 1212:     return sort(keys(%language));
1.14      harris41 1213: }
                   1214: 
                   1215: # -------------------------------------------------------- Language Description
                   1216: sub languagedescription {
1.16      harris41 1217:     return $language{shift(@_)};
1.14      harris41 1218: }
                   1219: 
                   1220: # --------------------------------------------------------------- Copyright IDs
                   1221: sub copyrightids {
1.16      harris41 1222:     return sort(keys(%cprtag));
1.14      harris41 1223: }
                   1224: 
                   1225: # ------------------------------------------------------- Copyright Description
                   1226: sub copyrightdescription {
1.16      harris41 1227:     return $cprtag{shift(@_)};
1.14      harris41 1228: }
                   1229: 
                   1230: # ------------------------------------------------------------- File Categories
                   1231: sub filecategories {
1.41      ng       1232:     return sort(keys(%category_extensions));
1.15      harris41 1233: }
1.14      harris41 1234: 
1.17      harris41 1235: # -------------------------------------- File Types within a specified category
1.15      harris41 1236: sub filecategorytypes {
1.41      ng       1237:     return @{$category_extensions{lc($_[0])}};
1.14      harris41 1238: }
                   1239: 
                   1240: # ------------------------------------------------------------------ File Types
                   1241: sub fileextensions {
1.16      harris41 1242:     return sort(keys(%fe));
1.14      harris41 1243: }
                   1244: 
                   1245: # ------------------------------------------------------------- Embedding Style
                   1246: sub fileembstyle {
1.16      harris41 1247:     return $fe{lc(shift(@_))};
1.14      harris41 1248: }
                   1249: 
                   1250: # ------------------------------------------------------------ Description Text
                   1251: sub filedescription {
1.16      harris41 1252:     return $fd{lc(shift(@_))};
                   1253: }
                   1254: 
                   1255: # ------------------------------------------------------------ Description Text
                   1256: sub filedescriptionex {
                   1257:     my $ex=shift;
                   1258:     return '.'.$ex.' '.$fd{lc($ex)};
1.12      harris41 1259: }
1.1       albertel 1260: 
1.40      ng       1261: # ---- Retrieve attempts by students
                   1262: # input
                   1263: # $symb             - problem including path
                   1264: # $username,$domain - that of the student
                   1265: # $course           - course name
                   1266: # $getattempt       - leave blank if want all attempts, else put something.
1.43      ng       1267: # $regexp           - regular expression. If string matches regexp send to
                   1268: # $gradesub         - routine that process the string if it matches regexp
1.40      ng       1269: # 
                   1270: # output
                   1271: # formatted as a table all the attempts, if any.
                   1272: #
1.1       albertel 1273: sub get_previous_attempt {
1.43      ng       1274:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 1275:   my $prevattempts='';
1.43      ng       1276:   no strict 'refs';
1.1       albertel 1277:   if ($symb) {
1.3       albertel 1278:     my (%returnhash)=
                   1279:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 1280:     if ($returnhash{'version'}) {
                   1281:       my %lasthash=();
                   1282:       my $version;
                   1283:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.19      harris41 1284:         foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1.1       albertel 1285: 	  $lasthash{$_}=$returnhash{$version.':'.$_};
1.19      harris41 1286:         }
1.1       albertel 1287:       }
1.43      ng       1288:       $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.40      ng       1289:       $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1.16      harris41 1290:       foreach (sort(keys %lasthash)) {
1.31      albertel 1291: 	my ($ign,@parts) = split(/\./,$_);
1.41      ng       1292: 	if ($#parts > 0) {
1.31      albertel 1293: 	  my $data=$parts[-1];
                   1294: 	  pop(@parts);
1.40      ng       1295: 	  $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.'&nbsp;</td>';
1.31      albertel 1296: 	} else {
1.41      ng       1297: 	  if ($#parts == 0) {
                   1298: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   1299: 	  } else {
                   1300: 	    $prevattempts.='<th>'.$ign.'</th>';
                   1301: 	  }
1.31      albertel 1302: 	}
1.16      harris41 1303:       }
1.40      ng       1304:       if ($getattempt eq '') {
                   1305: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
                   1306: 	  $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
                   1307: 	    foreach (sort(keys %lasthash)) {
                   1308: 	       my $value;
                   1309: 	       if ($_ =~ /timestamp/) {
                   1310: 		  $value=scalar(localtime($returnhash{$version.':'.$_}));
                   1311: 	       } else {
                   1312: 		  $value=$returnhash{$version.':'.$_};
                   1313: 	       }
                   1314: 	       $prevattempts.='<td>'.$value.'&nbsp;</td>';   
                   1315: 	    }
                   1316: 	 }
1.1       albertel 1317:       }
1.40      ng       1318:       $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1.16      harris41 1319:       foreach (sort(keys %lasthash)) {
1.5       albertel 1320: 	my $value;
                   1321: 	if ($_ =~ /timestamp/) {
                   1322: 	  $value=scalar(localtime($lasthash{$_}));
                   1323: 	} else {
                   1324: 	  $value=$lasthash{$_};
                   1325: 	}
1.49      ng       1326: 	if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1.40      ng       1327: 	$prevattempts.='<td>'.$value.'&nbsp;</td>';
1.16      harris41 1328:       }
1.40      ng       1329:       $prevattempts.='</tr></table></td></tr></table>';
1.1       albertel 1330:     } else {
                   1331:       $prevattempts='Nothing submitted - no attempts.';
                   1332:     }
                   1333:   } else {
                   1334:     $prevattempts='No data.';
                   1335:   }
1.10      albertel 1336: }
                   1337: 
                   1338: sub get_student_view {
1.64      sakharuk 1339:   my ($symb,$username,$domain,$courseid,$target) = @_;
1.10      albertel 1340:   my ($map,$id,$feedurl) = split(/___/,$symb);
                   1341:   my (%old,%moreenv);
                   1342:   my @elements=('symb','courseid','domain','username');
                   1343:   foreach my $element (@elements) {
                   1344:     $old{$element}=$ENV{'form.grade_'.$element};
                   1345:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1346:   }
1.64      sakharuk 1347:   if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1.11      albertel 1348:   &Apache::lonnet::appenv(%moreenv);
                   1349:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
                   1350:   &Apache::lonnet::delenv('form.grade_');
                   1351:   foreach my $element (@elements) {
                   1352:     $ENV{'form.grade_'.$element}=$old{$element};
                   1353:   }
                   1354:   $userview=~s/\<body[^\>]*\>//gi;
                   1355:   $userview=~s/\<\/body\>//gi;
                   1356:   $userview=~s/\<html\>//gi;
                   1357:   $userview=~s/\<\/html\>//gi;
                   1358:   $userview=~s/\<head\>//gi;
                   1359:   $userview=~s/\<\/head\>//gi;
                   1360:   $userview=~s/action\s*\=/would_be_action\=/gi;
                   1361:   return $userview;
                   1362: }
                   1363: 
                   1364: sub get_student_answers {
                   1365:   my ($symb,$username,$domain,$courseid) = @_;
                   1366:   my ($map,$id,$feedurl) = split(/___/,$symb);
                   1367:   my (%old,%moreenv);
                   1368:   my @elements=('symb','courseid','domain','username');
                   1369:   foreach my $element (@elements) {
                   1370:     $old{$element}=$ENV{'form.grade_'.$element};
                   1371:     $moreenv{'form.grade_'.$element}=eval '$'.$element #'
                   1372:   }
                   1373:   $moreenv{'form.grade_target'}='answer';
1.10      albertel 1374:   &Apache::lonnet::appenv(%moreenv);
                   1375:   my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
                   1376:   &Apache::lonnet::delenv('form.grade_');
                   1377:   foreach my $element (@elements) {
                   1378:     $ENV{'form.grade_'.$element}=$old{$element};
                   1379:   }
                   1380:   return $userview;
1.1       albertel 1381: }
1.37      matthew  1382: 
                   1383: ###############################################
1.51      www      1384: 
                   1385: 
                   1386: sub timehash {
                   1387:     my @ltime=localtime(shift);
                   1388:     return ( 'seconds' => $ltime[0],
                   1389:              'minutes' => $ltime[1],
                   1390:              'hours'   => $ltime[2],
                   1391:              'day'     => $ltime[3],
                   1392:              'month'   => $ltime[4]+1,
                   1393:              'year'    => $ltime[5]+1900,
                   1394:              'weekday' => $ltime[6],
                   1395:              'dayyear' => $ltime[7]+1,
                   1396:              'dlsav'   => $ltime[8] );
                   1397: }
                   1398: 
                   1399: sub maketime {
                   1400:     my %th=@_;
                   1401:     return POSIX::mktime(
                   1402:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
                   1403:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
                   1404: }
                   1405: 
1.70      www      1406: 
                   1407: #########################################
                   1408: #
                   1409: # Retro-fixing of un-backward-compatible time format
                   1410: 
                   1411: sub unsqltime {
                   1412:     my $timestamp=shift;
                   1413:     if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
                   1414:        $timestamp=&maketime(
                   1415: 	   'year'=>$1,'month'=>$2,'day'=>$3,
                   1416:            'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
                   1417:     }
                   1418:     return $timestamp;
                   1419: }
                   1420: 
                   1421: #########################################
1.51      www      1422: 
                   1423: sub findallcourses {
                   1424:     my %courses=();
                   1425:     my $now=time;
                   1426:     foreach (keys %ENV) {
                   1427: 	if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
                   1428: 	    my ($starttime,$endtime)=$ENV{$_};
                   1429:             my $active=1;
                   1430:             if ($starttime) {
                   1431: 		if ($now<$starttime) { $active=0; }
                   1432:             }
                   1433:             if ($endtime) {
                   1434:                 if ($now>$endtime) { $active=0; }
                   1435:             }
                   1436:             if ($active) { $courses{$1.'_'.$2}=1; }
                   1437:         }
                   1438:     }
                   1439:     return keys %courses;
                   1440: }
1.37      matthew  1441: 
1.54      www      1442: ###############################################
1.60      matthew  1443: ###############################################
                   1444: 
                   1445: =pod
                   1446: 
1.63      www      1447: =item &determinedomain()
1.60      matthew  1448: 
                   1449: Inputs: $domain (usually will be undef)
                   1450: 
1.63      www      1451: Returns: Determines which domain should be used for designs
1.60      matthew  1452: 
                   1453: =cut
1.54      www      1454: 
1.60      matthew  1455: ###############################################
1.63      www      1456: sub determinedomain {
                   1457:     my $domain=shift;
                   1458:    if (! $domain) {
1.60      matthew  1459:         # Determine domain if we have not been given one
                   1460:         $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
                   1461:         if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
                   1462:         if ($ENV{'request.role.domain'}) { 
                   1463:             $domain=$ENV{'request.role.domain'}; 
                   1464:         }
                   1465:     }
1.63      www      1466:     return $domain;
                   1467: }
                   1468: ###############################################
                   1469: =pod
                   1470: 
                   1471: =item &domainlogo()
                   1472: 
                   1473: Inputs: $domain (usually will be undef)
                   1474: 
                   1475: Returns: A link to a domain logo, if the domain logo exists.
                   1476: If the domain logo does not exist, a description of the domain.
                   1477: 
                   1478: =cut
                   1479: ###############################################
                   1480: sub domainlogo {
                   1481:     my $domain = &determinedomain(shift);    
                   1482:      # See if there is a logo
1.59      www      1483:     if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1.71      www      1484:         return '<img src="http://'.$ENV{'HTTP_HOST'}.':8080/adm/lonDomLogos/'.
                   1485:                $domain.'.gif" />';
1.60      matthew  1486:     } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
                   1487:         return $Apache::lonnet::domaindescription{$domain};
1.59      www      1488:     } else {
1.60      matthew  1489:         return '';
1.59      www      1490:     }
                   1491: }
1.63      www      1492: ##############################################
                   1493: 
                   1494: =pod
                   1495: 
                   1496: =item &designparm()
                   1497: 
                   1498: Inputs: $which parameter; $domain (usually will be undef)
                   1499: 
                   1500: Returns: value of designparamter $which
                   1501: 
                   1502: =cut
                   1503: ##############################################
                   1504: sub designparm {
                   1505:     my ($which,$domain)=@_;
                   1506:     $domain=&determinedomain($domain);
                   1507:     if ($designhash{$domain.'.'.$which}) {
                   1508: 	return $designhash{$domain.'.'.$which};
                   1509:     } else {
                   1510:         return $designhash{'default.'.$which};
                   1511:     }
                   1512: }
1.59      www      1513: 
1.60      matthew  1514: ###############################################
                   1515: ###############################################
                   1516: 
                   1517: =pod
                   1518: 
                   1519: =item &bodytag()
                   1520: 
                   1521: Returns a uniform header for LON-CAPA web pages.
                   1522: 
                   1523: Inputs: 
                   1524: 
                   1525:  $title, A title to be displayed on the page.
                   1526:  $function, the current role (can be undef).
                   1527:  $addentries, extra parameters for the <body> tag.
                   1528:  $bodyonly, if defined, only return the <body> tag.
                   1529:  $domain, if defined, force a given domain.
                   1530: 
                   1531: Returns: A uniform header for LON-CAPA web pages.  
                   1532: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   1533: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   1534: other decorations will be returned.
                   1535: 
                   1536: =cut
                   1537: 
                   1538: ###############################################
1.63      www      1539: 
                   1540: 
1.60      matthew  1541: ###############################################
1.54      www      1542: sub bodytag {
1.60      matthew  1543:     my ($title,$function,$addentries,$bodyonly,$domain)=@_;
1.55      www      1544:     unless ($function) {
                   1545: 	$function='student';
                   1546:         if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
                   1547: 	    $function='coordinator';
                   1548:         }
                   1549: 	if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
                   1550:             $function='admin';
                   1551:         }
                   1552:         if (($ENV{'request.role'}=~/^(au|ca)/) ||
                   1553:             ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
                   1554:             $function='author';
                   1555:         }
                   1556:     }
1.63      www      1557:     my $img=&designparm($function.'.img',$domain);
                   1558:     my $pgbg=&designparm($function.'.pgbg',$domain);
                   1559:     my $tabbg=&designparm($function.'.tabbg',$domain);
                   1560:     my $font=&designparm($function.'.font',$domain);
                   1561:     my $link=&designparm($function.'.link',$domain);
                   1562:     my $alink=&designparm($function.'.alink',$domain);
                   1563:     my $vlink=&designparm($function.'.vlink',$domain);
                   1564:     my $sidebg=&designparm($function.'.sidebg',$domain);
                   1565: 
                   1566:  # role and realm
1.55      www      1567:     my ($role,$realm)
                   1568:        =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
                   1569: # realm
1.54      www      1570:     if ($ENV{'request.course.id'}) {
1.55      www      1571: 	$realm=
                   1572:          $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.54      www      1573:     }
1.55      www      1574:     unless ($realm) { $realm='&nbsp;'; }
                   1575: # Set messages
1.60      matthew  1576:     my $messages=&domainlogo($domain);
1.55      www      1577: # Output
1.60      matthew  1578:     my $bodytag = <<END;
1.54      www      1579: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
                   1580: $addentries>
1.60      matthew  1581: END
                   1582:     if ($bodyonly) {
                   1583:         return $bodytag;
1.79      www      1584:     } elsif ($ENV{'browser.interface'} eq 'textual') {
                   1585:         return $bodytag.'<h1>LON-CAPA: '.$title.
                   1586:          '</h1><a href="/adm/menu">Main Menu</a><hr />';
1.60      matthew  1587:     } else {
                   1588:         return(<<ENDBODY);
                   1589: $bodytag
1.55      www      1590: <table width="100%" cellspacing="0" border="0" cellpadding="0">
                   1591: <tr><td bgcolor="$font">
1.71      www      1592: <img src="http://$ENV{'HTTP_HOST'}:8080/$img" /></td>
1.63      www      1593: <td bgcolor="$font"><font color='$sidebg'>$messages</font></td>
1.55      www      1594: </tr>
1.54      www      1595: <tr>
1.55      www      1596: <td rowspan="3" bgcolor="$tabbg">
                   1597: &nbsp;<font size="5"><b>$title</b></font>
1.54      www      1598: <td bgcolor="$tabbg"  align="right">
                   1599: <font size="2">
                   1600:     $ENV{'environment.firstname'}
                   1601:     $ENV{'environment.middlename'}
                   1602:     $ENV{'environment.lastname'}
                   1603:     $ENV{'environment.generation'}
1.55      www      1604:     </font>&nbsp;
1.54      www      1605: </td>
                   1606: </tr>
                   1607: <tr><td bgcolor="$tabbg" align="right">
1.55      www      1608: <font size="2">$role</font>&nbsp;
1.54      www      1609: </td></tr>
1.55      www      1610: <tr>
                   1611: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font>&nbsp;</td></tr>
1.54      www      1612: </table><br>
                   1613: ENDBODY
1.60      matthew  1614:     }
1.54      www      1615: }
1.37      matthew  1616: ###############################################
1.1       albertel 1617: 
1.6       albertel 1618: sub get_unprocessed_cgi {
1.25      albertel 1619:   my ($query,$possible_names)= @_;
1.26      matthew  1620:   # $Apache::lonxml::debug=1;
1.16      harris41 1621:   foreach (split(/&/,$query)) {
1.6       albertel 1622:     my ($name, $value) = split(/=/,$_);
1.25      albertel 1623:     $name = &Apache::lonnet::unescape($name);
                   1624:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   1625:       $value =~ tr/+/ /;
                   1626:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   1627:       &Apache::lonxml::debug("Seting :$name: to :$value:");
1.30      albertel 1628:       unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 1629:     }
1.16      harris41 1630:   }
1.6       albertel 1631: }
                   1632: 
1.7       albertel 1633: sub cacheheader {
1.23      www      1634:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.8       albertel 1635:   my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.7       albertel 1636:   my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
                   1637:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   1638:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
                   1639:   return $output;
                   1640: }
                   1641: 
1.9       albertel 1642: sub no_cache {
                   1643:   my ($r) = @_;
1.23      www      1644:   unless ($ENV{'request.method'} eq 'GET') { return ''; }
1.24      albertel 1645:   #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1.9       albertel 1646:   $r->no_cache(1);
                   1647:   $r->header_out("Pragma" => "no-cache");
1.24      albertel 1648:   #$r->header_out("Expires" => $date);
1.9       albertel 1649: }
1.25      albertel 1650: 
                   1651: sub add_to_env {
                   1652:   my ($name,$value)=@_;
1.28      albertel 1653:   if (defined($ENV{$name})) {
1.27      albertel 1654:     if (ref($ENV{$name})) {
1.25      albertel 1655:       #already have multiple values
                   1656:       push(@{ $ENV{$name} },$value);
                   1657:     } else {
                   1658:       #first time seeing multiple values, convert hash entry to an arrayref
                   1659:       my $first=$ENV{$name};
                   1660:       undef($ENV{$name});
                   1661:       push(@{ $ENV{$name} },$first,$value);
                   1662:     }
                   1663:   } else {
                   1664:     $ENV{$name}=$value;
                   1665:   }
1.31      albertel 1666: }
                   1667: 
1.41      ng       1668: =pod
1.45      matthew  1669: 
                   1670: =back 
1.41      ng       1671: 
                   1672: =head2 CSV Upload/Handling functions
1.38      albertel 1673: 
1.41      ng       1674: =over 4
                   1675: 
                   1676: =item  upfile_store($r)
                   1677: 
                   1678: Store uploaded file, $r should be the HTTP Request object,
                   1679: needs $ENV{'form.upfile'}
                   1680: returns $datatoken to be put into hidden field
                   1681: 
                   1682: =cut
1.31      albertel 1683: 
                   1684: sub upfile_store {
                   1685:     my $r=shift;
                   1686:     $ENV{'form.upfile'}=~s/\r/\n/gs;
                   1687:     $ENV{'form.upfile'}=~s/\f/\n/gs;
                   1688:     $ENV{'form.upfile'}=~s/\n+/\n/gs;
                   1689:     $ENV{'form.upfile'}=~s/\n+$//gs;
                   1690: 
                   1691:     my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
                   1692: 	'_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
                   1693:     {
                   1694: 	my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
                   1695: 				 '/tmp/'.$datatoken.'.tmp');
                   1696: 	print $fh $ENV{'form.upfile'};
                   1697:     }
                   1698:     return $datatoken;
                   1699: }
                   1700: 
1.56      matthew  1701: =pod
                   1702: 
1.41      ng       1703: =item load_tmp_file($r)
                   1704: 
                   1705: Load uploaded file from tmp, $r should be the HTTP Request object,
                   1706: needs $ENV{'form.datatoken'},
                   1707: sets $ENV{'form.upfile'} to the contents of the file
                   1708: 
                   1709: =cut
1.31      albertel 1710: 
                   1711: sub load_tmp_file {
                   1712:     my $r=shift;
                   1713:     my @studentdata=();
                   1714:     {
                   1715: 	my $fh;
                   1716: 	if ($fh=Apache::File->new($r->dir_config('lonDaemons').
                   1717: 				  '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
                   1718: 	    @studentdata=<$fh>;
                   1719: 	}
                   1720:     }
                   1721:     $ENV{'form.upfile'}=join('',@studentdata);
                   1722: }
                   1723: 
1.56      matthew  1724: =pod
                   1725: 
1.41      ng       1726: =item upfile_record_sep()
                   1727: 
                   1728: Separate uploaded file into records
                   1729: returns array of records,
                   1730: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
                   1731: 
                   1732: =cut
1.31      albertel 1733: 
                   1734: sub upfile_record_sep {
                   1735:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   1736:     } else {
                   1737: 	return split(/\n/,$ENV{'form.upfile'});
                   1738:     }
                   1739: }
                   1740: 
1.56      matthew  1741: =pod
                   1742: 
1.41      ng       1743: =item record_sep($record)
                   1744: 
                   1745: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
                   1746: 
                   1747: =cut
                   1748: 
1.31      albertel 1749: sub record_sep {
                   1750:     my $record=shift;
                   1751:     my %components=();
                   1752:     if ($ENV{'form.upfiletype'} eq 'xml') {
                   1753:     } elsif ($ENV{'form.upfiletype'} eq 'space') {
                   1754:         my $i=0;
                   1755:         foreach (split(/\s+/,$record)) {
                   1756:             my $field=$_;
                   1757:             $field=~s/^(\"|\')//;
                   1758:             $field=~s/(\"|\')$//;
                   1759:             $components{$i}=$field;
                   1760:             $i++;
                   1761:         }
                   1762:     } elsif ($ENV{'form.upfiletype'} eq 'tab') {
                   1763:         my $i=0;
                   1764:         foreach (split(/\t+/,$record)) {
                   1765:             my $field=$_;
                   1766:             $field=~s/^(\"|\')//;
                   1767:             $field=~s/(\"|\')$//;
                   1768:             $components{$i}=$field;
                   1769:             $i++;
                   1770:         }
                   1771:     } else {
                   1772:         my @allfields=split(/\,/,$record);
                   1773:         my $i=0;
                   1774:         my $j;
                   1775:         for ($j=0;$j<=$#allfields;$j++) {
                   1776:             my $field=$allfields[$j];
                   1777:             if ($field=~/^\s*(\"|\')/) {
                   1778: 		my $delimiter=$1;
                   1779:                 while (($field!~/$delimiter$/) && ($j<$#allfields)) {
                   1780: 		    $j++;
                   1781: 		    $field.=','.$allfields[$j];
                   1782: 		}
                   1783:                 $field=~s/^\s*$delimiter//;
                   1784:                 $field=~s/$delimiter\s*$//;
                   1785:             }
                   1786:             $components{$i}=$field;
                   1787: 	    $i++;
                   1788:         }
                   1789:     }
                   1790:     return %components;
                   1791: }
                   1792: 
1.56      matthew  1793: =pod
                   1794: 
1.41      ng       1795: =item upfile_select_html()
                   1796: 
                   1797: return HTML code to select file and specify its type
                   1798: 
                   1799: =cut
                   1800: 
1.31      albertel 1801: sub upfile_select_html {
                   1802:     return (<<'ENDUPFORM');
1.57      albertel 1803: <input type="file" name="upfile" size="50" />
1.31      albertel 1804: <br />Type: <select name="upfiletype">
                   1805: <option value="csv">CSV (comma separated values, spreadsheet)</option>
                   1806: <option value="space">Space separated</option>
                   1807: <option value="tab">Tabulator separated</option>
                   1808: <option value="xml">HTML/XML</option>
                   1809: </select>
                   1810: ENDUPFORM
                   1811: }
                   1812: 
1.56      matthew  1813: =pod
                   1814: 
1.41      ng       1815: =item csv_print_samples($r,$records)
                   1816: 
                   1817: Prints a table of sample values from each column uploaded $r is an
                   1818: Apache Request ref, $records is an arrayref from
                   1819: &Apache::loncommon::upfile_record_sep
                   1820: 
                   1821: =cut
                   1822: 
1.31      albertel 1823: sub csv_print_samples {
                   1824:     my ($r,$records) = @_;
                   1825:     my (%sone,%stwo,%sthree);
                   1826:     %sone=&record_sep($$records[0]);
                   1827:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   1828:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
                   1829: 
                   1830:     $r->print('Samples<br /><table border="2"><tr>');
                   1831:     foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column&nbsp;'.($_+1).'</th>'); }
                   1832:     $r->print('</tr>');
                   1833:     foreach my $hash (\%sone,\%stwo,\%sthree) {
                   1834: 	$r->print('<tr>');
                   1835: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   1836: 	    $r->print('<td>');
                   1837: 	    if (defined($$hash{$_})) { $r->print($$hash{$_}); }
                   1838: 	    $r->print('</td>');
                   1839: 	}
                   1840: 	$r->print('</tr>');
                   1841:     }
                   1842:     $r->print('</tr></table><br />'."\n");
                   1843: }
                   1844: 
1.56      matthew  1845: =pod
                   1846: 
1.41      ng       1847: =item csv_print_select_table($r,$records,$d)
                   1848: 
                   1849: Prints a table to create associations between values and table columns.
                   1850: $r is an Apache Request ref,
                   1851: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   1852: $d is an array of 2 element arrays (internal name, displayed name)
                   1853: 
                   1854: =cut
                   1855: 
1.31      albertel 1856: sub csv_print_select_table {
                   1857:     my ($r,$records,$d) = @_;
                   1858:     my $i=0;my %sone;
                   1859:     %sone=&record_sep($$records[0]);
                   1860:     $r->print('Associate columns with student attributes.'."\n".
                   1861: 	     '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
                   1862:     foreach (@$d) {
                   1863: 	my ($value,$display)=@{ $_ };
                   1864: 	$r->print('<tr><td>'.$display.'</td>');
                   1865: 
                   1866: 	$r->print('<td><select name=f'.$i.
1.32      matthew  1867: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 1868: 	$r->print('<option value="none"></option>');
                   1869: 	foreach (sort({$a <=> $b} keys(%sone))) {
                   1870: 	    $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
                   1871: 	}
                   1872: 	$r->print('</select></td></tr>'."\n");
                   1873: 	$i++;
                   1874:     }
                   1875:     $i--;
                   1876:     return $i;
                   1877: }
1.56      matthew  1878: 
                   1879: =pod
1.31      albertel 1880: 
1.41      ng       1881: =item csv_samples_select_table($r,$records,$d)
                   1882: 
                   1883: Prints a table of sample values from the upload and can make associate samples to internal names.
                   1884: 
                   1885: $r is an Apache Request ref,
                   1886: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   1887: $d is an array of 2 element arrays (internal name, displayed name)
                   1888: 
                   1889: =cut
                   1890: 
1.31      albertel 1891: sub csv_samples_select_table {
                   1892:     my ($r,$records,$d) = @_;
                   1893:     my %sone; my %stwo; my %sthree;
                   1894:     my $i=0;
                   1895: 
                   1896:     $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
                   1897:     %sone=&record_sep($$records[0]);
                   1898:     if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
                   1899:     if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
                   1900: 
                   1901:     foreach (sort keys %sone) {
                   1902: 	$r->print('<tr><td><select name=f'.$i.
1.32      matthew  1903: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 1904: 	foreach (@$d) {
                   1905: 	    my ($value,$display)=@{ $_ };
                   1906: 	    $r->print('<option value='.$value.'>'.$display.'</option>');
                   1907: 	}
                   1908: 	$r->print('</select></td><td>');
                   1909: 	if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
                   1910: 	if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
                   1911: 	if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
                   1912: 	$r->print('</td></tr>');
                   1913: 	$i++;
                   1914:     }
                   1915:     $i--;
                   1916:     return($i);
1.25      albertel 1917: }
1.1       albertel 1918: 1;
                   1919: __END__;
1.17      harris41 1920: 
1.41      ng       1921: =pod
                   1922: 
                   1923: =back
                   1924: 
                   1925: =head2 Access .tab File Data
                   1926: 
                   1927: =over 4
                   1928: 
1.35      matthew  1929: =item languageids() 
1.17      harris41 1930: 
1.35      matthew  1931: returns list of all language ids
1.17      harris41 1932: 
1.35      matthew  1933: =item languagedescription() 
1.17      harris41 1934: 
1.35      matthew  1935: returns description of a specified language id
1.17      harris41 1936: 
1.35      matthew  1937: =item copyrightids() 
1.17      harris41 1938: 
1.35      matthew  1939: returns list of all copyrights
1.17      harris41 1940: 
1.35      matthew  1941: =item copyrightdescription() 
1.17      harris41 1942: 
1.35      matthew  1943: returns description of a specified copyright id
1.17      harris41 1944: 
1.35      matthew  1945: =item filecategories() 
1.17      harris41 1946: 
1.35      matthew  1947: returns list of all file categories
1.17      harris41 1948: 
1.35      matthew  1949: =item filecategorytypes() 
1.17      harris41 1950: 
1.35      matthew  1951: returns list of file types belonging to a given file
1.17      harris41 1952: category
                   1953: 
1.35      matthew  1954: =item fileembstyle() 
1.17      harris41 1955: 
1.35      matthew  1956: returns embedding style for a specified file type
1.17      harris41 1957: 
1.35      matthew  1958: =item filedescription() 
1.17      harris41 1959: 
1.35      matthew  1960: returns description for a specified file type
1.17      harris41 1961: 
1.35      matthew  1962: =item filedescriptionex() 
1.17      harris41 1963: 
1.35      matthew  1964: returns description for a specified file type with
1.17      harris41 1965: extra formatting
                   1966: 
1.41      ng       1967: =back
                   1968: 
                   1969: =head2 Alternate Problem Views
                   1970: 
                   1971: =over 4
                   1972: 
1.35      matthew  1973: =item get_previous_attempt() 
1.17      harris41 1974: 
1.35      matthew  1975: return string with previous attempt on problem
1.17      harris41 1976: 
1.35      matthew  1977: =item get_student_view() 
1.17      harris41 1978: 
1.35      matthew  1979: show a snapshot of what student was looking at
1.17      harris41 1980: 
1.35      matthew  1981: =item get_student_answers() 
1.17      harris41 1982: 
1.35      matthew  1983: show a snapshot of how student was answering problem
1.17      harris41 1984: 
1.41      ng       1985: =back
                   1986: 
                   1987: =head2 HTTP Helper
                   1988: 
                   1989: =over 4
                   1990: 
                   1991: =item get_unprocessed_cgi($query,$possible_names)
                   1992: 
                   1993: Modify the %ENV hash to contain unprocessed CGI form parameters held in
                   1994: $query.  The parameters listed in $possible_names (an array reference),
                   1995: will be set in $ENV{'form.name'} if they do not already exist.
1.17      harris41 1996: 
1.41      ng       1997: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   1998: $possible_names is an ref to an array of form element names.  As an example:
                   1999: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
                   2000: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
1.17      harris41 2001: 
1.35      matthew  2002: =item cacheheader() 
1.17      harris41 2003: 
1.35      matthew  2004: returns cache-controlling header code
1.17      harris41 2005: 
1.65      matthew  2006: =item no_cache($r) 
1.17      harris41 2007: 
1.35      matthew  2008: specifies header code to not have cache
1.25      albertel 2009: 
1.35      matthew  2010: =item add_to_env($name,$value) 
1.25      albertel 2011: 
1.35      matthew  2012: adds $name to the %ENV hash with value
1.25      albertel 2013: $value, if $name already exists, the entry is converted to an array
                   2014: reference and $value is added to the array.
1.17      harris41 2015: 
                   2016: =back
                   2017: 
                   2018: =cut

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