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