File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.87:
download - view:
text,
annotated -
select for diffs
Mon Mar 10 20:21:45 2003 UTC (21 years, 7 months ago) by
matthew
Branches:
MAIN
CVS tags:
HEAD
Created loncommon::decode_user_agent() subroutine with code removed from
lonauth.pm. The code was modified to not require $r be passed along
ad nauseum.
Created lonhtmlcommon::javascript_nothing which returns an appropriate value
of nothing for use as the first parameter for window.open. Most notably,
IE on macs get a different version, "'javascript:void(0);'", than everyone
one else, "''". Of course IE on PC appearantly used to require the former
but now requires the latter.
lonmenu.pm and lonspreadsheet.pm were modified to use javascript_nothing.
lonauth was modified to use decode_user_agent.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.87 2003/03/10 20:21:45 matthew 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_dom_form($defdom,$name)
605:
606: Returns a string containing a <select name='$name' size='1'> form to
607: allow a user to select the domain to preform an operation in.
608: See loncreateuser.pm for an example invocation and use.
609:
610: =cut
611:
612: #-------------------------------------------
613: sub select_dom_form {
614: my ($defdom,$name) = @_;
615: my @domains = get_domains();
616: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
617: foreach (@domains) {
618: $selectdomain.="<option value=\"$_\" ".
619: ($_ eq $defdom ? 'selected' : '').
620: ">$_</option>\n";
621: }
622: $selectdomain.="</select>";
623: return $selectdomain;
624: }
625:
626: #-------------------------------------------
627:
628: =pod
629:
630: =item get_library_servers($domain)
631:
632: Returns a hash which contains keys like '103l3' and values like
633: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
634: given $domain.
635:
636: =cut
637:
638: #-------------------------------------------
639: sub get_library_servers {
640: my $domain = shift;
641: my %library_servers;
642: foreach (keys(%Apache::lonnet::libserv)) {
643: if ($Apache::lonnet::hostdom{$_} eq $domain) {
644: $library_servers{$_} = $Apache::lonnet::hostname{$_};
645: }
646: }
647: return %library_servers;
648: }
649:
650: #-------------------------------------------
651:
652: =pod
653:
654: =item home_server_option_list($domain)
655:
656: returns a string which contains an <option> list to be used in a
657: <select> form input. See loncreateuser.pm for an example.
658:
659: =cut
660:
661: #-------------------------------------------
662: sub home_server_option_list {
663: my $domain = shift;
664: my %servers = &get_library_servers($domain);
665: my $result = '';
666: foreach (sort keys(%servers)) {
667: $result.=
668: '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
669: }
670: return $result;
671: }
672: ###############################################################
673: ## End of home server <option> list generating code ##
674: ###############################################################
675:
676: ###############################################################
677: ###############################################################
678:
679: =pod
680:
681: =item &decode_user_agent()
682:
683: Inputs: $r
684:
685: Outputs:
686:
687: =over 4
688:
689: =item $httpbrowser
690:
691: =item $clientbrowser
692:
693: =item $clientversion
694:
695: =item $clientmathml
696:
697: =item $clientunicode
698:
699: =item $clientos
700:
701: =back
702:
703: =cut
704:
705: ###############################################################
706: ###############################################################
707: sub decode_user_agent {
708: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
709: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
710: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
711: my $clientbrowser='unknown';
712: my $clientversion='0';
713: my $clientmathml='';
714: my $clientunicode='0';
715: for (my $i=0;$i<=$#browsertype;$i++) {
716: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
717: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
718: $clientbrowser=$bname;
719: $httpbrowser=~/$vreg/i;
720: $clientversion=$1;
721: $clientmathml=($clientversion>=$minv);
722: $clientunicode=($clientversion>=$univ);
723: }
724: }
725: my $clientos='unknown';
726: if (($httpbrowser=~/linux/i) ||
727: ($httpbrowser=~/unix/i) ||
728: ($httpbrowser=~/ux/i) ||
729: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
730: if (($httpbrowser=~/vax/i) ||
731: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
732: if ($httpbrowser=~/next/i) { $clientos='next'; }
733: if (($httpbrowser=~/mac/i) ||
734: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
735: if ($httpbrowser=~/win/i) { $clientos='win'; }
736: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
737: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
738: $clientunicode,$clientos,);
739: }
740:
741: ###############################################################
742: ###############################################################
743:
744:
745: ###############################################################
746: ## Authentication changing form generation subroutines ##
747: ###############################################################
748: ##
749: ## All of the authform_xxxxxxx subroutines take their inputs in a
750: ## hash, and have reasonable default values.
751: ##
752: ## formname = the name given in the <form> tag.
753: #-------------------------------------------
754:
755: =pod
756:
757: =item authform_xxxxxx
758:
759: The authform_xxxxxx subroutines provide javascript and html forms which
760: handle some of the conveniences required for authentication forms.
761: This is not an optimal method, but it works.
762:
763: See loncreateuser.pm for invocation and use examples.
764:
765: =over 4
766:
767: =item authform_header
768:
769: =item authform_authorwarning
770:
771: =item authform_nochange
772:
773: =item authform_kerberos
774:
775: =item authform_internal
776:
777: =item authform_filesystem
778:
779: =back
780:
781: =cut
782:
783: #-------------------------------------------
784: sub authform_header{
785: my %in = (
786: formname => 'cu',
787: kerb_def_dom => '',
788: @_,
789: );
790: $in{'formname'} = 'document.' . $in{'formname'};
791: my $result='';
792:
793: #---------------------------------------------- Code for upper case translation
794: my $Javascript_toUpperCase;
795: unless ($in{kerb_def_dom}) {
796: $Javascript_toUpperCase =<<"END";
797: switch (choice) {
798: case 'krb': currentform.elements[choicearg].value =
799: currentform.elements[choicearg].value.toUpperCase();
800: break;
801: default:
802: }
803: END
804: } else {
805: $Javascript_toUpperCase = "";
806: }
807:
808: $result.=<<"END";
809: var current = new Object();
810: current.radiovalue = 'nochange';
811: current.argfield = null;
812:
813: function changed_radio(choice,currentform) {
814: var choicearg = choice + 'arg';
815: // If a radio button in changed, we need to change the argfield
816: if (current.radiovalue != choice) {
817: current.radiovalue = choice;
818: if (current.argfield != null) {
819: currentform.elements[current.argfield].value = '';
820: }
821: if (choice == 'nochange') {
822: current.argfield = null;
823: } else {
824: current.argfield = choicearg;
825: switch(choice) {
826: case 'krb':
827: currentform.elements[current.argfield].value =
828: "$in{'kerb_def_dom'}";
829: break;
830: default:
831: break;
832: }
833: }
834: }
835: return;
836: }
837:
838: function changed_text(choice,currentform) {
839: var choicearg = choice + 'arg';
840: if (currentform.elements[choicearg].value !='') {
841: $Javascript_toUpperCase
842: // clear old field
843: if ((current.argfield != choicearg) && (current.argfield != null)) {
844: currentform.elements[current.argfield].value = '';
845: }
846: current.argfield = choicearg;
847: }
848: set_auth_radio_buttons(choice,currentform);
849: return;
850: }
851:
852: function set_auth_radio_buttons(newvalue,currentform) {
853: var i=0;
854: while (i < currentform.login.length) {
855: if (currentform.login[i].value == newvalue) { break; }
856: i++;
857: }
858: if (i == currentform.login.length) {
859: return;
860: }
861: current.radiovalue = newvalue;
862: currentform.login[i].checked = true;
863: return;
864: }
865: END
866: return $result;
867: }
868:
869: sub authform_authorwarning{
870: my $result='';
871: $result=<<"END";
872: <i>As a general rule, only authors or co-authors should be filesystem
873: authenticated (which allows access to the server filesystem).</i>
874: END
875: return $result;
876: }
877:
878: sub authform_nochange{
879: my %in = (
880: formname => 'document.cu',
881: kerb_def_dom => 'MSU.EDU',
882: @_,
883: );
884: my $result='';
885: $result.=<<"END";
886: <input type="radio" name="login" value="nochange" checked="checked"
887: onclick="javascript:changed_radio('nochange',$in{'formname'});" />
888: Do not change login data
889: END
890: return $result;
891: }
892:
893: sub authform_kerberos{
894: my %in = (
895: formname => 'document.cu',
896: kerb_def_dom => 'MSU.EDU',
897: kerb_def_auth => 'krb4',
898: @_,
899: );
900: my $result='';
901: my $check4;
902: my $check5;
903: if ($in{'kerb_def_auth'} eq 'krb5') {
904: $check5 = " checked=\"on\"";
905: } else {
906: $check4 = " checked=\"on\"";
907: }
908: $result.=<<"END";
909: <input type="radio" name="login" value="krb"
910: onclick="javascript:changed_radio('krb',$in{'formname'});"
911: onchange="javascript:changed_radio('krb',$in{'formname'});" />
912: Kerberos authenticated with domain
913: <input type="text" size="10" name="krbarg" value="$in{'kerb_def_dom'}"
914: onchange="javascript:changed_text('krb',$in{'formname'});" />
915: <input type="radio" name="krbver" value="4" $check4 />Version 4
916: <input type="radio" name="krbver" value="5" $check5 />Version 5
917: END
918: return $result;
919: }
920:
921: sub authform_internal{
922: my %args = (
923: formname => 'document.cu',
924: kerb_def_dom => 'MSU.EDU',
925: @_,
926: );
927: my $result='';
928: $result.=<<"END";
929: <input type="radio" name="login" value="int"
930: onchange="javascript:changed_radio('int',$args{'formname'});"
931: onclick="javascript:changed_radio('int',$args{'formname'});" />
932: Internally authenticated (with initial password
933: <input type="text" size="10" name="intarg" value=""
934: onchange="javascript:changed_text('int',$args{'formname'});" />)
935: END
936: return $result;
937: }
938:
939: sub authform_local{
940: my %in = (
941: formname => 'document.cu',
942: kerb_def_dom => 'MSU.EDU',
943: @_,
944: );
945: my $result='';
946: $result.=<<"END";
947: <input type="radio" name="login" value="loc"
948: onchange="javascript:changed_radio('loc',$in{'formname'});"
949: onclick="javascript:changed_radio('loc',$in{'formname'});" />
950: Local Authentication with argument
951: <input type="text" size="10" name="locarg" value=""
952: onchange="javascript:changed_text('loc',$in{'formname'});" />
953: END
954: return $result;
955: }
956:
957: sub authform_filesystem{
958: my %in = (
959: formname => 'document.cu',
960: kerb_def_dom => 'MSU.EDU',
961: @_,
962: );
963: my $result='';
964: $result.=<<"END";
965: <input type="radio" name="login" value="fsys"
966: onchange="javascript:changed_radio('fsys',$in{'formname'});"
967: onclick="javascript:changed_radio('fsys',$in{'formname'});" />
968: Filesystem authenticated (with initial password
969: <input type="text" size="10" name="fsysarg" value=""
970: onchange="javascript:changed_text('fsys',$in{'formname'});">)
971: END
972: return $result;
973: }
974:
975: ###############################################################
976: ## End Authentication changing form generation functions ##
977: ###############################################################
978:
979: ###############################################################
980: ## Get Authentication Defaults for Domain ##
981: ###############################################################
982: ##
983: ## Returns default authentication type and an associated argument
984: ## as listed in file domain.tab
985: ##
986: #-------------------------------------------
987:
988: =pod
989:
990: =item get_auth_defaults
991:
992: get_auth_defaults($target_domain) returns the default authentication
993: type and an associated argument (initial password or a kerberos domain).
994: These values are stored in lonTabs/domain.tab
995:
996: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
997:
998: If target_domain is not found in domain.tab, returns nothing ('').
999:
1000: =over 4
1001:
1002: =item get_auth_defaults
1003:
1004: =back
1005:
1006: =cut
1007:
1008: #-------------------------------------------
1009: sub get_auth_defaults {
1010: my $domain=shift;
1011: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1012: }
1013: ###############################################################
1014: ## End Get Authentication Defaults for Domain ##
1015: ###############################################################
1016:
1017: ###############################################################
1018: ## Get Kerberos Defaults for Domain ##
1019: ###############################################################
1020: ##
1021: ## Returns default kerberos version and an associated argument
1022: ## as listed in file domain.tab. If not listed, provides
1023: ## appropriate default domain and kerberos version.
1024: ##
1025: #-------------------------------------------
1026:
1027: =pod
1028:
1029: =item get_kerberos_defaults
1030:
1031: get_kerberos_defaults($target_domain) returns the default kerberos
1032: version and domain. If not found in domain.tabs, it defaults to
1033: version 4 and the domain of the server.
1034:
1035: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1036:
1037: =over 4
1038:
1039: =item get_kerberos_defaults
1040:
1041: =back
1042:
1043: =cut
1044:
1045: #-------------------------------------------
1046: sub get_kerberos_defaults {
1047: my $domain=shift;
1048: my ($krbdef,$krbdefdom) =
1049: &Apache::loncommon::get_auth_defaults($domain);
1050: unless ($krbdef =~/^krb/ && $krbdefdom) {
1051: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1052: my $krbdefdom=$1;
1053: $krbdefdom=~tr/a-z/A-Z/;
1054: $krbdef = "krb4";
1055: }
1056: return ($krbdef,$krbdefdom);
1057: }
1058: ###############################################################
1059: ## End Get Kerberos Defaults for Domain ##
1060: ###############################################################
1061:
1062: ###############################################################
1063: ## Thesaurus Functions ##
1064: ###############################################################
1065:
1066: =pod
1067:
1068: =item initialize_keywords
1069:
1070: Initializes the package variable %Keywords if it is empty. Uses the
1071: package variable $thesaurus_db_file.
1072:
1073: =cut
1074:
1075: ###################################################
1076:
1077: sub initialize_keywords {
1078: return 1 if (scalar keys(%Keywords));
1079: # If we are here, %Keywords is empty, so fill it up
1080: # Make sure the file we need exists...
1081: if (! -e $thesaurus_db_file) {
1082: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1083: " failed because it does not exist");
1084: return 0;
1085: }
1086: # Set up the hash as a database
1087: my %thesaurus_db;
1088: if (! tie(%thesaurus_db,'GDBM_File',
1089: $thesaurus_db_file,&GDBM_READER(),0640)){
1090: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1091: $thesaurus_db_file);
1092: return 0;
1093: }
1094: # Get the average number of appearances of a word.
1095: my $avecount = $thesaurus_db{'average.count'};
1096: # Put keywords (those that appear > average) into %Keywords
1097: while (my ($word,$data)=each (%thesaurus_db)) {
1098: my ($count,undef) = split /:/,$data;
1099: $Keywords{$word}++ if ($count > $avecount);
1100: }
1101: untie %thesaurus_db;
1102: # Remove special values from %Keywords.
1103: foreach ('total.count','average.count') {
1104: delete($Keywords{$_}) if (exists($Keywords{$_}));
1105: }
1106: return 1;
1107: }
1108:
1109: ###################################################
1110:
1111: =pod
1112:
1113: =item keyword($word)
1114:
1115: Returns true if $word is a keyword. A keyword is a word that appears more
1116: than the average number of times in the thesaurus database. Calls
1117: &initialize_keywords
1118:
1119: =cut
1120:
1121: ###################################################
1122:
1123: sub keyword {
1124: return if (!&initialize_keywords());
1125: my $word=lc(shift());
1126: $word=~s/\W//g;
1127: return exists($Keywords{$word});
1128: }
1129:
1130: ###############################################################
1131:
1132: =pod
1133:
1134: =item get_related_words
1135:
1136: Look up a word in the thesaurus. Takes a scalar arguement and returns
1137: an array of words. If the keyword is not in the thesaurus, an empty array
1138: will be returned. The order of the words returned is determined by the
1139: database which holds them.
1140:
1141: Uses global $thesaurus_db_file.
1142:
1143: =cut
1144:
1145: ###############################################################
1146: sub get_related_words {
1147: my $keyword = shift;
1148: my %thesaurus_db;
1149: if (! -e $thesaurus_db_file) {
1150: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
1151: "failed because the file does not exist");
1152: return ();
1153: }
1154: if (! tie(%thesaurus_db,'GDBM_File',
1155: $thesaurus_db_file,&GDBM_READER(),0640)){
1156: return ();
1157: }
1158: my @Words=();
1159: if (exists($thesaurus_db{$keyword})) {
1160: $_ = $thesaurus_db{$keyword};
1161: (undef,@Words) = split/:/; # The first element is the number of times
1162: # the word appears. We do not need it now.
1163: for (my $i=0;$i<=$#Words;$i++) {
1164: ($Words[$i],undef)= split/\,/,$Words[$i];
1165: }
1166: }
1167: untie %thesaurus_db;
1168: return @Words;
1169: }
1170:
1171: ###############################################################
1172: ## End Thesaurus Functions ##
1173: ###############################################################
1174:
1175: # -------------------------------------------------------------- Plaintext name
1176: =pod
1177:
1178: =item plainname($uname,$udom)
1179:
1180: Gets a users name and returns it as a string in
1181: "first middle last generation"
1182: form
1183:
1184: =cut
1185:
1186: ###############################################################
1187: sub plainname {
1188: my ($uname,$udom)=@_;
1189: my %names=&Apache::lonnet::get('environment',
1190: ['firstname','middlename','lastname','generation'],
1191: $udom,$uname);
1192: my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1193: $names{'lastname'}.' '.$names{'generation'};
1194: $name=~s/\s+$//;
1195: $name=~s/\s+/ /g;
1196: return $name;
1197: }
1198:
1199: # -------------------------------------------------------------------- Nickname
1200: =pod
1201:
1202: =item nickname($uname,$udom)
1203:
1204: Gets a users name and returns it as a string as
1205:
1206: ""nickname""
1207:
1208: if the user has a nickname or
1209:
1210: "first middle last generation"
1211:
1212: if the user does not
1213:
1214: =cut
1215:
1216: sub nickname {
1217: my ($uname,$udom)=@_;
1218: my %names=&Apache::lonnet::get('environment',
1219: ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1220: my $name=$names{'nickname'};
1221: if ($name) {
1222: $name='"'.$name.'"';
1223: } else {
1224: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1225: $names{'lastname'}.' '.$names{'generation'};
1226: $name=~s/\s+$//;
1227: $name=~s/\s+/ /g;
1228: }
1229: return $name;
1230: }
1231:
1232:
1233: # ------------------------------------------------------------------ Screenname
1234:
1235: =pod
1236:
1237: =item screenname($uname,$udom)
1238:
1239: Gets a users screenname and returns it as a string
1240:
1241: =cut
1242:
1243: sub screenname {
1244: my ($uname,$udom)=@_;
1245: my %names=
1246: &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1247: return $names{'screenname'};
1248: }
1249:
1250: # ------------------------------------------------------------- Message Wrapper
1251:
1252: sub messagewrapper {
1253: my ($link,$un,$do)=@_;
1254: return
1255: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1256: }
1257: # --------------------------------------------------------------- Notes Wrapper
1258:
1259: sub noteswrapper {
1260: my ($link,$un,$do)=@_;
1261: return
1262: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1263: }
1264: # ------------------------------------------------------------- Aboutme Wrapper
1265:
1266: sub aboutmewrapper {
1267: my ($link,$username,$domain)=@_;
1268: return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1269: }
1270:
1271: # ------------------------------------------------------------ Syllabus Wrapper
1272:
1273:
1274: sub syllabuswrapper {
1275: my ($link,$un,$do,$tf)=@_;
1276: if ($tf) { $link='<font color="'.$tf.'">'.$link.'</font>'; }
1277: return "<a href='/public/$do/$un/syllabus'>$link</a>";
1278: }
1279:
1280: # ---------------------------------------------------------------- Language IDs
1281: sub languageids {
1282: return sort(keys(%language));
1283: }
1284:
1285: # -------------------------------------------------------- Language Description
1286: sub languagedescription {
1287: return $language{shift(@_)};
1288: }
1289:
1290: # --------------------------------------------------------------- Copyright IDs
1291: sub copyrightids {
1292: return sort(keys(%cprtag));
1293: }
1294:
1295: # ------------------------------------------------------- Copyright Description
1296: sub copyrightdescription {
1297: return $cprtag{shift(@_)};
1298: }
1299:
1300: # ------------------------------------------------------------- File Categories
1301: sub filecategories {
1302: return sort(keys(%category_extensions));
1303: }
1304:
1305: # -------------------------------------- File Types within a specified category
1306: sub filecategorytypes {
1307: return @{$category_extensions{lc($_[0])}};
1308: }
1309:
1310: # ------------------------------------------------------------------ File Types
1311: sub fileextensions {
1312: return sort(keys(%fe));
1313: }
1314:
1315: # ------------------------------------------------------------- Embedding Style
1316: sub fileembstyle {
1317: return $fe{lc(shift(@_))};
1318: }
1319:
1320: # ------------------------------------------------------------ Description Text
1321: sub filedescription {
1322: return $fd{lc(shift(@_))};
1323: }
1324:
1325: # ------------------------------------------------------------ Description Text
1326: sub filedescriptionex {
1327: my $ex=shift;
1328: return '.'.$ex.' '.$fd{lc($ex)};
1329: }
1330:
1331: # ---- Retrieve attempts by students
1332: # input
1333: # $symb - problem including path
1334: # $username,$domain - that of the student
1335: # $course - course name
1336: # $getattempt - leave blank if want all attempts, else put something.
1337: # $regexp - regular expression. If string matches regexp send to
1338: # $gradesub - routine that process the string if it matches regexp
1339: #
1340: # output
1341: # formatted as a table all the attempts, if any.
1342: #
1343: sub get_previous_attempt {
1344: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1345: my $prevattempts='';
1346: no strict 'refs';
1347: if ($symb) {
1348: my (%returnhash)=
1349: &Apache::lonnet::restore($symb,$course,$domain,$username);
1350: if ($returnhash{'version'}) {
1351: my %lasthash=();
1352: my $version;
1353: for ($version=1;$version<=$returnhash{'version'};$version++) {
1354: foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1355: $lasthash{$_}=$returnhash{$version.':'.$_};
1356: }
1357: }
1358: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1359: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1360: foreach (sort(keys %lasthash)) {
1361: my ($ign,@parts) = split(/\./,$_);
1362: if ($#parts > 0) {
1363: my $data=$parts[-1];
1364: pop(@parts);
1365: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
1366: } else {
1367: if ($#parts == 0) {
1368: $prevattempts.='<th>'.$parts[0].'</th>';
1369: } else {
1370: $prevattempts.='<th>'.$ign.'</th>';
1371: }
1372: }
1373: }
1374: if ($getattempt eq '') {
1375: for ($version=1;$version<=$returnhash{'version'};$version++) {
1376: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
1377: foreach (sort(keys %lasthash)) {
1378: my $value;
1379: if ($_ =~ /timestamp/) {
1380: $value=scalar(localtime($returnhash{$version.':'.$_}));
1381: } else {
1382: $value=$returnhash{$version.':'.$_};
1383: }
1384: $prevattempts.='<td>'.$value.' </td>';
1385: }
1386: }
1387: }
1388: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1389: foreach (sort(keys %lasthash)) {
1390: my $value;
1391: if ($_ =~ /timestamp/) {
1392: $value=scalar(localtime($lasthash{$_}));
1393: } else {
1394: $value=$lasthash{$_};
1395: }
1396: if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1397: $prevattempts.='<td>'.$value.' </td>';
1398: }
1399: $prevattempts.='</tr></table></td></tr></table>';
1400: } else {
1401: $prevattempts='Nothing submitted - no attempts.';
1402: }
1403: } else {
1404: $prevattempts='No data.';
1405: }
1406: }
1407:
1408: sub get_student_view {
1409: my ($symb,$username,$domain,$courseid,$target) = @_;
1410: my ($map,$id,$feedurl) = split(/___/,$symb);
1411: my (%old,%moreenv);
1412: my @elements=('symb','courseid','domain','username');
1413: foreach my $element (@elements) {
1414: $old{$element}=$ENV{'form.grade_'.$element};
1415: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1416: }
1417: if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1418: &Apache::lonnet::appenv(%moreenv);
1419: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
1420: &Apache::lonnet::delenv('form.grade_');
1421: foreach my $element (@elements) {
1422: $ENV{'form.grade_'.$element}=$old{$element};
1423: }
1424: $userview=~s/\<body[^\>]*\>//gi;
1425: $userview=~s/\<\/body\>//gi;
1426: $userview=~s/\<html\>//gi;
1427: $userview=~s/\<\/html\>//gi;
1428: $userview=~s/\<head\>//gi;
1429: $userview=~s/\<\/head\>//gi;
1430: $userview=~s/action\s*\=/would_be_action\=/gi;
1431: return $userview;
1432: }
1433:
1434: sub get_student_answers {
1435: my ($symb,$username,$domain,$courseid) = @_;
1436: my ($map,$id,$feedurl) = split(/___/,$symb);
1437: my (%old,%moreenv);
1438: my @elements=('symb','courseid','domain','username');
1439: foreach my $element (@elements) {
1440: $old{$element}=$ENV{'form.grade_'.$element};
1441: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1442: }
1443: $moreenv{'form.grade_target'}='answer';
1444: &Apache::lonnet::appenv(%moreenv);
1445: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl);
1446: &Apache::lonnet::delenv('form.grade_');
1447: foreach my $element (@elements) {
1448: $ENV{'form.grade_'.$element}=$old{$element};
1449: }
1450: return $userview;
1451: }
1452:
1453: ###############################################
1454:
1455:
1456: sub timehash {
1457: my @ltime=localtime(shift);
1458: return ( 'seconds' => $ltime[0],
1459: 'minutes' => $ltime[1],
1460: 'hours' => $ltime[2],
1461: 'day' => $ltime[3],
1462: 'month' => $ltime[4]+1,
1463: 'year' => $ltime[5]+1900,
1464: 'weekday' => $ltime[6],
1465: 'dayyear' => $ltime[7]+1,
1466: 'dlsav' => $ltime[8] );
1467: }
1468:
1469: sub maketime {
1470: my %th=@_;
1471: return POSIX::mktime(
1472: ($th{'seconds'},$th{'minutes'},$th{'hours'},
1473: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1474: }
1475:
1476:
1477: #########################################
1478: #
1479: # Retro-fixing of un-backward-compatible time format
1480:
1481: sub unsqltime {
1482: my $timestamp=shift;
1483: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1484: $timestamp=&maketime(
1485: 'year'=>$1,'month'=>$2,'day'=>$3,
1486: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1487: }
1488: return $timestamp;
1489: }
1490:
1491: #########################################
1492:
1493: sub findallcourses {
1494: my %courses=();
1495: my $now=time;
1496: foreach (keys %ENV) {
1497: if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
1498: my ($starttime,$endtime)=$ENV{$_};
1499: my $active=1;
1500: if ($starttime) {
1501: if ($now<$starttime) { $active=0; }
1502: }
1503: if ($endtime) {
1504: if ($now>$endtime) { $active=0; }
1505: }
1506: if ($active) { $courses{$1.'_'.$2}=1; }
1507: }
1508: }
1509: return keys %courses;
1510: }
1511:
1512: ###############################################
1513: ###############################################
1514:
1515: =pod
1516:
1517: =item &determinedomain()
1518:
1519: Inputs: $domain (usually will be undef)
1520:
1521: Returns: Determines which domain should be used for designs
1522:
1523: =cut
1524:
1525: ###############################################
1526: sub determinedomain {
1527: my $domain=shift;
1528: if (! $domain) {
1529: # Determine domain if we have not been given one
1530: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1531: if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
1532: if ($ENV{'request.role.domain'}) {
1533: $domain=$ENV{'request.role.domain'};
1534: }
1535: }
1536: return $domain;
1537: }
1538: ###############################################
1539: =pod
1540:
1541: =item &domainlogo()
1542:
1543: Inputs: $domain (usually will be undef)
1544:
1545: Returns: A link to a domain logo, if the domain logo exists.
1546: If the domain logo does not exist, a description of the domain.
1547:
1548: =cut
1549: ###############################################
1550: sub domainlogo {
1551: my $domain = &determinedomain(shift);
1552: # See if there is a logo
1553: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1554: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
1555: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1556: return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
1557: '/adm/lonDomLogos/'.$domain.'.gif" />';
1558: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
1559: return $Apache::lonnet::domaindescription{$domain};
1560: } else {
1561: return '';
1562: }
1563: }
1564: ##############################################
1565:
1566: =pod
1567:
1568: =item &designparm()
1569:
1570: Inputs: $which parameter; $domain (usually will be undef)
1571:
1572: Returns: value of designparamter $which
1573:
1574: =cut
1575: ##############################################
1576: sub designparm {
1577: my ($which,$domain)=@_;
1578: $domain=&determinedomain($domain);
1579: if ($designhash{$domain.'.'.$which}) {
1580: return $designhash{$domain.'.'.$which};
1581: } else {
1582: return $designhash{'default.'.$which};
1583: }
1584: }
1585:
1586: ###############################################
1587: ###############################################
1588:
1589: =pod
1590:
1591: =item &bodytag()
1592:
1593: Returns a uniform header for LON-CAPA web pages.
1594:
1595: Inputs:
1596:
1597: $title, A title to be displayed on the page.
1598: $function, the current role (can be undef).
1599: $addentries, extra parameters for the <body> tag.
1600: $bodyonly, if defined, only return the <body> tag.
1601: $domain, if defined, force a given domain.
1602: $forcereg, if page should register as content page (relevant for
1603: text interface only)
1604:
1605: Returns: A uniform header for LON-CAPA web pages.
1606: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
1607: If $bodyonly is undef or zero, an html string containing a <body> tag and
1608: other decorations will be returned.
1609:
1610: =cut
1611:
1612: ###############################################
1613:
1614:
1615: ###############################################
1616: sub bodytag {
1617: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
1618: unless ($function) {
1619: $function='student';
1620: if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
1621: $function='coordinator';
1622: }
1623: if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
1624: $function='admin';
1625: }
1626: if (($ENV{'request.role'}=~/^(au|ca)/) ||
1627: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
1628: $function='author';
1629: }
1630: }
1631: my $img=&designparm($function.'.img',$domain);
1632: my $pgbg=&designparm($function.'.pgbg',$domain);
1633: my $tabbg=&designparm($function.'.tabbg',$domain);
1634: my $font=&designparm($function.'.font',$domain);
1635: my $link=&designparm($function.'.link',$domain);
1636: my $alink=&designparm($function.'.alink',$domain);
1637: my $vlink=&designparm($function.'.vlink',$domain);
1638: my $sidebg=&designparm($function.'.sidebg',$domain);
1639:
1640: # role and realm
1641: my ($role,$realm)
1642: =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
1643: # realm
1644: if ($ENV{'request.course.id'}) {
1645: $realm=
1646: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1647: }
1648: unless ($realm) { $realm=' '; }
1649: # Set messages
1650: my $messages=&domainlogo($domain);
1651: # Output
1652: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
1653: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1654: my $bodytag = <<END;
1655: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
1656: $addentries>
1657: END
1658: if ($bodyonly) {
1659: return $bodytag;
1660: } elsif ($ENV{'browser.interface'} eq 'textual') {
1661: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
1662: $forcereg).
1663: '<h1>LON-CAPA: '.$title.'</h1>';
1664: } else {
1665: return(<<ENDBODY);
1666: $bodytag
1667: <table width="100%" cellspacing="0" border="0" cellpadding="0">
1668: <tr><td bgcolor="$font">
1669: <img src="http://$ENV{'HTTP_HOST'}:$lonhttpdPort$img" /></td>
1670: <td bgcolor="$font"><font color='$sidebg'>$messages</font></td>
1671: </tr>
1672: <tr>
1673: <td rowspan="3" bgcolor="$tabbg">
1674: <font size="5"><b>$title</b></font>
1675: <td bgcolor="$tabbg" align="right">
1676: <font size="2">
1677: $ENV{'environment.firstname'}
1678: $ENV{'environment.middlename'}
1679: $ENV{'environment.lastname'}
1680: $ENV{'environment.generation'}
1681: </font>
1682: </td>
1683: </tr>
1684: <tr><td bgcolor="$tabbg" align="right">
1685: <font size="2">$role</font>
1686: </td></tr>
1687: <tr>
1688: <td bgcolor="$tabbg" align="right"><font size="2">$realm</font> </td></tr>
1689: </table><br>
1690: ENDBODY
1691: }
1692: }
1693: ###############################################
1694:
1695: sub get_unprocessed_cgi {
1696: my ($query,$possible_names)= @_;
1697: # $Apache::lonxml::debug=1;
1698: foreach (split(/&/,$query)) {
1699: my ($name, $value) = split(/=/,$_);
1700: $name = &Apache::lonnet::unescape($name);
1701: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
1702: $value =~ tr/+/ /;
1703: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1704: &Apache::lonxml::debug("Seting :$name: to :$value:");
1705: unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1706: }
1707: }
1708: }
1709:
1710: sub cacheheader {
1711: unless ($ENV{'request.method'} eq 'GET') { return ''; }
1712: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1713: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1714: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
1715: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1716: return $output;
1717: }
1718:
1719: sub no_cache {
1720: my ($r) = @_;
1721: unless ($ENV{'request.method'} eq 'GET') { return ''; }
1722: #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
1723: $r->no_cache(1);
1724: $r->header_out("Pragma" => "no-cache");
1725: #$r->header_out("Expires" => $date);
1726: }
1727:
1728: sub add_to_env {
1729: my ($name,$value)=@_;
1730: if (defined($ENV{$name})) {
1731: if (ref($ENV{$name})) {
1732: #already have multiple values
1733: push(@{ $ENV{$name} },$value);
1734: } else {
1735: #first time seeing multiple values, convert hash entry to an arrayref
1736: my $first=$ENV{$name};
1737: undef($ENV{$name});
1738: push(@{ $ENV{$name} },$first,$value);
1739: }
1740: } else {
1741: $ENV{$name}=$value;
1742: }
1743: }
1744:
1745: =pod
1746:
1747: =back
1748:
1749: =head2 CSV Upload/Handling functions
1750:
1751: =over 4
1752:
1753: =item upfile_store($r)
1754:
1755: Store uploaded file, $r should be the HTTP Request object,
1756: needs $ENV{'form.upfile'}
1757: returns $datatoken to be put into hidden field
1758:
1759: =cut
1760:
1761: sub upfile_store {
1762: my $r=shift;
1763: $ENV{'form.upfile'}=~s/\r/\n/gs;
1764: $ENV{'form.upfile'}=~s/\f/\n/gs;
1765: $ENV{'form.upfile'}=~s/\n+/\n/gs;
1766: $ENV{'form.upfile'}=~s/\n+$//gs;
1767:
1768: my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
1769: '_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
1770: {
1771: my $fh=Apache::File->new('>'.$r->dir_config('lonDaemons').
1772: '/tmp/'.$datatoken.'.tmp');
1773: print $fh $ENV{'form.upfile'};
1774: }
1775: return $datatoken;
1776: }
1777:
1778: =pod
1779:
1780: =item load_tmp_file($r)
1781:
1782: Load uploaded file from tmp, $r should be the HTTP Request object,
1783: needs $ENV{'form.datatoken'},
1784: sets $ENV{'form.upfile'} to the contents of the file
1785:
1786: =cut
1787:
1788: sub load_tmp_file {
1789: my $r=shift;
1790: my @studentdata=();
1791: {
1792: my $fh;
1793: if ($fh=Apache::File->new($r->dir_config('lonDaemons').
1794: '/tmp/'.$ENV{'form.datatoken'}.'.tmp')) {
1795: @studentdata=<$fh>;
1796: }
1797: }
1798: $ENV{'form.upfile'}=join('',@studentdata);
1799: }
1800:
1801: =pod
1802:
1803: =item upfile_record_sep()
1804:
1805: Separate uploaded file into records
1806: returns array of records,
1807: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
1808:
1809: =cut
1810:
1811: sub upfile_record_sep {
1812: if ($ENV{'form.upfiletype'} eq 'xml') {
1813: } else {
1814: return split(/\n/,$ENV{'form.upfile'});
1815: }
1816: }
1817:
1818: =pod
1819:
1820: =item record_sep($record)
1821:
1822: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
1823:
1824: =cut
1825:
1826: sub record_sep {
1827: my $record=shift;
1828: my %components=();
1829: if ($ENV{'form.upfiletype'} eq 'xml') {
1830: } elsif ($ENV{'form.upfiletype'} eq 'space') {
1831: my $i=0;
1832: foreach (split(/\s+/,$record)) {
1833: my $field=$_;
1834: $field=~s/^(\"|\')//;
1835: $field=~s/(\"|\')$//;
1836: $components{$i}=$field;
1837: $i++;
1838: }
1839: } elsif ($ENV{'form.upfiletype'} eq 'tab') {
1840: my $i=0;
1841: foreach (split(/\t+/,$record)) {
1842: my $field=$_;
1843: $field=~s/^(\"|\')//;
1844: $field=~s/(\"|\')$//;
1845: $components{$i}=$field;
1846: $i++;
1847: }
1848: } else {
1849: my @allfields=split(/\,/,$record);
1850: my $i=0;
1851: my $j;
1852: for ($j=0;$j<=$#allfields;$j++) {
1853: my $field=$allfields[$j];
1854: if ($field=~/^\s*(\"|\')/) {
1855: my $delimiter=$1;
1856: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
1857: $j++;
1858: $field.=','.$allfields[$j];
1859: }
1860: $field=~s/^\s*$delimiter//;
1861: $field=~s/$delimiter\s*$//;
1862: }
1863: $components{$i}=$field;
1864: $i++;
1865: }
1866: }
1867: return %components;
1868: }
1869:
1870: =pod
1871:
1872: =item upfile_select_html()
1873:
1874: return HTML code to select file and specify its type
1875:
1876: =cut
1877:
1878: sub upfile_select_html {
1879: return (<<'ENDUPFORM');
1880: <input type="file" name="upfile" size="50" />
1881: <br />Type: <select name="upfiletype">
1882: <option value="csv">CSV (comma separated values, spreadsheet)</option>
1883: <option value="space">Space separated</option>
1884: <option value="tab">Tabulator separated</option>
1885: <option value="xml">HTML/XML</option>
1886: </select>
1887: ENDUPFORM
1888: }
1889:
1890: =pod
1891:
1892: =item csv_print_samples($r,$records)
1893:
1894: Prints a table of sample values from each column uploaded $r is an
1895: Apache Request ref, $records is an arrayref from
1896: &Apache::loncommon::upfile_record_sep
1897:
1898: =cut
1899:
1900: sub csv_print_samples {
1901: my ($r,$records) = @_;
1902: my (%sone,%stwo,%sthree);
1903: %sone=&record_sep($$records[0]);
1904: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
1905: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1906:
1907: $r->print('Samples<br /><table border="2"><tr>');
1908: foreach (sort({$a <=> $b} keys(%sone))) { $r->print('<th>Column '.($_+1).'</th>'); }
1909: $r->print('</tr>');
1910: foreach my $hash (\%sone,\%stwo,\%sthree) {
1911: $r->print('<tr>');
1912: foreach (sort({$a <=> $b} keys(%sone))) {
1913: $r->print('<td>');
1914: if (defined($$hash{$_})) { $r->print($$hash{$_}); }
1915: $r->print('</td>');
1916: }
1917: $r->print('</tr>');
1918: }
1919: $r->print('</tr></table><br />'."\n");
1920: }
1921:
1922: =pod
1923:
1924: =item csv_print_select_table($r,$records,$d)
1925:
1926: Prints a table to create associations between values and table columns.
1927: $r is an Apache Request ref,
1928: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1929: $d is an array of 2 element arrays (internal name, displayed name)
1930:
1931: =cut
1932:
1933: sub csv_print_select_table {
1934: my ($r,$records,$d) = @_;
1935: my $i=0;my %sone;
1936: %sone=&record_sep($$records[0]);
1937: $r->print('Associate columns with student attributes.'."\n".
1938: '<table border="2"><tr><th>Attribute</th><th>Column</th></tr>'."\n");
1939: foreach (@$d) {
1940: my ($value,$display)=@{ $_ };
1941: $r->print('<tr><td>'.$display.'</td>');
1942:
1943: $r->print('<td><select name=f'.$i.
1944: ' onchange="javascript:flip(this.form,'.$i.');">');
1945: $r->print('<option value="none"></option>');
1946: foreach (sort({$a <=> $b} keys(%sone))) {
1947: $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
1948: }
1949: $r->print('</select></td></tr>'."\n");
1950: $i++;
1951: }
1952: $i--;
1953: return $i;
1954: }
1955:
1956: =pod
1957:
1958: =item csv_samples_select_table($r,$records,$d)
1959:
1960: Prints a table of sample values from the upload and can make associate samples to internal names.
1961:
1962: $r is an Apache Request ref,
1963: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1964: $d is an array of 2 element arrays (internal name, displayed name)
1965:
1966: =cut
1967:
1968: sub csv_samples_select_table {
1969: my ($r,$records,$d) = @_;
1970: my %sone; my %stwo; my %sthree;
1971: my $i=0;
1972:
1973: $r->print('<table border=2><tr><th>Field</th><th>Samples</th></tr>');
1974: %sone=&record_sep($$records[0]);
1975: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
1976: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
1977:
1978: foreach (sort keys %sone) {
1979: $r->print('<tr><td><select name=f'.$i.
1980: ' onchange="javascript:flip(this.form,'.$i.');">');
1981: foreach (@$d) {
1982: my ($value,$display)=@{ $_ };
1983: $r->print('<option value='.$value.'>'.$display.'</option>');
1984: }
1985: $r->print('</select></td><td>');
1986: if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
1987: if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
1988: if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
1989: $r->print('</td></tr>');
1990: $i++;
1991: }
1992: $i--;
1993: return($i);
1994: }
1995:
1996: =pod
1997:
1998: =item check_if_partid_hidden($id,$symb,$udom,$uname)
1999:
2000: Returns either 1 or undef
2001:
2002: 1 if the part is to be hidden, undef if it is to be shown
2003:
2004: Arguments are:
2005:
2006: $id the id of the part to be checked
2007: $symb, optional the symb of the resource to check
2008: $udom, optional the domain of the user to check for
2009: $uname, optional the username of the user to check for
2010:
2011: =cut
2012:
2013: sub check_if_partid_hidden {
2014: my ($id,$symb,$udom,$uname) = @_;
2015: my $hiddenparts=&Apache::lonnet::EXT('resource.0.parameter_hiddenparts',
2016: $symb,$udom,$uname);
2017: my @hiddenlist=split(/,/,$hiddenparts);
2018: foreach my $checkid (@hiddenlist) {
2019: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return 1; }
2020: }
2021: return undef;
2022: }
2023:
2024:
2025:
2026: 1;
2027: __END__;
2028:
2029: =pod
2030:
2031: =back
2032:
2033: =head2 Access .tab File Data
2034:
2035: =over 4
2036:
2037: =item languageids()
2038:
2039: returns list of all language ids
2040:
2041: =item languagedescription()
2042:
2043: returns description of a specified language id
2044:
2045: =item copyrightids()
2046:
2047: returns list of all copyrights
2048:
2049: =item copyrightdescription()
2050:
2051: returns description of a specified copyright id
2052:
2053: =item filecategories()
2054:
2055: returns list of all file categories
2056:
2057: =item filecategorytypes()
2058:
2059: returns list of file types belonging to a given file
2060: category
2061:
2062: =item fileembstyle()
2063:
2064: returns embedding style for a specified file type
2065:
2066: =item filedescription()
2067:
2068: returns description for a specified file type
2069:
2070: =item filedescriptionex()
2071:
2072: returns description for a specified file type with
2073: extra formatting
2074:
2075: =back
2076:
2077: =head2 Alternate Problem Views
2078:
2079: =over 4
2080:
2081: =item get_previous_attempt()
2082:
2083: return string with previous attempt on problem
2084:
2085: =item get_student_view()
2086:
2087: show a snapshot of what student was looking at
2088:
2089: =item get_student_answers()
2090:
2091: show a snapshot of how student was answering problem
2092:
2093: =back
2094:
2095: =head2 HTTP Helper
2096:
2097: =over 4
2098:
2099: =item get_unprocessed_cgi($query,$possible_names)
2100:
2101: Modify the %ENV hash to contain unprocessed CGI form parameters held in
2102: $query. The parameters listed in $possible_names (an array reference),
2103: will be set in $ENV{'form.name'} if they do not already exist.
2104:
2105: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
2106: $possible_names is an ref to an array of form element names. As an example:
2107: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
2108: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
2109:
2110: =item cacheheader()
2111:
2112: returns cache-controlling header code
2113:
2114: =item no_cache($r)
2115:
2116: specifies header code to not have cache
2117:
2118: =item add_to_env($name,$value)
2119:
2120: adds $name to the %ENV hash with value
2121: $value, if $name already exists, the entry is converted to an array
2122: reference and $value is added to the array.
2123:
2124: =back
2125:
2126: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>