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