1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.160 2003/12/17 19:20:23 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:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet();
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::Constants qw(:common :http :methods);
62: use Apache::lonmsg();
63: use Apache::lonmenu();
64: use Apache::lonlocal;
65: use HTML::Entities;
66:
67: my $readit;
68:
69: ##
70: ## Global Variables
71: ##
72:
73: # ----------------------------------------------- Filetypes/Languages/Copyright
74: my %language;
75: my %supported_language;
76: my %cprtag;
77: my %fe; my %fd;
78: my %category_extensions;
79:
80: # ---------------------------------------------- Designs
81:
82: my %designhash;
83:
84: # ---------------------------------------------- Thesaurus variables
85: #
86: # %Keywords:
87: # A hash used by &keyword to determine if a word is considered a keyword.
88: # $thesaurus_db_file
89: # Scalar containing the full path to the thesaurus database.
90:
91: my %Keywords;
92: my $thesaurus_db_file;
93:
94: #
95: # Initialize values from language.tab, copyright.tab, filetypes.tab,
96: # thesaurus.tab, and filecategories.tab.
97: #
98: BEGIN {
99: # Variable initialization
100: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
101: #
102: unless ($readit) {
103: # ------------------------------------------------------------------- languages
104: {
105: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
106: '/language.tab';
107: if ( open(my $fh,"<$langtabfile") ) {
108: while (<$fh>) {
109: next if /^\#/;
110: chomp;
111: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
112: $language{$key}=$val.' - '.$enc;
113: if ($sup) {
114: $supported_language{$key}=$sup;
115: }
116: }
117: close($fh);
118: }
119: }
120: # ------------------------------------------------------------------ copyrights
121: {
122: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
123: '/copyright.tab';
124: if ( open (my $fh,"<$copyrightfile") ) {
125: while (<$fh>) {
126: next if /^\#/;
127: chomp;
128: my ($key,$val)=(split(/\s+/,$_,2));
129: $cprtag{$key}=$val;
130: }
131: close($fh);
132: }
133: }
134:
135: # -------------------------------------------------------------- domain designs
136:
137: my $filename;
138: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
139: opendir(DIR,$designdir);
140: while ($filename=readdir(DIR)) {
141: my ($domain)=($filename=~/^(\w+)\./);
142: {
143: my $designfile = $designdir.'/'.$filename;
144: if ( open (my $fh,"<$designfile") ) {
145: while (<$fh>) {
146: next if /^\#/;
147: chomp;
148: my ($key,$val)=(split(/\=/,$_));
149: if ($val) { $designhash{$domain.'.'.$key}=$val; }
150: }
151: close($fh);
152: }
153: }
154:
155: }
156: closedir(DIR);
157:
158:
159: # ------------------------------------------------------------- file categories
160: {
161: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
162: '/filecategories.tab';
163: if ( open (my $fh,"<$categoryfile") ) {
164: while (<$fh>) {
165: next if /^\#/;
166: chomp;
167: my ($extension,$category)=(split(/\s+/,$_,2));
168: push @{$category_extensions{lc($category)}},$extension;
169: }
170: close($fh);
171: }
172:
173: }
174: # ------------------------------------------------------------------ file types
175: {
176: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
177: '/filetypes.tab';
178: if ( open (my $fh,"<$typesfile") ) {
179: while (<$fh>) {
180: next if (/^\#/);
181: chomp;
182: my ($ending,$emb,$descr)=split(/\s+/,$_,3);
183: if ($descr ne '') {
184: $fe{$ending}=lc($emb);
185: $fd{$ending}=$descr;
186: }
187: }
188: close($fh);
189: }
190: }
191: &Apache::lonnet::logthis(
192: "<font color=yellow>INFO: Read file types</font>");
193: $readit=1;
194: } # end of unless($readit)
195:
196: }
197:
198: ###############################################################
199: ## HTML and Javascript Helper Functions ##
200: ###############################################################
201:
202: =pod
203:
204: =head1 HTML and Javascript Functions
205:
206: =over 4
207:
208: =item * browser_and_searcher_javascript ()
209:
210: X<browsing, javascript>X<searching, javascript>Returns a string
211: containing javascript with two functions, C<openbrowser> and
212: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
213: tags.
214:
215: =item * openbrowser(formname,elementname,only,omit) [javascript]
216:
217: inputs: formname, elementname, only, omit
218:
219: formname and elementname indicate the name of the html form and name of
220: the element that the results of the browsing selection are to be placed in.
221:
222: Specifying 'only' will restrict the browser to displaying only files
223: with the given extension. Can be a comma seperated list.
224:
225: Specifying 'omit' will restrict the browser to NOT displaying files
226: with the given extension. Can be a comma seperated list.
227:
228: =item * opensearcher(formname, elementname) [javascript]
229:
230: Inputs: formname, elementname
231:
232: formname and elementname specify the name of the html form and the name
233: of the element the selection from the search results will be placed in.
234:
235: =cut
236:
237: sub browser_and_searcher_javascript {
238: return <<END;
239: var editbrowser = null;
240: function openbrowser(formname,elementname,only,omit,titleelement) {
241: var url = '/res/?';
242: if (editbrowser == null) {
243: url += 'launch=1&';
244: }
245: url += 'catalogmode=interactive&';
246: url += 'mode=edit&';
247: url += 'form=' + formname + '&';
248: if (only != null) {
249: url += 'only=' + only + '&';
250: }
251: if (omit != null) {
252: url += 'omit=' + omit + '&';
253: }
254: if (titleelement != null) {
255: url += 'titleelement=' + titleelement + '&';
256: }
257: url += 'element=' + elementname + '';
258: var title = 'Browser';
259: var options = 'scrollbars=1,resizable=1,menubar=0';
260: options += ',width=700,height=600';
261: editbrowser = open(url,title,options,'1');
262: editbrowser.focus();
263: }
264: var editsearcher;
265: function opensearcher(formname,elementname,titleelement) {
266: var url = '/adm/searchcat?';
267: if (editsearcher == null) {
268: url += 'launch=1&';
269: }
270: url += 'catalogmode=interactive&';
271: url += 'mode=edit&';
272: url += 'form=' + formname + '&';
273: if (titleelement != null) {
274: url += 'titleelement=' + titleelement + '&';
275: }
276: url += 'element=' + elementname + '';
277: var title = 'Search';
278: var options = 'scrollbars=1,resizable=1,menubar=0';
279: options += ',width=700,height=600';
280: editsearcher = open(url,title,options,'1');
281: editsearcher.focus();
282: }
283: END
284: }
285:
286: sub studentbrowser_javascript {
287: unless (
288: (($ENV{'request.course.id'}) &&
289: (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})))
290: || ($ENV{'request.role'}=~/^(au|dc|su)/)
291: ) { return ''; }
292: return (<<'ENDSTDBRW');
293: <script type="text/javascript" language="Javascript" >
294: var stdeditbrowser;
295: function openstdbrowser(formname,uname,udom,roleflag) {
296: var url = '/adm/pickstudent?';
297: var filter;
298: eval('filter=document.'+formname+'.'+uname+'.value;');
299: if (filter != null) {
300: if (filter != '') {
301: url += 'filter='+filter+'&';
302: }
303: }
304: url += 'form=' + formname + '&unameelement='+uname+
305: '&udomelement='+udom;
306: if (roleflag) { url+="&roles=1"; }
307: var title = 'Student_Browser';
308: var options = 'scrollbars=1,resizable=1,menubar=0';
309: options += ',width=700,height=600';
310: stdeditbrowser = open(url,title,options,'1');
311: stdeditbrowser.focus();
312: }
313: </script>
314: ENDSTDBRW
315: }
316:
317: sub selectstudent_link {
318: my ($form,$unameele,$udomele)=@_;
319: if ($ENV{'request.course.id'}) {
320: unless (&Apache::lonnet::allowed('srm',$ENV{'request.course.id'})) {
321: return '';
322: }
323: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
324: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
325: }
326: if ($ENV{'request.role'}=~/^(au|dc|su)/) {
327: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
328: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
329: }
330: return '';
331: }
332:
333: sub coursebrowser_javascript {
334: my ($domainfilter)=@_;
335: return (<<ENDSTDBRW);
336: <script type="text/javascript" language="Javascript" >
337: var stdeditbrowser;
338: function opencrsbrowser(formname,uname,udom) {
339: var url = '/adm/pickcourse?';
340: var filter;
341: if (filter != null) {
342: if (filter != '') {
343: url += 'filter='+filter+'&';
344: }
345: }
346: var domainfilter='$domainfilter';
347: if (domainfilter != null) {
348: if (domainfilter != '') {
349: url += 'domainfilter='+domainfilter+'&';
350: }
351: }
352: url += 'form=' + formname + '&cnumelement='+uname+
353: '&cdomelement='+udom;
354: var title = 'Course_Browser';
355: var options = 'scrollbars=1,resizable=1,menubar=0';
356: options += ',width=700,height=600';
357: stdeditbrowser = open(url,title,options,'1');
358: stdeditbrowser.focus();
359: }
360: </script>
361: ENDSTDBRW
362: }
363:
364: sub selectcourse_link {
365: my ($form,$unameele,$udomele)=@_;
366: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
367: '","'.$udomele.'");'."'>".&mt('Select Course')."</a>";
368: }
369:
370: =pod
371:
372: =item * linked_select_forms(...)
373:
374: linked_select_forms returns a string containing a <script></script> block
375: and html for two <select> menus. The select menus will be linked in that
376: changing the value of the first menu will result in new values being placed
377: in the second menu. The values in the select menu will appear in alphabetical
378: order.
379:
380: linked_select_forms takes the following ordered inputs:
381:
382: =over 4
383:
384: =item * $formname, the name of the <form> tag
385:
386: =item * $middletext, the text which appears between the <select> tags
387:
388: =item * $firstdefault, the default value for the first menu
389:
390: =item * $firstselectname, the name of the first <select> tag
391:
392: =item * $secondselectname, the name of the second <select> tag
393:
394: =item * $hashref, a reference to a hash containing the data for the menus.
395:
396: =back
397:
398: Below is an example of such a hash. Only the 'text', 'default', and
399: 'select2' keys must appear as stated. keys(%menu) are the possible
400: values for the first select menu. The text that coincides with the
401: first menu value is given in $menu{$choice1}->{'text'}. The values
402: and text for the second menu are given in the hash pointed to by
403: $menu{$choice1}->{'select2'}.
404:
405: my %menu = ( A1 => { text =>"Choice A1" ,
406: default => "B3",
407: select2 => {
408: B1 => "Choice B1",
409: B2 => "Choice B2",
410: B3 => "Choice B3",
411: B4 => "Choice B4"
412: }
413: },
414: A2 => { text =>"Choice A2" ,
415: default => "C2",
416: select2 => {
417: C1 => "Choice C1",
418: C2 => "Choice C2",
419: C3 => "Choice C3"
420: }
421: },
422: A3 => { text =>"Choice A3" ,
423: default => "D6",
424: select2 => {
425: D1 => "Choice D1",
426: D2 => "Choice D2",
427: D3 => "Choice D3",
428: D4 => "Choice D4",
429: D5 => "Choice D5",
430: D6 => "Choice D6",
431: D7 => "Choice D7"
432: }
433: }
434: );
435:
436: =cut
437:
438: sub linked_select_forms {
439: my ($formname,
440: $middletext,
441: $firstdefault,
442: $firstselectname,
443: $secondselectname,
444: $hashref
445: ) = @_;
446: my $second = "document.$formname.$secondselectname";
447: my $first = "document.$formname.$firstselectname";
448: # output the javascript to do the changing
449: my $result = '';
450: $result.="<script>\n";
451: $result.="var select2data = new Object();\n";
452: $" = '","';
453: my $debug = '';
454: foreach my $s1 (sort(keys(%$hashref))) {
455: $result.="select2data.d_$s1 = new Object();\n";
456: $result.="select2data.d_$s1.def = new String('".
457: $hashref->{$s1}->{'default'}."');\n";
458: $result.="select2data.d_$s1.values = new Array(";
459: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
460: $result.="\"@s2values\");\n";
461: $result.="select2data.d_$s1.texts = new Array(";
462: my @s2texts;
463: foreach my $value (@s2values) {
464: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
465: }
466: $result.="\"@s2texts\");\n";
467: }
468: $"=' ';
469: $result.= <<"END";
470:
471: function select1_changed() {
472: // Determine new choice
473: var newvalue = "d_" + $first.value;
474: // update select2
475: var values = select2data[newvalue].values;
476: var texts = select2data[newvalue].texts;
477: var select2def = select2data[newvalue].def;
478: var i;
479: // out with the old
480: for (i = 0; i < $second.options.length; i++) {
481: $second.options[i] = null;
482: }
483: // in with the nuclear
484: for (i=0;i<values.length; i++) {
485: $second.options[i] = new Option(values[i]);
486: $second.options[i].value = values[i];
487: $second.options[i].text = texts[i];
488: if (values[i] == select2def) {
489: $second.options[i].selected = true;
490: }
491: }
492: }
493: </script>
494: END
495: # output the initial values for the selection lists
496: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
497: foreach my $value (sort(keys(%$hashref))) {
498: $result.=" <option value=\"$value\" ";
499: $result.=" selected=\"true\" " if ($value eq $firstdefault);
500: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
501: }
502: $result .= "</select>\n";
503: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
504: $result .= $middletext;
505: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
506: my $seconddefault = $hashref->{$firstdefault}->{'default'};
507: foreach my $value (sort(keys(%select2))) {
508: $result.=" <option value=\"$value\" ";
509: $result.=" selected=\"true\" " if ($value eq $seconddefault);
510: $result.=">".&mt($select2{$value})."</option>\n";
511: }
512: $result .= "</select>\n";
513: # return $debug;
514: return $result;
515: } # end of sub linked_select_forms {
516:
517: =pod
518:
519: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
520:
521: Returns a string corresponding to an HTML link to the given help
522: $topic, where $topic corresponds to the name of a .tex file in
523: /home/httpd/html/adm/help/tex, with underscores replaced by
524: spaces.
525:
526: $text will optionally be linked to the same topic, allowing you to
527: link text in addition to the graphic. If you do not want to link
528: text, but wish to specify one of the later parameters, pass an
529: empty string.
530:
531: $stayOnPage is a value that will be interpreted as a boolean. If true,
532: the link will not open a new window. If false, the link will open
533: a new window using Javascript. (Default is false.)
534:
535: $width and $height are optional numerical parameters that will
536: override the width and height of the popped up window, which may
537: be useful for certain help topics with big pictures included.
538:
539: =cut
540:
541: sub help_open_topic {
542: my ($topic, $text, $stayOnPage, $width, $height) = @_;
543: $text = "" if (not defined $text);
544: $stayOnPage = 0 if (not defined $stayOnPage);
545: if ($ENV{'browser.interface'} eq 'textual' ||
546: $ENV{'environment.remote'} eq 'off' ) {
547: $stayOnPage=1;
548: }
549: $width = 350 if (not defined $width);
550: $height = 400 if (not defined $height);
551: my $filename = $topic;
552: $filename =~ s/ /_/g;
553:
554: my $template = "";
555: my $link;
556:
557: $topic=~s/\W/\_/g;
558:
559: if (!$stayOnPage)
560: {
561: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
562: }
563: else
564: {
565: $link = "/adm/help/${filename}.hlp";
566: }
567:
568: # Add the text
569: if ($text ne "")
570: {
571: $template .=
572: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
573: "<td bgcolor='#5555FF'><a href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
574: }
575:
576: # Add the graphic
577: $template .= <<"ENDTEMPLATE";
578: <a href="$link"><image src="/adm/help/gif/smallHelp.gif" border="0" alt="(Help: $topic)" /></a>
579: ENDTEMPLATE
580: if ($text ne '') { $template.='</td></tr></table>' };
581: return $template;
582:
583: }
584:
585: # This is a quicky function for Latex cheatsheet editing, since it
586: # appears in at least four places
587: sub helpLatexCheatsheet {
588: my $other = shift;
589: my $addOther = '';
590: if ($other) {
591: $addOther = Apache::loncommon::help_open_topic($other, shift,
592: undef, undef, 600) .
593: '</td><td>';
594: }
595: return '<table><tr><td>'.
596: $addOther .
597: &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
598: undef,undef,600)
599: .'</td><td>'.
600: &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
601: undef,undef,600)
602: .'</td></tr></table>';
603: }
604:
605: =pod
606:
607: =item * csv_translate($text)
608:
609: Translate $text to allow it to be output as a 'comma seperated values'
610: format.
611:
612: =cut
613:
614: sub csv_translate {
615: my $text = shift;
616: $text =~ s/\"/\"\"/g;
617: $text =~ s/\n//g;
618: return $text;
619: }
620:
621: =pod
622:
623: =item * change_content_javascript():
624:
625: This and the next function allow you to create small sections of an
626: otherwise static HTML page that you can update on the fly with
627: Javascript, even in Netscape 4.
628:
629: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
630: must be written to the HTML page once. It will prove the Javascript
631: function "change(name, content)". Calling the change function with the
632: name of the section
633: you want to update, matching the name passed to C<changable_area>, and
634: the new content you want to put in there, will put the content into
635: that area.
636:
637: B<Note>: Netscape 4 only reserves enough space for the changable area
638: to contain room for the original contents. You need to "make space"
639: for whatever changes you wish to make, and be B<sure> to check your
640: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
641: it's adequate for updating a one-line status display, but little more.
642: This script will set the space to 100% width, so you only need to
643: worry about height in Netscape 4.
644:
645: Modern browsers are much less limiting, and if you can commit to the
646: user not using Netscape 4, this feature may be used freely with
647: pretty much any HTML.
648:
649: =cut
650:
651: sub change_content_javascript {
652: # If we're on Netscape 4, we need to use Layer-based code
653: if ($ENV{'browser.type'} eq 'netscape' &&
654: $ENV{'browser.version'} =~ /^4\./) {
655: return (<<NETSCAPE4);
656: function change(name, content) {
657: doc = document.layers[name+"___escape"].layers[0].document;
658: doc.open();
659: doc.write(content);
660: doc.close();
661: }
662: NETSCAPE4
663: } else {
664: # Otherwise, we need to use semi-standards-compliant code
665: # (technically, "innerHTML" isn't standard but the equivalent
666: # is really scary, and every useful browser supports it
667: return (<<DOMBASED);
668: function change(name, content) {
669: element = document.getElementById(name);
670: element.innerHTML = content;
671: }
672: DOMBASED
673: }
674: }
675:
676: =pod
677:
678: =item * changable_area($name, $origContent):
679:
680: This provides a "changable area" that can be modified on the fly via
681: the Javascript code provided in C<change_content_javascript>. $name is
682: the name you will use to reference the area later; do not repeat the
683: same name on a given HTML page more then once. $origContent is what
684: the area will originally contain, which can be left blank.
685:
686: =cut
687:
688: sub changable_area {
689: my ($name, $origContent) = @_;
690:
691: if ($ENV{'browser.type'} eq 'netscape' &&
692: $ENV{'browser.version'} =~ /^4\./) {
693: # If this is netscape 4, we need to use the Layer tag
694: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
695: } else {
696: return "<span id='$name'>$origContent</span>";
697: }
698: }
699:
700: =pod
701:
702: =back
703:
704: =cut
705:
706: ###############################################################
707: ## Home server <option> list generating code ##
708: ###############################################################
709:
710: =pod
711:
712: =head1 Home Server option list generating code
713:
714: =over 4
715:
716: =item * get_domains()
717:
718: Returns an array containing each of the domains listed in the hosts.tab
719: file.
720:
721: =cut
722:
723: #-------------------------------------------
724: sub get_domains {
725: # The code below was stolen from "The Perl Cookbook", p 102, 1st ed.
726: my @domains;
727: my %seen;
728: foreach (sort values(%Apache::lonnet::hostdom)) {
729: push (@domains,$_) unless $seen{$_}++;
730: }
731: return @domains;
732: }
733:
734: #-------------------------------------------
735:
736: =pod
737:
738: =item * select_form($defdom,$name,%hash)
739:
740: Returns a string containing a <select name='$name' size='1'> form to
741: allow a user to select options from a hash option_name => displayed text.
742: See lonrights.pm for an example invocation and use.
743:
744: =cut
745:
746: #-------------------------------------------
747: sub select_form {
748: my ($def,$name,%hash) = @_;
749: my $selectform = "<select name=\"$name\" size=\"1\">\n";
750: my @keys;
751: if (exists($hash{'select_form_order'})) {
752: @keys=@{$hash{'select_form_order'}};
753: } else {
754: @keys=sort(keys(%hash));
755: }
756: foreach (@keys) {
757: $selectform.="<option value=\"$_\" ".
758: ($_ eq $def ? 'selected' : '').
759: ">".&mt($hash{$_})."</option>\n";
760: }
761: $selectform.="</select>";
762: return $selectform;
763: }
764:
765:
766: #-------------------------------------------
767:
768: =pod
769:
770: =item * select_dom_form($defdom,$name,$includeempty)
771:
772: Returns a string containing a <select name='$name' size='1'> form to
773: allow a user to select the domain to preform an operation in.
774: See loncreateuser.pm for an example invocation and use.
775:
776: If the $includeempty flag is set, it also includes an empty choice ("no domain
777: selected");
778:
779: =cut
780:
781: #-------------------------------------------
782: sub select_dom_form {
783: my ($defdom,$name,$includeempty) = @_;
784: my @domains = get_domains();
785: if ($includeempty) { @domains=('',@domains); }
786: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
787: foreach (@domains) {
788: $selectdomain.="<option value=\"$_\" ".
789: ($_ eq $defdom ? 'selected' : '').
790: ">$_</option>\n";
791: }
792: $selectdomain.="</select>";
793: return $selectdomain;
794: }
795:
796: #-------------------------------------------
797:
798: =pod
799:
800: =item * get_library_servers($domain)
801:
802: Returns a hash which contains keys like '103l3' and values like
803: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
804: given $domain.
805:
806: =cut
807:
808: #-------------------------------------------
809: sub get_library_servers {
810: my $domain = shift;
811: my %library_servers;
812: foreach (keys(%Apache::lonnet::libserv)) {
813: if ($Apache::lonnet::hostdom{$_} eq $domain) {
814: $library_servers{$_} = $Apache::lonnet::hostname{$_};
815: }
816: }
817: return %library_servers;
818: }
819:
820: #-------------------------------------------
821:
822: =pod
823:
824: =item * home_server_option_list($domain)
825:
826: returns a string which contains an <option> list to be used in a
827: <select> form input. See loncreateuser.pm for an example.
828:
829: =cut
830:
831: #-------------------------------------------
832: sub home_server_option_list {
833: my $domain = shift;
834: my %servers = &get_library_servers($domain);
835: my $result = '';
836: foreach (sort keys(%servers)) {
837: $result.=
838: '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
839: }
840: return $result;
841: }
842:
843: =pod
844:
845: =back
846:
847: =cut
848:
849: ###############################################################
850: ## Decoding User Agent ##
851: ###############################################################
852:
853: =pod
854:
855: =head1 Decoding the User Agent
856:
857: =over 4
858:
859: =item * &decode_user_agent()
860:
861: Inputs: $r
862:
863: Outputs:
864:
865: =over 4
866:
867: =item * $httpbrowser
868:
869: =item * $clientbrowser
870:
871: =item * $clientversion
872:
873: =item * $clientmathml
874:
875: =item * $clientunicode
876:
877: =item * $clientos
878:
879: =back
880:
881: =back
882:
883: =cut
884:
885: ###############################################################
886: ###############################################################
887: sub decode_user_agent {
888: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
889: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
890: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
891: my $clientbrowser='unknown';
892: my $clientversion='0';
893: my $clientmathml='';
894: my $clientunicode='0';
895: for (my $i=0;$i<=$#browsertype;$i++) {
896: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
897: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
898: $clientbrowser=$bname;
899: $httpbrowser=~/$vreg/i;
900: $clientversion=$1;
901: $clientmathml=($clientversion>=$minv);
902: $clientunicode=($clientversion>=$univ);
903: }
904: }
905: my $clientos='unknown';
906: if (($httpbrowser=~/linux/i) ||
907: ($httpbrowser=~/unix/i) ||
908: ($httpbrowser=~/ux/i) ||
909: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
910: if (($httpbrowser=~/vax/i) ||
911: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
912: if ($httpbrowser=~/next/i) { $clientos='next'; }
913: if (($httpbrowser=~/mac/i) ||
914: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
915: if ($httpbrowser=~/win/i) { $clientos='win'; }
916: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
917: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
918: $clientunicode,$clientos,);
919: }
920:
921: ###############################################################
922: ## Authentication changing form generation subroutines ##
923: ###############################################################
924: ##
925: ## All of the authform_xxxxxxx subroutines take their inputs in a
926: ## hash, and have reasonable default values.
927: ##
928: ## formname = the name given in the <form> tag.
929: #-------------------------------------------
930:
931: =pod
932:
933: =head1 Authentication Routines
934:
935: =over 4
936:
937: =item * authform_xxxxxx
938:
939: The authform_xxxxxx subroutines provide javascript and html forms which
940: handle some of the conveniences required for authentication forms.
941: This is not an optimal method, but it works.
942:
943: See loncreateuser.pm for invocation and use examples.
944:
945: =over 4
946:
947: =item * authform_header
948:
949: =item * authform_authorwarning
950:
951: =item * authform_nochange
952:
953: =item * authform_kerberos
954:
955: =item * authform_internal
956:
957: =item * authform_filesystem
958:
959: =back
960:
961: =back
962:
963: =cut
964:
965: #-------------------------------------------
966: sub authform_header{
967: my %in = (
968: formname => 'cu',
969: kerb_def_dom => '',
970: @_,
971: );
972: $in{'formname'} = 'document.' . $in{'formname'};
973: my $result='';
974:
975: #---------------------------------------------- Code for upper case translation
976: my $Javascript_toUpperCase;
977: unless ($in{kerb_def_dom}) {
978: $Javascript_toUpperCase =<<"END";
979: switch (choice) {
980: case 'krb': currentform.elements[choicearg].value =
981: currentform.elements[choicearg].value.toUpperCase();
982: break;
983: default:
984: }
985: END
986: } else {
987: $Javascript_toUpperCase = "";
988: }
989:
990: $result.=<<"END";
991: var current = new Object();
992: current.radiovalue = 'nochange';
993: current.argfield = null;
994:
995: function changed_radio(choice,currentform) {
996: var choicearg = choice + 'arg';
997: // If a radio button in changed, we need to change the argfield
998: if (current.radiovalue != choice) {
999: current.radiovalue = choice;
1000: if (current.argfield != null) {
1001: currentform.elements[current.argfield].value = '';
1002: }
1003: if (choice == 'nochange') {
1004: current.argfield = null;
1005: } else {
1006: current.argfield = choicearg;
1007: switch(choice) {
1008: case 'krb':
1009: currentform.elements[current.argfield].value =
1010: "$in{'kerb_def_dom'}";
1011: break;
1012: default:
1013: break;
1014: }
1015: }
1016: }
1017: return;
1018: }
1019:
1020: function changed_text(choice,currentform) {
1021: var choicearg = choice + 'arg';
1022: if (currentform.elements[choicearg].value !='') {
1023: $Javascript_toUpperCase
1024: // clear old field
1025: if ((current.argfield != choicearg) && (current.argfield != null)) {
1026: currentform.elements[current.argfield].value = '';
1027: }
1028: current.argfield = choicearg;
1029: }
1030: set_auth_radio_buttons(choice,currentform);
1031: return;
1032: }
1033:
1034: function set_auth_radio_buttons(newvalue,currentform) {
1035: var i=0;
1036: while (i < currentform.login.length) {
1037: if (currentform.login[i].value == newvalue) { break; }
1038: i++;
1039: }
1040: if (i == currentform.login.length) {
1041: return;
1042: }
1043: current.radiovalue = newvalue;
1044: currentform.login[i].checked = true;
1045: return;
1046: }
1047: END
1048: return $result;
1049: }
1050:
1051: sub authform_authorwarning{
1052: my $result='';
1053: $result='<i>'.
1054: &mt('As a general rule, only authors or co-authors should be '.
1055: 'filesystem authenticated '.
1056: '(which allows access to the server filesystem).')."</i>\n";
1057: return $result;
1058: }
1059:
1060: sub authform_nochange{
1061: my %in = (
1062: formname => 'document.cu',
1063: kerb_def_dom => 'MSU.EDU',
1064: @_,
1065: );
1066: my $result = &mt('[_1] Do not change login data',
1067: '<input type="radio" name="login" value="nochange" '.
1068: 'checked="checked" onclick="'.
1069: "javascript:changed_radio('nochange',$in{'formname'});".'" />');
1070: return $result;
1071: }
1072:
1073: sub authform_kerberos{
1074: my %in = (
1075: formname => 'document.cu',
1076: kerb_def_dom => 'MSU.EDU',
1077: kerb_def_auth => 'krb4',
1078: @_,
1079: );
1080: my ($check4,$check5);
1081: if ($in{'kerb_def_auth'} eq 'krb5') {
1082: $check5 = " checked=\"on\"";
1083: } else {
1084: $check4 = " checked=\"on\"";
1085: }
1086: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1087: my $result .= &mt
1088: ('[_1] Kerberos authenticated with domain [_2] '.
1089: '[_3] Version 4 [_4] Version 5',
1090: '<input type="radio" name="login" value="krb" '.
1091: 'onclick="'.$jscall.'" onchange="'.$jscall.'" />',
1092: '<input type="text" size="10" name="krbarg" '.
1093: 'value="'.$in{'kerb_def_dom'}.'" '.
1094: 'onchange="'.$jscall.'" />',
1095: '<input type="radio" name="krbver" value="4" '.$check4.' />',
1096: '<input type="radio" name="krbver" value="5" '.$check5.' />');
1097: return $result;
1098: }
1099:
1100: sub authform_internal{
1101: my %args = (
1102: formname => 'document.cu',
1103: kerb_def_dom => 'MSU.EDU',
1104: @_,
1105: );
1106: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1107: my $result.=&mt
1108: ('[_1] Internally authenticated (with initial password [_2])',
1109: '<input type="radio" name="login" value="int" '.
1110: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1111: '<input type="text" size="10" name="intarg" value="" '.
1112: 'onchange="'.$jscall.'" />');
1113: return $result;
1114: }
1115:
1116: sub authform_local{
1117: my %in = (
1118: formname => 'document.cu',
1119: kerb_def_dom => 'MSU.EDU',
1120: @_,
1121: );
1122: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1123: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1124: '<input type="radio" name="login" value="loc" '.
1125: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1126: '<input type="text" size="10" name="locarg" value="" '.
1127: 'onchange="'.$jscall.'" />');
1128: return $result;
1129: }
1130:
1131: sub authform_filesystem{
1132: my %in = (
1133: formname => 'document.cu',
1134: kerb_def_dom => 'MSU.EDU',
1135: @_,
1136: );
1137: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1138: my $result.= &mt
1139: ('[_1] Filesystem Authenticated (with initial password [_2])',
1140: '<input type="radio" name="login" value="fsys" '.
1141: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1142: '<input type="text" size="10" name="fsysarg" value="" '.
1143: 'onchange="'.$jscall.'" />');
1144: return $result;
1145: }
1146:
1147: ###############################################################
1148: ## Get Authentication Defaults for Domain ##
1149: ###############################################################
1150:
1151: =pod
1152:
1153: =head1 Domains and Authentication
1154:
1155: Returns default authentication type and an associated argument as
1156: listed in file 'domain.tab'.
1157:
1158: =over 4
1159:
1160: =item * get_auth_defaults
1161:
1162: get_auth_defaults($target_domain) returns the default authentication
1163: type and an associated argument (initial password or a kerberos domain).
1164: These values are stored in lonTabs/domain.tab
1165:
1166: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1167:
1168: If target_domain is not found in domain.tab, returns nothing ('').
1169:
1170: =cut
1171:
1172: #-------------------------------------------
1173: sub get_auth_defaults {
1174: my $domain=shift;
1175: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1176: }
1177: ###############################################################
1178: ## End Get Authentication Defaults for Domain ##
1179: ###############################################################
1180:
1181: ###############################################################
1182: ## Get Kerberos Defaults for Domain ##
1183: ###############################################################
1184: ##
1185: ## Returns default kerberos version and an associated argument
1186: ## as listed in file domain.tab. If not listed, provides
1187: ## appropriate default domain and kerberos version.
1188: ##
1189: #-------------------------------------------
1190:
1191: =pod
1192:
1193: =item * get_kerberos_defaults
1194:
1195: get_kerberos_defaults($target_domain) returns the default kerberos
1196: version and domain. If not found in domain.tabs, it defaults to
1197: version 4 and the domain of the server.
1198:
1199: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1200:
1201: =cut
1202:
1203: #-------------------------------------------
1204: sub get_kerberos_defaults {
1205: my $domain=shift;
1206: my ($krbdef,$krbdefdom) =
1207: &Apache::loncommon::get_auth_defaults($domain);
1208: unless ($krbdef =~/^krb/ && $krbdefdom) {
1209: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1210: my $krbdefdom=$1;
1211: $krbdefdom=~tr/a-z/A-Z/;
1212: $krbdef = "krb4";
1213: }
1214: return ($krbdef,$krbdefdom);
1215: }
1216:
1217: =pod
1218:
1219: =back
1220:
1221: =cut
1222:
1223: ###############################################################
1224: ## Thesaurus Functions ##
1225: ###############################################################
1226:
1227: =pod
1228:
1229: =head1 Thesaurus Functions
1230:
1231: =over 4
1232:
1233: =item * initialize_keywords
1234:
1235: Initializes the package variable %Keywords if it is empty. Uses the
1236: package variable $thesaurus_db_file.
1237:
1238: =cut
1239:
1240: ###################################################
1241:
1242: sub initialize_keywords {
1243: return 1 if (scalar keys(%Keywords));
1244: # If we are here, %Keywords is empty, so fill it up
1245: # Make sure the file we need exists...
1246: if (! -e $thesaurus_db_file) {
1247: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1248: " failed because it does not exist");
1249: return 0;
1250: }
1251: # Set up the hash as a database
1252: my %thesaurus_db;
1253: if (! tie(%thesaurus_db,'GDBM_File',
1254: $thesaurus_db_file,&GDBM_READER(),0640)){
1255: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1256: $thesaurus_db_file);
1257: return 0;
1258: }
1259: # Get the average number of appearances of a word.
1260: my $avecount = $thesaurus_db{'average.count'};
1261: # Put keywords (those that appear > average) into %Keywords
1262: while (my ($word,$data)=each (%thesaurus_db)) {
1263: my ($count,undef) = split /:/,$data;
1264: $Keywords{$word}++ if ($count > $avecount);
1265: }
1266: untie %thesaurus_db;
1267: # Remove special values from %Keywords.
1268: foreach ('total.count','average.count') {
1269: delete($Keywords{$_}) if (exists($Keywords{$_}));
1270: }
1271: return 1;
1272: }
1273:
1274: ###################################################
1275:
1276: =pod
1277:
1278: =item * keyword($word)
1279:
1280: Returns true if $word is a keyword. A keyword is a word that appears more
1281: than the average number of times in the thesaurus database. Calls
1282: &initialize_keywords
1283:
1284: =cut
1285:
1286: ###################################################
1287:
1288: sub keyword {
1289: return if (!&initialize_keywords());
1290: my $word=lc(shift());
1291: $word=~s/\W//g;
1292: return exists($Keywords{$word});
1293: }
1294:
1295: ###############################################################
1296:
1297: =pod
1298:
1299: =item * get_related_words
1300:
1301: Look up a word in the thesaurus. Takes a scalar argument and returns
1302: an array of words. If the keyword is not in the thesaurus, an empty array
1303: will be returned. The order of the words returned is determined by the
1304: database which holds them.
1305:
1306: Uses global $thesaurus_db_file.
1307:
1308: =cut
1309:
1310: ###############################################################
1311: sub get_related_words {
1312: my $keyword = shift;
1313: my %thesaurus_db;
1314: if (! -e $thesaurus_db_file) {
1315: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
1316: "failed because the file does not exist");
1317: return ();
1318: }
1319: if (! tie(%thesaurus_db,'GDBM_File',
1320: $thesaurus_db_file,&GDBM_READER(),0640)){
1321: return ();
1322: }
1323: my @Words=();
1324: if (exists($thesaurus_db{$keyword})) {
1325: $_ = $thesaurus_db{$keyword};
1326: (undef,@Words) = split/:/; # The first element is the number of times
1327: # the word appears. We do not need it now.
1328: for (my $i=0;$i<=$#Words;$i++) {
1329: ($Words[$i],undef)= split/\,/,$Words[$i];
1330: }
1331: }
1332: untie %thesaurus_db;
1333: return @Words;
1334: }
1335:
1336: =pod
1337:
1338: =back
1339:
1340: =cut
1341:
1342: # -------------------------------------------------------------- Plaintext name
1343: =pod
1344:
1345: =head1 User Name Functions
1346:
1347: =over 4
1348:
1349: =item * plainname($uname,$udom)
1350:
1351: Takes a users logon name and returns it as a string in
1352: "first middle last generation" form
1353:
1354: =cut
1355:
1356: ###############################################################
1357: sub plainname {
1358: my ($uname,$udom)=@_;
1359: my %names=&Apache::lonnet::get('environment',
1360: ['firstname','middlename','lastname','generation'],
1361: $udom,$uname);
1362: my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1363: $names{'lastname'}.' '.$names{'generation'};
1364: $name=~s/\s+$//;
1365: $name=~s/\s+/ /g;
1366: return $name;
1367: }
1368:
1369: # -------------------------------------------------------------------- Nickname
1370: =pod
1371:
1372: =item * nickname($uname,$udom)
1373:
1374: Gets a users name and returns it as a string as
1375:
1376: ""nickname""
1377:
1378: if the user has a nickname or
1379:
1380: "first middle last generation"
1381:
1382: if the user does not
1383:
1384: =cut
1385:
1386: sub nickname {
1387: my ($uname,$udom)=@_;
1388: my %names=&Apache::lonnet::get('environment',
1389: ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1390: my $name=$names{'nickname'};
1391: if ($name) {
1392: $name='"'.$name.'"';
1393: } else {
1394: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1395: $names{'lastname'}.' '.$names{'generation'};
1396: $name=~s/\s+$//;
1397: $name=~s/\s+/ /g;
1398: }
1399: return $name;
1400: }
1401:
1402:
1403: # ------------------------------------------------------------------ Screenname
1404:
1405: =pod
1406:
1407: =item * screenname($uname,$udom)
1408:
1409: Gets a users screenname and returns it as a string
1410:
1411: =cut
1412:
1413: sub screenname {
1414: my ($uname,$udom)=@_;
1415: my %names=
1416: &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1417: return $names{'screenname'};
1418: }
1419:
1420: # ------------------------------------------------------------- Message Wrapper
1421:
1422: sub messagewrapper {
1423: my ($link,$un,$do)=@_;
1424: return
1425: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1426: }
1427: # --------------------------------------------------------------- Notes Wrapper
1428:
1429: sub noteswrapper {
1430: my ($link,$un,$do)=@_;
1431: return
1432: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1433: }
1434: # ------------------------------------------------------------- Aboutme Wrapper
1435:
1436: sub aboutmewrapper {
1437: my ($link,$username,$domain)=@_;
1438: return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1439: }
1440:
1441: # ------------------------------------------------------------ Syllabus Wrapper
1442:
1443:
1444: sub syllabuswrapper {
1445: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
1446: if ($fontcolor) {
1447: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
1448: }
1449: return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1450: }
1451:
1452: =pod
1453:
1454: =back
1455:
1456: =head1 Access .tab File Data
1457:
1458: =over 4
1459:
1460: =item * languageids()
1461:
1462: returns list of all language ids
1463:
1464: =cut
1465:
1466: sub languageids {
1467: return sort(keys(%language));
1468: }
1469:
1470: =pod
1471:
1472: =item * languagedescription()
1473:
1474: returns description of a specified language id
1475:
1476: =cut
1477:
1478: sub languagedescription {
1479: my $code=shift;
1480: return ($supported_language{$code}?'* ':'').
1481: $language{$code}.
1482: ($supported_language{$code}?' ('.&mt('interface available').')':'');
1483: }
1484:
1485: sub plainlanguagedescription {
1486: my $code=shift;
1487: return $language{$code};
1488: }
1489:
1490: sub supportedlanguagecode {
1491: my $code=shift;
1492: return $supported_language{$code};
1493: }
1494:
1495: =pod
1496:
1497: =item * copyrightids()
1498:
1499: returns list of all copyrights
1500:
1501: =cut
1502:
1503: sub copyrightids {
1504: return sort(keys(%cprtag));
1505: }
1506:
1507: =pod
1508:
1509: =item * copyrightdescription()
1510:
1511: returns description of a specified copyright id
1512:
1513: =cut
1514:
1515: sub copyrightdescription {
1516: return $cprtag{shift(@_)};
1517: }
1518:
1519: =pod
1520:
1521: =item * filecategories()
1522:
1523: returns list of all file categories
1524:
1525: =cut
1526:
1527: sub filecategories {
1528: return sort(keys(%category_extensions));
1529: }
1530:
1531: =pod
1532:
1533: =item * filecategorytypes()
1534:
1535: returns list of file types belonging to a given file
1536: category
1537:
1538: =cut
1539:
1540: sub filecategorytypes {
1541: return @{$category_extensions{lc($_[0])}};
1542: }
1543:
1544: =pod
1545:
1546: =item * fileembstyle()
1547:
1548: returns embedding style for a specified file type
1549:
1550: =cut
1551:
1552: sub fileembstyle {
1553: return $fe{lc(shift(@_))};
1554: }
1555:
1556: =pod
1557:
1558: =item * filedescription()
1559:
1560: returns description for a specified file type
1561:
1562: =cut
1563:
1564: sub filedescription {
1565: return $fd{lc(shift(@_))};
1566: }
1567:
1568: =pod
1569:
1570: =item * filedescriptionex()
1571:
1572: returns description for a specified file type with
1573: extra formatting
1574:
1575: =cut
1576:
1577: sub filedescriptionex {
1578: my $ex=shift;
1579: return '.'.$ex.' '.$fd{lc($ex)};
1580: }
1581:
1582: # End of .tab access
1583: =pod
1584:
1585: =back
1586:
1587: =cut
1588:
1589: # ------------------------------------------------------------------ File Types
1590: sub fileextensions {
1591: return sort(keys(%fe));
1592: }
1593:
1594: # ----------------------------------------------------------- Display Languages
1595: # returns a hash with all desired display languages
1596: #
1597:
1598: sub display_languages {
1599: my %languages=();
1600: foreach (&preferred_languages()) {
1601: $languages{$_}=1;
1602: }
1603: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1604: if ($ENV{'form.displaylanguage'}) {
1605: foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
1606: $languages{$_}=1;
1607: }
1608: }
1609: return %languages;
1610: }
1611:
1612: sub preferred_languages {
1613: my @languages=();
1614: if ($ENV{'environment.languages'}) {
1615: @languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
1616: }
1617: if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
1618: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1619: $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1620: }
1621: my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
1622: if ($browser) {
1623: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
1624: }
1625: if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
1626: @languages=(@languages,
1627: $Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
1628: }
1629: if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
1630: @languages=(@languages,
1631: $Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
1632: }
1633: if ($Apache::lonnet::domain_lang_def{
1634: $Apache::lonnet::perlvar{'lonDefDomain'}}) {
1635: @languages=(@languages,
1636: $Apache::lonnet::domain_lang_def{
1637: $Apache::lonnet::perlvar{'lonDefDomain'}});
1638: }
1639: # turn "en-ca" into "en-ca,en"
1640: my @genlanguages;
1641: foreach (@languages) {
1642: unless ($_=~/\w/) { next; }
1643: push (@genlanguages,$_);
1644: if ($_=~/(\-|\_)/) {
1645: push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
1646: }
1647: }
1648: return @genlanguages;
1649: }
1650:
1651: ###############################################################
1652: ## Student Answer Attempts ##
1653: ###############################################################
1654:
1655: =pod
1656:
1657: =head1 Alternate Problem Views
1658:
1659: =over 4
1660:
1661: =item * get_previous_attempt($symb, $username, $domain, $course,
1662: $getattempt, $regexp, $gradesub)
1663:
1664: Return string with previous attempt on problem. Arguments:
1665:
1666: =over 4
1667:
1668: =item * $symb: Problem, including path
1669:
1670: =item * $username: username of the desired student
1671:
1672: =item * $domain: domain of the desired student
1673:
1674: =item * $course: Course ID
1675:
1676: =item * $getattempt: Leave blank for all attempts, otherwise put
1677: something
1678:
1679: =item * $regexp: if string matches this regexp, the string will be
1680: sent to $gradesub
1681:
1682: =item * $gradesub: routine that processes the string if it matches $regexp
1683:
1684: =back
1685:
1686: The output string is a table containing all desired attempts, if any.
1687:
1688: =cut
1689:
1690: sub get_previous_attempt {
1691: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1692: my $prevattempts='';
1693: no strict 'refs';
1694: if ($symb) {
1695: my (%returnhash)=
1696: &Apache::lonnet::restore($symb,$course,$domain,$username);
1697: if ($returnhash{'version'}) {
1698: my %lasthash=();
1699: my $version;
1700: for ($version=1;$version<=$returnhash{'version'};$version++) {
1701: foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1702: $lasthash{$_}=$returnhash{$version.':'.$_};
1703: }
1704: }
1705: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1706: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1707: foreach (sort(keys %lasthash)) {
1708: my ($ign,@parts) = split(/\./,$_);
1709: if ($#parts > 0) {
1710: my $data=$parts[-1];
1711: pop(@parts);
1712: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
1713: } else {
1714: if ($#parts == 0) {
1715: $prevattempts.='<th>'.$parts[0].'</th>';
1716: } else {
1717: $prevattempts.='<th>'.$ign.'</th>';
1718: }
1719: }
1720: }
1721: if ($getattempt eq '') {
1722: for ($version=1;$version<=$returnhash{'version'};$version++) {
1723: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
1724: foreach (sort(keys %lasthash)) {
1725: my $value;
1726: if ($_ =~ /timestamp/) {
1727: $value=scalar(localtime($returnhash{$version.':'.$_}));
1728: } else {
1729: $value=$returnhash{$version.':'.$_};
1730: }
1731: $prevattempts.='<td>'.&Apache::lonnet::unescape($value).' </td>';
1732: }
1733: }
1734: }
1735: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1736: foreach (sort(keys %lasthash)) {
1737: my $value;
1738: if ($_ =~ /timestamp/) {
1739: $value=scalar(localtime($lasthash{$_}));
1740: } else {
1741: $value=$lasthash{$_};
1742: }
1743: $value=&Apache::lonnet::unescape($value);
1744: if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1745: $prevattempts.='<td>'.$value.' </td>';
1746: }
1747: $prevattempts.='</tr></table></td></tr></table>';
1748: } else {
1749: $prevattempts='Nothing submitted - no attempts.';
1750: }
1751: } else {
1752: $prevattempts='No data.';
1753: }
1754: }
1755:
1756: sub relative_to_absolute {
1757: my ($url,$output)=@_;
1758: my $parser=HTML::TokeParser->new(\$output);
1759: my $token;
1760: my $thisdir=$url;
1761: my @rlinks=();
1762: while ($token=$parser->get_token) {
1763: if ($token->[0] eq 'S') {
1764: if ($token->[1] eq 'a') {
1765: if ($token->[2]->{'href'}) {
1766: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
1767: }
1768: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
1769: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
1770: } elsif ($token->[1] eq 'base') {
1771: $thisdir=$token->[2]->{'href'};
1772: }
1773: }
1774: }
1775: $thisdir=~s-/[^/]*$--;
1776: foreach (@rlinks) {
1777: unless (($_=~/^http:\/\//i) ||
1778: ($_=~/^\//) ||
1779: ($_=~/^javascript:/i) ||
1780: ($_=~/^mailto:/i) ||
1781: ($_=~/^\#/)) {
1782: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
1783: $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
1784: }
1785: }
1786: # -------------------------------------------------- Deal with Applet codebases
1787: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
1788: return $output;
1789: }
1790:
1791: =pod
1792:
1793: =item * get_student_view
1794:
1795: show a snapshot of what student was looking at
1796:
1797: =cut
1798:
1799: sub get_student_view {
1800: my ($symb,$username,$domain,$courseid,$target) = @_;
1801: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1802: my (%old,%moreenv);
1803: my @elements=('symb','courseid','domain','username');
1804: foreach my $element (@elements) {
1805: $old{$element}=$ENV{'form.grade_'.$element};
1806: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1807: }
1808: if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1809: &Apache::lonnet::appenv(%moreenv);
1810: $feedurl=&Apache::lonnet::clutter($feedurl);
1811: my $userview=&Apache::lonnet::ssi_body($feedurl);
1812: &Apache::lonnet::delenv('form.grade_');
1813: foreach my $element (@elements) {
1814: $ENV{'form.grade_'.$element}=$old{$element};
1815: }
1816: $userview=~s/\<body[^\>]*\>//gi;
1817: $userview=~s/\<\/body\>//gi;
1818: $userview=~s/\<html\>//gi;
1819: $userview=~s/\<\/html\>//gi;
1820: $userview=~s/\<head\>//gi;
1821: $userview=~s/\<\/head\>//gi;
1822: $userview=~s/action\s*\=/would_be_action\=/gi;
1823: $userview=&relative_to_absolute($feedurl,$userview);
1824: return $userview;
1825: }
1826:
1827: =pod
1828:
1829: =item * get_student_answers()
1830:
1831: show a snapshot of how student was answering problem
1832:
1833: =cut
1834:
1835: sub get_student_answers {
1836: my ($symb,$username,$domain,$courseid,%form) = @_;
1837: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1838: my (%old,%moreenv);
1839: my @elements=('symb','courseid','domain','username');
1840: foreach my $element (@elements) {
1841: $old{$element}=$ENV{'form.grade_'.$element};
1842: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1843: }
1844: $moreenv{'form.grade_target'}='answer';
1845: &Apache::lonnet::appenv(%moreenv);
1846: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
1847: &Apache::lonnet::delenv('form.grade_');
1848: foreach my $element (@elements) {
1849: $ENV{'form.grade_'.$element}=$old{$element};
1850: }
1851: return $userview;
1852: }
1853:
1854: =pod
1855:
1856: =item * &submlink()
1857:
1858: Inputs: $text $uname $udom $symb
1859:
1860: Returns: A link to grades.pm such as to see the SUBM view of a student
1861:
1862: =cut
1863:
1864: ###############################################
1865: sub submlink {
1866: my ($text,$uname,$udom,$symb)=@_;
1867: if (!($uname && $udom)) {
1868: (my $cursymb, my $courseid,$udom,$uname)=
1869: &Apache::lonxml::whichuser($symb);
1870: if (!$symb) { $symb=$cursymb; }
1871: }
1872: if (!$symb) { $symb=&symbread(); }
1873: return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
1874: '&userdom='.$udom.'&command=submission">'.$text.'</a>';
1875: }
1876: ##############################################
1877:
1878: =pod
1879:
1880: =back
1881:
1882: =cut
1883:
1884: ###############################################
1885:
1886:
1887: sub timehash {
1888: my @ltime=localtime(shift);
1889: return ( 'seconds' => $ltime[0],
1890: 'minutes' => $ltime[1],
1891: 'hours' => $ltime[2],
1892: 'day' => $ltime[3],
1893: 'month' => $ltime[4]+1,
1894: 'year' => $ltime[5]+1900,
1895: 'weekday' => $ltime[6],
1896: 'dayyear' => $ltime[7]+1,
1897: 'dlsav' => $ltime[8] );
1898: }
1899:
1900: sub maketime {
1901: my %th=@_;
1902: return POSIX::mktime(
1903: ($th{'seconds'},$th{'minutes'},$th{'hours'},
1904: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1905: }
1906:
1907:
1908: #########################################
1909: #
1910: # Retro-fixing of un-backward-compatible time format
1911:
1912: sub unsqltime {
1913: my $timestamp=shift;
1914: if ($timestamp=~/^(\d+)\-(\d+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)$/) {
1915: $timestamp=&maketime(
1916: 'year'=>$1,'month'=>$2,'day'=>$3,
1917: 'hours'=>$4,'minutes'=>$5,'seconds'=>$6);
1918: }
1919: return $timestamp;
1920: }
1921:
1922: #########################################
1923:
1924: sub findallcourses {
1925: my %courses=();
1926: my $now=time;
1927: foreach (keys %ENV) {
1928: if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
1929: my ($starttime,$endtime)=$ENV{$_};
1930: my $active=1;
1931: if ($starttime) {
1932: if ($now<$starttime) { $active=0; }
1933: }
1934: if ($endtime) {
1935: if ($now>$endtime) { $active=0; }
1936: }
1937: if ($active) { $courses{$1.'_'.$2}=1; }
1938: }
1939: }
1940: return keys %courses;
1941: }
1942:
1943: ###############################################
1944: ###############################################
1945:
1946: =pod
1947:
1948: =head1 Domain Template Functions
1949:
1950: =over 4
1951:
1952: =item * &determinedomain()
1953:
1954: Inputs: $domain (usually will be undef)
1955:
1956: Returns: Determines which domain should be used for designs
1957:
1958: =cut
1959:
1960: ###############################################
1961: sub determinedomain {
1962: my $domain=shift;
1963: if (! $domain) {
1964: # Determine domain if we have not been given one
1965: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1966: if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
1967: if ($ENV{'request.role.domain'}) {
1968: $domain=$ENV{'request.role.domain'};
1969: }
1970: }
1971: return $domain;
1972: }
1973: ###############################################
1974: =pod
1975:
1976: =item * &domainlogo()
1977:
1978: Inputs: $domain (usually will be undef)
1979:
1980: Returns: A link to a domain logo, if the domain logo exists.
1981: If the domain logo does not exist, a description of the domain.
1982:
1983: =cut
1984:
1985: ###############################################
1986: sub domainlogo {
1987: my $domain = &determinedomain(shift);
1988: # See if there is a logo
1989: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1990: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
1991: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
1992: return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
1993: '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
1994: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
1995: return $Apache::lonnet::domaindescription{$domain};
1996: } else {
1997: return '';
1998: }
1999: }
2000: ##############################################
2001:
2002: =pod
2003:
2004: =item * &designparm()
2005:
2006: Inputs: $which parameter; $domain (usually will be undef)
2007:
2008: Returns: value of designparamter $which
2009:
2010: =cut
2011:
2012: ##############################################
2013: sub designparm {
2014: my ($which,$domain)=@_;
2015: if ($ENV{'browser.blackwhite'} eq 'on') {
2016: if ($which=~/\.(font|alink|vlink|link)$/) {
2017: return '#000000';
2018: }
2019: if ($which=~/\.(pgbg|sidebg)$/) {
2020: return '#FFFFFF';
2021: }
2022: if ($which=~/\.tabbg$/) {
2023: return '#CCCCCC';
2024: }
2025: }
2026: if ($ENV{'environment.color.'.$which}) {
2027: return $ENV{'environment.color.'.$which};
2028: }
2029: $domain=&determinedomain($domain);
2030: if ($designhash{$domain.'.'.$which}) {
2031: return $designhash{$domain.'.'.$which};
2032: } else {
2033: return $designhash{'default.'.$which};
2034: }
2035: }
2036:
2037: ###############################################
2038: ###############################################
2039:
2040: =pod
2041:
2042: =back
2043:
2044: =head1 HTTP Helpers
2045:
2046: =over 4
2047:
2048: =item * &bodytag()
2049:
2050: Returns a uniform header for LON-CAPA web pages.
2051:
2052: Inputs:
2053:
2054: =over 4
2055:
2056: =item * $title, A title to be displayed on the page.
2057:
2058: =item * $function, the current role (can be undef).
2059:
2060: =item * $addentries, extra parameters for the <body> tag.
2061:
2062: =item * $bodyonly, if defined, only return the <body> tag.
2063:
2064: =item * $domain, if defined, force a given domain.
2065:
2066: =item * $forcereg, if page should register as content page (relevant for
2067: text interface only)
2068:
2069: =back
2070:
2071: Returns: A uniform header for LON-CAPA web pages.
2072: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
2073: If $bodyonly is undef or zero, an html string containing a <body> tag and
2074: other decorations will be returned.
2075:
2076: =cut
2077:
2078: sub bodytag {
2079: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
2080: $title=&mt($title);
2081: unless ($function) {
2082: $function='student';
2083: if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
2084: $function='coordinator';
2085: }
2086: if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
2087: $function='admin';
2088: }
2089: if (($ENV{'request.role'}=~/^(au|ca)/) ||
2090: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
2091: $function='author';
2092: }
2093: }
2094: my $img=&designparm($function.'.img',$domain);
2095: my $pgbg=&designparm($function.'.pgbg',$domain);
2096: my $tabbg=&designparm($function.'.tabbg',$domain);
2097: my $font=&designparm($function.'.font',$domain);
2098: my $link=&designparm($function.'.link',$domain);
2099: my $alink=&designparm($function.'.alink',$domain);
2100: my $vlink=&designparm($function.'.vlink',$domain);
2101: my $sidebg=&designparm($function.'.sidebg',$domain);
2102: # Accessibility font enhance
2103: unless ($addentries) { $addentries=''; }
2104: my $addstyle='';
2105: if ($ENV{'browser.fontenhance'} eq 'on') {
2106: $addstyle=' font-size: x-large;';
2107: }
2108: # role and realm
2109: my ($role,$realm)
2110: =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
2111: # realm
2112: if ($ENV{'request.course.id'}) {
2113: $realm=
2114: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
2115: }
2116: unless ($realm) { $realm=' '; }
2117: # Set messages
2118: my $messages=&domainlogo($domain);
2119: # Port for miniserver
2120: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
2121: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
2122: # construct main body tag
2123: my $bodytag = <<END;
2124: <style>
2125: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
2126: a:focus { color: red; background: yellow }
2127: </style>
2128: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
2129: style="margin-top: 0px;$addstyle" $addentries>
2130: END
2131: my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
2132: $lonhttpdPort.$img.'" alt="'.$function.'" />';
2133: if ($bodyonly) {
2134: return $bodytag;
2135: } elsif ($ENV{'browser.interface'} eq 'textual') {
2136: # Accessibility
2137: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2138: $forcereg).
2139: '<h1>LON-CAPA: '.$title.'</h1>';
2140: } elsif ($ENV{'environment.remote'} eq 'off') {
2141: # No Remote
2142: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2143: $forcereg).
2144: '<table bgcolor="'.$pgbg.'" width="100%" border="0" cellspacing="3" cellpadding="3"><tr><td bgcolor="'.$tabbg.'"><font face="Arial, Helvetica, sans-serif" size="+3" color="'.$font.'"><b>'.$title.
2145: '</b></font></td></tr></table>';
2146: }
2147:
2148: #
2149: # Top frame rendering, Remote is up
2150: #
2151: return(<<ENDBODY);
2152: $bodytag
2153: <table width="100%" cellspacing="0" border="0" cellpadding="0">
2154: <tr><td bgcolor="$sidebg">
2155: $upperleft</td>
2156: <td bgcolor="$sidebg" align="right">$messages </td>
2157: </tr>
2158: <tr>
2159: <td rowspan="3" bgcolor="$tabbg">
2160: <font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
2161: <td bgcolor="$tabbg" align="right">
2162: <font size="2" face="Arial, Helvetica, sans-serif">
2163: $ENV{'environment.firstname'}
2164: $ENV{'environment.middlename'}
2165: $ENV{'environment.lastname'}
2166: $ENV{'environment.generation'}
2167: </font>
2168: </td>
2169: </tr>
2170: <tr><td bgcolor="$tabbg" align="right">
2171: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>
2172: </td></tr>
2173: <tr>
2174: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font> </td></tr>
2175: </table><br>
2176: ENDBODY
2177: }
2178:
2179: ###############################################
2180:
2181: sub get_posted_cgi {
2182: my $r=shift;
2183:
2184: my $buffer;
2185:
2186: $r->read($buffer,$r->header_in('Content-length'),0);
2187: unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
2188: my @pairs=split(/&/,$buffer);
2189: my $pair;
2190: foreach $pair (@pairs) {
2191: my ($name,$value) = split(/=/,$pair);
2192: $value =~ tr/+/ /;
2193: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2194: $name =~ tr/+/ /;
2195: $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2196: &add_to_env("form.$name",$value);
2197: }
2198: } else {
2199: my $contentsep=$1;
2200: my @lines = split (/\n/,$buffer);
2201: my $name='';
2202: my $value='';
2203: my $fname='';
2204: my $fmime='';
2205: my $i;
2206: for ($i=0;$i<=$#lines;$i++) {
2207: if ($lines[$i]=~/^$contentsep/) {
2208: if ($name) {
2209: chomp($value);
2210: if ($fname) {
2211: $ENV{"form.$name.filename"}=$fname;
2212: $ENV{"form.$name.mimetype"}=$fmime;
2213: } else {
2214: $value=~s/\s+$//s;
2215: }
2216: &add_to_env("form.$name",$value);
2217: }
2218: if ($i<$#lines) {
2219: $i++;
2220: $lines[$i]=~
2221: /Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
2222: $name=$1;
2223: $value='';
2224: if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
2225: $fname=$1;
2226: if
2227: ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
2228: $fmime=$1;
2229: $i++;
2230: } else {
2231: $fmime='';
2232: }
2233: } else {
2234: $fname='';
2235: $fmime='';
2236: }
2237: $i++;
2238: }
2239: } else {
2240: $value.=$lines[$i]."\n";
2241: }
2242: }
2243: }
2244: $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
2245: $r->method_number(M_GET);
2246: $r->method('GET');
2247: $r->headers_in->unset('Content-length');
2248: }
2249:
2250: =pod
2251:
2252: =item * get_unprocessed_cgi($query,$possible_names)
2253:
2254: Modify the %ENV hash to contain unprocessed CGI form parameters held in
2255: $query. The parameters listed in $possible_names (an array reference),
2256: will be set in $ENV{'form.name'} if they do not already exist.
2257:
2258: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
2259: $possible_names is an ref to an array of form element names. As an example:
2260: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
2261: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
2262:
2263: =cut
2264:
2265: sub get_unprocessed_cgi {
2266: my ($query,$possible_names)= @_;
2267: # $Apache::lonxml::debug=1;
2268: foreach (split(/&/,$query)) {
2269: my ($name, $value) = split(/=/,$_);
2270: $name = &Apache::lonnet::unescape($name);
2271: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
2272: $value =~ tr/+/ /;
2273: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2274: &Apache::lonxml::debug("Seting :$name: to :$value:");
2275: unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
2276: }
2277: }
2278: }
2279:
2280: =pod
2281:
2282: =item * cacheheader()
2283:
2284: returns cache-controlling header code
2285:
2286: =cut
2287:
2288: sub cacheheader {
2289: unless ($ENV{'request.method'} eq 'GET') { return ''; }
2290: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
2291: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
2292: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
2293: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
2294: return $output;
2295: }
2296:
2297: =pod
2298:
2299: =item * no_cache($r)
2300:
2301: specifies header code to not have cache
2302:
2303: =cut
2304:
2305: sub no_cache {
2306: my ($r) = @_;
2307: unless ($ENV{'request.method'} eq 'GET') { return ''; }
2308: #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
2309: $r->no_cache(1);
2310: $r->header_out("Pragma" => "no-cache");
2311: #$r->header_out("Expires" => $date);
2312: }
2313:
2314: sub content_type {
2315: my ($r,$type,$charset) = @_;
2316: unless ($charset) {
2317: $charset=&Apache::lonlocal::current_encoding;
2318: }
2319: $r->content_type($type.($charset?'; charset='.$charset:''));
2320: }
2321:
2322: =pod
2323:
2324: =item * add_to_env($name,$value)
2325:
2326: adds $name to the %ENV hash with value
2327: $value, if $name already exists, the entry is converted to an array
2328: reference and $value is added to the array.
2329:
2330: =cut
2331:
2332: sub add_to_env {
2333: my ($name,$value)=@_;
2334: if (defined($ENV{$name})) {
2335: if (ref($ENV{$name})) {
2336: #already have multiple values
2337: push(@{ $ENV{$name} },$value);
2338: } else {
2339: #first time seeing multiple values, convert hash entry to an arrayref
2340: my $first=$ENV{$name};
2341: undef($ENV{$name});
2342: push(@{ $ENV{$name} },$first,$value);
2343: }
2344: } else {
2345: $ENV{$name}=$value;
2346: }
2347: }
2348:
2349: =pod
2350:
2351: =item * get_env_multiple($name)
2352:
2353: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
2354: values may be defined and end up as an array ref.
2355:
2356: returns an array of values
2357:
2358: =cut
2359:
2360: sub get_env_multiple {
2361: my ($name) = @_;
2362: my @values;
2363: if (defined($ENV{$name})) {
2364: # exists is it an array
2365: if (ref($ENV{$name})) {
2366: @values=@{ $ENV{$name} };
2367: } else {
2368: $values[0]=$ENV{$name};
2369: }
2370: }
2371: return(@values);
2372: }
2373:
2374:
2375: =pod
2376:
2377: =back
2378:
2379: =head1 CSV Upload/Handling functions
2380:
2381: =over 4
2382:
2383: =item * upfile_store($r)
2384:
2385: Store uploaded file, $r should be the HTTP Request object,
2386: needs $ENV{'form.upfile'}
2387: returns $datatoken to be put into hidden field
2388:
2389: =cut
2390:
2391: sub upfile_store {
2392: my $r=shift;
2393: $ENV{'form.upfile'}=~s/\r/\n/gs;
2394: $ENV{'form.upfile'}=~s/\f/\n/gs;
2395: $ENV{'form.upfile'}=~s/\n+/\n/gs;
2396: $ENV{'form.upfile'}=~s/\n+$//gs;
2397:
2398: my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
2399: '_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
2400: {
2401: my $datafile = $r->dir_config('lonDaemons').
2402: '/tmp/'.$datatoken.'.tmp';
2403: if ( open(my $fh,">$datafile") ) {
2404: print $fh $ENV{'form.upfile'};
2405: close($fh);
2406: }
2407: }
2408: return $datatoken;
2409: }
2410:
2411: =pod
2412:
2413: =item * load_tmp_file($r)
2414:
2415: Load uploaded file from tmp, $r should be the HTTP Request object,
2416: needs $ENV{'form.datatoken'},
2417: sets $ENV{'form.upfile'} to the contents of the file
2418:
2419: =cut
2420:
2421: sub load_tmp_file {
2422: my $r=shift;
2423: my @studentdata=();
2424: {
2425: my $studentfile = $r->dir_config('lonDaemons').
2426: '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
2427: if ( open(my $fh,"<$studentfile") ) {
2428: @studentdata=<$fh>;
2429: close($fh);
2430: }
2431: }
2432: $ENV{'form.upfile'}=join('',@studentdata);
2433: }
2434:
2435: =pod
2436:
2437: =item * upfile_record_sep()
2438:
2439: Separate uploaded file into records
2440: returns array of records,
2441: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
2442:
2443: =cut
2444:
2445: sub upfile_record_sep {
2446: if ($ENV{'form.upfiletype'} eq 'xml') {
2447: } else {
2448: return split(/\n/,$ENV{'form.upfile'});
2449: }
2450: }
2451:
2452: =pod
2453:
2454: =item * record_sep($record)
2455:
2456: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
2457:
2458: =cut
2459:
2460: sub record_sep {
2461: my $record=shift;
2462: my %components=();
2463: if ($ENV{'form.upfiletype'} eq 'xml') {
2464: } elsif ($ENV{'form.upfiletype'} eq 'space') {
2465: my $i=0;
2466: foreach (split(/\s+/,$record)) {
2467: my $field=$_;
2468: $field=~s/^(\"|\')//;
2469: $field=~s/(\"|\')$//;
2470: $components{$i}=$field;
2471: $i++;
2472: }
2473: } elsif ($ENV{'form.upfiletype'} eq 'tab') {
2474: my $i=0;
2475: foreach (split(/\t+/,$record)) {
2476: my $field=$_;
2477: $field=~s/^(\"|\')//;
2478: $field=~s/(\"|\')$//;
2479: $components{$i}=$field;
2480: $i++;
2481: }
2482: } else {
2483: my @allfields=split(/\,/,$record);
2484: my $i=0;
2485: my $j;
2486: for ($j=0;$j<=$#allfields;$j++) {
2487: my $field=$allfields[$j];
2488: if ($field=~/^\s*(\"|\')/) {
2489: my $delimiter=$1;
2490: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
2491: $j++;
2492: $field.=','.$allfields[$j];
2493: }
2494: $field=~s/^\s*$delimiter//;
2495: $field=~s/$delimiter\s*$//;
2496: }
2497: $components{$i}=$field;
2498: $i++;
2499: }
2500: }
2501: return %components;
2502: }
2503:
2504: ######################################################
2505: ######################################################
2506:
2507: =pod
2508:
2509: =item * upfile_select_html()
2510:
2511: Return HTML code to select a file from the users machine and specify
2512: the file type.
2513:
2514: =cut
2515:
2516: ######################################################
2517: ######################################################
2518: sub upfile_select_html {
2519: my %Types = (
2520: csv => &mt('CSV (comma separated values, spreadsheet)'),
2521: space => &mt('Space separated'),
2522: tab => &mt('Tabulator separated'),
2523: # xml => &mt('HTML/XML'),
2524: );
2525: my $Str = '<input type="file" name="upfile" size="50" />'.
2526: '<br />Type: <select name="upfiletype">';
2527: foreach my $type (sort(keys(%Types))) {
2528: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
2529: }
2530: $Str .= "</select>\n";
2531: return $Str;
2532: }
2533:
2534: ######################################################
2535: ######################################################
2536:
2537: =pod
2538:
2539: =item * csv_print_samples($r,$records)
2540:
2541: Prints a table of sample values from each column uploaded $r is an
2542: Apache Request ref, $records is an arrayref from
2543: &Apache::loncommon::upfile_record_sep
2544:
2545: =cut
2546:
2547: ######################################################
2548: ######################################################
2549: sub csv_print_samples {
2550: my ($r,$records) = @_;
2551: my (%sone,%stwo,%sthree);
2552: %sone=&record_sep($$records[0]);
2553: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2554: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
2555: #
2556: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
2557: foreach (sort({$a <=> $b} keys(%sone))) {
2558: $r->print('<th>'.&mt('Column [_1]',($_+1)).'</th>'); }
2559: $r->print('</tr>');
2560: foreach my $hash (\%sone,\%stwo,\%sthree) {
2561: $r->print('<tr>');
2562: foreach (sort({$a <=> $b} keys(%sone))) {
2563: $r->print('<td>');
2564: if (defined($$hash{$_})) { $r->print($$hash{$_}); }
2565: $r->print('</td>');
2566: }
2567: $r->print('</tr>');
2568: }
2569: $r->print('</tr></table><br />'."\n");
2570: }
2571:
2572: ######################################################
2573: ######################################################
2574:
2575: =pod
2576:
2577: =item * csv_print_select_table($r,$records,$d)
2578:
2579: Prints a table to create associations between values and table columns.
2580:
2581: $r is an Apache Request ref,
2582: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2583: $d is an array of 2 element arrays (internal name, displayed name)
2584:
2585: =cut
2586:
2587: ######################################################
2588: ######################################################
2589: sub csv_print_select_table {
2590: my ($r,$records,$d) = @_;
2591: my $i=0;my %sone;
2592: %sone=&record_sep($$records[0]);
2593: $r->print(&mt('Associate columns with student attributes.')."\n".
2594: '<table border="2"><tr>'.
2595: '<th>'.&mt('Attribute').'</th>'.
2596: '<th>'.&mt('Column').'</th></tr>'."\n");
2597: foreach (@$d) {
2598: my ($value,$display)=@{ $_ };
2599: $r->print('<tr><td>'.$display.'</td>');
2600:
2601: $r->print('<td><select name=f'.$i.
2602: ' onchange="javascript:flip(this.form,'.$i.');">');
2603: $r->print('<option value="none"></option>');
2604: foreach (sort({$a <=> $b} keys(%sone))) {
2605: $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
2606: }
2607: $r->print('</select></td></tr>'."\n");
2608: $i++;
2609: }
2610: $i--;
2611: return $i;
2612: }
2613:
2614: ######################################################
2615: ######################################################
2616:
2617: =pod
2618:
2619: =item * csv_samples_select_table($r,$records,$d)
2620:
2621: Prints a table of sample values from the upload and can make associate samples to internal names.
2622:
2623: $r is an Apache Request ref,
2624: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2625: $d is an array of 2 element arrays (internal name, displayed name)
2626:
2627: =cut
2628:
2629: ######################################################
2630: ######################################################
2631: sub csv_samples_select_table {
2632: my ($r,$records,$d) = @_;
2633: my %sone; my %stwo; my %sthree;
2634: my $i=0;
2635: #
2636: $r->print('<table border=2><tr><th>'.
2637: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
2638: %sone=&record_sep($$records[0]);
2639: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2640: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
2641: #
2642: foreach (sort keys %sone) {
2643: $r->print('<tr><td><select name="f'.$i.'"'.
2644: ' onchange="javascript:flip(this.form,'.$i.');">');
2645: foreach (@$d) {
2646: my ($value,$display)=@{ $_ };
2647: $r->print('<option value="'.$value.'">'.$display.'</option>');
2648: }
2649: $r->print('</select></td><td>');
2650: if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
2651: if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
2652: if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
2653: $r->print('</td></tr>');
2654: $i++;
2655: }
2656: $i--;
2657: return($i);
2658: }
2659:
2660: ######################################################
2661: ######################################################
2662:
2663: =pod
2664:
2665: =item clean_excel_name($name)
2666:
2667: Returns a replacement for $name which does not contain any illegal characters.
2668:
2669: =cut
2670:
2671: ######################################################
2672: ######################################################
2673: sub clean_excel_name {
2674: my ($name) = @_;
2675: $name =~ s/[:\*\?\/\\]//g;
2676: if (length($name) > 31) {
2677: $name = substr($name,0,31);
2678: }
2679: return $name;
2680: }
2681:
2682: =pod
2683:
2684: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
2685:
2686: Returns either 1 or undef
2687:
2688: 1 if the part is to be hidden, undef if it is to be shown
2689:
2690: Arguments are:
2691:
2692: $id the id of the part to be checked
2693: $symb, optional the symb of the resource to check
2694: $udom, optional the domain of the user to check for
2695: $uname, optional the username of the user to check for
2696:
2697: =cut
2698:
2699: sub check_if_partid_hidden {
2700: my ($id,$symb,$udom,$uname) = @_;
2701: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
2702: $symb,$udom,$uname);
2703: my $truth=1;
2704: #if the string starts with !, then the list is the list to show not hide
2705: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
2706: my @hiddenlist=split(/,/,$hiddenparts);
2707: foreach my $checkid (@hiddenlist) {
2708: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
2709: }
2710: return !$truth;
2711: }
2712:
2713:
2714: ############################################################
2715: ############################################################
2716:
2717: =pod
2718:
2719: =back
2720:
2721: =head1 cgi-bin script and graphing routines
2722:
2723: =over 4
2724:
2725: =item get_cgi_id
2726:
2727: Inputs: none
2728:
2729: Returns an id which can be used to pass environment variables
2730: to various cgi-bin scripts. These environment variables will
2731: be removed from the users environment after a given time by
2732: the routine &Apache::lonnet::transfer_profile_to_env.
2733:
2734: =cut
2735:
2736: ############################################################
2737: ############################################################
2738: my $uniq=0;
2739: sub get_cgi_id {
2740: $uniq=($uniq+1)%100000;
2741: return (time.'_'.$uniq);
2742: }
2743:
2744: ############################################################
2745: ############################################################
2746:
2747: =pod
2748:
2749: =item DrawBarGraph
2750:
2751: Facilitates the plotting of data in a (stacked) bar graph.
2752: Puts plot definition data into the users environment in order for
2753: graph.png to plot it. Returns an <img> tag for the plot.
2754: The bars on the plot are labeled '1','2',...,'n'.
2755:
2756: Inputs:
2757:
2758: =over 4
2759:
2760: =item $Title: string, the title of the plot
2761:
2762: =item $xlabel: string, text describing the X-axis of the plot
2763:
2764: =item $ylabel: string, text describing the Y-axis of the plot
2765:
2766: =item $Max: scalar, the maximum Y value to use in the plot
2767: If $Max is < any data point, the graph will not be rendered.
2768:
2769: =item $colors: array ref holding the colors to be used for the data sets when
2770: they are plotted. If undefined, default values will be used.
2771:
2772: =item @Values: An array of array references. Each array reference holds data
2773: to be plotted in a stacked bar chart.
2774:
2775: =back
2776:
2777: Returns:
2778:
2779: An <img> tag which references graph.png and the appropriate identifying
2780: information for the plot.
2781:
2782: =cut
2783:
2784: ############################################################
2785: ############################################################
2786: sub DrawBarGraph {
2787: my ($Title,$xlabel,$ylabel,$Max,$colors,@Values)=@_;
2788: #
2789: if (! defined($colors)) {
2790: $colors = ['#33ff00',
2791: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
2792: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
2793: ];
2794: }
2795: #
2796: my $identifier = &get_cgi_id();
2797: my $id = 'cgi.'.$identifier;
2798: if (! @Values || ref($Values[0]) ne 'ARRAY') {
2799: return '';
2800: }
2801: my $NumBars = scalar(@{$Values[0]});
2802: my %ValuesHash;
2803: my $NumSets=1;
2804: foreach my $array (@Values) {
2805: next if (! ref($array));
2806: $ValuesHash{$id.'.data.'.$NumSets++} =
2807: join(',',@$array);
2808: }
2809: #
2810: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
2811: if ($NumBars < 10) {
2812: $width = 120+$NumBars*15;
2813: $xskip = 1;
2814: $bar_width = 15;
2815: } elsif ($NumBars <= 25) {
2816: $width = 120+$NumBars*11;
2817: $xskip = 5;
2818: $bar_width = 8;
2819: } elsif ($NumBars <= 50) {
2820: $width = 120+$NumBars*8;
2821: $xskip = 5;
2822: $bar_width = 4;
2823: } else {
2824: $width = 120+$NumBars*8;
2825: $xskip = 5;
2826: $bar_width = 4;
2827: }
2828: #
2829: my @Labels;
2830: for (my $i=0;$i<@{$Values[0]};$i++) {
2831: push (@Labels,$i+1);
2832: }
2833: #
2834: $Max = 1 if ($Max < 1);
2835: if ( int($Max) < $Max ) {
2836: $Max++;
2837: $Max = int($Max);
2838: }
2839: $Title = '' if (! defined($Title));
2840: $xlabel = '' if (! defined($xlabel));
2841: $ylabel = '' if (! defined($ylabel));
2842: $ValuesHash{$id.'.title'} = &Apache::lonnet::escape($Title);
2843: $ValuesHash{$id.'.xlabel'} = &Apache::lonnet::escape($xlabel);
2844: $ValuesHash{$id.'.ylabel'} = &Apache::lonnet::escape($ylabel);
2845: $ValuesHash{$id.'.y_max_value'} = $Max;
2846: $ValuesHash{$id.'.NumBars'} = $NumBars;
2847: $ValuesHash{$id.'.NumSets'} = $NumSets;
2848: $ValuesHash{$id.'.PlotType'} = 'bar';
2849: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2850: $ValuesHash{$id.'.height'} = $height;
2851: $ValuesHash{$id.'.width'} = $width;
2852: $ValuesHash{$id.'.xskip'} = $xskip;
2853: $ValuesHash{$id.'.bar_width'} = $bar_width;
2854: $ValuesHash{$id.'.labels'} = join(',',@Labels);
2855: #
2856: &Apache::lonnet::appenv(%ValuesHash);
2857: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2858: }
2859:
2860: ############################################################
2861: ############################################################
2862:
2863: =pod
2864:
2865: =item DrawXYGraph
2866:
2867: Facilitates the plotting of data in an XY graph.
2868: Puts plot definition data into the users environment in order for
2869: graph.png to plot it. Returns an <img> tag for the plot.
2870:
2871: Inputs:
2872:
2873: =over 4
2874:
2875: =item $Title: string, the title of the plot
2876:
2877: =item $xlabel: string, text describing the X-axis of the plot
2878:
2879: =item $ylabel: string, text describing the Y-axis of the plot
2880:
2881: =item $Max: scalar, the maximum Y value to use in the plot
2882: If $Max is < any data point, the graph will not be rendered.
2883:
2884: =item $colors: Array ref containing the hex color codes for the data to be
2885: plotted in. If undefined, default values will be used.
2886:
2887: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2888:
2889: =item $Ydata: Array ref containing Array refs.
2890: Each of the contained arrays will be plotted as a seperate curve.
2891:
2892: =item %Values: hash indicating or overriding any default values which are
2893: passed to graph.png.
2894: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2895:
2896: =back
2897:
2898: Returns:
2899:
2900: An <img> tag which references graph.png and the appropriate identifying
2901: information for the plot.
2902:
2903: =cut
2904:
2905: ############################################################
2906: ############################################################
2907: sub DrawXYGraph {
2908: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
2909: #
2910: # Create the identifier for the graph
2911: my $identifier = &get_cgi_id();
2912: my $id = 'cgi.'.$identifier;
2913: #
2914: $Title = '' if (! defined($Title));
2915: $xlabel = '' if (! defined($xlabel));
2916: $ylabel = '' if (! defined($ylabel));
2917: my %ValuesHash =
2918: (
2919: $id.'.title' => &Apache::lonnet::escape($Title),
2920: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
2921: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
2922: $id.'.y_max_value'=> $Max,
2923: $id.'.labels' => join(',',@$Xlabels),
2924: $id.'.PlotType' => 'XY',
2925: );
2926: #
2927: if (defined($colors) && ref($colors) eq 'ARRAY') {
2928: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2929: }
2930: #
2931: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
2932: return '';
2933: }
2934: my $NumSets=1;
2935: foreach my $array (@{$Ydata}){
2936: next if (! ref($array));
2937: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
2938: }
2939: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
2940: #
2941: # Deal with other parameters
2942: while (my ($key,$value) = each(%Values)) {
2943: $ValuesHash{$id.'.'.$key} = $value;
2944: }
2945: #
2946: &Apache::lonnet::appenv(%ValuesHash);
2947: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2948: }
2949:
2950: ############################################################
2951: ############################################################
2952:
2953: =pod
2954:
2955: =item DrawXYYGraph
2956:
2957: Facilitates the plotting of data in an XY graph with two Y axes.
2958: Puts plot definition data into the users environment in order for
2959: graph.png to plot it. Returns an <img> tag for the plot.
2960:
2961: Inputs:
2962:
2963: =over 4
2964:
2965: =item $Title: string, the title of the plot
2966:
2967: =item $xlabel: string, text describing the X-axis of the plot
2968:
2969: =item $ylabel: string, text describing the Y-axis of the plot
2970:
2971: =item $colors: Array ref containing the hex color codes for the data to be
2972: plotted in. If undefined, default values will be used.
2973:
2974: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2975:
2976: =item $Ydata1: The first data set
2977:
2978: =item $Min1: The minimum value of the left Y-axis
2979:
2980: =item $Max1: The maximum value of the left Y-axis
2981:
2982: =item $Ydata2: The second data set
2983:
2984: =item $Min2: The minimum value of the right Y-axis
2985:
2986: =item $Max2: The maximum value of the left Y-axis
2987:
2988: =item %Values: hash indicating or overriding any default values which are
2989: passed to graph.png.
2990: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2991:
2992: =back
2993:
2994: Returns:
2995:
2996: An <img> tag which references graph.png and the appropriate identifying
2997: information for the plot.
2998:
2999: =cut
3000:
3001: ############################################################
3002: ############################################################
3003: sub DrawXYYGraph {
3004: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
3005: $Ydata2,$Min2,$Max2,%Values)=@_;
3006: #
3007: # Create the identifier for the graph
3008: my $identifier = &get_cgi_id();
3009: my $id = 'cgi.'.$identifier;
3010: #
3011: $Title = '' if (! defined($Title));
3012: $xlabel = '' if (! defined($xlabel));
3013: $ylabel = '' if (! defined($ylabel));
3014: my %ValuesHash =
3015: (
3016: $id.'.title' => &Apache::lonnet::escape($Title),
3017: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
3018: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
3019: $id.'.labels' => join(',',@$Xlabels),
3020: $id.'.PlotType' => 'XY',
3021: $id.'.NumSets' => 2,
3022: $id.'.two_axes' => 1,
3023: $id.'.y1_max_value' => $Max1,
3024: $id.'.y1_min_value' => $Min1,
3025: $id.'.y2_max_value' => $Max2,
3026: $id.'.y2_min_value' => $Min2,
3027: );
3028: #
3029: if (defined($colors) && ref($colors) eq 'ARRAY') {
3030: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
3031: }
3032: #
3033: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
3034: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
3035: return '';
3036: }
3037: my $NumSets=1;
3038: foreach my $array ($Ydata1,$Ydata2){
3039: next if (! ref($array));
3040: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
3041: }
3042: #
3043: # Deal with other parameters
3044: while (my ($key,$value) = each(%Values)) {
3045: $ValuesHash{$id.'.'.$key} = $value;
3046: }
3047: #
3048: &Apache::lonnet::appenv(%ValuesHash);
3049: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
3050: }
3051:
3052: ############################################################
3053: ############################################################
3054:
3055: =pod
3056:
3057: =back
3058:
3059: =head1 Statistics helper routines?
3060:
3061: Bad place for them but what the hell.
3062:
3063: =over 4
3064:
3065: =item &chartlink
3066:
3067: Returns a link to the chart for a specific student.
3068:
3069: Inputs:
3070:
3071: =over 4
3072:
3073: =item $linktext: The text of the link
3074:
3075: =item $sname: The students username
3076:
3077: =item $sdomain: The students domain
3078:
3079: =back
3080:
3081: =back
3082:
3083: =cut
3084:
3085: ############################################################
3086: ############################################################
3087: sub chartlink {
3088: my ($linktext, $sname, $sdomain) = @_;
3089: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
3090: '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
3091: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
3092: '">'.$linktext.'</a>';
3093: }
3094:
3095: #######################################################
3096: #######################################################
3097:
3098: =pod
3099:
3100: =head1 Course Environment Routines
3101:
3102: =over 4
3103:
3104: =item &restore_course_settings
3105:
3106: =item &store_course_settings
3107:
3108: Restores/Store indicated form parameters from the course environment.
3109: Will not overwrite existing values of the form parameters.
3110:
3111: Inputs:
3112: a scalar describing the data (e.g. 'chart', 'problem_analysis')
3113:
3114: a hash ref describing the data to be stored. For example:
3115:
3116: %Save_Parameters = ('Status' => 'scalar',
3117: 'chartoutputmode' => 'scalar',
3118: 'chartoutputdata' => 'scalar',
3119: 'Section' => 'array',
3120: 'StudentData' => 'array',
3121: 'Maps' => 'array');
3122:
3123: Returns: both routines return nothing
3124:
3125: =cut
3126:
3127: #######################################################
3128: #######################################################
3129: sub store_course_settings {
3130: # save to the environment
3131: # appenv the same items, just to be safe
3132: my $courseid = $ENV{'request.course.id'};
3133: my $coursedom = $ENV{'course.'.$courseid.'.domain'};
3134: my ($prefix,$Settings) = @_;
3135: my %SaveHash;
3136: my %AppHash;
3137: while (my ($setting,$type) = each(%$Settings)) {
3138: my $basename = 'env.internal.'.$prefix.'.'.$setting;
3139: my $envname = 'course.'.$courseid.'.'.$basename;
3140: if (exists($ENV{'form.'.$setting})) {
3141: # Save this value away
3142: if ($type eq 'scalar' &&
3143: (! exists($ENV{$envname}) ||
3144: $ENV{$envname} ne $ENV{'form.'.$setting})) {
3145: $SaveHash{$basename} = $ENV{'form.'.$setting};
3146: $AppHash{$envname} = $ENV{'form.'.$setting};
3147: } elsif ($type eq 'array') {
3148: my $stored_form;
3149: if (ref($ENV{'form.'.$setting})) {
3150: $stored_form = join(',',
3151: map {
3152: &Apache::lonnet::escape($_);
3153: } sort(@{$ENV{'form.'.$setting}}));
3154: } else {
3155: $stored_form =
3156: &Apache::lonnet::escape($ENV{'form.'.$setting});
3157: }
3158: # Determine if the array contents are the same.
3159: if ($stored_form ne $ENV{$envname}) {
3160: $SaveHash{$basename} = $stored_form;
3161: $AppHash{$envname} = $stored_form;
3162: }
3163: }
3164: }
3165: }
3166: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
3167: $coursedom,
3168: $ENV{'course.'.$courseid.'.num'});
3169: if ($put_result !~ /^(ok|delayed)/) {
3170: &Apache::lonnet::logthis('unable to save form parameters, '.
3171: 'got error:'.$put_result);
3172: }
3173: # Make sure these settings stick around in this session, too
3174: &Apache::lonnet::appenv(%AppHash);
3175: return;
3176: }
3177:
3178: sub restore_course_settings {
3179: my $courseid = $ENV{'request.course.id'};
3180: my ($prefix,$Settings) = @_;
3181: while (my ($setting,$type) = each(%$Settings)) {
3182: next if (exists($ENV{'form.'.$setting}));
3183: my $envname = 'course.'.$courseid.'.env.internal.'.$prefix.
3184: '.'.$setting;
3185: if (exists($ENV{$envname})) {
3186: if ($type eq 'scalar') {
3187: $ENV{'form.'.$setting} = $ENV{$envname};
3188: } elsif ($type eq 'array') {
3189: $ENV{'form.'.$setting} = [
3190: map {
3191: &Apache::lonnet::unescape($_);
3192: } split(',',$ENV{$envname})
3193: ];
3194: }
3195: }
3196: }
3197: }
3198:
3199: ############################################################
3200: ############################################################
3201:
3202: sub propath {
3203: my ($udom,$uname)=@_;
3204: $udom=~s/\W//g;
3205: $uname=~s/\W//g;
3206: my $subdir=$uname.'__';
3207: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3208: my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3209: return $proname;
3210: }
3211:
3212: sub icon {
3213: my ($file)=@_;
3214: my @file_ext = split(/\./,$file);
3215: my $curfext = $file_ext[-1];
3216: my $iconname="unknown.gif";
3217: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
3218: # The unless conditional that follows is a bit of overkill
3219: $iconname = $curfext.".gif" unless
3220: (!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn');
3221: return $Apache::lonnet::perlvar{'lonIconsURL'}."/$iconname";
3222: }
3223:
3224: =pod
3225:
3226: =back
3227:
3228: =cut
3229:
3230: 1;
3231: __END__;
3232:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>