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