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