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