1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.283 2005/11/08 03:08:15 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::Constants qw(:common :http :methods);
62: use Apache::lonmenu();
63: use Apache::lonlocal;
64: use HTML::Entities;
65:
66: my $readit;
67:
68: ##
69: ## Global Variables
70: ##
71:
72: # ----------------------------------------------- Filetypes/Languages/Copyright
73: my %language;
74: my %supported_language;
75: my %cprtag;
76: my %scprtag;
77: my %fe; my %fd;
78: my %category_extensions;
79:
80: # ---------------------------------------------- Designs
81:
82: my %designhash;
83:
84: # ---------------------------------------------- Thesaurus variables
85: #
86: # %Keywords:
87: # A hash used by &keyword to determine if a word is considered a keyword.
88: # $thesaurus_db_file
89: # Scalar containing the full path to the thesaurus database.
90:
91: my %Keywords;
92: my $thesaurus_db_file;
93:
94: #
95: # Initialize values from language.tab, copyright.tab, filetypes.tab,
96: # thesaurus.tab, and filecategories.tab.
97: #
98: BEGIN {
99: # Variable initialization
100: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
101: #
102: unless ($readit) {
103: # ------------------------------------------------------------------- languages
104: {
105: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
106: '/language.tab';
107: if ( open(my $fh,"<$langtabfile") ) {
108: while (<$fh>) {
109: next if /^\#/;
110: chomp;
111: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$_));
112: $language{$key}=$val.' - '.$enc;
113: if ($sup) {
114: $supported_language{$key}=$sup;
115: }
116: }
117: close($fh);
118: }
119: }
120: # ------------------------------------------------------------------ copyrights
121: {
122: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
123: '/copyright.tab';
124: if ( open (my $fh,"<$copyrightfile") ) {
125: while (<$fh>) {
126: next if /^\#/;
127: chomp;
128: my ($key,$val)=(split(/\s+/,$_,2));
129: $cprtag{$key}=$val;
130: }
131: close($fh);
132: }
133: }
134: # ------------------------------------------------------------------ source copyrights
135: {
136: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
137: '/source_copyright.tab';
138: if ( open (my $fh,"<$sourcecopyrightfile") ) {
139: while (<$fh>) {
140: next if /^\#/;
141: chomp;
142: my ($key,$val)=(split(/\s+/,$_,2));
143: $scprtag{$key}=$val;
144: }
145: close($fh);
146: }
147: }
148:
149: # -------------------------------------------------------------- domain designs
150:
151: my $filename;
152: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
153: opendir(DIR,$designdir);
154: while ($filename=readdir(DIR)) {
155: 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)
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:
1174: =cut
1175:
1176: #-------------------------------------------
1177: sub multiple_select_form {
1178: my ($name,$value,$size,$hash)=@_;
1179: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1180: my $output='';
1181: if (! defined($size)) {
1182: $size = 4;
1183: if (scalar(keys(%$hash))<4) {
1184: $size = scalar(keys(%$hash));
1185: }
1186: }
1187: $output.="\n<select name='$name' size='$size' multiple='1'>";
1188: foreach (sort(keys(%$hash))) {
1189: $output.='<option value="'.$_.'" ';
1190: $output.='selected="selected" ' if ($selected{$_});
1191: $output.='>'.$hash->{$_}."</option>\n";
1192: }
1193: $output.="</select>\n";
1194: return $output;
1195: }
1196:
1197: #-------------------------------------------
1198:
1199: =pod
1200:
1201: =item * select_form($defdom,$name,%hash)
1202:
1203: Returns a string containing a <select name='$name' size='1'> form to
1204: allow a user to select options from a hash option_name => displayed text.
1205: See lonrights.pm for an example invocation and use.
1206:
1207: =cut
1208:
1209: #-------------------------------------------
1210: sub select_form {
1211: my ($def,$name,%hash) = @_;
1212: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1213: my @keys;
1214: if (exists($hash{'select_form_order'})) {
1215: @keys=@{$hash{'select_form_order'}};
1216: } else {
1217: @keys=sort(keys(%hash));
1218: }
1219: foreach (@keys) {
1220: $selectform.="<option value=\"$_\" ".
1221: ($_ eq $def ? 'selected="selected" ' : '').
1222: ">".&mt($hash{$_})."</option>\n";
1223: }
1224: $selectform.="</select>";
1225: return $selectform;
1226: }
1227:
1228: sub gradeleveldescription {
1229: my $gradelevel=shift;
1230: my %gradelevels=(0 => 'Not specified',
1231: 1 => 'Grade 1',
1232: 2 => 'Grade 2',
1233: 3 => 'Grade 3',
1234: 4 => 'Grade 4',
1235: 5 => 'Grade 5',
1236: 6 => 'Grade 6',
1237: 7 => 'Grade 7',
1238: 8 => 'Grade 8',
1239: 9 => 'Grade 9',
1240: 10 => 'Grade 10',
1241: 11 => 'Grade 11',
1242: 12 => 'Grade 12',
1243: 13 => 'Grade 13',
1244: 14 => '100 Level',
1245: 15 => '200 Level',
1246: 16 => '300 Level',
1247: 17 => '400 Level',
1248: 18 => 'Graduate Level');
1249: return &mt($gradelevels{$gradelevel});
1250: }
1251:
1252: sub select_level_form {
1253: my ($deflevel,$name)=@_;
1254: unless ($deflevel) { $deflevel=0; }
1255: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1256: for (my $i=0; $i<=18; $i++) {
1257: $selectform.="<option value=\"$i\" ".
1258: ($i==$deflevel ? 'selected="selected" ' : '').
1259: ">".&gradeleveldescription($i)."</option>\n";
1260: }
1261: $selectform.="</select>";
1262: return $selectform;
1263: }
1264:
1265: #-------------------------------------------
1266:
1267: =pod
1268:
1269: =item * select_dom_form($defdom,$name,$includeempty)
1270:
1271: Returns a string containing a <select name='$name' size='1'> form to
1272: allow a user to select the domain to preform an operation in.
1273: See loncreateuser.pm for an example invocation and use.
1274:
1275: If the $includeempty flag is set, it also includes an empty choice ("no domain
1276: selected");
1277:
1278: =cut
1279:
1280: #-------------------------------------------
1281: sub select_dom_form {
1282: my ($defdom,$name,$includeempty) = @_;
1283: my @domains = get_domains();
1284: if ($includeempty) { @domains=('',@domains); }
1285: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1286: foreach (@domains) {
1287: $selectdomain.="<option value=\"$_\" ".
1288: ($_ eq $defdom ? 'selected="selected" ' : '').
1289: ">$_</option>\n";
1290: }
1291: $selectdomain.="</select>";
1292: return $selectdomain;
1293: }
1294:
1295: #-------------------------------------------
1296:
1297: =pod
1298:
1299: =item * get_library_servers($domain)
1300:
1301: Returns a hash which contains keys like '103l3' and values like
1302: 'kirk.lite.msu.edu'. All of the keys will be for machines in the
1303: given $domain.
1304:
1305: =cut
1306:
1307: #-------------------------------------------
1308: sub get_library_servers {
1309: my $domain = shift;
1310: my %library_servers;
1311: foreach (keys(%Apache::lonnet::libserv)) {
1312: if ($Apache::lonnet::hostdom{$_} eq $domain) {
1313: $library_servers{$_} = $Apache::lonnet::hostname{$_};
1314: }
1315: }
1316: return %library_servers;
1317: }
1318:
1319: #-------------------------------------------
1320:
1321: =pod
1322:
1323: =item * home_server_option_list($domain)
1324:
1325: returns a string which contains an <option> list to be used in a
1326: <select> form input. See loncreateuser.pm for an example.
1327:
1328: =cut
1329:
1330: #-------------------------------------------
1331: sub home_server_option_list {
1332: my $domain = shift;
1333: my %servers = &get_library_servers($domain);
1334: my $result = '';
1335: foreach (sort keys(%servers)) {
1336: $result.=
1337: '<option value="'.$_.'">'.$_.' '.$servers{$_}."</option>\n";
1338: }
1339: return $result;
1340: }
1341:
1342: =pod
1343:
1344: =back
1345:
1346: =cut
1347:
1348: ###############################################################
1349: ## Decoding User Agent ##
1350: ###############################################################
1351:
1352: =pod
1353:
1354: =head1 Decoding the User Agent
1355:
1356: =over 4
1357:
1358: =item * &decode_user_agent()
1359:
1360: Inputs: $r
1361:
1362: Outputs:
1363:
1364: =over 4
1365:
1366: =item * $httpbrowser
1367:
1368: =item * $clientbrowser
1369:
1370: =item * $clientversion
1371:
1372: =item * $clientmathml
1373:
1374: =item * $clientunicode
1375:
1376: =item * $clientos
1377:
1378: =back
1379:
1380: =back
1381:
1382: =cut
1383:
1384: ###############################################################
1385: ###############################################################
1386: sub decode_user_agent {
1387: my ($r)=@_;
1388: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1389: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1390: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1391: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1392: my $clientbrowser='unknown';
1393: my $clientversion='0';
1394: my $clientmathml='';
1395: my $clientunicode='0';
1396: for (my $i=0;$i<=$#browsertype;$i++) {
1397: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1398: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1399: $clientbrowser=$bname;
1400: $httpbrowser=~/$vreg/i;
1401: $clientversion=$1;
1402: $clientmathml=($clientversion>=$minv);
1403: $clientunicode=($clientversion>=$univ);
1404: }
1405: }
1406: my $clientos='unknown';
1407: if (($httpbrowser=~/linux/i) ||
1408: ($httpbrowser=~/unix/i) ||
1409: ($httpbrowser=~/ux/i) ||
1410: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1411: if (($httpbrowser=~/vax/i) ||
1412: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1413: if ($httpbrowser=~/next/i) { $clientos='next'; }
1414: if (($httpbrowser=~/mac/i) ||
1415: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1416: if ($httpbrowser=~/win/i) { $clientos='win'; }
1417: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1418: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1419: $clientunicode,$clientos,);
1420: }
1421:
1422: ###############################################################
1423: ## Authentication changing form generation subroutines ##
1424: ###############################################################
1425: ##
1426: ## All of the authform_xxxxxxx subroutines take their inputs in a
1427: ## hash, and have reasonable default values.
1428: ##
1429: ## formname = the name given in the <form> tag.
1430: #-------------------------------------------
1431:
1432: =pod
1433:
1434: =head1 Authentication Routines
1435:
1436: =over 4
1437:
1438: =item * authform_xxxxxx
1439:
1440: The authform_xxxxxx subroutines provide javascript and html forms which
1441: handle some of the conveniences required for authentication forms.
1442: This is not an optimal method, but it works.
1443:
1444: See loncreateuser.pm for invocation and use examples.
1445:
1446: =over 4
1447:
1448: =item * authform_header
1449:
1450: =item * authform_authorwarning
1451:
1452: =item * authform_nochange
1453:
1454: =item * authform_kerberos
1455:
1456: =item * authform_internal
1457:
1458: =item * authform_filesystem
1459:
1460: =back
1461:
1462: =back
1463:
1464: =cut
1465:
1466: #-------------------------------------------
1467: sub authform_header{
1468: my %in = (
1469: formname => 'cu',
1470: kerb_def_dom => '',
1471: @_,
1472: );
1473: $in{'formname'} = 'document.' . $in{'formname'};
1474: my $result='';
1475:
1476: #---------------------------------------------- Code for upper case translation
1477: my $Javascript_toUpperCase;
1478: unless ($in{kerb_def_dom}) {
1479: $Javascript_toUpperCase =<<"END";
1480: switch (choice) {
1481: case 'krb': currentform.elements[choicearg].value =
1482: currentform.elements[choicearg].value.toUpperCase();
1483: break;
1484: default:
1485: }
1486: END
1487: } else {
1488: $Javascript_toUpperCase = "";
1489: }
1490:
1491: my $radioval = "'nochange'";
1492: if (exists($in{'curr_authtype'}) &&
1493: defined($in{'curr_authtype'}) &&
1494: $in{'curr_authtype'} ne '') {
1495: $radioval = "'$in{'curr_authtype'}arg'";
1496: }
1497: my $argfield = 'null';
1498: if ( grep/^mode$/,(keys %in) ) {
1499: if ($in{'mode'} eq 'modifycourse') {
1500: if ( grep/^curr_authtype$/,(keys %in) ) {
1501: $radioval = "'$in{'curr_authtype'}'";
1502: }
1503: if ( grep/^curr_autharg$/,(keys %in) ) {
1504: unless ($in{'curr_autharg'} eq '') {
1505: $argfield = "'$in{'curr_autharg'}'";
1506: }
1507: }
1508: }
1509: }
1510:
1511: $result.=<<"END";
1512: var current = new Object();
1513: current.radiovalue = $radioval;
1514: current.argfield = $argfield;
1515:
1516: function changed_radio(choice,currentform) {
1517: var choicearg = choice + 'arg';
1518: // If a radio button in changed, we need to change the argfield
1519: if (current.radiovalue != choice) {
1520: current.radiovalue = choice;
1521: if (current.argfield != null) {
1522: currentform.elements[current.argfield].value = '';
1523: }
1524: if (choice == 'nochange') {
1525: current.argfield = null;
1526: } else {
1527: current.argfield = choicearg;
1528: switch(choice) {
1529: case 'krb':
1530: currentform.elements[current.argfield].value =
1531: "$in{'kerb_def_dom'}";
1532: break;
1533: default:
1534: break;
1535: }
1536: }
1537: }
1538: return;
1539: }
1540:
1541: function changed_text(choice,currentform) {
1542: var choicearg = choice + 'arg';
1543: if (currentform.elements[choicearg].value !='') {
1544: $Javascript_toUpperCase
1545: // clear old field
1546: if ((current.argfield != choicearg) && (current.argfield != null)) {
1547: currentform.elements[current.argfield].value = '';
1548: }
1549: current.argfield = choicearg;
1550: }
1551: set_auth_radio_buttons(choice,currentform);
1552: return;
1553: }
1554:
1555: function set_auth_radio_buttons(newvalue,currentform) {
1556: var i=0;
1557: while (i < currentform.login.length) {
1558: if (currentform.login[i].value == newvalue) { break; }
1559: i++;
1560: }
1561: if (i == currentform.login.length) {
1562: return;
1563: }
1564: current.radiovalue = newvalue;
1565: currentform.login[i].checked = true;
1566: return;
1567: }
1568: END
1569: return $result;
1570: }
1571:
1572: sub authform_authorwarning{
1573: my $result='';
1574: $result='<i>'.
1575: &mt('As a general rule, only authors or co-authors should be '.
1576: 'filesystem authenticated '.
1577: '(which allows access to the server filesystem).')."</i>\n";
1578: return $result;
1579: }
1580:
1581: sub authform_nochange{
1582: my %in = (
1583: formname => 'document.cu',
1584: kerb_def_dom => 'MSU.EDU',
1585: @_,
1586: );
1587: my $result = '<label>'.&mt('[_1] Do not change login data',
1588: '<input type="radio" name="login" value="nochange" '.
1589: 'checked="checked" onclick="'.
1590: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
1591: '</label>';
1592: return $result;
1593: }
1594:
1595: sub authform_kerberos{
1596: my %in = (
1597: formname => 'document.cu',
1598: kerb_def_dom => 'MSU.EDU',
1599: kerb_def_auth => 'krb4',
1600: @_,
1601: );
1602: my ($check4,$check5,$krbarg);
1603: if ($in{'kerb_def_auth'} eq 'krb5') {
1604: $check5 = " checked=\"on\"";
1605: } else {
1606: $check4 = " checked=\"on\"";
1607: }
1608: $krbarg = $in{'kerb_def_dom'};
1609:
1610: my $krbcheck = "";
1611: if ( grep/^curr_authtype$/,(keys %in) ) {
1612: if ($in{'curr_authtype'} =~ m/^krb/) {
1613: $krbcheck = " checked=\"on\"";
1614: if ( grep/^curr_autharg$/,(keys %in) ) {
1615: $krbarg = $in{'curr_autharg'};
1616: }
1617: }
1618: }
1619:
1620: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1621: my $result .= &mt
1622: ('[_1] Kerberos authenticated with domain [_2] '.
1623: '[_3] Version 4 [_4] Version 5 [_5]',
1624: '<label><input type="radio" name="login" value="krb" '.
1625: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1626: '</label><input type="text" size="10" name="krbarg" '.
1627: 'value="'.$krbarg.'" '.
1628: 'onchange="'.$jscall.'" />',
1629: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
1630: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
1631: '</label>');
1632: return $result;
1633: }
1634:
1635: sub authform_internal{
1636: my %args = (
1637: formname => 'document.cu',
1638: kerb_def_dom => 'MSU.EDU',
1639: @_,
1640: );
1641:
1642: my $intcheck = "";
1643: my $intarg = 'value=""';
1644: if ( grep/^curr_authtype$/,(keys %args) ) {
1645: if ($args{'curr_authtype'} eq 'int') {
1646: $intcheck = " checked=\"on\"";
1647: if ( grep/^curr_autharg$/,(keys %args) ) {
1648: $intarg = "value=\"$args{'curr_autharg'}\"";
1649: }
1650: }
1651: }
1652:
1653: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1654: my $result.=&mt
1655: ('[_1] Internally authenticated (with initial password [_2])',
1656: '<label><input type="radio" name="login" value="int" '.$intcheck.
1657: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1658: '</label><input type="text" size="10" name="intarg" '.$intarg.
1659: ' onchange="'.$jscall.'" />');
1660: return $result;
1661: }
1662:
1663: sub authform_local{
1664: my %in = (
1665: formname => 'document.cu',
1666: kerb_def_dom => 'MSU.EDU',
1667: @_,
1668: );
1669:
1670: my $loccheck = "";
1671: my $locarg = 'value=""';
1672: if ( grep/^curr_authtype$/,(keys %in) ) {
1673: if ($in{'curr_authtype'} eq 'loc') {
1674: $loccheck = " checked=\"on\"";
1675: if ( grep/^curr_autharg$/,(keys %in) ) {
1676: $locarg = "value=\"$in{'curr_autharg'}\"";
1677: }
1678: }
1679: }
1680:
1681: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1682: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1683: '<label><input type="radio" name="login" value="loc" '.$loccheck.
1684: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1685: '</label><input type="text" size="10" name="locarg" '.$locarg.
1686: ' onchange="'.$jscall.'" />');
1687: return $result;
1688: }
1689:
1690: sub authform_filesystem{
1691: my %in = (
1692: formname => 'document.cu',
1693: kerb_def_dom => 'MSU.EDU',
1694: @_,
1695: );
1696: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1697: my $result.= &mt
1698: ('[_1] Filesystem Authenticated (with initial password [_2])',
1699: '<label><input type="radio" name="login" value="fsys" '.
1700: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1701: '</label><input type="text" size="10" name="fsysarg" value="" '.
1702: 'onchange="'.$jscall.'" />');
1703: return $result;
1704: }
1705:
1706: ###############################################################
1707: ## Get Authentication Defaults for Domain ##
1708: ###############################################################
1709:
1710: =pod
1711:
1712: =head1 Domains and Authentication
1713:
1714: Returns default authentication type and an associated argument as
1715: listed in file 'domain.tab'.
1716:
1717: =over 4
1718:
1719: =item * get_auth_defaults
1720:
1721: get_auth_defaults($target_domain) returns the default authentication
1722: type and an associated argument (initial password or a kerberos domain).
1723: These values are stored in lonTabs/domain.tab
1724:
1725: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1726:
1727: If target_domain is not found in domain.tab, returns nothing ('').
1728:
1729: =cut
1730:
1731: #-------------------------------------------
1732: sub get_auth_defaults {
1733: my $domain=shift;
1734: return ($Apache::lonnet::domain_auth_def{$domain},$Apache::lonnet::domain_auth_arg_def{$domain});
1735: }
1736: ###############################################################
1737: ## End Get Authentication Defaults for Domain ##
1738: ###############################################################
1739:
1740: ###############################################################
1741: ## Get Kerberos Defaults for Domain ##
1742: ###############################################################
1743: ##
1744: ## Returns default kerberos version and an associated argument
1745: ## as listed in file domain.tab. If not listed, provides
1746: ## appropriate default domain and kerberos version.
1747: ##
1748: #-------------------------------------------
1749:
1750: =pod
1751:
1752: =item * get_kerberos_defaults
1753:
1754: get_kerberos_defaults($target_domain) returns the default kerberos
1755: version and domain. If not found in domain.tabs, it defaults to
1756: version 4 and the domain of the server.
1757:
1758: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1759:
1760: =cut
1761:
1762: #-------------------------------------------
1763: sub get_kerberos_defaults {
1764: my $domain=shift;
1765: my ($krbdef,$krbdefdom) =
1766: &Apache::loncommon::get_auth_defaults($domain);
1767: unless ($krbdef =~/^krb/ && $krbdefdom) {
1768: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1769: my $krbdefdom=$1;
1770: $krbdefdom=~tr/a-z/A-Z/;
1771: $krbdef = "krb4";
1772: }
1773: return ($krbdef,$krbdefdom);
1774: }
1775:
1776: =pod
1777:
1778: =back
1779:
1780: =cut
1781:
1782: ###############################################################
1783: ## Thesaurus Functions ##
1784: ###############################################################
1785:
1786: =pod
1787:
1788: =head1 Thesaurus Functions
1789:
1790: =over 4
1791:
1792: =item * initialize_keywords
1793:
1794: Initializes the package variable %Keywords if it is empty. Uses the
1795: package variable $thesaurus_db_file.
1796:
1797: =cut
1798:
1799: ###################################################
1800:
1801: sub initialize_keywords {
1802: return 1 if (scalar keys(%Keywords));
1803: # If we are here, %Keywords is empty, so fill it up
1804: # Make sure the file we need exists...
1805: if (! -e $thesaurus_db_file) {
1806: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1807: " failed because it does not exist");
1808: return 0;
1809: }
1810: # Set up the hash as a database
1811: my %thesaurus_db;
1812: if (! tie(%thesaurus_db,'GDBM_File',
1813: $thesaurus_db_file,&GDBM_READER(),0640)){
1814: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1815: $thesaurus_db_file);
1816: return 0;
1817: }
1818: # Get the average number of appearances of a word.
1819: my $avecount = $thesaurus_db{'average.count'};
1820: # Put keywords (those that appear > average) into %Keywords
1821: while (my ($word,$data)=each (%thesaurus_db)) {
1822: my ($count,undef) = split /:/,$data;
1823: $Keywords{$word}++ if ($count > $avecount);
1824: }
1825: untie %thesaurus_db;
1826: # Remove special values from %Keywords.
1827: foreach ('total.count','average.count') {
1828: delete($Keywords{$_}) if (exists($Keywords{$_}));
1829: }
1830: return 1;
1831: }
1832:
1833: ###################################################
1834:
1835: =pod
1836:
1837: =item * keyword($word)
1838:
1839: Returns true if $word is a keyword. A keyword is a word that appears more
1840: than the average number of times in the thesaurus database. Calls
1841: &initialize_keywords
1842:
1843: =cut
1844:
1845: ###################################################
1846:
1847: sub keyword {
1848: return if (!&initialize_keywords());
1849: my $word=lc(shift());
1850: $word=~s/\W//g;
1851: return exists($Keywords{$word});
1852: }
1853:
1854: ###############################################################
1855:
1856: =pod
1857:
1858: =item * get_related_words
1859:
1860: Look up a word in the thesaurus. Takes a scalar argument and returns
1861: an array of words. If the keyword is not in the thesaurus, an empty array
1862: will be returned. The order of the words returned is determined by the
1863: database which holds them.
1864:
1865: Uses global $thesaurus_db_file.
1866:
1867: =cut
1868:
1869: ###############################################################
1870: sub get_related_words {
1871: my $keyword = shift;
1872: my %thesaurus_db;
1873: if (! -e $thesaurus_db_file) {
1874: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
1875: "failed because the file does not exist");
1876: return ();
1877: }
1878: if (! tie(%thesaurus_db,'GDBM_File',
1879: $thesaurus_db_file,&GDBM_READER(),0640)){
1880: return ();
1881: }
1882: my @Words=();
1883: if (exists($thesaurus_db{$keyword})) {
1884: $_ = $thesaurus_db{$keyword};
1885: (undef,@Words) = split/:/; # The first element is the number of times
1886: # the word appears. We do not need it now.
1887: for (my $i=0;$i<=$#Words;$i++) {
1888: ($Words[$i],undef)= split/\,/,$Words[$i];
1889: }
1890: }
1891: untie %thesaurus_db;
1892: return @Words;
1893: }
1894:
1895: =pod
1896:
1897: =back
1898:
1899: =cut
1900:
1901: # -------------------------------------------------------------- Plaintext name
1902: =pod
1903:
1904: =head1 User Name Functions
1905:
1906: =over 4
1907:
1908: =item * plainname($uname,$udom,$first)
1909:
1910: Takes a users logon name and returns it as a string in
1911: "first middle last generation" form
1912: if $first is set to 'lastname' then it returns it as
1913: 'lastname generation, firstname middlename' if their is a lastname
1914:
1915: =cut
1916:
1917: ###############################################################
1918: sub plainname {
1919: my ($uname,$udom,$first)=@_;
1920: my %names=&Apache::lonnet::get('environment',
1921: ['firstname','middlename','lastname','generation'],
1922: $udom,$uname);
1923: my $name=&Apache::lonnet::format_name($names{'firstname'},
1924: $names{'middlename'},
1925: $names{'lastname'},
1926: $names{'generation'},$first);
1927: $name=~s/^\s+//;
1928: $name=~s/\s+$//;
1929: $name=~s/\s+/ /g;
1930: if ($name !~ /\S/) { $name=$uname.'@'.$udom; }
1931: return $name;
1932: }
1933:
1934: # -------------------------------------------------------------------- Nickname
1935: =pod
1936:
1937: =item * nickname($uname,$udom)
1938:
1939: Gets a users name and returns it as a string as
1940:
1941: ""nickname""
1942:
1943: if the user has a nickname or
1944:
1945: "first middle last generation"
1946:
1947: if the user does not
1948:
1949: =cut
1950:
1951: sub nickname {
1952: my ($uname,$udom)=@_;
1953: my %names;
1954: if ($uname eq $env{'user.name'} &&
1955: $udom eq $env{'user.domain'}) {
1956: %names=('nickname' => $env{'environment.nickname'} ,
1957: 'firstname' => $env{'environment.firstname'} ,
1958: 'middlename' => $env{'environment.middlename'},
1959: 'lastname' => $env{'environment.lastname'} ,
1960: 'generation' => $env{'environment.generation'});
1961: } else {
1962: %names=&Apache::lonnet::get('environment',
1963: ['nickname','firstname','middlename',
1964: 'lastname','generation'],$udom,$uname);
1965: }
1966: my $name=$names{'nickname'};
1967: if ($name) {
1968: $name='"'.$name.'"';
1969: } else {
1970: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
1971: $names{'lastname'}.' '.$names{'generation'};
1972: $name=~s/\s+$//;
1973: $name=~s/\s+/ /g;
1974: }
1975: return $name;
1976: }
1977:
1978:
1979: # ------------------------------------------------------------------ Screenname
1980:
1981: =pod
1982:
1983: =item * screenname($uname,$udom)
1984:
1985: Gets a users screenname and returns it as a string
1986:
1987: =cut
1988:
1989: sub screenname {
1990: my ($uname,$udom)=@_;
1991: if ($uname eq $env{'user.name'} &&
1992: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1993: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1994: return $names{'screenname'};
1995: }
1996:
1997:
1998: # ------------------------------------------------------------- Message Wrapper
1999:
2000: sub messagewrapper {
2001: my ($link,$username,$domain)=@_;
2002: return
2003: '<a href="/adm/email?compose=individual&'.
2004: 'recname='.$username.'&recdom='.$domain.'" '.
2005: 'title="'.&mt('Send message').'">'.$link.'</a>';
2006: }
2007: # --------------------------------------------------------------- Notes Wrapper
2008:
2009: sub noteswrapper {
2010: my ($link,$un,$do)=@_;
2011: return
2012: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2013: }
2014: # ------------------------------------------------------------- Aboutme Wrapper
2015:
2016: sub aboutmewrapper {
2017: my ($link,$username,$domain,$target)=@_;
2018: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2019: ($target?' target="$target"':'').' title="'.&mt('View this users personal page').'">'.$link.'</a>';
2020: }
2021:
2022: # ------------------------------------------------------------ Syllabus Wrapper
2023:
2024:
2025: sub syllabuswrapper {
2026: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2027: if ($fontcolor) {
2028: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2029: }
2030: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2031: }
2032:
2033: sub track_student_link {
2034: my ($linktext,$sname,$sdom,$target,$start) = @_;
2035: my $link ="/adm/trackstudent?";
2036: my $title = 'View recent activity';
2037: if (defined($sname) && $sname !~ /^\s*$/ &&
2038: defined($sdom) && $sdom !~ /^\s*$/) {
2039: $link .= "selected_student=$sname:$sdom";
2040: $title .= ' of this student';
2041: }
2042: if (defined($target) && $target !~ /^\s*$/) {
2043: $target = qq{target="$target"};
2044: } else {
2045: $target = '';
2046: }
2047: if ($start) { $link.='&start='.$start; }
2048: return qq{<a href="$link" title="$title" $target>$linktext</a>};
2049: }
2050:
2051: =pod
2052:
2053: =back
2054:
2055: =head1 Access .tab File Data
2056:
2057: =over 4
2058:
2059: =item * languageids()
2060:
2061: returns list of all language ids
2062:
2063: =cut
2064:
2065: sub languageids {
2066: return sort(keys(%language));
2067: }
2068:
2069: =pod
2070:
2071: =item * languagedescription()
2072:
2073: returns description of a specified language id
2074:
2075: =cut
2076:
2077: sub languagedescription {
2078: my $code=shift;
2079: return ($supported_language{$code}?'* ':'').
2080: $language{$code}.
2081: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2082: }
2083:
2084: sub plainlanguagedescription {
2085: my $code=shift;
2086: return $language{$code};
2087: }
2088:
2089: sub supportedlanguagecode {
2090: my $code=shift;
2091: return $supported_language{$code};
2092: }
2093:
2094: =pod
2095:
2096: =item * copyrightids()
2097:
2098: returns list of all copyrights
2099:
2100: =cut
2101:
2102: sub copyrightids {
2103: return sort(keys(%cprtag));
2104: }
2105:
2106: =pod
2107:
2108: =item * copyrightdescription()
2109:
2110: returns description of a specified copyright id
2111:
2112: =cut
2113:
2114: sub copyrightdescription {
2115: return &mt($cprtag{shift(@_)});
2116: }
2117:
2118: =pod
2119:
2120: =item * source_copyrightids()
2121:
2122: returns list of all source copyrights
2123:
2124: =cut
2125:
2126: sub source_copyrightids {
2127: return sort(keys(%scprtag));
2128: }
2129:
2130: =pod
2131:
2132: =item * source_copyrightdescription()
2133:
2134: returns description of a specified source copyright id
2135:
2136: =cut
2137:
2138: sub source_copyrightdescription {
2139: return &mt($scprtag{shift(@_)});
2140: }
2141:
2142: =pod
2143:
2144: =item * filecategories()
2145:
2146: returns list of all file categories
2147:
2148: =cut
2149:
2150: sub filecategories {
2151: return sort(keys(%category_extensions));
2152: }
2153:
2154: =pod
2155:
2156: =item * filecategorytypes()
2157:
2158: returns list of file types belonging to a given file
2159: category
2160:
2161: =cut
2162:
2163: sub filecategorytypes {
2164: return @{$category_extensions{lc($_[0])}};
2165: }
2166:
2167: =pod
2168:
2169: =item * fileembstyle()
2170:
2171: returns embedding style for a specified file type
2172:
2173: =cut
2174:
2175: sub fileembstyle {
2176: return $fe{lc(shift(@_))};
2177: }
2178:
2179:
2180: sub filecategoryselect {
2181: my ($name,$value)=@_;
2182: return &select_form($value,$name,
2183: '' => &mt('Any category'),
2184: map { $_,$_ } sort(keys(%category_extensions)));
2185: }
2186:
2187: =pod
2188:
2189: =item * filedescription()
2190:
2191: returns description for a specified file type
2192:
2193: =cut
2194:
2195: sub filedescription {
2196: my $file_description = $fd{lc(shift())};
2197: $file_description =~ s:([\[\]]):~$1:g;
2198: return &mt($file_description);
2199: }
2200:
2201: =pod
2202:
2203: =item * filedescriptionex()
2204:
2205: returns description for a specified file type with
2206: extra formatting
2207:
2208: =cut
2209:
2210: sub filedescriptionex {
2211: my $ex=shift;
2212: my $file_description = $fd{lc($ex)};
2213: $file_description =~ s:([\[\]]):~$1:g;
2214: return '.'.$ex.' '.&mt($file_description);
2215: }
2216:
2217: # End of .tab access
2218: =pod
2219:
2220: =back
2221:
2222: =cut
2223:
2224: # ------------------------------------------------------------------ File Types
2225: sub fileextensions {
2226: return sort(keys(%fe));
2227: }
2228:
2229: # ----------------------------------------------------------- Display Languages
2230: # returns a hash with all desired display languages
2231: #
2232:
2233: sub display_languages {
2234: my %languages=();
2235: foreach (&preferred_languages()) {
2236: $languages{$_}=1;
2237: }
2238: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
2239: if ($env{'form.displaylanguage'}) {
2240: foreach (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
2241: $languages{$_}=1;
2242: }
2243: }
2244: return %languages;
2245: }
2246:
2247: sub preferred_languages {
2248: my @languages=();
2249: if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
2250: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
2251: $env{'course.'.$env{'request.course.id'}.'.languages'}));
2252: }
2253: if ($env{'environment.languages'}) {
2254: @languages=split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'});
2255: }
2256: my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
2257: if ($browser) {
2258: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
2259: }
2260: if ($Apache::lonnet::domain_lang_def{$env{'user.domain'}}) {
2261: @languages=(@languages,
2262: $Apache::lonnet::domain_lang_def{$env{'user.domain'}});
2263: }
2264: if ($Apache::lonnet::domain_lang_def{$env{'request.role.domain'}}) {
2265: @languages=(@languages,
2266: $Apache::lonnet::domain_lang_def{$env{'request.role.domain'}});
2267: }
2268: if ($Apache::lonnet::domain_lang_def{
2269: $Apache::lonnet::perlvar{'lonDefDomain'}}) {
2270: @languages=(@languages,
2271: $Apache::lonnet::domain_lang_def{
2272: $Apache::lonnet::perlvar{'lonDefDomain'}});
2273: }
2274: # turn "en-ca" into "en-ca,en"
2275: my @genlanguages;
2276: foreach (@languages) {
2277: unless ($_=~/\w/) { next; }
2278: push (@genlanguages,$_);
2279: if ($_=~/(\-|\_)/) {
2280: push (@genlanguages,(split(/(\-|\_)/,$_))[0]);
2281: }
2282: }
2283: return @genlanguages;
2284: }
2285:
2286: ###############################################################
2287: ## Student Answer Attempts ##
2288: ###############################################################
2289:
2290: =pod
2291:
2292: =head1 Alternate Problem Views
2293:
2294: =over 4
2295:
2296: =item * get_previous_attempt($symb, $username, $domain, $course,
2297: $getattempt, $regexp, $gradesub)
2298:
2299: Return string with previous attempt on problem. Arguments:
2300:
2301: =over 4
2302:
2303: =item * $symb: Problem, including path
2304:
2305: =item * $username: username of the desired student
2306:
2307: =item * $domain: domain of the desired student
2308:
2309: =item * $course: Course ID
2310:
2311: =item * $getattempt: Leave blank for all attempts, otherwise put
2312: something
2313:
2314: =item * $regexp: if string matches this regexp, the string will be
2315: sent to $gradesub
2316:
2317: =item * $gradesub: routine that processes the string if it matches $regexp
2318:
2319: =back
2320:
2321: The output string is a table containing all desired attempts, if any.
2322:
2323: =cut
2324:
2325: sub get_previous_attempt {
2326: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
2327: my $prevattempts='';
2328: no strict 'refs';
2329: if ($symb) {
2330: my (%returnhash)=
2331: &Apache::lonnet::restore($symb,$course,$domain,$username);
2332: if ($returnhash{'version'}) {
2333: my %lasthash=();
2334: my $version;
2335: for ($version=1;$version<=$returnhash{'version'};$version++) {
2336: foreach (sort(split(/\:/,$returnhash{$version.':keys'}))) {
2337: $lasthash{$_}=$returnhash{$version.':'.$_};
2338: }
2339: }
2340: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
2341: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
2342: foreach (sort(keys %lasthash)) {
2343: my ($ign,@parts) = split(/\./,$_);
2344: if ($#parts > 0) {
2345: my $data=$parts[-1];
2346: pop(@parts);
2347: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
2348: } else {
2349: if ($#parts == 0) {
2350: $prevattempts.='<th>'.$parts[0].'</th>';
2351: } else {
2352: $prevattempts.='<th>'.$ign.'</th>';
2353: }
2354: }
2355: }
2356: if ($getattempt eq '') {
2357: for ($version=1;$version<=$returnhash{'version'};$version++) {
2358: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
2359: foreach (sort(keys %lasthash)) {
2360: my $value;
2361: if ($_ =~ /timestamp/) {
2362: $value=scalar(localtime($returnhash{$version.':'.$_}));
2363: } else {
2364: $value=$returnhash{$version.':'.$_};
2365: }
2366: $prevattempts.='<td>'.&Apache::lonnet::unescape($value).' </td>';
2367: }
2368: }
2369: }
2370: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
2371: foreach (sort(keys %lasthash)) {
2372: my $value;
2373: if ($_ =~ /timestamp/) {
2374: $value=scalar(localtime($lasthash{$_}));
2375: } else {
2376: $value=$lasthash{$_};
2377: }
2378: $value=&Apache::lonnet::unescape($value);
2379: if ($_ =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
2380: $prevattempts.='<td>'.$value.' </td>';
2381: }
2382: $prevattempts.='</tr></table></td></tr></table>';
2383: } else {
2384: $prevattempts='Nothing submitted - no attempts.';
2385: }
2386: } else {
2387: $prevattempts='No data.';
2388: }
2389: }
2390:
2391: sub relative_to_absolute {
2392: my ($url,$output)=@_;
2393: my $parser=HTML::TokeParser->new(\$output);
2394: my $token;
2395: my $thisdir=$url;
2396: my @rlinks=();
2397: while ($token=$parser->get_token) {
2398: if ($token->[0] eq 'S') {
2399: if ($token->[1] eq 'a') {
2400: if ($token->[2]->{'href'}) {
2401: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
2402: }
2403: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
2404: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
2405: } elsif ($token->[1] eq 'base') {
2406: $thisdir=$token->[2]->{'href'};
2407: }
2408: }
2409: }
2410: $thisdir=~s-/[^/]*$--;
2411: foreach (@rlinks) {
2412: unless (($_=~/^http:\/\//i) ||
2413: ($_=~/^\//) ||
2414: ($_=~/^javascript:/i) ||
2415: ($_=~/^mailto:/i) ||
2416: ($_=~/^\#/)) {
2417: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$_);
2418: $output=~s/(\"|\'|\=\s*)$_(\"|\'|\s|\>)/$1$newlocation$2/;
2419: }
2420: }
2421: # -------------------------------------------------- Deal with Applet codebases
2422: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
2423: return $output;
2424: }
2425:
2426: =pod
2427:
2428: =item * get_student_view
2429:
2430: show a snapshot of what student was looking at
2431:
2432: =cut
2433:
2434: sub get_student_view {
2435: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
2436: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2437: my (%form);
2438: my @elements=('symb','courseid','domain','username');
2439: foreach my $element (@elements) {
2440: $form{'grade_'.$element}=eval '$'.$element #'
2441: }
2442: if (defined($moreenv)) {
2443: %form=(%form,%{$moreenv});
2444: }
2445: if (defined($target)) { $form{'grade_target'} = $target; }
2446: $feedurl=&Apache::lonnet::clutter($feedurl);
2447: my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
2448: $userview=~s/\<body[^\>]*\>//gi;
2449: $userview=~s/\<\/body\>//gi;
2450: $userview=~s/\<html\>//gi;
2451: $userview=~s/\<\/html\>//gi;
2452: $userview=~s/\<head\>//gi;
2453: $userview=~s/\<\/head\>//gi;
2454: $userview=~s/action\s*\=/would_be_action\=/gi;
2455: $userview=&relative_to_absolute($feedurl,$userview);
2456: return $userview;
2457: }
2458:
2459: =pod
2460:
2461: =item * get_student_answers()
2462:
2463: show a snapshot of how student was answering problem
2464:
2465: =cut
2466:
2467: sub get_student_answers {
2468: my ($symb,$username,$domain,$courseid,%form) = @_;
2469: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2470: my (%moreenv);
2471: my @elements=('symb','courseid','domain','username');
2472: foreach my $element (@elements) {
2473: $moreenv{'grade_'.$element}=eval '$'.$element #'
2474: }
2475: $moreenv{'grade_target'}='answer';
2476: %moreenv=(%form,%moreenv);
2477: my $userview=&Apache::lonnet::ssi('/res/'.$feedurl,%moreenv);
2478: return $userview;
2479: }
2480:
2481: =pod
2482:
2483: =item * &submlink()
2484:
2485: Inputs: $text $uname $udom $symb $target
2486:
2487: Returns: A link to grades.pm such as to see the SUBM view of a student
2488:
2489: =cut
2490:
2491: ###############################################
2492: sub submlink {
2493: my ($text,$uname,$udom,$symb,$target)=@_;
2494: if (!($uname && $udom)) {
2495: (my $cursymb, my $courseid,$udom,$uname)=
2496: &Apache::lonxml::whichuser($symb);
2497: if (!$symb) { $symb=$cursymb; }
2498: }
2499: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2500: $symb=&Apache::lonnet::escape($symb);
2501: if ($target) { $target="target=\"$target\""; }
2502: return '<a href="/adm/grades?&command=submission&'.
2503: 'symb='.$symb.'&student='.$uname.
2504: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
2505: }
2506: ##############################################
2507:
2508: =pod
2509:
2510: =item * &pgrdlink()
2511:
2512: Inputs: $text $uname $udom $symb $target
2513:
2514: Returns: A link to grades.pm such as to see the PGRD view of a student
2515:
2516: =cut
2517:
2518: ###############################################
2519: sub pgrdlink {
2520: my $link=&submlink(@_);
2521: $link=~s/(&command=submission)/$1&showgrading=yes/;
2522: return $link;
2523: }
2524: ##############################################
2525:
2526: =pod
2527:
2528: =item * &pprmlink()
2529:
2530: Inputs: $text $uname $udom $symb $target
2531:
2532: Returns: A link to parmset.pm such as to see the PPRM view of a
2533: student and a specific resource
2534:
2535: =cut
2536:
2537: ###############################################
2538: sub pprmlink {
2539: my ($text,$uname,$udom,$symb,$target)=@_;
2540: if (!($uname && $udom)) {
2541: (my $cursymb, my $courseid,$udom,$uname)=
2542: &Apache::lonxml::whichuser($symb);
2543: if (!$symb) { $symb=$cursymb; }
2544: }
2545: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2546: $symb=&Apache::lonnet::escape($symb);
2547: if ($target) { $target="target=\"$target\""; }
2548: return '<a href="/adm/parmset?&command=set&'.
2549: 'symb='.$symb.'&uname='.$uname.
2550: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
2551: }
2552: ##############################################
2553:
2554: =pod
2555:
2556: =back
2557:
2558: =cut
2559:
2560: ###############################################
2561:
2562:
2563: sub timehash {
2564: my @ltime=localtime(shift);
2565: return ( 'seconds' => $ltime[0],
2566: 'minutes' => $ltime[1],
2567: 'hours' => $ltime[2],
2568: 'day' => $ltime[3],
2569: 'month' => $ltime[4]+1,
2570: 'year' => $ltime[5]+1900,
2571: 'weekday' => $ltime[6],
2572: 'dayyear' => $ltime[7]+1,
2573: 'dlsav' => $ltime[8] );
2574: }
2575:
2576: sub maketime {
2577: my %th=@_;
2578: return POSIX::mktime(
2579: ($th{'seconds'},$th{'minutes'},$th{'hours'},
2580: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
2581: }
2582:
2583: #########################################
2584:
2585: sub findallcourses {
2586: my %courses=();
2587: my $now=time;
2588: foreach (keys %env) {
2589: if ($_=~/^user\.role\.\w+\.\/(\w+)\/(\w+)/) {
2590: my ($starttime,$endtime)=$env{$_};
2591: my $active=1;
2592: if ($starttime) {
2593: if ($now<$starttime) { $active=0; }
2594: }
2595: if ($endtime) {
2596: if ($now>$endtime) { $active=0; }
2597: }
2598: if ($active) { $courses{$1.'_'.$2}=1; }
2599: }
2600: }
2601: return keys %courses;
2602: }
2603:
2604: ###############################################
2605: ###############################################
2606:
2607: =pod
2608:
2609: =head1 Domain Template Functions
2610:
2611: =over 4
2612:
2613: =item * &determinedomain()
2614:
2615: Inputs: $domain (usually will be undef)
2616:
2617: Returns: Determines which domain should be used for designs
2618:
2619: =cut
2620:
2621: ###############################################
2622: sub determinedomain {
2623: my $domain=shift;
2624: if (! $domain) {
2625: # Determine domain if we have not been given one
2626: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
2627: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
2628: if ($env{'request.role.domain'}) {
2629: $domain=$env{'request.role.domain'};
2630: }
2631: }
2632: return $domain;
2633: }
2634: ###############################################
2635: =pod
2636:
2637: =item * &domainlogo()
2638:
2639: Inputs: $domain (usually will be undef)
2640:
2641: Returns: A link to a domain logo, if the domain logo exists.
2642: If the domain logo does not exist, a description of the domain.
2643:
2644: =cut
2645:
2646: ###############################################
2647: sub domainlogo {
2648: my $domain = &determinedomain(shift);
2649: # See if there is a logo
2650: if (-e '/home/httpd/html/adm/lonDomLogos/'.$domain.'.gif') {
2651: my $logo=&lonhttpdurl("/adm/lonDomLogos/$domain.gif");
2652: return '<img src="'.$logo.'" alt="'.$domain.'" />';
2653: } elsif(exists($Apache::lonnet::domaindescription{$domain})) {
2654: return $Apache::lonnet::domaindescription{$domain};
2655: } else {
2656: return '';
2657: }
2658: }
2659: ##############################################
2660:
2661: =pod
2662:
2663: =item * &designparm()
2664:
2665: Inputs: $which parameter; $domain (usually will be undef)
2666:
2667: Returns: value of designparamter $which
2668:
2669: =cut
2670:
2671: ##############################################
2672: sub designparm {
2673: my ($which,$domain)=@_;
2674: if ($env{'browser.blackwhite'} eq 'on') {
2675: if ($which=~/\.(font|alink|vlink|link)$/) {
2676: return '#000000';
2677: }
2678: if ($which=~/\.(pgbg|sidebg)$/) {
2679: return '#FFFFFF';
2680: }
2681: if ($which=~/\.tabbg$/) {
2682: return '#CCCCCC';
2683: }
2684: }
2685: if ($env{'environment.color.'.$which}) {
2686: return $env{'environment.color.'.$which};
2687: }
2688: $domain=&determinedomain($domain);
2689: if ($designhash{$domain.'.'.$which}) {
2690: return $designhash{$domain.'.'.$which};
2691: } else {
2692: return $designhash{'default.'.$which};
2693: }
2694: }
2695:
2696: ###############################################
2697: ###############################################
2698:
2699: =pod
2700:
2701: =back
2702:
2703: =head1 HTTP Helpers
2704:
2705: =over 4
2706:
2707: =item * &bodytag()
2708:
2709: Returns a uniform header for LON-CAPA web pages.
2710:
2711: Inputs:
2712:
2713: =over 4
2714:
2715: =item * $title, A title to be displayed on the page.
2716:
2717: =item * $function, the current role (can be undef).
2718:
2719: =item * $addentries, extra parameters for the <body> tag.
2720:
2721: =item * $bodyonly, if defined, only return the <body> tag.
2722:
2723: =item * $domain, if defined, force a given domain.
2724:
2725: =item * $forcereg, if page should register as content page (relevant for
2726: text interface only)
2727:
2728: =back
2729:
2730: Returns: A uniform header for LON-CAPA web pages.
2731: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
2732: If $bodyonly is undef or zero, an html string containing a <body> tag and
2733: other decorations will be returned.
2734:
2735: =cut
2736:
2737: sub bodytag {
2738: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,$notopbar)=@_;
2739: $title=&mt($title);
2740: $function = &get_users_function() if (!$function);
2741: my $img=&designparm($function.'.img',$domain);
2742: my $pgbg=&designparm($function.'.pgbg',$domain);
2743: my $tabbg=&designparm($function.'.tabbg',$domain);
2744: my $font=&designparm($function.'.font',$domain);
2745: my $link=&designparm($function.'.link',$domain);
2746: my $alink=&designparm($function.'.alink',$domain);
2747: my $vlink=&designparm($function.'.vlink',$domain);
2748: my $sidebg=&designparm($function.'.sidebg',$domain);
2749: # Accessibility font enhance
2750: unless ($addentries) { $addentries=''; }
2751: my $addstyle='';
2752: if ($env{'browser.fontenhance'} eq 'on') {
2753: $addstyle=' font-size: x-large;';
2754: }
2755: # role and realm
2756: my ($role,$realm)
2757: =&Apache::lonnet::plaintext((split(/\./,$env{'request.role'}))[0]);
2758: # realm
2759: if ($env{'request.course.id'}) {
2760: $realm=
2761: $env{'course.'.$env{'request.course.id'}.'.description'};
2762: }
2763: unless ($realm) { $realm=' '; }
2764: # Set messages
2765: my $messages=&domainlogo($domain);
2766: # Port for miniserver
2767: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
2768: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
2769: # construct main body tag
2770: my $bodytag = <<END;
2771: <style type="text/css">
2772: h1, h2, h3, th { font-family: Arial, Helvetica, sans-serif }
2773: a:focus { color: red; background: yellow }
2774: </style>
2775: <body bgcolor="$pgbg" text="$font" alink="$alink" vlink="$vlink" link="$link"
2776: style="margin-top: 0px;$addstyle" $addentries>
2777: END
2778: &Apache::lontexconvert::jsMath_reset();
2779: if ($env{'environment.texengine'} eq 'jsMath') {
2780: $bodytag.=&Apache::lontexconvert::jsMath_header();
2781: }
2782:
2783: my $upperleft='<img src="http://'.$ENV{'HTTP_HOST'}.':'.
2784: $lonhttpdPort.$img.'" alt="'.$function.'" />';
2785: if ($bodyonly) {
2786: return $bodytag;
2787: } elsif ($env{'browser.interface'} eq 'textual') {
2788: # Accessibility
2789:
2790: return $bodytag.&Apache::lonmenu::menubuttons($forcereg,'web',
2791: $forcereg).
2792: '<h1>LON-CAPA: '.$title.'</h1>';
2793: } elsif ($env{'environment.remote'} eq 'off') {
2794: # No Remote
2795: my $roleinfo=(<<ENDROLE);
2796: <td bgcolor="$tabbg" align="right">
2797: <font size="2" face="Arial, Helvetica, sans-serif">
2798: $env{'environment.firstname'}
2799: $env{'environment.middlename'}
2800: $env{'environment.lastname'}
2801: $env{'environment.generation'}
2802: </font>
2803: <br />
2804: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>
2805: <br />
2806: <font size="2" face="Arial, Helvetica, sans-serif">$realm</font>
2807: </td>
2808: ENDROLE
2809: my $titleinfo = '<font face="Arial, Helvetica, sans-serif" size="+3" color="'.
2810: $font.'"><b>'.$title.'</b></font>';
2811: if ($customtitle) {
2812: $titleinfo = $customtitle;
2813: }
2814:
2815: if ($env{'request.state'} eq 'construct') {
2816: my ($uname,$thisdisfn)=
2817: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
2818: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
2819: $formaction=~s/\/+/\//g;
2820: unless ($customtitle) { #this is for resources; directories have customtitle, and crumbs and select recent are created in lonpubdir.pm
2821: my $parentpath = '';
2822: my $lastitem = '';
2823: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
2824: $parentpath = $1;
2825: $lastitem = $2;
2826: } else {
2827: $lastitem = $thisdisfn;
2828: }
2829: $titleinfo = &Apache::loncommon::help_open_menu('','','','',3,'Authoring').
2830: '<font face="Arial, Helvetica, sans-serif"><b>Construction Space</b>:</font> '.
2831: '<form name="dirs" method="post" action="'.$formaction
2832: .'" target="_top"><tt><b>'
2833: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
2834: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
2835: .'</form>'
2836: .&Apache::lonmenu::constspaceform();
2837:
2838: }
2839: $forcereg=1;
2840: }
2841: my $titletable = '<table bgcolor="'.$pgbg.'" width="100%" border="0" '.
2842: 'cellspacing="3" cellpadding="3">'.
2843: '<tr><td bgcolor="'.$tabbg.'">'.
2844: $titleinfo.'</td>'.$roleinfo.'</tr></table>';
2845: if ($env{'request.state'} eq 'construct') {
2846: if ($notopbar) {
2847: $bodytag .= $titletable;
2848: } else {
2849: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg,$titletable);
2850: }
2851: } else {
2852: if ($notopbar) {
2853: $bodytag .= $titletable;
2854: } else {
2855: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,'web',$forcereg).
2856: $titletable;
2857: }
2858: }
2859: return $bodytag;
2860: }
2861:
2862: #
2863: # Top frame rendering, Remote is up
2864: #
2865: my $titleinfo = ' <font size="5" face="Arial, Helvetica, sans-serif"><b>'.$title.'</b></font>';
2866: if ($customtitle) {
2867: $titleinfo = $customtitle;
2868: }
2869: #
2870: # Extra info if you are the DC
2871: my $dc_info = '';
2872: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
2873: $env{'course.'.$env{'request.course.id'}.
2874: '.domain'}.'/'})) {
2875: my $cid = $env{'request.course.id'};
2876: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
2877: $dc_info = '('.$dc_info.')';
2878: }
2879: #
2880: return(<<ENDBODY);
2881: $bodytag
2882: <table width="100%" cellspacing="0" border="0" cellpadding="0">
2883: <tr><td bgcolor="$sidebg">
2884: $upperleft</td>
2885: <td bgcolor="$sidebg" align="right">$messages </td>
2886: </tr>
2887: <tr>
2888: <td rowspan="3" bgcolor="$tabbg">
2889: $titleinfo $dc_info
2890: </td><td bgcolor="$tabbg" align="right">
2891: <font size="2" face="Arial, Helvetica, sans-serif">
2892: $env{'environment.firstname'}
2893: $env{'environment.middlename'}
2894: $env{'environment.lastname'}
2895: $env{'environment.generation'}
2896: </font>
2897: </td>
2898: </tr>
2899: <tr><td bgcolor="$tabbg" align="right">
2900: <font size="2" face="Arial, Helvetica, sans-serif">$role</font>
2901: </td></tr>
2902: <tr>
2903: <td bgcolor="$tabbg" align="right"><font size="2" face="Arial, Helvetica, sans-serif">$realm</font> </td></tr>
2904: </table><br />
2905: ENDBODY
2906: }
2907:
2908: ###############################################
2909: ###############################################
2910:
2911: =pod
2912:
2913: =back
2914:
2915: =head1 HTTP Helpers
2916:
2917: =over 4
2918:
2919: =item * &endbodytag()
2920:
2921: Returns a uniform footer for LON-CAPA web pages.
2922:
2923: Inputs:
2924:
2925: =over 4
2926:
2927: =back
2928:
2929: Returns: A uniform footer for LON-CAPA web pages.
2930:
2931: =cut
2932:
2933: sub endbodytag {
2934: my $endbodytag='</body>';
2935: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
2936: return $endbodytag;
2937: }
2938:
2939: ###############################################
2940:
2941: =pod
2942:
2943: =item get_users_function
2944:
2945: Used by &bodytag to determine the current users primary role.
2946: Returns either 'student','coordinator','admin', or 'author'.
2947:
2948: =cut
2949:
2950: ###############################################
2951: sub get_users_function {
2952: my $function = 'student';
2953: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
2954: $function='coordinator';
2955: }
2956: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
2957: $function='admin';
2958: }
2959: if (($env{'request.role'}=~/^(au|ca)/) ||
2960: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
2961: $function='author';
2962: }
2963: return $function;
2964: }
2965:
2966: ###############################################
2967:
2968: =pod
2969:
2970: =item check_user_status
2971:
2972: Determines current status of supplied role for a
2973: specific user. Roles can be active, previous or future.
2974:
2975: Inputs:
2976: user's domain, user's username, course's domain,
2977: course's number, optional section/group.
2978:
2979: Outputs:
2980: role status: active, previous or future.
2981:
2982: =cut
2983:
2984: sub check_user_status {
2985: my ($udom,$uname,$cdom,$crs,$role,$secgrp) = @_;
2986: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
2987: my @uroles = keys %userinfo;
2988: my $srchstr;
2989: my $active_chk = 'none';
2990: if (@uroles > 0) {
2991: if (($role eq 'cc') || ($secgrp eq '') || (!defined($secgrp))) {
2992: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
2993: } else {
2994: $srchstr = '/'.$cdom.'/'.$crs.'/'.$secgrp.'_'.$role; }
2995: if (grep/^$srchstr$/,@uroles) {
2996: my $role_end = 0;
2997: my $role_start = 0;
2998: $active_chk = 'active';
2999: if ($userinfo{$srchstr} =~ m/^($role)_(\d+)/) {
3000: $role_end = $2;
3001: if ($userinfo{$srchstr} =~ m/^($role)_($role_end)_(\d+)$/) {
3002: $role_start = $3;
3003: }
3004: }
3005: if ($role_start > 0) {
3006: if (time < $role_start) {
3007: $active_chk = 'future';
3008: }
3009: }
3010: if ($role_end > 0) {
3011: if (time > $role_end) {
3012: $active_chk = 'previous';
3013: }
3014: }
3015: }
3016: }
3017: return $active_chk;
3018: }
3019:
3020: ###############################################
3021:
3022: =pod
3023:
3024: =item get_sections
3025:
3026: Determines all the sections for a course including
3027: sections with students and sections containing other roles.
3028: Incoming parameters: domain, course number, reference to
3029: section hash (keys to be section/group IDs), reference to
3030: array containing roles for which sections should be gathered
3031: (optional). If the fourth argument is undefined, sections
3032: are gathered for any role.
3033:
3034: Returns number of sections.
3035:
3036: =cut
3037:
3038: ###############################################
3039: sub get_sections {
3040: my ($cdom,$cnum,$sectioncount,$possible_roles) = @_;
3041: if (!($cdom && $cnum)) { return 0; }
3042: my $numsections = 0;
3043:
3044: if (!defined($possible_roles) || (grep/^st$/,@$possible_roles)) {
3045: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
3046: my $sec_index = &Apache::loncoursedata::CL_SECTION();
3047: my $status_index = &Apache::loncoursedata::CL_STATUS();
3048: while (my ($student,$data) = each %$classlist) {
3049: my ($section,$status) = ($data->[$sec_index],
3050: $data->[$status_index]);
3051: unless ($section eq '-1' || $section =~ /^\s*$/) {
3052: if (!defined($$sectioncount{$section})) { $numsections++; }
3053: $$sectioncount{$section}++;
3054: }
3055: }
3056: }
3057: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
3058: foreach my $user (sort(keys(%courseroles))) {
3059: if ($user !~ /^(\w{2})/) { next; }
3060: my ($role) = ($user =~ /^(\w{2})/);
3061: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
3062: my $section;
3063: if ($role eq 'cr' &&
3064: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
3065: $section=$1;
3066: }
3067: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
3068: if (!defined($section) || $section eq '-1') { next; }
3069: if (!defined($$sectioncount{$section})) { $numsections++; }
3070: $$sectioncount{$section}++;
3071: }
3072: return $numsections;
3073: }
3074:
3075: ###############################################
3076:
3077: =pod
3078:
3079: =item get_course_users
3080:
3081: Retrieves usernames:domains for users in the specified course
3082: with specific role(s), and access status.
3083:
3084: Incoming parameters:
3085: 1. course domain
3086: 2. course number
3087: 3. access status: users must have - either active,
3088: previous, future, or all.
3089: 4. reference to array of permissible roles
3090: 5. reference to results object (hash of hashes).
3091: Keys of top level hash are roles.
3092: Keys of inner hashes are username:domain, with
3093: values set to access type.
3094:
3095: =cut
3096:
3097: ###############################################
3098:
3099: sub get_course_users {
3100: my ($cdom,$cnum,$types,$roles,$users) = @_;
3101: if (grep/^st$/,@{$roles}) {
3102: my $statusidx = &Apache::loncoursedata::CL_STATUS();
3103: my $startidx = &Apache::loncoursedata::CL_START();
3104: my $endidx = &Apache::loncoursedata::CL_END();
3105: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
3106: my $now = time;
3107: foreach my $student (keys(%{$classlist})) {
3108: if (defined($$types{'active'})) {
3109: if ($$classlist{$student}[$statusidx] eq 'Active') {
3110: push(@{$$users{st}{$student}},'active');
3111: }
3112: }
3113: if (defined($$types{'previous'})) {
3114: if ($$classlist{$student}[$endidx] <= $now) {
3115: push(@{$$users{st}{$student}},'previous');
3116: }
3117: }
3118: if (defined($$types{'future'})) {
3119: if (($$classlist{$student}[$startidx] > $now) && ($$classlist{$student}[$endidx] > $now) || ($$classlist{$student}[$endidx] == 0) || ($$classlist{$student}[$endidx] eq '')) {
3120: push(@{$$users{st}{$student}},'future');
3121: }
3122: }
3123: }
3124: }
3125: if ((@{$roles} > 0) && (@{$roles} ne "st")) {
3126: my @coursepersonnel = &Apache::lonnet::getkeys('nohist_userroles',$cdom,$cnum);
3127: foreach my $person (@coursepersonnel) {
3128: my ($role,$user) = ($person =~ /^([^:]*):([^:]+:[^:]+)/);
3129: $user =~ s/:$//;
3130: if (($role) && (grep(/^$role$/,@{$roles}))) {
3131: my ($uname,$udom) = split(/:/,$user);
3132: if ($uname ne '' && $udom ne '') {
3133: my $status = &check_user_status($udom,$uname,$cdom,$cnum,$role);
3134: foreach my $type (keys(%{$types})) {
3135: if ($status eq $type) {
3136: $$users{$role}{$user} = $type;
3137: }
3138: }
3139: }
3140: }
3141: }
3142: if (grep/^ow$/,@{$roles}) {
3143: if ((defined($cdom)) && (defined($cnum))) {
3144: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
3145: if ( defined($csettings{'internal.courseowner'}) ) {
3146: my $owner = $csettings{'internal.courseowner'};
3147: $$users{'ow'}{$owner.':'.$cdom} = 'any';
3148: }
3149: }
3150: }
3151: }
3152: return;
3153: }
3154:
3155:
3156:
3157: ###############################################
3158:
3159: sub get_posted_cgi {
3160: my $r=shift;
3161:
3162: my $buffer;
3163: if ($r->header_in('Content-length')) {
3164: $r->read($buffer,$r->header_in('Content-length'),0);
3165: }
3166: unless ($buffer=~/^(\-+\w+)\s+Content\-Disposition\:\s*form\-data/si) {
3167: my @pairs=split(/&/,$buffer);
3168: my $pair;
3169: foreach $pair (@pairs) {
3170: my ($name,$value) = split(/=/,$pair);
3171: $value =~ tr/+/ /;
3172: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3173: $name =~ tr/+/ /;
3174: $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3175: &add_to_env("form.$name",$value);
3176: }
3177: } else {
3178: my $contentsep=$1;
3179: my @lines = split (/\n/,$buffer);
3180: my $name='';
3181: my $value='';
3182: my $fname='';
3183: my $fmime='';
3184: my $i;
3185: for ($i=0;$i<=$#lines;$i++) {
3186: if ($lines[$i]=~/^$contentsep/) {
3187: if ($name) {
3188: chomp($value);
3189: if ($fname) {
3190: $env{"form.$name.filename"}=$fname;
3191: $env{"form.$name.mimetype"}=$fmime;
3192: } else {
3193: $value=~s/\s+$//s;
3194: }
3195: &add_to_env("form.$name",$value);
3196: }
3197: if ($i<$#lines) {
3198: $i++;
3199: $lines[$i]=~
3200: /Content\-Disposition\:\s*form\-data\;\s*name\=\"([^\"]+)\"/i;
3201: $name=$1;
3202: $value='';
3203: if ($lines[$i]=~/filename\=\"([^\"]+)\"/i) {
3204: $fname=$1;
3205: if
3206: ($lines[$i+1]=~/Content\-Type\:\s*([\w\-\/]+)/i) {
3207: $fmime=$1;
3208: $i++;
3209: } else {
3210: $fmime='';
3211: }
3212: } else {
3213: $fname='';
3214: $fmime='';
3215: }
3216: $i++;
3217: }
3218: } else {
3219: $value.=$lines[$i]."\n";
3220: }
3221: }
3222: }
3223: $env{'request.method'}=$ENV{'REQUEST_METHOD'};
3224: $r->method_number(M_GET);
3225: $r->method('GET');
3226: $r->headers_in->unset('Content-length');
3227: }
3228:
3229: =pod
3230:
3231: =item * get_unprocessed_cgi($query,$possible_names)
3232:
3233: Modify the %env hash to contain unprocessed CGI form parameters held in
3234: $query. The parameters listed in $possible_names (an array reference),
3235: will be set in $env{'form.name'} if they do not already exist.
3236:
3237: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
3238: $possible_names is an ref to an array of form element names. As an example:
3239: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
3240: will result in $env{'form.uname'} and $env{'form.udom'} being set.
3241:
3242: =cut
3243:
3244: sub get_unprocessed_cgi {
3245: my ($query,$possible_names)= @_;
3246: # $Apache::lonxml::debug=1;
3247: foreach (split(/&/,$query)) {
3248: my ($name, $value) = split(/=/,$_);
3249: $name = &Apache::lonnet::unescape($name);
3250: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
3251: $value =~ tr/+/ /;
3252: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3253: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
3254: }
3255: }
3256: }
3257:
3258: =pod
3259:
3260: =item * cacheheader()
3261:
3262: returns cache-controlling header code
3263:
3264: =cut
3265:
3266: sub cacheheader {
3267: unless ($env{'request.method'} eq 'GET') { return ''; }
3268: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
3269: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
3270: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
3271: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
3272: return $output;
3273: }
3274:
3275: =pod
3276:
3277: =item * no_cache($r)
3278:
3279: specifies header code to not have cache
3280:
3281: =cut
3282:
3283: sub no_cache {
3284: my ($r) = @_;
3285: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
3286: $env{'request.method'} ne 'GET') { return ''; }
3287: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
3288: $r->no_cache(1);
3289: $r->header_out("Expires" => $date);
3290: $r->header_out("Pragma" => "no-cache");
3291: }
3292:
3293: sub content_type {
3294: my ($r,$type,$charset) = @_;
3295: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
3296: unless ($charset) {
3297: $charset=&Apache::lonlocal::current_encoding;
3298: }
3299: if ($charset) { $type.='; charset='.$charset; }
3300: if ($r) {
3301: $r->content_type($type);
3302: } else {
3303: print("Content-type: $type\n\n");
3304: }
3305: }
3306:
3307: =pod
3308:
3309: =item * add_to_env($name,$value)
3310:
3311: adds $name to the %env hash with value
3312: $value, if $name already exists, the entry is converted to an array
3313: reference and $value is added to the array.
3314:
3315: =cut
3316:
3317: sub add_to_env {
3318: my ($name,$value)=@_;
3319: if (defined($env{$name})) {
3320: if (ref($env{$name})) {
3321: #already have multiple values
3322: push(@{ $env{$name} },$value);
3323: } else {
3324: #first time seeing multiple values, convert hash entry to an arrayref
3325: my $first=$env{$name};
3326: undef($env{$name});
3327: push(@{ $env{$name} },$first,$value);
3328: }
3329: } else {
3330: $env{$name}=$value;
3331: }
3332: }
3333:
3334: =pod
3335:
3336: =item * get_env_multiple($name)
3337:
3338: gets $name from the %env hash, it seemlessly handles the cases where multiple
3339: values may be defined and end up as an array ref.
3340:
3341: returns an array of values
3342:
3343: =cut
3344:
3345: sub get_env_multiple {
3346: my ($name) = @_;
3347: my @values;
3348: if (defined($env{$name})) {
3349: # exists is it an array
3350: if (ref($env{$name})) {
3351: @values=@{ $env{$name} };
3352: } else {
3353: $values[0]=$env{$name};
3354: }
3355: }
3356: return(@values);
3357: }
3358:
3359:
3360: =pod
3361:
3362: =back
3363:
3364: =head1 CSV Upload/Handling functions
3365:
3366: =over 4
3367:
3368: =item * upfile_store($r)
3369:
3370: Store uploaded file, $r should be the HTTP Request object,
3371: needs $env{'form.upfile'}
3372: returns $datatoken to be put into hidden field
3373:
3374: =cut
3375:
3376: sub upfile_store {
3377: my $r=shift;
3378: $env{'form.upfile'}=~s/\r/\n/gs;
3379: $env{'form.upfile'}=~s/\f/\n/gs;
3380: $env{'form.upfile'}=~s/\n+/\n/gs;
3381: $env{'form.upfile'}=~s/\n+$//gs;
3382:
3383: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
3384: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
3385: {
3386: my $datafile = $r->dir_config('lonDaemons').
3387: '/tmp/'.$datatoken.'.tmp';
3388: if ( open(my $fh,">$datafile") ) {
3389: print $fh $env{'form.upfile'};
3390: close($fh);
3391: }
3392: }
3393: return $datatoken;
3394: }
3395:
3396: =pod
3397:
3398: =item * load_tmp_file($r)
3399:
3400: Load uploaded file from tmp, $r should be the HTTP Request object,
3401: needs $env{'form.datatoken'},
3402: sets $env{'form.upfile'} to the contents of the file
3403:
3404: =cut
3405:
3406: sub load_tmp_file {
3407: my $r=shift;
3408: my @studentdata=();
3409: {
3410: my $studentfile = $r->dir_config('lonDaemons').
3411: '/tmp/'.$env{'form.datatoken'}.'.tmp';
3412: if ( open(my $fh,"<$studentfile") ) {
3413: @studentdata=<$fh>;
3414: close($fh);
3415: }
3416: }
3417: $env{'form.upfile'}=join('',@studentdata);
3418: }
3419:
3420: =pod
3421:
3422: =item * upfile_record_sep()
3423:
3424: Separate uploaded file into records
3425: returns array of records,
3426: needs $env{'form.upfile'} and $env{'form.upfiletype'}
3427:
3428: =cut
3429:
3430: sub upfile_record_sep {
3431: if ($env{'form.upfiletype'} eq 'xml') {
3432: } else {
3433: my @records;
3434: foreach my $line (split(/\n/,$env{'form.upfile'})) {
3435: if ($line=~/^\s*$/) { next; }
3436: push(@records,$line);
3437: }
3438: return @records;
3439: }
3440: }
3441:
3442: =pod
3443:
3444: =item * record_sep($record)
3445:
3446: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
3447:
3448: =cut
3449:
3450: sub takeleft {
3451: my $index=shift;
3452: return substr('0000'.$index,-4,4);
3453: }
3454:
3455: sub record_sep {
3456: my $record=shift;
3457: my %components=();
3458: if ($env{'form.upfiletype'} eq 'xml') {
3459: } elsif ($env{'form.upfiletype'} eq 'space') {
3460: my $i=0;
3461: foreach (split(/\s+/,$record)) {
3462: my $field=$_;
3463: $field=~s/^(\"|\')//;
3464: $field=~s/(\"|\')$//;
3465: $components{&takeleft($i)}=$field;
3466: $i++;
3467: }
3468: } elsif ($env{'form.upfiletype'} eq 'tab') {
3469: my $i=0;
3470: foreach (split(/\t/,$record)) {
3471: my $field=$_;
3472: $field=~s/^(\"|\')//;
3473: $field=~s/(\"|\')$//;
3474: $components{&takeleft($i)}=$field;
3475: $i++;
3476: }
3477: } else {
3478: my @allfields=split(/\,/,$record);
3479: my $i=0;
3480: my $j;
3481: for ($j=0;$j<=$#allfields;$j++) {
3482: my $field=$allfields[$j];
3483: if ($field=~/^\s*(\"|\')/) {
3484: my $delimiter=$1;
3485: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
3486: $j++;
3487: $field.=','.$allfields[$j];
3488: }
3489: $field=~s/^\s*$delimiter//;
3490: $field=~s/$delimiter\s*$//;
3491: }
3492: $components{&takeleft($i)}=$field;
3493: $i++;
3494: }
3495: }
3496: return %components;
3497: }
3498:
3499: ######################################################
3500: ######################################################
3501:
3502: =pod
3503:
3504: =item * upfile_select_html()
3505:
3506: Return HTML code to select a file from the users machine and specify
3507: the file type.
3508:
3509: =cut
3510:
3511: ######################################################
3512: ######################################################
3513: sub upfile_select_html {
3514: my %Types = (
3515: csv => &mt('CSV (comma separated values, spreadsheet)'),
3516: space => &mt('Space separated'),
3517: tab => &mt('Tabulator separated'),
3518: # xml => &mt('HTML/XML'),
3519: );
3520: my $Str = '<input type="file" name="upfile" size="50" />'.
3521: '<br />Type: <select name="upfiletype">';
3522: foreach my $type (sort(keys(%Types))) {
3523: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
3524: }
3525: $Str .= "</select>\n";
3526: return $Str;
3527: }
3528:
3529: ######################################################
3530: ######################################################
3531:
3532: =pod
3533:
3534: =item * csv_print_samples($r,$records)
3535:
3536: Prints a table of sample values from each column uploaded $r is an
3537: Apache Request ref, $records is an arrayref from
3538: &Apache::loncommon::upfile_record_sep
3539:
3540: =cut
3541:
3542: ######################################################
3543: ######################################################
3544: sub csv_print_samples {
3545: my ($r,$records) = @_;
3546: my (%sone,%stwo,%sthree);
3547: %sone=&record_sep($$records[0]);
3548: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
3549: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
3550: #
3551: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
3552: foreach (sort({$a <=> $b} keys(%sone))) {
3553: $r->print('<th>'.&mt('Column [_1]',($_+1)).'</th>'); }
3554: $r->print('</tr>');
3555: foreach my $hash (\%sone,\%stwo,\%sthree) {
3556: $r->print('<tr>');
3557: foreach (sort({$a <=> $b} keys(%sone))) {
3558: $r->print('<td>');
3559: if (defined($$hash{$_})) { $r->print($$hash{$_}); }
3560: $r->print('</td>');
3561: }
3562: $r->print('</tr>');
3563: }
3564: $r->print('</tr></table><br />'."\n");
3565: }
3566:
3567: ######################################################
3568: ######################################################
3569:
3570: =pod
3571:
3572: =item * csv_print_select_table($r,$records,$d)
3573:
3574: Prints a table to create associations between values and table columns.
3575:
3576: $r is an Apache Request ref,
3577: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
3578: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
3579:
3580: =cut
3581:
3582: ######################################################
3583: ######################################################
3584: sub csv_print_select_table {
3585: my ($r,$records,$d) = @_;
3586: my $i=0;my %sone;
3587: %sone=&record_sep($$records[0]);
3588: $r->print(&mt('Associate columns with student attributes.')."\n".
3589: '<table border="2"><tr>'.
3590: '<th>'.&mt('Attribute').'</th>'.
3591: '<th>'.&mt('Column').'</th></tr>'."\n");
3592: foreach (@$d) {
3593: my ($value,$display,$defaultcol)=@{ $_ };
3594: $r->print('<tr><td>'.$display.'</td>');
3595:
3596: $r->print('<td><select name=f'.$i.
3597: ' onchange="javascript:flip(this.form,'.$i.');">');
3598: $r->print('<option value="none"></option>');
3599: foreach (sort({$a <=> $b} keys(%sone))) {
3600: $r->print('<option value="'.$_.'"'.
3601: ($_ eq $defaultcol ? ' selected="selected" ' : '').
3602: '>Column '.($_+1).'</option>');
3603: }
3604: $r->print('</select></td></tr>'."\n");
3605: $i++;
3606: }
3607: $i--;
3608: return $i;
3609: }
3610:
3611: ######################################################
3612: ######################################################
3613:
3614: =pod
3615:
3616: =item * csv_samples_select_table($r,$records,$d)
3617:
3618: Prints a table of sample values from the upload and can make associate samples to internal names.
3619:
3620: $r is an Apache Request ref,
3621: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
3622: $d is an array of 2 element arrays (internal name, displayed name)
3623:
3624: =cut
3625:
3626: ######################################################
3627: ######################################################
3628: sub csv_samples_select_table {
3629: my ($r,$records,$d) = @_;
3630: my %sone; my %stwo; my %sthree;
3631: my $i=0;
3632: #
3633: $r->print('<table border=2><tr><th>'.
3634: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
3635: %sone=&record_sep($$records[0]);
3636: if (defined($$records[1])) {%stwo=&record_sep($$records[1]);}
3637: if (defined($$records[2])) {%sthree=&record_sep($$records[2]);}
3638: #
3639: foreach (sort keys %sone) {
3640: $r->print('<tr><td><select name="f'.$i.'"'.
3641: ' onchange="javascript:flip(this.form,'.$i.');">');
3642: foreach (@$d) {
3643: my ($value,$display,$defaultcol)=@{ $_ };
3644: $r->print('<option value="'.$value.'"'.
3645: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
3646: $display.'</option>');
3647: }
3648: $r->print('</select></td><td>');
3649: if (defined($sone{$_})) { $r->print($sone{$_}."<br />\n"); }
3650: if (defined($stwo{$_})) { $r->print($stwo{$_}."<br />\n"); }
3651: if (defined($sthree{$_})) { $r->print($sthree{$_}."<br />\n"); }
3652: $r->print('</td></tr>');
3653: $i++;
3654: }
3655: $i--;
3656: return($i);
3657: }
3658:
3659: ######################################################
3660: ######################################################
3661:
3662: =pod
3663:
3664: =item clean_excel_name($name)
3665:
3666: Returns a replacement for $name which does not contain any illegal characters.
3667:
3668: =cut
3669:
3670: ######################################################
3671: ######################################################
3672: sub clean_excel_name {
3673: my ($name) = @_;
3674: $name =~ s/[:\*\?\/\\]//g;
3675: if (length($name) > 31) {
3676: $name = substr($name,0,31);
3677: }
3678: return $name;
3679: }
3680:
3681: =pod
3682:
3683: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
3684:
3685: Returns either 1 or undef
3686:
3687: 1 if the part is to be hidden, undef if it is to be shown
3688:
3689: Arguments are:
3690:
3691: $id the id of the part to be checked
3692: $symb, optional the symb of the resource to check
3693: $udom, optional the domain of the user to check for
3694: $uname, optional the username of the user to check for
3695:
3696: =cut
3697:
3698: sub check_if_partid_hidden {
3699: my ($id,$symb,$udom,$uname) = @_;
3700: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
3701: $symb,$udom,$uname);
3702: my $truth=1;
3703: #if the string starts with !, then the list is the list to show not hide
3704: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
3705: my @hiddenlist=split(/,/,$hiddenparts);
3706: foreach my $checkid (@hiddenlist) {
3707: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
3708: }
3709: return !$truth;
3710: }
3711:
3712:
3713: ############################################################
3714: ############################################################
3715:
3716: =pod
3717:
3718: =back
3719:
3720: =head1 cgi-bin script and graphing routines
3721:
3722: =over 4
3723:
3724: =item get_cgi_id
3725:
3726: Inputs: none
3727:
3728: Returns an id which can be used to pass environment variables
3729: to various cgi-bin scripts. These environment variables will
3730: be removed from the users environment after a given time by
3731: the routine &Apache::lonnet::transfer_profile_to_env.
3732:
3733: =cut
3734:
3735: ############################################################
3736: ############################################################
3737: my $uniq=0;
3738: sub get_cgi_id {
3739: $uniq=($uniq+1)%100000;
3740: return (time.'_'.$$.'_'.$uniq);
3741: }
3742:
3743: ############################################################
3744: ############################################################
3745:
3746: =pod
3747:
3748: =item DrawBarGraph
3749:
3750: Facilitates the plotting of data in a (stacked) bar graph.
3751: Puts plot definition data into the users environment in order for
3752: graph.png to plot it. Returns an <img> tag for the plot.
3753: The bars on the plot are labeled '1','2',...,'n'.
3754:
3755: Inputs:
3756:
3757: =over 4
3758:
3759: =item $Title: string, the title of the plot
3760:
3761: =item $xlabel: string, text describing the X-axis of the plot
3762:
3763: =item $ylabel: string, text describing the Y-axis of the plot
3764:
3765: =item $Max: scalar, the maximum Y value to use in the plot
3766: If $Max is < any data point, the graph will not be rendered.
3767:
3768: =item $colors: array ref holding the colors to be used for the data sets when
3769: they are plotted. If undefined, default values will be used.
3770:
3771: =item $labels: array ref holding the labels to use on the x-axis for the bars.
3772:
3773: =item @Values: An array of array references. Each array reference holds data
3774: to be plotted in a stacked bar chart.
3775:
3776: =item If the final element of @Values is a hash reference the key/value
3777: pairs will be added to the graph definition.
3778:
3779: =back
3780:
3781: Returns:
3782:
3783: An <img> tag which references graph.png and the appropriate identifying
3784: information for the plot.
3785:
3786: =cut
3787:
3788: ############################################################
3789: ############################################################
3790: sub DrawBarGraph {
3791: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
3792: #
3793: if (! defined($colors)) {
3794: $colors = ['#33ff00',
3795: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
3796: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
3797: ];
3798: }
3799: my $extra_settings = {};
3800: if (ref($Values[-1]) eq 'HASH') {
3801: $extra_settings = pop(@Values);
3802: }
3803: #
3804: my $identifier = &get_cgi_id();
3805: my $id = 'cgi.'.$identifier;
3806: if (! @Values || ref($Values[0]) ne 'ARRAY') {
3807: return '';
3808: }
3809: #
3810: my @Labels;
3811: if (defined($labels)) {
3812: @Labels = @$labels;
3813: } else {
3814: for (my $i=0;$i<@{$Values[0]};$i++) {
3815: push (@Labels,$i+1);
3816: }
3817: }
3818: #
3819: my $NumBars = scalar(@{$Values[0]});
3820: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
3821: my %ValuesHash;
3822: my $NumSets=1;
3823: foreach my $array (@Values) {
3824: next if (! ref($array));
3825: $ValuesHash{$id.'.data.'.$NumSets++} =
3826: join(',',@$array);
3827: }
3828: #
3829: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
3830: if ($NumBars < 3) {
3831: $width = 120+$NumBars*32;
3832: $xskip = 1;
3833: $bar_width = 30;
3834: } elsif ($NumBars < 5) {
3835: $width = 120+$NumBars*20;
3836: $xskip = 1;
3837: $bar_width = 20;
3838: } elsif ($NumBars < 10) {
3839: $width = 120+$NumBars*15;
3840: $xskip = 1;
3841: $bar_width = 15;
3842: } elsif ($NumBars <= 25) {
3843: $width = 120+$NumBars*11;
3844: $xskip = 5;
3845: $bar_width = 8;
3846: } elsif ($NumBars <= 50) {
3847: $width = 120+$NumBars*8;
3848: $xskip = 5;
3849: $bar_width = 4;
3850: } else {
3851: $width = 120+$NumBars*8;
3852: $xskip = 5;
3853: $bar_width = 4;
3854: }
3855: #
3856: $Max = 1 if ($Max < 1);
3857: if ( int($Max) < $Max ) {
3858: $Max++;
3859: $Max = int($Max);
3860: }
3861: $Title = '' if (! defined($Title));
3862: $xlabel = '' if (! defined($xlabel));
3863: $ylabel = '' if (! defined($ylabel));
3864: $ValuesHash{$id.'.title'} = &Apache::lonnet::escape($Title);
3865: $ValuesHash{$id.'.xlabel'} = &Apache::lonnet::escape($xlabel);
3866: $ValuesHash{$id.'.ylabel'} = &Apache::lonnet::escape($ylabel);
3867: $ValuesHash{$id.'.y_max_value'} = $Max;
3868: $ValuesHash{$id.'.NumBars'} = $NumBars;
3869: $ValuesHash{$id.'.NumSets'} = $NumSets;
3870: $ValuesHash{$id.'.PlotType'} = 'bar';
3871: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
3872: $ValuesHash{$id.'.height'} = $height;
3873: $ValuesHash{$id.'.width'} = $width;
3874: $ValuesHash{$id.'.xskip'} = $xskip;
3875: $ValuesHash{$id.'.bar_width'} = $bar_width;
3876: $ValuesHash{$id.'.labels'} = join(',',@Labels);
3877: #
3878: # Deal with other parameters
3879: while (my ($key,$value) = each(%$extra_settings)) {
3880: $ValuesHash{$id.'.'.$key} = $value;
3881: }
3882: #
3883: &Apache::lonnet::appenv(%ValuesHash);
3884: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
3885: }
3886:
3887: ############################################################
3888: ############################################################
3889:
3890: =pod
3891:
3892: =item DrawXYGraph
3893:
3894: Facilitates the plotting of data in an XY graph.
3895: Puts plot definition data into the users environment in order for
3896: graph.png to plot it. Returns an <img> tag for the plot.
3897:
3898: Inputs:
3899:
3900: =over 4
3901:
3902: =item $Title: string, the title of the plot
3903:
3904: =item $xlabel: string, text describing the X-axis of the plot
3905:
3906: =item $ylabel: string, text describing the Y-axis of the plot
3907:
3908: =item $Max: scalar, the maximum Y value to use in the plot
3909: If $Max is < any data point, the graph will not be rendered.
3910:
3911: =item $colors: Array ref containing the hex color codes for the data to be
3912: plotted in. If undefined, default values will be used.
3913:
3914: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
3915:
3916: =item $Ydata: Array ref containing Array refs.
3917: Each of the contained arrays will be plotted as a separate curve.
3918:
3919: =item %Values: hash indicating or overriding any default values which are
3920: passed to graph.png.
3921: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
3922:
3923: =back
3924:
3925: Returns:
3926:
3927: An <img> tag which references graph.png and the appropriate identifying
3928: information for the plot.
3929:
3930: =cut
3931:
3932: ############################################################
3933: ############################################################
3934: sub DrawXYGraph {
3935: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
3936: #
3937: # Create the identifier for the graph
3938: my $identifier = &get_cgi_id();
3939: my $id = 'cgi.'.$identifier;
3940: #
3941: $Title = '' if (! defined($Title));
3942: $xlabel = '' if (! defined($xlabel));
3943: $ylabel = '' if (! defined($ylabel));
3944: my %ValuesHash =
3945: (
3946: $id.'.title' => &Apache::lonnet::escape($Title),
3947: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
3948: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
3949: $id.'.y_max_value'=> $Max,
3950: $id.'.labels' => join(',',@$Xlabels),
3951: $id.'.PlotType' => 'XY',
3952: );
3953: #
3954: if (defined($colors) && ref($colors) eq 'ARRAY') {
3955: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
3956: }
3957: #
3958: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
3959: return '';
3960: }
3961: my $NumSets=1;
3962: foreach my $array (@{$Ydata}){
3963: next if (! ref($array));
3964: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
3965: }
3966: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
3967: #
3968: # Deal with other parameters
3969: while (my ($key,$value) = each(%Values)) {
3970: $ValuesHash{$id.'.'.$key} = $value;
3971: }
3972: #
3973: &Apache::lonnet::appenv(%ValuesHash);
3974: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
3975: }
3976:
3977: ############################################################
3978: ############################################################
3979:
3980: =pod
3981:
3982: =item DrawXYYGraph
3983:
3984: Facilitates the plotting of data in an XY graph with two Y axes.
3985: Puts plot definition data into the users environment in order for
3986: graph.png to plot it. Returns an <img> tag for the plot.
3987:
3988: Inputs:
3989:
3990: =over 4
3991:
3992: =item $Title: string, the title of the plot
3993:
3994: =item $xlabel: string, text describing the X-axis of the plot
3995:
3996: =item $ylabel: string, text describing the Y-axis of the plot
3997:
3998: =item $colors: Array ref containing the hex color codes for the data to be
3999: plotted in. If undefined, default values will be used.
4000:
4001: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
4002:
4003: =item $Ydata1: The first data set
4004:
4005: =item $Min1: The minimum value of the left Y-axis
4006:
4007: =item $Max1: The maximum value of the left Y-axis
4008:
4009: =item $Ydata2: The second data set
4010:
4011: =item $Min2: The minimum value of the right Y-axis
4012:
4013: =item $Max2: The maximum value of the left Y-axis
4014:
4015: =item %Values: hash indicating or overriding any default values which are
4016: passed to graph.png.
4017: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
4018:
4019: =back
4020:
4021: Returns:
4022:
4023: An <img> tag which references graph.png and the appropriate identifying
4024: information for the plot.
4025:
4026: =cut
4027:
4028: ############################################################
4029: ############################################################
4030: sub DrawXYYGraph {
4031: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
4032: $Ydata2,$Min2,$Max2,%Values)=@_;
4033: #
4034: # Create the identifier for the graph
4035: my $identifier = &get_cgi_id();
4036: my $id = 'cgi.'.$identifier;
4037: #
4038: $Title = '' if (! defined($Title));
4039: $xlabel = '' if (! defined($xlabel));
4040: $ylabel = '' if (! defined($ylabel));
4041: my %ValuesHash =
4042: (
4043: $id.'.title' => &Apache::lonnet::escape($Title),
4044: $id.'.xlabel' => &Apache::lonnet::escape($xlabel),
4045: $id.'.ylabel' => &Apache::lonnet::escape($ylabel),
4046: $id.'.labels' => join(',',@$Xlabels),
4047: $id.'.PlotType' => 'XY',
4048: $id.'.NumSets' => 2,
4049: $id.'.two_axes' => 1,
4050: $id.'.y1_max_value' => $Max1,
4051: $id.'.y1_min_value' => $Min1,
4052: $id.'.y2_max_value' => $Max2,
4053: $id.'.y2_min_value' => $Min2,
4054: );
4055: #
4056: if (defined($colors) && ref($colors) eq 'ARRAY') {
4057: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
4058: }
4059: #
4060: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
4061: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
4062: return '';
4063: }
4064: my $NumSets=1;
4065: foreach my $array ($Ydata1,$Ydata2){
4066: next if (! ref($array));
4067: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
4068: }
4069: #
4070: # Deal with other parameters
4071: while (my ($key,$value) = each(%Values)) {
4072: $ValuesHash{$id.'.'.$key} = $value;
4073: }
4074: #
4075: &Apache::lonnet::appenv(%ValuesHash);
4076: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
4077: }
4078:
4079: ############################################################
4080: ############################################################
4081:
4082: =pod
4083:
4084: =back
4085:
4086: =head1 Statistics helper routines?
4087:
4088: Bad place for them but what the hell.
4089:
4090: =over 4
4091:
4092: =item &chartlink
4093:
4094: Returns a link to the chart for a specific student.
4095:
4096: Inputs:
4097:
4098: =over 4
4099:
4100: =item $linktext: The text of the link
4101:
4102: =item $sname: The students username
4103:
4104: =item $sdomain: The students domain
4105:
4106: =back
4107:
4108: =back
4109:
4110: =cut
4111:
4112: ############################################################
4113: ############################################################
4114: sub chartlink {
4115: my ($linktext, $sname, $sdomain) = @_;
4116: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
4117: '&SelectedStudent='.&Apache::lonnet::escape($sname.':'.$sdomain).
4118: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
4119: '">'.$linktext.'</a>';
4120: }
4121:
4122: #######################################################
4123: #######################################################
4124:
4125: =pod
4126:
4127: =head1 Course Environment Routines
4128:
4129: =over 4
4130:
4131: =item &restore_course_settings
4132:
4133: =item &store_course_settings
4134:
4135: Restores/Store indicated form parameters from the course environment.
4136: Will not overwrite existing values of the form parameters.
4137:
4138: Inputs:
4139: a scalar describing the data (e.g. 'chart', 'problem_analysis')
4140:
4141: a hash ref describing the data to be stored. For example:
4142:
4143: %Save_Parameters = ('Status' => 'scalar',
4144: 'chartoutputmode' => 'scalar',
4145: 'chartoutputdata' => 'scalar',
4146: 'Section' => 'array',
4147: 'StudentData' => 'array',
4148: 'Maps' => 'array');
4149:
4150: Returns: both routines return nothing
4151:
4152: =cut
4153:
4154: #######################################################
4155: #######################################################
4156: sub store_course_settings {
4157: # save to the environment
4158: # appenv the same items, just to be safe
4159: my $courseid = $env{'request.course.id'};
4160: my $coursedom = $env{'course.'.$courseid.'.domain'};
4161: my ($prefix,$Settings) = @_;
4162: my %SaveHash;
4163: my %AppHash;
4164: while (my ($setting,$type) = each(%$Settings)) {
4165: my $basename = 'internal.'.$prefix.'.'.$setting;
4166: my $envname = 'course.'.$courseid.'.'.$basename;
4167: if (exists($env{'form.'.$setting})) {
4168: # Save this value away
4169: if ($type eq 'scalar' &&
4170: (! exists($env{$envname}) ||
4171: $env{$envname} ne $env{'form.'.$setting})) {
4172: $SaveHash{$basename} = $env{'form.'.$setting};
4173: $AppHash{$envname} = $env{'form.'.$setting};
4174: } elsif ($type eq 'array') {
4175: my $stored_form;
4176: if (ref($env{'form.'.$setting})) {
4177: $stored_form = join(',',
4178: map {
4179: &Apache::lonnet::escape($_);
4180: } sort(@{$env{'form.'.$setting}}));
4181: } else {
4182: $stored_form =
4183: &Apache::lonnet::escape($env{'form.'.$setting});
4184: }
4185: # Determine if the array contents are the same.
4186: if ($stored_form ne $env{$envname}) {
4187: $SaveHash{$basename} = $stored_form;
4188: $AppHash{$envname} = $stored_form;
4189: }
4190: }
4191: }
4192: }
4193: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
4194: $coursedom,
4195: $env{'course.'.$courseid.'.num'});
4196: if ($put_result !~ /^(ok|delayed)/) {
4197: &Apache::lonnet::logthis('unable to save form parameters, '.
4198: 'got error:'.$put_result);
4199: }
4200: # Make sure these settings stick around in this session, too
4201: &Apache::lonnet::appenv(%AppHash);
4202: return;
4203: }
4204:
4205: sub restore_course_settings {
4206: my $courseid = $env{'request.course.id'};
4207: my ($prefix,$Settings) = @_;
4208: while (my ($setting,$type) = each(%$Settings)) {
4209: next if (exists($env{'form.'.$setting}));
4210: my $envname = 'course.'.$courseid.'.internal.'.$prefix.
4211: '.'.$setting;
4212: if (exists($env{$envname})) {
4213: if ($type eq 'scalar') {
4214: $env{'form.'.$setting} = $env{$envname};
4215: } elsif ($type eq 'array') {
4216: $env{'form.'.$setting} = [
4217: map {
4218: &Apache::lonnet::unescape($_);
4219: } split(',',$env{$envname})
4220: ];
4221: }
4222: }
4223: }
4224: }
4225:
4226: ############################################################
4227: ############################################################
4228:
4229: sub propath {
4230: my ($udom,$uname)=@_;
4231: $udom=~s/\W//g;
4232: $uname=~s/\W//g;
4233: my $subdir=$uname.'__';
4234: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
4235: my $proname="$Apache::lonnet::perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
4236: return $proname;
4237: }
4238:
4239: sub icon {
4240: my ($file)=@_;
4241: my $curfext = (split(/\./,$file))[-1];
4242: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
4243: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
4244: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
4245: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
4246: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
4247: $curfext.".gif") {
4248: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
4249: $curfext.".gif";
4250: }
4251: }
4252: return &lonhttpdurl($iconname);
4253: }
4254:
4255: sub lonhttpdurl {
4256: my ($url)=@_;
4257: my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
4258: if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
4259: return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
4260: }
4261:
4262: sub connection_aborted {
4263: my ($r)=@_;
4264: $r->print(" ");$r->rflush();
4265: my $c = $r->connection;
4266: return $c->aborted();
4267: }
4268:
4269: # Escapes strings that may have embedded 's that will be put into
4270: # strings as 'strings'.
4271: sub escape_single {
4272: my ($input) = @_;
4273: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
4274: $input =~ s/\'/\\\'/g; # Esacpe the 's....
4275: return $input;
4276: }
4277:
4278: # Same as escape_single, but escape's "'s This
4279: # can be used for "strings"
4280: sub escape_double {
4281: my ($input) = @_;
4282: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
4283: $input =~ s/\"/\\\"/g; # Esacpe the "s....
4284: return $input;
4285: }
4286:
4287: # Escapes the last element of a full URL.
4288: sub escape_url {
4289: my ($url) = @_;
4290: my @urlslices = split(/\//, $url,-1);
4291: my $lastitem = &Apache::lonnet::escape(pop(@urlslices));
4292: return join('/',@urlslices).'/'.$lastitem;
4293: }
4294: =pod
4295:
4296: =back
4297:
4298: =cut
4299:
4300: 1;
4301: __END__;
4302:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>