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