1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.164 2003/12/26 21:17:37 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
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: sub select_level_form {
766: my ($deflevel,$name)=@_;
767: unless ($deflevel) { $deflevel=0; }
768: return &select_form($deflevel,$name,(
769: 0 => 'Not specified',
770: 1 => 'Grade 1',
771: 2 => 'Grade 2',
772: 3 => 'Grade 3',
773: 4 => 'Grade 4',
774: 5 => 'Grade 5',
775: 6 => 'Grade 6',
776: 7 => 'Grade 7',
777: 8 => 'Grade 8',
778: 9 => 'Grade 9',
779: 10 => 'Grade 10',
780: 11 => 'Grade 11',
781: 12 => 'Grade 12',
782: 13 => 'Grade 13',
783: 14 => '100 Level',
784: 15 => '200 Level',
785: 16 => '300 Level',
786: 17 => '400 Level',
787: 18 => 'Graduate Level'));
788: }
789: #-------------------------------------------
790:
791: =pod
792:
793: =item * select_dom_form($defdom,$name,$includeempty)
794:
795: Returns a string containing a <select name='$name' size='1'> form to
796: allow a user to select the domain to preform an operation in.
797: See loncreateuser.pm for an example invocation and use.
798:
799: If the $includeempty flag is set, it also includes an empty choice ("no domain
800: selected");
801:
802: =cut
803:
804: #-------------------------------------------
805: sub select_dom_form {
806: my ($defdom,$name,$includeempty) = @_;
807: my @domains = get_domains();
808: if ($includeempty) { @domains=('',@domains); }
809: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
810: foreach (@domains) {
811: $selectdomain.="<option value=\"$_\" ".
812: ($_ eq $defdom ? 'selected' : '').
813: ">$_</option>\n";
814: }
815: $selectdomain.="</select>";
816: return $selectdomain;
817: }
818:
819: #-------------------------------------------
820:
821: =pod
822:
823: =item * get_library_servers($domain)
824:
825: Returns a hash which contains keys like '103l3' and values like
826: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
827: given $domain.
828:
829: =cut
830:
831: #-------------------------------------------
832: sub get_library_servers {
833: my $domain = shift;
834: my %library_servers;
835: foreach (keys(%Apache::lonnet::libserv)) {
836: if ($Apache::lonnet::hostdom{$_} eq $domain) {
837: $library_servers{$_} = $Apache::lonnet::hostname{$_};
838: }
839: }
840: return %library_servers;
841: }
842:
843: #-------------------------------------------
844:
845: =pod
846:
847: =item * home_server_option_list($domain)
848:
849: returns a string which contains an <option> list to be used in a
850: <select> form input. See loncreateuser.pm for an example.
851:
852: =cut
853:
854: #-------------------------------------------
855: sub home_server_option_list {
856: my $domain = shift;
857: my %servers = &get_library_servers($domain);
858: my $result = '';
859: foreach (sort keys(%servers)) {
860: $result.=
861: '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
862: }
863: return $result;
864: }
865:
866: =pod
867:
868: =back
869:
870: =cut
871:
872: ###############################################################
873: ## Decoding User Agent ##
874: ###############################################################
875:
876: =pod
877:
878: =head1 Decoding the User Agent
879:
880: =over 4
881:
882: =item * &decode_user_agent()
883:
884: Inputs: $r
885:
886: Outputs:
887:
888: =over 4
889:
890: =item * $httpbrowser
891:
892: =item * $clientbrowser
893:
894: =item * $clientversion
895:
896: =item * $clientmathml
897:
898: =item * $clientunicode
899:
900: =item * $clientos
901:
902: =back
903:
904: =back
905:
906: =cut
907:
908: ###############################################################
909: ###############################################################
910: sub decode_user_agent {
911: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
912: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
913: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
914: my $clientbrowser='unknown';
915: my $clientversion='0';
916: my $clientmathml='';
917: my $clientunicode='0';
918: for (my $i=0;$i<=$#browsertype;$i++) {
919: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
920: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
921: $clientbrowser=$bname;
922: $httpbrowser=~/$vreg/i;
923: $clientversion=$1;
924: $clientmathml=($clientversion>=$minv);
925: $clientunicode=($clientversion>=$univ);
926: }
927: }
928: my $clientos='unknown';
929: if (($httpbrowser=~/linux/i) ||
930: ($httpbrowser=~/unix/i) ||
931: ($httpbrowser=~/ux/i) ||
932: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
933: if (($httpbrowser=~/vax/i) ||
934: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
935: if ($httpbrowser=~/next/i) { $clientos='next'; }
936: if (($httpbrowser=~/mac/i) ||
937: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
938: if ($httpbrowser=~/win/i) { $clientos='win'; }
939: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
940: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
941: $clientunicode,$clientos,);
942: }
943:
944: ###############################################################
945: ## Authentication changing form generation subroutines ##
946: ###############################################################
947: ##
948: ## All of the authform_xxxxxxx subroutines take their inputs in a
949: ## hash, and have reasonable default values.
950: ##
951: ## formname = the name given in the <form> tag.
952: #-------------------------------------------
953:
954: =pod
955:
956: =head1 Authentication Routines
957:
958: =over 4
959:
960: =item * authform_xxxxxx
961:
962: The authform_xxxxxx subroutines provide javascript and html forms which
963: handle some of the conveniences required for authentication forms.
964: This is not an optimal method, but it works.
965:
966: See loncreateuser.pm for invocation and use examples.
967:
968: =over 4
969:
970: =item * authform_header
971:
972: =item * authform_authorwarning
973:
974: =item * authform_nochange
975:
976: =item * authform_kerberos
977:
978: =item * authform_internal
979:
980: =item * authform_filesystem
981:
982: =back
983:
984: =back
985:
986: =cut
987:
988: #-------------------------------------------
989: sub authform_header{
990: my %in = (
991: formname => 'cu',
992: kerb_def_dom => '',
993: @_,
994: );
995: $in{'formname'} = 'document.' . $in{'formname'};
996: my $result='';
997:
998: #---------------------------------------------- Code for upper case translation
999: my $Javascript_toUpperCase;
1000: unless ($in{kerb_def_dom}) {
1001: $Javascript_toUpperCase =<<"END";
1002: switch (choice) {
1003: case 'krb': currentform.elements[choicearg].value =
1004: currentform.elements[choicearg].value.toUpperCase();
1005: break;
1006: default:
1007: }
1008: END
1009: } else {
1010: $Javascript_toUpperCase = "";
1011: }
1012:
1013: $result.=<<"END";
1014: var current = new Object();
1015: current.radiovalue = 'nochange';
1016: current.argfield = null;
1017:
1018: function changed_radio(choice,currentform) {
1019: var choicearg = choice + 'arg';
1020: // If a radio button in changed, we need to change the argfield
1021: if (current.radiovalue != choice) {
1022: current.radiovalue = choice;
1023: if (current.argfield != null) {
1024: currentform.elements[current.argfield].value = '';
1025: }
1026: if (choice == 'nochange') {
1027: current.argfield = null;
1028: } else {
1029: current.argfield = choicearg;
1030: switch(choice) {
1031: case 'krb':
1032: currentform.elements[current.argfield].value =
1033: "$in{'kerb_def_dom'}";
1034: break;
1035: default:
1036: break;
1037: }
1038: }
1039: }
1040: return;
1041: }
1042:
1043: function changed_text(choice,currentform) {
1044: var choicearg = choice + 'arg';
1045: if (currentform.elements[choicearg].value !='') {
1046: $Javascript_toUpperCase
1047: // clear old field
1048: if ((current.argfield != choicearg) && (current.argfield != null)) {
1049: currentform.elements[current.argfield].value = '';
1050: }
1051: current.argfield = choicearg;
1052: }
1053: set_auth_radio_buttons(choice,currentform);
1054: return;
1055: }
1056:
1057: function set_auth_radio_buttons(newvalue,currentform) {
1058: var i=0;
1059: while (i < currentform.login.length) {
1060: if (currentform.login[i].value == newvalue) { break; }
1061: i++;
1062: }
1063: if (i == currentform.login.length) {
1064: return;
1065: }
1066: current.radiovalue = newvalue;
1067: currentform.login[i].checked = true;
1068: return;
1069: }
1070: END
1071: return $result;
1072: }
1073:
1074: sub authform_authorwarning{
1075: my $result='';
1076: $result='<i>'.
1077: &mt('As a general rule, only authors or co-authors should be '.
1078: 'filesystem authenticated '.
1079: '(which allows access to the server filesystem).')."</i>\n";
1080: return $result;
1081: }
1082:
1083: sub authform_nochange{
1084: my %in = (
1085: formname => 'document.cu',
1086: kerb_def_dom => 'MSU.EDU',
1087: @_,
1088: );
1089: my $result = &mt('[_1] Do not change login data',
1090: '<input type="radio" name="login" value="nochange" '.
1091: 'checked="checked" onclick="'.
1092: "javascript:changed_radio('nochange',$in{'formname'});".'" />');
1093: return $result;
1094: }
1095:
1096: sub authform_kerberos{
1097: my %in = (
1098: formname => 'document.cu',
1099: kerb_def_dom => 'MSU.EDU',
1100: kerb_def_auth => 'krb4',
1101: @_,
1102: );
1103: my ($check4,$check5);
1104: if ($in{'kerb_def_auth'} eq 'krb5') {
1105: $check5 = " checked=\"on\"";
1106: } else {
1107: $check4 = " checked=\"on\"";
1108: }
1109: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1110: my $result .= &mt
1111: ('[_1] Kerberos authenticated with domain [_2] '.
1112: '[_3] Version 4 [_4] Version 5',
1113: '<input type="radio" name="login" value="krb" '.
1114: 'onclick="'.$jscall.'" onchange="'.$jscall.'" />',
1115: '<input type="text" size="10" name="krbarg" '.
1116: 'value="'.$in{'kerb_def_dom'}.'" '.
1117: 'onchange="'.$jscall.'" />',
1118: '<input type="radio" name="krbver" value="4" '.$check4.' />',
1119: '<input type="radio" name="krbver" value="5" '.$check5.' />');
1120: return $result;
1121: }
1122:
1123: sub authform_internal{
1124: my %args = (
1125: formname => 'document.cu',
1126: kerb_def_dom => 'MSU.EDU',
1127: @_,
1128: );
1129: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1130: my $result.=&mt
1131: ('[_1] Internally authenticated (with initial password [_2])',
1132: '<input type="radio" name="login" value="int" '.
1133: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1134: '<input type="text" size="10" name="intarg" value="" '.
1135: 'onchange="'.$jscall.'" />');
1136: return $result;
1137: }
1138:
1139: sub authform_local{
1140: my %in = (
1141: formname => 'document.cu',
1142: kerb_def_dom => 'MSU.EDU',
1143: @_,
1144: );
1145: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1146: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1147: '<input type="radio" name="login" value="loc" '.
1148: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1149: '<input type="text" size="10" name="locarg" value="" '.
1150: 'onchange="'.$jscall.'" />');
1151: return $result;
1152: }
1153:
1154: sub authform_filesystem{
1155: my %in = (
1156: formname => 'document.cu',
1157: kerb_def_dom => 'MSU.EDU',
1158: @_,
1159: );
1160: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1161: my $result.= &mt
1162: ('[_1] Filesystem Authenticated (with initial password [_2])',
1163: '<input type="radio" name="login" value="fsys" '.
1164: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1165: '<input type="text" size="10" name="fsysarg" value="" '.
1166: 'onchange="'.$jscall.'" />');
1167: return $result;
1168: }
1169:
1170: ###############################################################
1171: ## Get Authentication Defaults for Domain ##
1172: ###############################################################
1173:
1174: =pod
1175:
1176: =head1 Domains and Authentication
1177:
1178: Returns default authentication type and an associated argument as
1179: listed in file 'domain.tab'.
1180:
1181: =over 4
1182:
1183: =item * get_auth_defaults
1184:
1185: get_auth_defaults($target_domain) returns the default authentication
1186: type and an associated argument (initial password or a kerberos domain).
1187: These values are stored in lonTabs/domain.tab
1188:
1189: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1190:
1191: If target_domain is not found in domain.tab, returns nothing ('').
1192:
1193: =cut
1194:
1195: #-------------------------------------------
1196: sub get_auth_defaults {
1197: my $domain=shift;
1198: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1199: }
1200: ###############################################################
1201: ## End Get Authentication Defaults for Domain ##
1202: ###############################################################
1203:
1204: ###############################################################
1205: ## Get Kerberos Defaults for Domain ##
1206: ###############################################################
1207: ##
1208: ## Returns default kerberos version and an associated argument
1209: ## as listed in file domain.tab. If not listed, provides
1210: ## appropriate default domain and kerberos version.
1211: ##
1212: #-------------------------------------------
1213:
1214: =pod
1215:
1216: =item * get_kerberos_defaults
1217:
1218: get_kerberos_defaults($target_domain) returns the default kerberos
1219: version and domain. If not found in domain.tabs, it defaults to
1220: version 4 and the domain of the server.
1221:
1222: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1223:
1224: =cut
1225:
1226: #-------------------------------------------
1227: sub get_kerberos_defaults {
1228: my $domain=shift;
1229: my ($krbdef,$krbdefdom) =
1230: &Apache::loncommon::get_auth_defaults($domain);
1231: unless ($krbdef =~/^krb/ && $krbdefdom) {
1232: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1233: my $krbdefdom=$1;
1234: $krbdefdom=~tr/a-z/A-Z/;
1235: $krbdef = "krb4";
1236: }
1237: return ($krbdef,$krbdefdom);
1238: }
1239:
1240: =pod
1241:
1242: =back
1243:
1244: =cut
1245:
1246: ###############################################################
1247: ## Thesaurus Functions ##
1248: ###############################################################
1249:
1250: =pod
1251:
1252: =head1 Thesaurus Functions
1253:
1254: =over 4
1255:
1256: =item * initialize_keywords
1257:
1258: Initializes the package variable %Keywords if it is empty. Uses the
1259: package variable $thesaurus_db_file.
1260:
1261: =cut
1262:
1263: ###################################################
1264:
1265: sub initialize_keywords {
1266: return 1 if (scalar keys(%Keywords));
1267: # If we are here, %Keywords is empty, so fill it up
1268: # Make sure the file we need exists...
1269: if (! -e $thesaurus_db_file) {
1270: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1271: " failed because it does not exist");
1272: return 0;
1273: }
1274: # Set up the hash as a database
1275: my %thesaurus_db;
1276: if (! tie(%thesaurus_db,'GDBM_File',
1277: $thesaurus_db_file,&GDBM_READER(),0640)){
1278: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1279: $thesaurus_db_file);
1280: return 0;
1281: }
1282: # Get the average number of appearances of a word.
1283: my $avecount = $thesaurus_db{'average.count'};
1284: # Put keywords (those that appear > average) into %Keywords
1285: while (my ($word,$data)=each (%thesaurus_db)) {
1286: my ($count,undef) = split /:/,$data;
1287: $Keywords{$word}++ if ($count > $avecount);
1288: }
1289: untie %thesaurus_db;
1290: # Remove special values from %Keywords.
1291: foreach ('total.count','average.count') {
1292: delete($Keywords{$_}) if (exists($Keywords{$_}));
1293: }
1294: return 1;
1295: }
1296:
1297: ###################################################
1298:
1299: =pod
1300:
1301: =item * keyword($word)
1302:
1303: Returns true if $word is a keyword. A keyword is a word that appears more
1304: than the average number of times in the thesaurus database. Calls
1305: &initialize_keywords
1306:
1307: =cut
1308:
1309: ###################################################
1310:
1311: sub keyword {
1312: return if (!&initialize_keywords());
1313: my $word=lc(shift());
1314: $word=~s/\W//g;
1315: return exists($Keywords{$word});
1316: }
1317:
1318: ###############################################################
1319:
1320: =pod
1321:
1322: =item * get_related_words
1323:
1324: Look up a word in the thesaurus. Takes a scalar argument and returns
1325: an array of words. If the keyword is not in the thesaurus, an empty array
1326: will be returned. The order of the words returned is determined by the
1327: database which holds them.
1328:
1329: Uses global $thesaurus_db_file.
1330:
1331: =cut
1332:
1333: ###############################################################
1334: sub get_related_words {
1335: my $keyword = shift;
1336: my %thesaurus_db;
1337: if (! -e $thesaurus_db_file) {
1338: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
1339: "failed because the file does not exist");
1340: return ();
1341: }
1342: if (! tie(%thesaurus_db,'GDBM_File',
1343: $thesaurus_db_file,&GDBM_READER(),0640)){
1344: return ();
1345: }
1346: my @Words=();
1347: if (exists($thesaurus_db{$keyword})) {
1348: $_ = $thesaurus_db{$keyword};
1349: (undef,@Words) = split/:/; # The first element is the number of times
1350: # the word appears. We do not need it now.
1351: for (my $i=0;$i<=$#Words;$i++) {
1352: ($Words[$i],undef)= split/\,/,$Words[$i];
1353: }
1354: }
1355: untie %thesaurus_db;
1356: return @Words;
1357: }
1358:
1359: =pod
1360:
1361: =back
1362:
1363: =cut
1364:
1365: # -------------------------------------------------------------- Plaintext name
1366: =pod
1367:
1368: =head1 User Name Functions
1369:
1370: =over 4
1371:
1372: =item * plainname($uname,$udom)
1373:
1374: Takes a users logon name and returns it as a string in
1375: "first middle last generation" form
1376:
1377: =cut
1378:
1379: ###############################################################
1380: sub plainname {
1381: my ($uname,$udom)=@_;
1382: my %names=&Apache::lonnet::get('environment',
1383: ['firstname','middlename','lastname','generation'],
1384: $udom,$uname);
1385: my $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1386: $names{'lastname'}.' '.$names{'generation'};
1387: $name=~s/\s+$//;
1388: $name=~s/\s+/ /g;
1389: return $name;
1390: }
1391:
1392: # -------------------------------------------------------------------- Nickname
1393: =pod
1394:
1395: =item * nickname($uname,$udom)
1396:
1397: Gets a users name and returns it as a string as
1398:
1399: ""nickname""
1400:
1401: if the user has a nickname or
1402:
1403: "first middle last generation"
1404:
1405: if the user does not
1406:
1407: =cut
1408:
1409: sub nickname {
1410: my ($uname,$udom)=@_;
1411: my %names=&Apache::lonnet::get('environment',
1412: ['nickname','firstname','middlename','lastname','generation'],$udom,$uname);
1413: my $name=$names{'nickname'};
1414: if ($name) {
1415: $name='"'.$name.'"';
1416: } else {
1417: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1418: $names{'lastname'}.' '.$names{'generation'};
1419: $name=~s/\s+$//;
1420: $name=~s/\s+/ /g;
1421: }
1422: return $name;
1423: }
1424:
1425:
1426: # ------------------------------------------------------------------ Screenname
1427:
1428: =pod
1429:
1430: =item * screenname($uname,$udom)
1431:
1432: Gets a users screenname and returns it as a string
1433:
1434: =cut
1435:
1436: sub screenname {
1437: my ($uname,$udom)=@_;
1438: my %names=
1439: &Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1440: return $names{'screenname'};
1441: }
1442:
1443: # ------------------------------------------------------------- Message Wrapper
1444:
1445: sub messagewrapper {
1446: my ($link,$un,$do)=@_;
1447: return
1448: "<a href='/adm/email?compose=individual&recname=$un&recdom=$do'>$link</a>";
1449: }
1450: # --------------------------------------------------------------- Notes Wrapper
1451:
1452: sub noteswrapper {
1453: my ($link,$un,$do)=@_;
1454: return
1455: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
1456: }
1457: # ------------------------------------------------------------- Aboutme Wrapper
1458:
1459: sub aboutmewrapper {
1460: my ($link,$username,$domain)=@_;
1461: return "<a href='/adm/$domain/$username/aboutme'>$link</a>";
1462: }
1463:
1464: # ------------------------------------------------------------ Syllabus Wrapper
1465:
1466:
1467: sub syllabuswrapper {
1468: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
1469: if ($fontcolor) {
1470: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
1471: }
1472: return "<a href='/public/$domain/$coursedir/syllabus'>$linktext</a>";
1473: }
1474:
1475: =pod
1476:
1477: =back
1478:
1479: =head1 Access .tab File Data
1480:
1481: =over 4
1482:
1483: =item * languageids()
1484:
1485: returns list of all language ids
1486:
1487: =cut
1488:
1489: sub languageids {
1490: return sort(keys(%language));
1491: }
1492:
1493: =pod
1494:
1495: =item * languagedescription()
1496:
1497: returns description of a specified language id
1498:
1499: =cut
1500:
1501: sub languagedescription {
1502: my $code=shift;
1503: return ($supported_language{$code}?'* ':'').
1504: $language{$code}.
1505: ($supported_language{$code}?' ('.&mt('interface available').')':'');
1506: }
1507:
1508: sub plainlanguagedescription {
1509: my $code=shift;
1510: return $language{$code};
1511: }
1512:
1513: sub supportedlanguagecode {
1514: my $code=shift;
1515: return $supported_language{$code};
1516: }
1517:
1518: =pod
1519:
1520: =item * copyrightids()
1521:
1522: returns list of all copyrights
1523:
1524: =cut
1525:
1526: sub copyrightids {
1527: return sort(keys(%cprtag));
1528: }
1529:
1530: =pod
1531:
1532: =item * copyrightdescription()
1533:
1534: returns description of a specified copyright id
1535:
1536: =cut
1537:
1538: sub copyrightdescription {
1539: return $cprtag{shift(@_)};
1540: }
1541:
1542: =pod
1543:
1544: =item * filecategories()
1545:
1546: returns list of all file categories
1547:
1548: =cut
1549:
1550: sub filecategories {
1551: return sort(keys(%category_extensions));
1552: }
1553:
1554: =pod
1555:
1556: =item * filecategorytypes()
1557:
1558: returns list of file types belonging to a given file
1559: category
1560:
1561: =cut
1562:
1563: sub filecategorytypes {
1564: return @{$category_extensions{lc($_[0])}};
1565: }
1566:
1567: =pod
1568:
1569: =item * fileembstyle()
1570:
1571: returns embedding style for a specified file type
1572:
1573: =cut
1574:
1575: sub fileembstyle {
1576: return $fe{lc(shift(@_))};
1577: }
1578:
1579: =pod
1580:
1581: =item * filedescription()
1582:
1583: returns description for a specified file type
1584:
1585: =cut
1586:
1587: sub filedescription {
1588: return $fd{lc(shift(@_))};
1589: }
1590:
1591: =pod
1592:
1593: =item * filedescriptionex()
1594:
1595: returns description for a specified file type with
1596: extra formatting
1597:
1598: =cut
1599:
1600: sub filedescriptionex {
1601: my $ex=shift;
1602: return '.'.$ex.' '.$fd{lc($ex)};
1603: }
1604:
1605: # End of .tab access
1606: =pod
1607:
1608: =back
1609:
1610: =cut
1611:
1612: # ------------------------------------------------------------------ File Types
1613: sub fileextensions {
1614: return sort(keys(%fe));
1615: }
1616:
1617: # ----------------------------------------------------------- Display Languages
1618: # returns a hash with all desired display languages
1619: #
1620:
1621: sub display_languages {
1622: my %languages=();
1623: foreach (&preferred_languages()) {
1624: $languages{$_}=1;
1625: }
1626: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1627: if ($ENV{'form.displaylanguage'}) {
1628: foreach (split(/\s*(\,|\;|\:)\s*/,$ENV{'form.displaylanguage'})) {
1629: $languages{$_}=1;
1630: }
1631: }
1632: return %languages;
1633: }
1634:
1635: sub preferred_languages {
1636: my @languages=();
1637: if ($ENV{'environment.languages'}) {
1638: @languages=split(/\s*(\,|\;|\:)\s*/,$ENV{'environment.languages'});
1639: }
1640: if ($ENV{'course.'.$ENV{'request.course.id'}.'.languages'}) {
1641: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
1642: $ENV{'course.'.$ENV{'request.course.id'}.'.languages'}));
1643: }
1644: my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
1645: if ($browser) {
1646: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
1647: }
1648: if ($Apache::lonnet::domain_lang_def{$ENV{'user.domain'}}) {
1649: @languages=(@languages,
1650: $Apache::lonnet::domain_lang_def{$ENV{'user.domain'}});
1651: }
1652: if ($Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}}) {
1653: @languages=(@languages,
1654: $Apache::lonnet::domain_lang_def{$ENV{'request.role.domain'}});
1655: }
1656: if ($Apache::lonnet::domain_lang_def{
1657: $Apache::lonnet::perlvar{'lonDefDomain'}}) {
1658: @languages=(@languages,
1659: $Apache::lonnet::domain_lang_def{
1660: $Apache::lonnet::perlvar{'lonDefDomain'}});
1661: }
1662: # turn "en-ca" into "en-ca,en"
1663: my @genlanguages;
1664: foreach (@languages) {
1665: unless ($_=~/\w/) { next; }
1666: push (@genlanguages,$_);
1667: if ($_=~/(\-|\_)/) {
1668: push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
1669: }
1670: }
1671: return @genlanguages;
1672: }
1673:
1674: ###############################################################
1675: ## Student Answer Attempts ##
1676: ###############################################################
1677:
1678: =pod
1679:
1680: =head1 Alternate Problem Views
1681:
1682: =over 4
1683:
1684: =item * get_previous_attempt($symb, $username, $domain, $course,
1685: $getattempt, $regexp, $gradesub)
1686:
1687: Return string with previous attempt on problem. Arguments:
1688:
1689: =over 4
1690:
1691: =item * $symb: Problem, including path
1692:
1693: =item * $username: username of the desired student
1694:
1695: =item * $domain: domain of the desired student
1696:
1697: =item * $course: Course ID
1698:
1699: =item * $getattempt: Leave blank for all attempts, otherwise put
1700: something
1701:
1702: =item * $regexp: if string matches this regexp, the string will be
1703: sent to $gradesub
1704:
1705: =item * $gradesub: routine that processes the string if it matches $regexp
1706:
1707: =back
1708:
1709: The output string is a table containing all desired attempts, if any.
1710:
1711: =cut
1712:
1713: sub get_previous_attempt {
1714: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1715: my $prevattempts='';
1716: no strict 'refs';
1717: if ($symb) {
1718: my (%returnhash)=
1719: &Apache::lonnet::restore($symb,$course,$domain,$username);
1720: if ($returnhash{'version'}) {
1721: my %lasthash=();
1722: my $version;
1723: for ($version=1;$version<=$returnhash{'version'};$version++) {
1724: foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
1725: $lasthash{$_}=$returnhash{$version.':'.$_};
1726: }
1727: }
1728: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1729: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
1730: foreach (sort(keys %lasthash)) {
1731: my ($ign,@parts) = split(/\./,$_);
1732: if ($#parts > 0) {
1733: my $data=$parts[-1];
1734: pop(@parts);
1735: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
1736: } else {
1737: if ($#parts == 0) {
1738: $prevattempts.='<th>'.$parts[0].'</th>';
1739: } else {
1740: $prevattempts.='<th>'.$ign.'</th>';
1741: }
1742: }
1743: }
1744: if ($getattempt eq '') {
1745: for ($version=1;$version<=$returnhash{'version'};$version++) {
1746: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
1747: foreach (sort(keys %lasthash)) {
1748: my $value;
1749: if ($_ =~ /timestamp/) {
1750: $value=scalar(localtime($returnhash{$version.':'.$_}));
1751: } else {
1752: $value=$returnhash{$version.':'.$_};
1753: }
1754: $prevattempts.='<td>'.&Apache::lonnet::unescape($value).' </td>';
1755: }
1756: }
1757: }
1758: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
1759: foreach (sort(keys %lasthash)) {
1760: my $value;
1761: if ($_ =~ /timestamp/) {
1762: $value=scalar(localtime($lasthash{$_}));
1763: } else {
1764: $value=$lasthash{$_};
1765: }
1766: $value=&Apache::lonnet::unescape($value);
1767: if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
1768: $prevattempts.='<td>'.$value.' </td>';
1769: }
1770: $prevattempts.='</tr></table></td></tr></table>';
1771: } else {
1772: $prevattempts='Nothing submitted - no attempts.';
1773: }
1774: } else {
1775: $prevattempts='No data.';
1776: }
1777: }
1778:
1779: sub relative_to_absolute {
1780: my ($url,$output)=@_;
1781: my $parser=HTML::TokeParser->new(\$output);
1782: my $token;
1783: my $thisdir=$url;
1784: my @rlinks=();
1785: while ($token=$parser->get_token) {
1786: if ($token->[0] eq 'S') {
1787: if ($token->[1] eq 'a') {
1788: if ($token->[2]->{'href'}) {
1789: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
1790: }
1791: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
1792: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
1793: } elsif ($token->[1] eq 'base') {
1794: $thisdir=$token->[2]->{'href'};
1795: }
1796: }
1797: }
1798: $thisdir=~s-/[^/]*$--;
1799: foreach (@rlinks) {
1800: unless (($_=~/^http:\/\//i) ||
1801: ($_=~/^\//) ||
1802: ($_=~/^javascript:/i) ||
1803: ($_=~/^mailto:/i) ||
1804: ($_=~/^\#/)) {
1805: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
1806: $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
1807: }
1808: }
1809: # -------------------------------------------------- Deal with Applet codebases
1810: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
1811: return $output;
1812: }
1813:
1814: =pod
1815:
1816: =item * get_student_view
1817:
1818: show a snapshot of what student was looking at
1819:
1820: =cut
1821:
1822: sub get_student_view {
1823: my ($symb,$username,$domain,$courseid,$target) = @_;
1824: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1825: my (%old,%moreenv);
1826: my @elements=('symb','courseid','domain','username');
1827: foreach my $element (@elements) {
1828: $old{$element}=$ENV{'form.grade_'.$element};
1829: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1830: }
1831: if ($target eq 'tex') {$moreenv{'form.grade_target'} = 'tex';}
1832: &Apache::lonnet::appenv(%moreenv);
1833: $feedurl=&Apache::lonnet::clutter($feedurl);
1834: my $userview=&Apache::lonnet::ssi_body($feedurl);
1835: &Apache::lonnet::delenv('form.grade_');
1836: foreach my $element (@elements) {
1837: $ENV{'form.grade_'.$element}=$old{$element};
1838: }
1839: $userview=~s/\<body[^\>]*\>//gi;
1840: $userview=~s/\<\/body\>//gi;
1841: $userview=~s/\<html\>//gi;
1842: $userview=~s/\<\/html\>//gi;
1843: $userview=~s/\<head\>//gi;
1844: $userview=~s/\<\/head\>//gi;
1845: $userview=~s/action\s*\=/would_be_action\=/gi;
1846: $userview=&relative_to_absolute($feedurl,$userview);
1847: return $userview;
1848: }
1849:
1850: =pod
1851:
1852: =item * get_student_answers()
1853:
1854: show a snapshot of how student was answering problem
1855:
1856: =cut
1857:
1858: sub get_student_answers {
1859: my ($symb,$username,$domain,$courseid,%form) = @_;
1860: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1861: my (%old,%moreenv);
1862: my @elements=('symb','courseid','domain','username');
1863: foreach my $element (@elements) {
1864: $old{$element}=$ENV{'form.grade_'.$element};
1865: $moreenv{'form.grade_'.$element}=eval '$'.$element #'
1866: }
1867: $moreenv{'form.grade_target'}='answer';
1868: &Apache::lonnet::appenv(%moreenv);
1869: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%form);
1870: &Apache::lonnet::delenv('form.grade_');
1871: foreach my $element (@elements) {
1872: $ENV{'form.grade_'.$element}=$old{$element};
1873: }
1874: return $userview;
1875: }
1876:
1877: =pod
1878:
1879: =item * &submlink()
1880:
1881: Inputs: $text $uname $udom $symb
1882:
1883: Returns: A link to grades.pm such as to see the SUBM view of a student
1884:
1885: =cut
1886:
1887: ###############################################
1888: sub submlink {
1889: my ($text,$uname,$udom,$symb)=@_;
1890: if (!($uname && $udom)) {
1891: (my $cursymb, my $courseid,$udom,$uname)=
1892: &Apache::lonxml::whichuser($symb);
1893: if (!$symb) { $symb=$cursymb; }
1894: }
1895: if (!$symb) { $symb=&symbread(); }
1896: return '<a href="/adm/grades?symb='.$symb.'&student='.$uname.
1897: '&userdom='.$udom.'&command=submission">'.$text.'</a>';
1898: }
1899: ##############################################
1900:
1901: =pod
1902:
1903: =back
1904:
1905: =cut
1906:
1907: ###############################################
1908:
1909:
1910: sub timehash {
1911: my @ltime=localtime(shift);
1912: return ( 'seconds' => $ltime[0],
1913: 'minutes' => $ltime[1],
1914: 'hours' => $ltime[2],
1915: 'day' => $ltime[3],
1916: 'month' => $ltime[4]+1,
1917: 'year' => $ltime[5]+1900,
1918: 'weekday' => $ltime[6],
1919: 'dayyear' => $ltime[7]+1,
1920: 'dlsav' => $ltime[8] );
1921: }
1922:
1923: sub maketime {
1924: my %th=@_;
1925: return POSIX::mktime(
1926: ($th{'seconds'},$th{'minutes'},$th{'hours'},
1927: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,$th{'dlsav'}));
1928: }
1929:
1930: #########################################
1931:
1932: sub findallcourses {
1933: my %courses=();
1934: my $now=time;
1935: foreach (keys %ENV) {
1936: if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
1937: my ($starttime,$endtime)=$ENV{$_};
1938: my $active=1;
1939: if ($starttime) {
1940: if ($now<$starttime) { $active=0; }
1941: }
1942: if ($endtime) {
1943: if ($now>$endtime) { $active=0; }
1944: }
1945: if ($active) { $courses{$1.'_'.$2}=1; }
1946: }
1947: }
1948: return keys %courses;
1949: }
1950:
1951: ###############################################
1952: ###############################################
1953:
1954: =pod
1955:
1956: =head1 Domain Template Functions
1957:
1958: =over 4
1959:
1960: =item * &determinedomain()
1961:
1962: Inputs: $domain (usually will be undef)
1963:
1964: Returns: Determines which domain should be used for designs
1965:
1966: =cut
1967:
1968: ###############################################
1969: sub determinedomain {
1970: my $domain=shift;
1971: if (! $domain) {
1972: # Determine domain if we have not been given one
1973: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
1974: if ($ENV{'user.domain'}) { $domain=$ENV{'user.domain'}; }
1975: if ($ENV{'request.role.domain'}) {
1976: $domain=$ENV{'request.role.domain'};
1977: }
1978: }
1979: return $domain;
1980: }
1981: ###############################################
1982: =pod
1983:
1984: =item * &domainlogo()
1985:
1986: Inputs: $domain (usually will be undef)
1987:
1988: Returns: A link to a domain logo, if the domain logo exists.
1989: If the domain logo does not exist, a description of the domain.
1990:
1991: =cut
1992:
1993: ###############################################
1994: sub domainlogo {
1995: my $domain = &determinedomain(shift);
1996: # See if there is a logo
1997: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
1998: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
1999: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
2000: return '<img src="http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.
2001: '/adm/lonDomLogos/'.$domain.'.gif" alt="'.$domain.'" />';
2002: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
2003: return $Apache::lonnet::domaindescription{$domain};
2004: } else {
2005: return '';
2006: }
2007: }
2008: ##############################################
2009:
2010: =pod
2011:
2012: =item * &designparm()
2013:
2014: Inputs: $which parameter; $domain (usually will be undef)
2015:
2016: Returns: value of designparamter $which
2017:
2018: =cut
2019:
2020: ##############################################
2021: sub designparm {
2022: my ($which,$domain)=@_;
2023: if ($ENV{'browser.blackwhite'} eq 'on') {
2024: if ($which=~/\.(font|alink|vlink|link)$/) {
2025: return '#000000';
2026: }
2027: if ($which=~/\.(pgbg|sidebg)$/) {
2028: return '#FFFFFF';
2029: }
2030: if ($which=~/\.tabbg$/) {
2031: return '#CCCCCC';
2032: }
2033: }
2034: if ($ENV{'environment.color.'.$which}) {
2035: return $ENV{'environment.color.'.$which};
2036: }
2037: $domain=&determinedomain($domain);
2038: if ($designhash{$domain.'.'.$which}) {
2039: return $designhash{$domain.'.'.$which};
2040: } else {
2041: return $designhash{'default.'.$which};
2042: }
2043: }
2044:
2045: ###############################################
2046: ###############################################
2047:
2048: =pod
2049:
2050: =back
2051:
2052: =head1 HTTP Helpers
2053:
2054: =over 4
2055:
2056: =item * &bodytag()
2057:
2058: Returns a uniform header for LON-CAPA web pages.
2059:
2060: Inputs:
2061:
2062: =over 4
2063:
2064: =item * $title, A title to be displayed on the page.
2065:
2066: =item * $function, the current role (can be undef).
2067:
2068: =item * $addentries, extra parameters for the <body> tag.
2069:
2070: =item * $bodyonly, if defined, only return the <body> tag.
2071:
2072: =item * $domain, if defined, force a given domain.
2073:
2074: =item * $forcereg, if page should register as content page (relevant for
2075: text interface only)
2076:
2077: =back
2078:
2079: Returns: A uniform header for LON-CAPA web pages.
2080: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
2081: If $bodyonly is undef or zero, an html string containing a <body> tag and
2082: other decorations will be returned.
2083:
2084: =cut
2085:
2086: sub bodytag {
2087: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg)=@_;
2088: $title=&mt($title);
2089: unless ($function) {
2090: $function='student';
2091: if ($ENV{'request.role'}=~/^(cc|in|ta|ep)/) {
2092: $function='coordinator';
2093: }
2094: if ($ENV{'request.role'}=~/^(su|dc|ad|li)/) {
2095: $function='admin';
2096: }
2097: if (($ENV{'request.role'}=~/^(au|ca)/) ||
2098: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
2099: $function='author';
2100: }
2101: }
2102: my $img=&designparm($function.'.img',$domain);
2103: my $pgbg=&designparm($function.'.pgbg',$domain);
2104: my $tabbg=&designparm($function.'.tabbg',$domain);
2105: my $font=&designparm($function.'.font',$domain);
2106: my $link=&designparm($function.'.link',$domain);
2107: my $alink=&designparm($function.'.alink',$domain);
2108: my $vlink=&designparm($function.'.vlink',$domain);
2109: my $sidebg=&designparm($function.'.sidebg',$domain);
2110: # Accessibility font enhance
2111: unless ($addentries) { $addentries=''; }
2112: my $addstyle='';
2113: if ($ENV{'browser.fontenhance'} eq 'on') {
2114: $addstyle=' font-size: x-large;';
2115: }
2116: # role and realm
2117: my ($role,$realm)
2118: =&Apache::lonnet::plaintext((split(/\./,$ENV{'request.role'}))[0]);
2119: # realm
2120: if ($ENV{'request.course.id'}) {
2121: $realm=
2122: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
2123: }
2124: unless ($realm) { $realm=' '; }
2125: # Set messages
2126: my $messages=&domainlogo($domain);
2127: # Port for miniserver
2128: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
2129: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
2130: # construct main body tag
2131: my $bodytag = <<END;
2132: <style>
2133: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
2134: a:focus { color: red; background: yellow }
2135: </style>
2136: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
2137: style="margin-top: 0px;$addstyle" $addentries>
2138: END
2139: my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
2140: $lonhttpdPort.$img.'" alt="'.$function.'" />';
2141: if ($bodyonly) {
2142: return $bodytag;
2143: } elsif ($ENV{'browser.interface'} eq 'textual') {
2144: # Accessibility
2145: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2146: $forcereg).
2147: '<h1>LON-CAPA: '.$title.'</h1>';
2148: } elsif ($ENV{'environment.remote'} eq 'off') {
2149: # No Remote
2150: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2151: $forcereg).
2152: '<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.
2153: '</b></font></td></tr></table>';
2154: }
2155:
2156: #
2157: # Top frame rendering, Remote is up
2158: #
2159: return(<<ENDBODY);
2160: $bodytag
2161: <table width="100%" cellspacing="0" border="0" cellpadding="0">
2162: <tr><td bgcolor="$sidebg">
2163: $upperleft</td>
2164: <td bgcolor="$sidebg" align="right">$messages </td>
2165: </tr>
2166: <tr>
2167: <td rowspan="3" bgcolor="$tabbg">
2168: <font size="5" face="Arial, Helvetica, sans-serif"><b>$title</b></font>
2169: <td bgcolor="$tabbg" align="right">
2170: <font size="2" face="Arial, Helvetica, sans-serif">
2171: $ENV{'environment.firstname'}
2172: $ENV{'environment.middlename'}
2173: $ENV{'environment.lastname'}
2174: $ENV{'environment.generation'}
2175: </font>
2176: </td>
2177: </tr>
2178: <tr><td bgcolor="$tabbg" align="right">
2179: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>
2180: </td></tr>
2181: <tr>
2182: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font> </td></tr>
2183: </table><br>
2184: ENDBODY
2185: }
2186:
2187: ###############################################
2188:
2189: sub get_posted_cgi {
2190: my $r=shift;
2191:
2192: my $buffer;
2193:
2194: $r->read($buffer,$r->header_in('Content-length'),0);
2195: unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
2196: my @pairs=split(/&/,$buffer);
2197: my $pair;
2198: foreach $pair (@pairs) {
2199: my ($name,$value) = split(/=/,$pair);
2200: $value =~ tr/+/ /;
2201: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2202: $name =~ tr/+/ /;
2203: $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2204: &add_to_env("form.$name",$value);
2205: }
2206: } else {
2207: my $contentsep=$1;
2208: my @lines = split (/\n/,$buffer);
2209: my $name='';
2210: my $value='';
2211: my $fname='';
2212: my $fmime='';
2213: my $i;
2214: for ($i=0;$i<=$#lines;$i++) {
2215: if ($lines[$i]=~/^$contentsep/) {
2216: if ($name) {
2217: chomp($value);
2218: if ($fname) {
2219: $ENV{"form.$name.filename"}=$fname;
2220: $ENV{"form.$name.mimetype"}=$fmime;
2221: } else {
2222: $value=~s/\s+$//s;
2223: }
2224: &add_to_env("form.$name",$value);
2225: }
2226: if ($i<$#lines) {
2227: $i++;
2228: $lines[$i]=~
2229: /Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
2230: $name=$1;
2231: $value='';
2232: if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
2233: $fname=$1;
2234: if
2235: ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
2236: $fmime=$1;
2237: $i++;
2238: } else {
2239: $fmime='';
2240: }
2241: } else {
2242: $fname='';
2243: $fmime='';
2244: }
2245: $i++;
2246: }
2247: } else {
2248: $value.=$lines[$i]."\n";
2249: }
2250: }
2251: }
2252: $ENV{'request.method'}=$ENV{'REQUEST_METHOD'};
2253: $r->method_number(M_GET);
2254: $r->method('GET');
2255: $r->headers_in->unset('Content-length');
2256: }
2257:
2258: =pod
2259:
2260: =item * get_unprocessed_cgi($query,$possible_names)
2261:
2262: Modify the %ENV hash to contain unprocessed CGI form parameters held in
2263: $query. The parameters listed in $possible_names (an array reference),
2264: will be set in $ENV{'form.name'} if they do not already exist.
2265:
2266: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
2267: $possible_names is an ref to an array of form element names. As an example:
2268: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
2269: will result in $ENV{'form.uname'} and $ENV{'form.udom'} being set.
2270:
2271: =cut
2272:
2273: sub get_unprocessed_cgi {
2274: my ($query,$possible_names)= @_;
2275: # $Apache::lonxml::debug=1;
2276: foreach (split(/&/,$query)) {
2277: my ($name, $value) = split(/=/,$_);
2278: $name = &Apache::lonnet::unescape($name);
2279: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
2280: $value =~ tr/+/ /;
2281: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
2282: &Apache::lonxml::debug("Seting :$name: to :$value:");
2283: unless (defined($ENV{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
2284: }
2285: }
2286: }
2287:
2288: =pod
2289:
2290: =item * cacheheader()
2291:
2292: returns cache-controlling header code
2293:
2294: =cut
2295:
2296: sub cacheheader {
2297: unless ($ENV{'request.method'} eq 'GET') { return ''; }
2298: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
2299: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
2300: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
2301: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
2302: return $output;
2303: }
2304:
2305: =pod
2306:
2307: =item * no_cache($r)
2308:
2309: specifies header code to not have cache
2310:
2311: =cut
2312:
2313: sub no_cache {
2314: my ($r) = @_;
2315: unless ($ENV{'request.method'} eq 'GET') { return ''; }
2316: #my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
2317: $r->no_cache(1);
2318: $r->header_out("Pragma" => "no-cache");
2319: #$r->header_out("Expires" => $date);
2320: }
2321:
2322: sub content_type {
2323: my ($r,$type,$charset) = @_;
2324: unless ($charset) {
2325: $charset=&Apache::lonlocal::current_encoding;
2326: }
2327: $r->content_type($type.($charset?'; charset='.$charset:''));
2328: }
2329:
2330: =pod
2331:
2332: =item * add_to_env($name,$value)
2333:
2334: adds $name to the %ENV hash with value
2335: $value, if $name already exists, the entry is converted to an array
2336: reference and $value is added to the array.
2337:
2338: =cut
2339:
2340: sub add_to_env {
2341: my ($name,$value)=@_;
2342: if (defined($ENV{$name})) {
2343: if (ref($ENV{$name})) {
2344: #already have multiple values
2345: push(@{ $ENV{$name} },$value);
2346: } else {
2347: #first time seeing multiple values, convert hash entry to an arrayref
2348: my $first=$ENV{$name};
2349: undef($ENV{$name});
2350: push(@{ $ENV{$name} },$first,$value);
2351: }
2352: } else {
2353: $ENV{$name}=$value;
2354: }
2355: }
2356:
2357: =pod
2358:
2359: =item * get_env_multiple($name)
2360:
2361: gets $name from the %ENV hash, it seemlessly handles the cases where multiple
2362: values may be defined and end up as an array ref.
2363:
2364: returns an array of values
2365:
2366: =cut
2367:
2368: sub get_env_multiple {
2369: my ($name) = @_;
2370: my @values;
2371: if (defined($ENV{$name})) {
2372: # exists is it an array
2373: if (ref($ENV{$name})) {
2374: @values=@{ $ENV{$name} };
2375: } else {
2376: $values[0]=$ENV{$name};
2377: }
2378: }
2379: return(@values);
2380: }
2381:
2382:
2383: =pod
2384:
2385: =back
2386:
2387: =head1 CSV Upload/Handling functions
2388:
2389: =over 4
2390:
2391: =item * upfile_store($r)
2392:
2393: Store uploaded file, $r should be the HTTP Request object,
2394: needs $ENV{'form.upfile'}
2395: returns $datatoken to be put into hidden field
2396:
2397: =cut
2398:
2399: sub upfile_store {
2400: my $r=shift;
2401: $ENV{'form.upfile'}=~s/\r/\n/gs;
2402: $ENV{'form.upfile'}=~s/\f/\n/gs;
2403: $ENV{'form.upfile'}=~s/\n+/\n/gs;
2404: $ENV{'form.upfile'}=~s/\n+$//gs;
2405:
2406: my $datatoken=$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
2407: '_enroll_'.$ENV{'request.course.id'}.'_'.time.'_'.$$;
2408: {
2409: my $datafile = $r->dir_config('lonDaemons').
2410: '/tmp/'.$datatoken.'.tmp';
2411: if ( open(my $fh,">$datafile") ) {
2412: print $fh $ENV{'form.upfile'};
2413: close($fh);
2414: }
2415: }
2416: return $datatoken;
2417: }
2418:
2419: =pod
2420:
2421: =item * load_tmp_file($r)
2422:
2423: Load uploaded file from tmp, $r should be the HTTP Request object,
2424: needs $ENV{'form.datatoken'},
2425: sets $ENV{'form.upfile'} to the contents of the file
2426:
2427: =cut
2428:
2429: sub load_tmp_file {
2430: my $r=shift;
2431: my @studentdata=();
2432: {
2433: my $studentfile = $r->dir_config('lonDaemons').
2434: '/tmp/'.$ENV{'form.datatoken'}.'.tmp';
2435: if ( open(my $fh,"<$studentfile") ) {
2436: @studentdata=<$fh>;
2437: close($fh);
2438: }
2439: }
2440: $ENV{'form.upfile'}=join('',@studentdata);
2441: }
2442:
2443: =pod
2444:
2445: =item * upfile_record_sep()
2446:
2447: Separate uploaded file into records
2448: returns array of records,
2449: needs $ENV{'form.upfile'} and $ENV{'form.upfiletype'}
2450:
2451: =cut
2452:
2453: sub upfile_record_sep {
2454: if ($ENV{'form.upfiletype'} eq 'xml') {
2455: } else {
2456: return split(/\n/,$ENV{'form.upfile'});
2457: }
2458: }
2459:
2460: =pod
2461:
2462: =item * record_sep($record)
2463:
2464: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $ENV{'form.upfiletype'}
2465:
2466: =cut
2467:
2468: sub record_sep {
2469: my $record=shift;
2470: my %components=();
2471: if ($ENV{'form.upfiletype'} eq 'xml') {
2472: } elsif ($ENV{'form.upfiletype'} eq 'space') {
2473: my $i=0;
2474: foreach (split(/\s+/,$record)) {
2475: my $field=$_;
2476: $field=~s/^(\"|\')//;
2477: $field=~s/(\"|\')$//;
2478: $components{$i}=$field;
2479: $i++;
2480: }
2481: } elsif ($ENV{'form.upfiletype'} eq 'tab') {
2482: my $i=0;
2483: foreach (split(/\t+/,$record)) {
2484: my $field=$_;
2485: $field=~s/^(\"|\')//;
2486: $field=~s/(\"|\')$//;
2487: $components{$i}=$field;
2488: $i++;
2489: }
2490: } else {
2491: my @allfields=split(/\,/,$record);
2492: my $i=0;
2493: my $j;
2494: for ($j=0;$j<=$#allfields;$j++) {
2495: my $field=$allfields[$j];
2496: if ($field=~/^\s*(\"|\')/) {
2497: my $delimiter=$1;
2498: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
2499: $j++;
2500: $field.=','.$allfields[$j];
2501: }
2502: $field=~s/^\s*$delimiter//;
2503: $field=~s/$delimiter\s*$//;
2504: }
2505: $components{$i}=$field;
2506: $i++;
2507: }
2508: }
2509: return %components;
2510: }
2511:
2512: ######################################################
2513: ######################################################
2514:
2515: =pod
2516:
2517: =item * upfile_select_html()
2518:
2519: Return HTML code to select a file from the users machine and specify
2520: the file type.
2521:
2522: =cut
2523:
2524: ######################################################
2525: ######################################################
2526: sub upfile_select_html {
2527: my %Types = (
2528: csv => &mt('CSV (comma separated values, spreadsheet)'),
2529: space => &mt('Space separated'),
2530: tab => &mt('Tabulator separated'),
2531: # xml => &mt('HTML/XML'),
2532: );
2533: my $Str = '<input type="file" name="upfile" size="50" />'.
2534: '<br />Type: <select name="upfiletype">';
2535: foreach my $type (sort(keys(%Types))) {
2536: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
2537: }
2538: $Str .= "</select>\n";
2539: return $Str;
2540: }
2541:
2542: ######################################################
2543: ######################################################
2544:
2545: =pod
2546:
2547: =item * csv_print_samples($r,$records)
2548:
2549: Prints a table of sample values from each column uploaded $r is an
2550: Apache Request ref, $records is an arrayref from
2551: &Apache::loncommon::upfile_record_sep
2552:
2553: =cut
2554:
2555: ######################################################
2556: ######################################################
2557: sub csv_print_samples {
2558: my ($r,$records) = @_;
2559: my (%sone,%stwo,%sthree);
2560: %sone=&record_sep($$records[0]);
2561: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2562: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
2563: #
2564: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
2565: foreach (sort({$a <=> $b} keys(%sone))) {
2566: $r->print('<th>'.&mt('Column [_1]',($_+1)).'</th>'); }
2567: $r->print('</tr>');
2568: foreach my $hash (\%sone,\%stwo,\%sthree) {
2569: $r->print('<tr>');
2570: foreach (sort({$a <=> $b} keys(%sone))) {
2571: $r->print('<td>');
2572: if (defined($$hash{$_})) { $r->print($$hash{$_}); }
2573: $r->print('</td>');
2574: }
2575: $r->print('</tr>');
2576: }
2577: $r->print('</tr></table><br />'."\n");
2578: }
2579:
2580: ######################################################
2581: ######################################################
2582:
2583: =pod
2584:
2585: =item * csv_print_select_table($r,$records,$d)
2586:
2587: Prints a table to create associations between values and table columns.
2588:
2589: $r is an Apache Request ref,
2590: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2591: $d is an array of 2 element arrays (internal name, displayed name)
2592:
2593: =cut
2594:
2595: ######################################################
2596: ######################################################
2597: sub csv_print_select_table {
2598: my ($r,$records,$d) = @_;
2599: my $i=0;my %sone;
2600: %sone=&record_sep($$records[0]);
2601: $r->print(&mt('Associate columns with student attributes.')."\n".
2602: '<table border="2"><tr>'.
2603: '<th>'.&mt('Attribute').'</th>'.
2604: '<th>'.&mt('Column').'</th></tr>'."\n");
2605: foreach (@$d) {
2606: my ($value,$display)=@{ $_ };
2607: $r->print('<tr><td>'.$display.'</td>');
2608:
2609: $r->print('<td><select name=f'.$i.
2610: ' onchange="javascript:flip(this.form,'.$i.');">');
2611: $r->print('<option value="none"></option>');
2612: foreach (sort({$a <=> $b} keys(%sone))) {
2613: $r->print('<option value="'.$_.'">Column '.($_+1).'</option>');
2614: }
2615: $r->print('</select></td></tr>'."\n");
2616: $i++;
2617: }
2618: $i--;
2619: return $i;
2620: }
2621:
2622: ######################################################
2623: ######################################################
2624:
2625: =pod
2626:
2627: =item * csv_samples_select_table($r,$records,$d)
2628:
2629: Prints a table of sample values from the upload and can make associate samples to internal names.
2630:
2631: $r is an Apache Request ref,
2632: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
2633: $d is an array of 2 element arrays (internal name, displayed name)
2634:
2635: =cut
2636:
2637: ######################################################
2638: ######################################################
2639: sub csv_samples_select_table {
2640: my ($r,$records,$d) = @_;
2641: my %sone; my %stwo; my %sthree;
2642: my $i=0;
2643: #
2644: $r->print('<table border=2><tr><th>'.
2645: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
2646: %sone=&record_sep($$records[0]);
2647: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
2648: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
2649: #
2650: foreach (sort keys %sone) {
2651: $r->print('<tr><td><select name="f'.$i.'"'.
2652: ' onchange="javascript:flip(this.form,'.$i.');">');
2653: foreach (@$d) {
2654: my ($value,$display)=@{ $_ };
2655: $r->print('<option value="'.$value.'">'.$display.'</option>');
2656: }
2657: $r->print('</select></td><td>');
2658: if (defined($sone{$_})) { $r->print($sone{$_}."</br>\n"); }
2659: if (defined($stwo{$_})) { $r->print($stwo{$_}."</br>\n"); }
2660: if (defined($sthree{$_})) { $r->print($sthree{$_}."</br>\n"); }
2661: $r->print('</td></tr>');
2662: $i++;
2663: }
2664: $i--;
2665: return($i);
2666: }
2667:
2668: ######################################################
2669: ######################################################
2670:
2671: =pod
2672:
2673: =item clean_excel_name($name)
2674:
2675: Returns a replacement for $name which does not contain any illegal characters.
2676:
2677: =cut
2678:
2679: ######################################################
2680: ######################################################
2681: sub clean_excel_name {
2682: my ($name) = @_;
2683: $name =~ s/[:\*\?\/\\]//g;
2684: if (length($name) > 31) {
2685: $name = substr($name,0,31);
2686: }
2687: return $name;
2688: }
2689:
2690: =pod
2691:
2692: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
2693:
2694: Returns either 1 or undef
2695:
2696: 1 if the part is to be hidden, undef if it is to be shown
2697:
2698: Arguments are:
2699:
2700: $id the id of the part to be checked
2701: $symb, optional the symb of the resource to check
2702: $udom, optional the domain of the user to check for
2703: $uname, optional the username of the user to check for
2704:
2705: =cut
2706:
2707: sub check_if_partid_hidden {
2708: my ($id,$symb,$udom,$uname) = @_;
2709: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
2710: $symb,$udom,$uname);
2711: my $truth=1;
2712: #if the string starts with !, then the list is the list to show not hide
2713: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
2714: my @hiddenlist=split(/,/,$hiddenparts);
2715: foreach my $checkid (@hiddenlist) {
2716: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
2717: }
2718: return !$truth;
2719: }
2720:
2721:
2722: ############################################################
2723: ############################################################
2724:
2725: =pod
2726:
2727: =back
2728:
2729: =head1 cgi-bin script and graphing routines
2730:
2731: =over 4
2732:
2733: =item get_cgi_id
2734:
2735: Inputs: none
2736:
2737: Returns an id which can be used to pass environment variables
2738: to various cgi-bin scripts. These environment variables will
2739: be removed from the users environment after a given time by
2740: the routine &Apache::lonnet::transfer_profile_to_env.
2741:
2742: =cut
2743:
2744: ############################################################
2745: ############################################################
2746: my $uniq=0;
2747: sub get_cgi_id {
2748: $uniq=($uniq+1)%100000;
2749: return (time.'_'.$uniq);
2750: }
2751:
2752: ############################################################
2753: ############################################################
2754:
2755: =pod
2756:
2757: =item DrawBarGraph
2758:
2759: Facilitates the plotting of data in a (stacked) bar graph.
2760: Puts plot definition data into the users environment in order for
2761: graph.png to plot it. Returns an <img> tag for the plot.
2762: The bars on the plot are labeled '1','2',...,'n'.
2763:
2764: Inputs:
2765:
2766: =over 4
2767:
2768: =item $Title: string, the title of the plot
2769:
2770: =item $xlabel: string, text describing the X-axis of the plot
2771:
2772: =item $ylabel: string, text describing the Y-axis of the plot
2773:
2774: =item $Max: scalar, the maximum Y value to use in the plot
2775: If $Max is < any data point, the graph will not be rendered.
2776:
2777: =item $colors: array ref holding the colors to be used for the data sets when
2778: they are plotted. If undefined, default values will be used.
2779:
2780: =item @Values: An array of array references. Each array reference holds data
2781: to be plotted in a stacked bar chart.
2782:
2783: =back
2784:
2785: Returns:
2786:
2787: An <img> tag which references graph.png and the appropriate identifying
2788: information for the plot.
2789:
2790: =cut
2791:
2792: ############################################################
2793: ############################################################
2794: sub DrawBarGraph {
2795: my ($Title,$xlabel,$ylabel,$Max,$colors,@Values)=@_;
2796: #
2797: if (! defined($colors)) {
2798: $colors = ['#33ff00',
2799: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
2800: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
2801: ];
2802: }
2803: #
2804: my $identifier = &get_cgi_id();
2805: my $id = 'cgi.'.$identifier;
2806: if (! @Values || ref($Values[0]) ne 'ARRAY') {
2807: return '';
2808: }
2809: my $NumBars = scalar(@{$Values[0]});
2810: my %ValuesHash;
2811: my $NumSets=1;
2812: foreach my $array (@Values) {
2813: next if (! ref($array));
2814: $ValuesHash{$id.'.data.'.$NumSets++} =
2815: join(',',@$array);
2816: }
2817: #
2818: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
2819: if ($NumBars < 10) {
2820: $width = 120+$NumBars*15;
2821: $xskip = 1;
2822: $bar_width = 15;
2823: } elsif ($NumBars <= 25) {
2824: $width = 120+$NumBars*11;
2825: $xskip = 5;
2826: $bar_width = 8;
2827: } elsif ($NumBars <= 50) {
2828: $width = 120+$NumBars*8;
2829: $xskip = 5;
2830: $bar_width = 4;
2831: } else {
2832: $width = 120+$NumBars*8;
2833: $xskip = 5;
2834: $bar_width = 4;
2835: }
2836: #
2837: my @Labels;
2838: for (my $i=0;$i<@{$Values[0]};$i++) {
2839: push (@Labels,$i+1);
2840: }
2841: #
2842: $Max = 1 if ($Max < 1);
2843: if ( int($Max) < $Max ) {
2844: $Max++;
2845: $Max = int($Max);
2846: }
2847: $Title = '' if (! defined($Title));
2848: $xlabel = '' if (! defined($xlabel));
2849: $ylabel = '' if (! defined($ylabel));
2850: $ValuesHash{$id.'.title'} = &Apache::lonnet::escape($Title);
2851: $ValuesHash{$id.'.xlabel'} = &Apache::lonnet::escape($xlabel);
2852: $ValuesHash{$id.'.ylabel'} = &Apache::lonnet::escape($ylabel);
2853: $ValuesHash{$id.'.y_max_value'} = $Max;
2854: $ValuesHash{$id.'.NumBars'} = $NumBars;
2855: $ValuesHash{$id.'.NumSets'} = $NumSets;
2856: $ValuesHash{$id.'.PlotType'} = 'bar';
2857: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2858: $ValuesHash{$id.'.height'} = $height;
2859: $ValuesHash{$id.'.width'} = $width;
2860: $ValuesHash{$id.'.xskip'} = $xskip;
2861: $ValuesHash{$id.'.bar_width'} = $bar_width;
2862: $ValuesHash{$id.'.labels'} = join(',',@Labels);
2863: #
2864: &Apache::lonnet::appenv(%ValuesHash);
2865: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2866: }
2867:
2868: ############################################################
2869: ############################################################
2870:
2871: =pod
2872:
2873: =item DrawXYGraph
2874:
2875: Facilitates the plotting of data in an XY graph.
2876: Puts plot definition data into the users environment in order for
2877: graph.png to plot it. Returns an <img> tag for the plot.
2878:
2879: Inputs:
2880:
2881: =over 4
2882:
2883: =item $Title: string, the title of the plot
2884:
2885: =item $xlabel: string, text describing the X-axis of the plot
2886:
2887: =item $ylabel: string, text describing the Y-axis of the plot
2888:
2889: =item $Max: scalar, the maximum Y value to use in the plot
2890: If $Max is < any data point, the graph will not be rendered.
2891:
2892: =item $colors: Array ref containing the hex color codes for the data to be
2893: plotted in. If undefined, default values will be used.
2894:
2895: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2896:
2897: =item $Ydata: Array ref containing Array refs.
2898: Each of the contained arrays will be plotted as a seperate curve.
2899:
2900: =item %Values: hash indicating or overriding any default values which are
2901: passed to graph.png.
2902: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2903:
2904: =back
2905:
2906: Returns:
2907:
2908: An <img> tag which references graph.png and the appropriate identifying
2909: information for the plot.
2910:
2911: =cut
2912:
2913: ############################################################
2914: ############################################################
2915: sub DrawXYGraph {
2916: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
2917: #
2918: # Create the identifier for the graph
2919: my $identifier = &get_cgi_id();
2920: my $id = 'cgi.'.$identifier;
2921: #
2922: $Title = '' if (! defined($Title));
2923: $xlabel = '' if (! defined($xlabel));
2924: $ylabel = '' if (! defined($ylabel));
2925: my %ValuesHash =
2926: (
2927: $id.'.title' => &Apache::lonnet::escape($Title),
2928: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
2929: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
2930: $id.'.y_max_value'=> $Max,
2931: $id.'.labels' => join(',',@$Xlabels),
2932: $id.'.PlotType' => 'XY',
2933: );
2934: #
2935: if (defined($colors) && ref($colors) eq 'ARRAY') {
2936: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
2937: }
2938: #
2939: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
2940: return '';
2941: }
2942: my $NumSets=1;
2943: foreach my $array (@{$Ydata}){
2944: next if (! ref($array));
2945: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
2946: }
2947: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
2948: #
2949: # Deal with other parameters
2950: while (my ($key,$value) = each(%Values)) {
2951: $ValuesHash{$id.'.'.$key} = $value;
2952: }
2953: #
2954: &Apache::lonnet::appenv(%ValuesHash);
2955: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
2956: }
2957:
2958: ############################################################
2959: ############################################################
2960:
2961: =pod
2962:
2963: =item DrawXYYGraph
2964:
2965: Facilitates the plotting of data in an XY graph with two Y axes.
2966: Puts plot definition data into the users environment in order for
2967: graph.png to plot it. Returns an <img> tag for the plot.
2968:
2969: Inputs:
2970:
2971: =over 4
2972:
2973: =item $Title: string, the title of the plot
2974:
2975: =item $xlabel: string, text describing the X-axis of the plot
2976:
2977: =item $ylabel: string, text describing the Y-axis of the plot
2978:
2979: =item $colors: Array ref containing the hex color codes for the data to be
2980: plotted in. If undefined, default values will be used.
2981:
2982: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
2983:
2984: =item $Ydata1: The first data set
2985:
2986: =item $Min1: The minimum value of the left Y-axis
2987:
2988: =item $Max1: The maximum value of the left Y-axis
2989:
2990: =item $Ydata2: The second data set
2991:
2992: =item $Min2: The minimum value of the right Y-axis
2993:
2994: =item $Max2: The maximum value of the left Y-axis
2995:
2996: =item %Values: hash indicating or overriding any default values which are
2997: passed to graph.png.
2998: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
2999:
3000: =back
3001:
3002: Returns:
3003:
3004: An <img> tag which references graph.png and the appropriate identifying
3005: information for the plot.
3006:
3007: =cut
3008:
3009: ############################################################
3010: ############################################################
3011: sub DrawXYYGraph {
3012: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
3013: $Ydata2,$Min2,$Max2,%Values)=@_;
3014: #
3015: # Create the identifier for the graph
3016: my $identifier = &get_cgi_id();
3017: my $id = 'cgi.'.$identifier;
3018: #
3019: $Title = '' if (! defined($Title));
3020: $xlabel = '' if (! defined($xlabel));
3021: $ylabel = '' if (! defined($ylabel));
3022: my %ValuesHash =
3023: (
3024: $id.'.title' => &Apache::lonnet::escape($Title),
3025: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
3026: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
3027: $id.'.labels' => join(',',@$Xlabels),
3028: $id.'.PlotType' => 'XY',
3029: $id.'.NumSets' => 2,
3030: $id.'.two_axes' => 1,
3031: $id.'.y1_max_value' => $Max1,
3032: $id.'.y1_min_value' => $Min1,
3033: $id.'.y2_max_value' => $Max2,
3034: $id.'.y2_min_value' => $Min2,
3035: );
3036: #
3037: if (defined($colors) && ref($colors) eq 'ARRAY') {
3038: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
3039: }
3040: #
3041: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
3042: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
3043: return '';
3044: }
3045: my $NumSets=1;
3046: foreach my $array ($Ydata1,$Ydata2){
3047: next if (! ref($array));
3048: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
3049: }
3050: #
3051: # Deal with other parameters
3052: while (my ($key,$value) = each(%Values)) {
3053: $ValuesHash{$id.'.'.$key} = $value;
3054: }
3055: #
3056: &Apache::lonnet::appenv(%ValuesHash);
3057: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
3058: }
3059:
3060: ############################################################
3061: ############################################################
3062:
3063: =pod
3064:
3065: =back
3066:
3067: =head1 Statistics helper routines?
3068:
3069: Bad place for them but what the hell.
3070:
3071: =over 4
3072:
3073: =item &chartlink
3074:
3075: Returns a link to the chart for a specific student.
3076:
3077: Inputs:
3078:
3079: =over 4
3080:
3081: =item $linktext: The text of the link
3082:
3083: =item $sname: The students username
3084:
3085: =item $sdomain: The students domain
3086:
3087: =back
3088:
3089: =back
3090:
3091: =cut
3092:
3093: ############################################################
3094: ############################################################
3095: sub chartlink {
3096: my ($linktext, $sname, $sdomain) = @_;
3097: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
3098: '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
3099: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
3100: '">'.$linktext.'</a>';
3101: }
3102:
3103: #######################################################
3104: #######################################################
3105:
3106: =pod
3107:
3108: =head1 Course Environment Routines
3109:
3110: =over 4
3111:
3112: =item &restore_course_settings
3113:
3114: =item &store_course_settings
3115:
3116: Restores/Store indicated form parameters from the course environment.
3117: Will not overwrite existing values of the form parameters.
3118:
3119: Inputs:
3120: a scalar describing the data (e.g. 'chart', 'problem_analysis')
3121:
3122: a hash ref describing the data to be stored. For example:
3123:
3124: %Save_Parameters = ('Status' => 'scalar',
3125: 'chartoutputmode' => 'scalar',
3126: 'chartoutputdata' => 'scalar',
3127: 'Section' => 'array',
3128: 'StudentData' => 'array',
3129: 'Maps' => 'array');
3130:
3131: Returns: both routines return nothing
3132:
3133: =cut
3134:
3135: #######################################################
3136: #######################################################
3137: sub store_course_settings {
3138: # save to the environment
3139: # appenv the same items, just to be safe
3140: my $courseid = $ENV{'request.course.id'};
3141: my $coursedom = $ENV{'course.'.$courseid.'.domain'};
3142: my ($prefix,$Settings) = @_;
3143: my %SaveHash;
3144: my %AppHash;
3145: while (my ($setting,$type) = each(%$Settings)) {
3146: my $basename = 'env.internal.'.$prefix.'.'.$setting;
3147: my $envname = 'course.'.$courseid.'.'.$basename;
3148: if (exists($ENV{'form.'.$setting})) {
3149: # Save this value away
3150: if ($type eq 'scalar' &&
3151: (! exists($ENV{$envname}) ||
3152: $ENV{$envname} ne $ENV{'form.'.$setting})) {
3153: $SaveHash{$basename} = $ENV{'form.'.$setting};
3154: $AppHash{$envname} = $ENV{'form.'.$setting};
3155: } elsif ($type eq 'array') {
3156: my $stored_form;
3157: if (ref($ENV{'form.'.$setting})) {
3158: $stored_form = join(',',
3159: map {
3160: &Apache::lonnet::escape($_);
3161: } sort(@{$ENV{'form.'.$setting}}));
3162: } else {
3163: $stored_form =
3164: &Apache::lonnet::escape($ENV{'form.'.$setting});
3165: }
3166: # Determine if the array contents are the same.
3167: if ($stored_form ne $ENV{$envname}) {
3168: $SaveHash{$basename} = $stored_form;
3169: $AppHash{$envname} = $stored_form;
3170: }
3171: }
3172: }
3173: }
3174: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
3175: $coursedom,
3176: $ENV{'course.'.$courseid.'.num'});
3177: if ($put_result !~ /^(ok|delayed)/) {
3178: &Apache::lonnet::logthis('unable to save form parameters, '.
3179: 'got error:'.$put_result);
3180: }
3181: # Make sure these settings stick around in this session, too
3182: &Apache::lonnet::appenv(%AppHash);
3183: return;
3184: }
3185:
3186: sub restore_course_settings {
3187: my $courseid = $ENV{'request.course.id'};
3188: my ($prefix,$Settings) = @_;
3189: while (my ($setting,$type) = each(%$Settings)) {
3190: next if (exists($ENV{'form.'.$setting}));
3191: my $envname = 'course.'.$courseid.'.env.internal.'.$prefix.
3192: '.'.$setting;
3193: if (exists($ENV{$envname})) {
3194: if ($type eq 'scalar') {
3195: $ENV{'form.'.$setting} = $ENV{$envname};
3196: } elsif ($type eq 'array') {
3197: $ENV{'form.'.$setting} = [
3198: map {
3199: &Apache::lonnet::unescape($_);
3200: } split(',',$ENV{$envname})
3201: ];
3202: }
3203: }
3204: }
3205: }
3206:
3207: ############################################################
3208: ############################################################
3209:
3210: sub propath {
3211: my ($udom,$uname)=@_;
3212: $udom=~s/\W//g;
3213: $uname=~s/\W//g;
3214: my $subdir=$uname.'__';
3215: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3216: my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3217: return $proname;
3218: }
3219:
3220: sub icon {
3221: my ($file)=@_;
3222: my @file_ext = split(/\./,$file);
3223: my $curfext = $file_ext[-1];
3224: my $iconname="unknown.gif";
3225: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
3226: # The unless conditional that follows is a bit of overkill
3227: $iconname = $curfext.".gif" unless
3228: (!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn');
3229: return $Apache::lonnet::perlvar{'lonIconsURL'}."/$iconname";
3230: }
3231:
3232: =pod
3233:
3234: =back
3235:
3236: =cut
3237:
3238: 1;
3239: __END__;
3240:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>