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