1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.542 2007/07/02 15:37:15 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use HTML::Entities;
65: use Apache::lonhtmlcommon();
66: use Apache::loncoursedata();
67: use Apache::lontexconvert();
68: use Apache::lonclonecourse();
69: use LONCAPA qw(:DEFAULT :match);
70:
71: # ---------------------------------------------- Designs
72: use vars qw(%defaultdesign);
73:
74: my $readit;
75:
76:
77: ##
78: ## Global Variables
79: ##
80:
81: # ----------------------------------------------- Filetypes/Languages/Copyright
82: my %language;
83: my %supported_language;
84: my %cprtag;
85: my %scprtag;
86: my %fe; my %fd; my %fm;
87: my %category_extensions;
88:
89: # ---------------------------------------------- Thesaurus variables
90: #
91: # %Keywords:
92: # A hash used by &keyword to determine if a word is considered a keyword.
93: # $thesaurus_db_file
94: # Scalar containing the full path to the thesaurus database.
95:
96: my %Keywords;
97: my $thesaurus_db_file;
98:
99: #
100: # Initialize values from language.tab, copyright.tab, filetypes.tab,
101: # thesaurus.tab, and filecategories.tab.
102: #
103: BEGIN {
104: # Variable initialization
105: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
106: #
107: unless ($readit) {
108: # ------------------------------------------------------------------- languages
109: {
110: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
111: '/language.tab';
112: if ( open(my $fh,"<$langtabfile") ) {
113: while (my $line = <$fh>) {
114: next if ($line=~/^\#/);
115: chomp($line);
116: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
117: $language{$key}=$val.' - '.$enc;
118: if ($sup) {
119: $supported_language{$key}=$sup;
120: }
121: }
122: close($fh);
123: }
124: }
125: # ------------------------------------------------------------------ copyrights
126: {
127: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
128: '/copyright.tab';
129: if ( open (my $fh,"<$copyrightfile") ) {
130: while (my $line = <$fh>) {
131: next if ($line=~/^\#/);
132: chomp($line);
133: my ($key,$val)=(split(/\s+/,$line,2));
134: $cprtag{$key}=$val;
135: }
136: close($fh);
137: }
138: }
139: # ----------------------------------------------------------- source copyrights
140: {
141: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
142: '/source_copyright.tab';
143: if ( open (my $fh,"<$sourcecopyrightfile") ) {
144: while (my $line = <$fh>) {
145: next if ($line =~ /^\#/);
146: chomp($line);
147: my ($key,$val)=(split(/\s+/,$line,2));
148: $scprtag{$key}=$val;
149: }
150: close($fh);
151: }
152: }
153:
154: # -------------------------------------------------------------- default domain designs
155: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
156: my $designfile = $designdir.'/default.tab';
157: if ( open (my $fh,"<$designfile") ) {
158: while (my $line = <$fh>) {
159: next if ($line =~ /^\#/);
160: chomp($line);
161: my ($key,$val)=(split(/\=/,$line));
162: if ($val) { $defaultdesign{$key}=$val; }
163: }
164: close($fh);
165: }
166:
167: # ------------------------------------------------------------- file categories
168: {
169: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
170: '/filecategories.tab';
171: if ( open (my $fh,"<$categoryfile") ) {
172: while (my $line = <$fh>) {
173: next if ($line =~ /^\#/);
174: chomp($line);
175: my ($extension,$category)=(split(/\s+/,$line,2));
176: push @{$category_extensions{lc($category)}},$extension;
177: }
178: close($fh);
179: }
180:
181: }
182: # ------------------------------------------------------------------ file types
183: {
184: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
185: '/filetypes.tab';
186: if ( open (my $fh,"<$typesfile") ) {
187: while (my $line = <$fh>) {
188: next if ($line =~ /^\#/);
189: chomp($line);
190: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
191: if ($descr ne '') {
192: $fe{$ending}=lc($emb);
193: $fd{$ending}=$descr;
194: if ($mime ne 'unk') { $fm{$ending}=$mime; }
195: }
196: }
197: close($fh);
198: }
199: }
200: &Apache::lonnet::logthis(
201: "<font color=yellow>INFO: Read file types</font>");
202: $readit=1;
203: } # end of unless($readit)
204:
205: }
206:
207: ###############################################################
208: ## HTML and Javascript Helper Functions ##
209: ###############################################################
210:
211: =pod
212:
213: =head1 HTML and Javascript Functions
214:
215: =over 4
216:
217: =item * browser_and_searcher_javascript ()
218:
219: X<browsing, javascript>X<searching, javascript>Returns a string
220: containing javascript with two functions, C<openbrowser> and
221: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
222: tags.
223:
224: =item * openbrowser(formname,elementname,only,omit) [javascript]
225:
226: inputs: formname, elementname, only, omit
227:
228: formname and elementname indicate the name of the html form and name of
229: the element that the results of the browsing selection are to be placed in.
230:
231: Specifying 'only' will restrict the browser to displaying only files
232: with the given extension. Can be a comma separated list.
233:
234: Specifying 'omit' will restrict the browser to NOT displaying files
235: with the given extension. Can be a comma separated list.
236:
237: =item * opensearcher(formname, elementname) [javascript]
238:
239: Inputs: formname, elementname
240:
241: formname and elementname specify the name of the html form and the name
242: of the element the selection from the search results will be placed in.
243:
244: =cut
245:
246: sub browser_and_searcher_javascript {
247: my ($mode)=@_;
248: if (!defined($mode)) { $mode='edit'; }
249: my $resurl=&escape_single(&lastresurl());
250: return <<END;
251: // <!-- BEGIN LON-CAPA Internal
252: var editbrowser = null;
253: function openbrowser(formname,elementname,only,omit,titleelement) {
254: var url = '$resurl/?';
255: if (editbrowser == null) {
256: url += 'launch=1&';
257: }
258: url += 'catalogmode=interactive&';
259: url += 'mode=$mode&';
260: url += 'form=' + formname + '&';
261: if (only != null) {
262: url += 'only=' + only + '&';
263: } else {
264: url += 'only=&';
265: }
266: if (omit != null) {
267: url += 'omit=' + omit + '&';
268: } else {
269: url += 'omit=&';
270: }
271: if (titleelement != null) {
272: url += 'titleelement=' + titleelement + '&';
273: } else {
274: url += 'titleelement=&';
275: }
276: url += 'element=' + elementname + '';
277: var title = 'Browser';
278: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
279: options += ',width=700,height=600';
280: editbrowser = open(url,title,options,'1');
281: editbrowser.focus();
282: }
283: var editsearcher;
284: function opensearcher(formname,elementname,titleelement) {
285: var url = '/adm/searchcat?';
286: if (editsearcher == null) {
287: url += 'launch=1&';
288: }
289: url += 'catalogmode=interactive&';
290: url += 'mode=$mode&';
291: url += 'form=' + formname + '&';
292: if (titleelement != null) {
293: url += 'titleelement=' + titleelement + '&';
294: } else {
295: url += 'titleelement=&';
296: }
297: url += 'element=' + elementname + '';
298: var title = 'Search';
299: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
300: options += ',width=700,height=600';
301: editsearcher = open(url,title,options,'1');
302: editsearcher.focus();
303: }
304: // END LON-CAPA Internal -->
305: END
306: }
307:
308: sub lastresurl {
309: if ($env{'environment.lastresurl'}) {
310: return $env{'environment.lastresurl'}
311: } else {
312: return '/res';
313: }
314: }
315:
316: sub storeresurl {
317: my $resurl=&Apache::lonnet::clutter(shift);
318: unless ($resurl=~/^\/res/) { return 0; }
319: $resurl=~s/\/$//;
320: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
321: &Apache::lonnet::appenv('environment.lastresurl' => $resurl);
322: return 1;
323: }
324:
325: sub studentbrowser_javascript {
326: unless (
327: (($env{'request.course.id'}) &&
328: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
329: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
330: '/'.$env{'request.course.sec'})
331: ))
332: || ($env{'request.role'}=~/^(au|dc|su)/)
333: ) { return ''; }
334: return (<<'ENDSTDBRW');
335: <script type="text/javascript" language="Javascript" >
336: var stdeditbrowser;
337: function openstdbrowser(formname,uname,udom,roleflag) {
338: var url = '/adm/pickstudent?';
339: var filter;
340: eval('filter=document.'+formname+'.'+uname+'.value;');
341: if (filter != null) {
342: if (filter != '') {
343: url += 'filter='+filter+'&';
344: }
345: }
346: url += 'form=' + formname + '&unameelement='+uname+
347: '&udomelement='+udom;
348: if (roleflag) { url+="&roles=1"; }
349: var title = 'Student_Browser';
350: var options = 'scrollbars=1,resizable=1,menubar=0';
351: options += ',width=700,height=600';
352: stdeditbrowser = open(url,title,options,'1');
353: stdeditbrowser.focus();
354: }
355: </script>
356: ENDSTDBRW
357: }
358:
359: sub selectstudent_link {
360: my ($form,$unameele,$udomele)=@_;
361: if ($env{'request.course.id'}) {
362: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
363: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
364: '/'.$env{'request.course.sec'})) {
365: return '';
366: }
367: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
368: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
369: }
370: if ($env{'request.role'}=~/^(au|dc|su)/) {
371: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
372: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
373: }
374: return '';
375: }
376:
377: sub coursebrowser_javascript {
378: my ($domainfilter,$sec_element,$formname)=@_;
379: 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');
380: my $output = '
381: <script type="text/javascript">
382: var stdeditbrowser;'."\n";
383: $output .= <<"ENDSTDBRW";
384: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
385: var url = '/adm/pickcourse?';
386: var domainfilter = '';
387: var formid = getFormIdByName(formname);
388: if (formid > -1) {
389: var domid = getIndexByName(formid,udom);
390: if (domid > -1) {
391: if (document.forms[formid].elements[domid].type == 'select-one') {
392: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
393: }
394: if (document.forms[formid].elements[domid].type == 'hidden') {
395: domainfilter=document.forms[formid].elements[domid].value;
396: }
397: }
398: }
399: if (domainfilter != null) {
400: if (domainfilter != '') {
401: url += 'domainfilter='+domainfilter+'&';
402: }
403: }
404: url += 'form=' + formname + '&cnumelement='+uname+
405: '&cdomelement='+udom+
406: '&cnameelement='+desc;
407: if (extra_element !=null && extra_element != '') {
408: if (formname == 'rolechoice') {
409: url += '&roleelement='+extra_element;
410: if (domainfilter == null || domainfilter == '') {
411: url += '&domainfilter='+extra_element;
412: }
413: }
414: else {
415: if (formname == 'portform') {
416: url += '&setroles='+extra_element;
417: }
418: }
419: }
420: if (multflag !=null && multflag != '') {
421: url += '&multiple='+multflag;
422: }
423: if (crstype == 'Course/Group') {
424: if (formname == 'cu') {
425: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
426: if (crstype == "") {
427: alert("$crs_or_grp_alert");
428: return;
429: }
430: }
431: }
432: if (crstype !=null && crstype != '') {
433: url += '&type='+crstype;
434: }
435: var title = 'Course_Browser';
436: var options = 'scrollbars=1,resizable=1,menubar=0';
437: options += ',width=700,height=600';
438: stdeditbrowser = open(url,title,options,'1');
439: stdeditbrowser.focus();
440: }
441:
442: function getFormIdByName(formname) {
443: for (var i=0;i<document.forms.length;i++) {
444: if (document.forms[i].name == formname) {
445: return i;
446: }
447: }
448: return -1;
449: }
450:
451: function getIndexByName(formid,item) {
452: for (var i=0;i<document.forms[formid].elements.length;i++) {
453: if (document.forms[formid].elements[i].name == item) {
454: return i;
455: }
456: }
457: return -1;
458: }
459: ENDSTDBRW
460: if ($sec_element ne '') {
461: $output .= &setsec_javascript($sec_element,$formname);
462: }
463: $output .= '
464: </script>';
465: return $output;
466: }
467:
468: sub setsec_javascript {
469: my ($sec_element,$formname) = @_;
470: my $setsections = qq|
471: function setSect(sectionlist) {
472: var sectionsArray = sectionlist.split(",");
473: var numSections = sectionsArray.length;
474: document.$formname.$sec_element.length = 0;
475: if (numSections == 0) {
476: document.$formname.$sec_element.multiple=false;
477: document.$formname.$sec_element.size=1;
478: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
479: } else {
480: if (numSections == 1) {
481: document.$formname.$sec_element.multiple=false;
482: document.$formname.$sec_element.size=1;
483: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
484: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
485: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
486: } else {
487: for (var i=0; i<numSections; i++) {
488: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
489: }
490: document.$formname.$sec_element.multiple=true
491: if (numSections < 3) {
492: document.$formname.$sec_element.size=numSections;
493: } else {
494: document.$formname.$sec_element.size=3;
495: }
496: document.$formname.$sec_element.options[0].selected = false
497: }
498: }
499: }
500: |;
501: return $setsections;
502: }
503:
504:
505: sub selectcourse_link {
506: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
507: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
508: '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
509: }
510:
511: sub check_uncheck_jscript {
512: my $jscript = <<"ENDSCRT";
513: function checkAll(field) {
514: if (field.length > 0) {
515: for (i = 0; i < field.length; i++) {
516: field[i].checked = true ;
517: }
518: } else {
519: field.checked = true
520: }
521: }
522:
523: function uncheckAll(field) {
524: if (field.length > 0) {
525: for (i = 0; i < field.length; i++) {
526: field[i].checked = false ;
527: } } else {
528: field.checked = false ;
529: }
530: }
531: ENDSCRT
532: return $jscript;
533: }
534:
535:
536: =pod
537:
538: =item * linked_select_forms(...)
539:
540: linked_select_forms returns a string containing a <script></script> block
541: and html for two <select> menus. The select menus will be linked in that
542: changing the value of the first menu will result in new values being placed
543: in the second menu. The values in the select menu will appear in alphabetical
544: order.
545:
546: linked_select_forms takes the following ordered inputs:
547:
548: =over 4
549:
550: =item * $formname, the name of the <form> tag
551:
552: =item * $middletext, the text which appears between the <select> tags
553:
554: =item * $firstdefault, the default value for the first menu
555:
556: =item * $firstselectname, the name of the first <select> tag
557:
558: =item * $secondselectname, the name of the second <select> tag
559:
560: =item * $hashref, a reference to a hash containing the data for the menus.
561:
562: =back
563:
564: Below is an example of such a hash. Only the 'text', 'default', and
565: 'select2' keys must appear as stated. keys(%menu) are the possible
566: values for the first select menu. The text that coincides with the
567: first menu value is given in $menu{$choice1}->{'text'}. The values
568: and text for the second menu are given in the hash pointed to by
569: $menu{$choice1}->{'select2'}.
570:
571: my %menu = ( A1 => { text =>"Choice A1" ,
572: default => "B3",
573: select2 => {
574: B1 => "Choice B1",
575: B2 => "Choice B2",
576: B3 => "Choice B3",
577: B4 => "Choice B4"
578: }
579: },
580: A2 => { text =>"Choice A2" ,
581: default => "C2",
582: select2 => {
583: C1 => "Choice C1",
584: C2 => "Choice C2",
585: C3 => "Choice C3"
586: }
587: },
588: A3 => { text =>"Choice A3" ,
589: default => "D6",
590: select2 => {
591: D1 => "Choice D1",
592: D2 => "Choice D2",
593: D3 => "Choice D3",
594: D4 => "Choice D4",
595: D5 => "Choice D5",
596: D6 => "Choice D6",
597: D7 => "Choice D7"
598: }
599: }
600: );
601:
602: =cut
603:
604: sub linked_select_forms {
605: my ($formname,
606: $middletext,
607: $firstdefault,
608: $firstselectname,
609: $secondselectname,
610: $hashref
611: ) = @_;
612: my $second = "document.$formname.$secondselectname";
613: my $first = "document.$formname.$firstselectname";
614: # output the javascript to do the changing
615: my $result = '';
616: $result.="<script type=\"text/javascript\">\n";
617: $result.="var select2data = new Object();\n";
618: $" = '","';
619: my $debug = '';
620: foreach my $s1 (sort(keys(%$hashref))) {
621: $result.="select2data.d_$s1 = new Object();\n";
622: $result.="select2data.d_$s1.def = new String('".
623: $hashref->{$s1}->{'default'}."');\n";
624: $result.="select2data.d_$s1.values = new Array(";
625: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
626: $result.="\"@s2values\");\n";
627: $result.="select2data.d_$s1.texts = new Array(";
628: my @s2texts;
629: foreach my $value (@s2values) {
630: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
631: }
632: $result.="\"@s2texts\");\n";
633: }
634: $"=' ';
635: $result.= <<"END";
636:
637: function select1_changed() {
638: // Determine new choice
639: var newvalue = "d_" + $first.value;
640: // update select2
641: var values = select2data[newvalue].values;
642: var texts = select2data[newvalue].texts;
643: var select2def = select2data[newvalue].def;
644: var i;
645: // out with the old
646: for (i = 0; i < $second.options.length; i++) {
647: $second.options[i] = null;
648: }
649: // in with the nuclear
650: for (i=0;i<values.length; i++) {
651: $second.options[i] = new Option(values[i]);
652: $second.options[i].value = values[i];
653: $second.options[i].text = texts[i];
654: if (values[i] == select2def) {
655: $second.options[i].selected = true;
656: }
657: }
658: }
659: </script>
660: END
661: # output the initial values for the selection lists
662: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
663: foreach my $value (sort(keys(%$hashref))) {
664: $result.=" <option value=\"$value\" ";
665: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
666: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
667: }
668: $result .= "</select>\n";
669: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
670: $result .= $middletext;
671: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
672: my $seconddefault = $hashref->{$firstdefault}->{'default'};
673: foreach my $value (sort(keys(%select2))) {
674: $result.=" <option value=\"$value\" ";
675: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
676: $result.=">".&mt($select2{$value})."</option>\n";
677: }
678: $result .= "</select>\n";
679: # return $debug;
680: return $result;
681: } # end of sub linked_select_forms {
682:
683: =pod
684:
685: =item * help_open_topic($topic, $text, $stayOnPage, $width, $height)
686:
687: Returns a string corresponding to an HTML link to the given help
688: $topic, where $topic corresponds to the name of a .tex file in
689: /home/httpd/html/adm/help/tex, with underscores replaced by
690: spaces.
691:
692: $text will optionally be linked to the same topic, allowing you to
693: link text in addition to the graphic. If you do not want to link
694: text, but wish to specify one of the later parameters, pass an
695: empty string.
696:
697: $stayOnPage is a value that will be interpreted as a boolean. If true,
698: the link will not open a new window. If false, the link will open
699: a new window using Javascript. (Default is false.)
700:
701: $width and $height are optional numerical parameters that will
702: override the width and height of the popped up window, which may
703: be useful for certain help topics with big pictures included.
704:
705: =cut
706:
707: sub help_open_topic {
708: my ($topic, $text, $stayOnPage, $width, $height) = @_;
709: $text = "" if (not defined $text);
710: $stayOnPage = 0 if (not defined $stayOnPage);
711: if ($env{'browser.interface'} eq 'textual' ||
712: $env{'environment.remote'} eq 'off' ) {
713: $stayOnPage=1;
714: }
715: $width = 350 if (not defined $width);
716: $height = 400 if (not defined $height);
717: my $filename = $topic;
718: $filename =~ s/ /_/g;
719:
720: my $template = "";
721: my $link;
722:
723: $topic=~s/\W/\_/g;
724:
725: if (!$stayOnPage)
726: {
727: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
728: }
729: else
730: {
731: $link = "/adm/help/${filename}.hlp";
732: }
733:
734: # Add the text
735: if ($text ne "")
736: {
737: $template .=
738: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
739: "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
740: }
741:
742: # Add the graphic
743: my $title = &mt('Online Help');
744: my $helpicon=&lonhttpdurl("/adm/help/gif/smallHelp.gif");
745: $template .= <<"ENDTEMPLATE";
746: <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
747: ENDTEMPLATE
748: if ($text ne '') { $template.='</td></tr></table>' };
749: return $template;
750:
751: }
752:
753: # This is a quicky function for Latex cheatsheet editing, since it
754: # appears in at least four places
755: sub helpLatexCheatsheet {
756: my $other = shift;
757: my $addOther = '';
758: if ($other) {
759: $addOther = Apache::loncommon::help_open_topic($other, shift,
760: undef, undef, 600) .
761: '</td><td>';
762: }
763: return '<table><tr><td>'.
764: $addOther .
765: &Apache::loncommon::help_open_topic("Greek_Symbols",'Greek Symbols',
766: undef,undef,600)
767: .'</td><td>'.
768: &Apache::loncommon::help_open_topic("Other_Symbols",'Other Symbols',
769: undef,undef,600)
770: .'</td></tr></table>';
771: }
772:
773: sub general_help {
774: my $helptopic='Student_Intro';
775: if ($env{'request.role'}=~/^(ca|au)/) {
776: $helptopic='Authoring_Intro';
777: } elsif ($env{'request.role'}=~/^cc/) {
778: $helptopic='Course_Coordination_Intro';
779: }
780: return $helptopic;
781: }
782:
783: sub update_help_link {
784: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
785: my $origurl = $ENV{'REQUEST_URI'};
786: $origurl=~s|^/~|/priv/|;
787: my $timestamp = time;
788: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
789: $$datum = &escape($$datum);
790: }
791:
792: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
793: my $output .= <<"ENDOUTPUT";
794: <script type="text/javascript">
795: banner_link = '$banner_link';
796: </script>
797: ENDOUTPUT
798: return $output;
799: }
800:
801: # now just updates the help link and generates a blue icon
802: sub help_open_menu {
803: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
804: = @_;
805:
806: $stayOnPage = 0 if (not defined $stayOnPage);
807: if ($env{'browser.interface'} eq 'textual' ||
808: $env{'environment.remote'} eq 'off' ) {
809: $stayOnPage=1;
810: }
811: my $output;
812: if ($component_help) {
813: if (!$text) {
814: $output=&help_open_topic($component_help,undef,$stayOnPage,
815: $width,$height);
816: } else {
817: my $help_text;
818: $help_text=&unescape($topic);
819: $output='<table><tr><td>'.
820: &help_open_topic($component_help,$help_text,$stayOnPage,
821: $width,$height).'</td></tr></table>';
822: }
823: }
824: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
825: return $output.$banner_link;
826: }
827:
828: sub top_nav_help {
829: my ($text) = @_;
830:
831: $text = &mt($text);
832:
833: my $stayOnPage =
834: ($env{'browser.interface'} eq 'textual' ||
835: $env{'environment.remote'} eq 'off' );
836: my $link= ($stayOnPage) ? "javascript:helpMenu('display')"
837: : "javascript:helpMenu('open')";
838: my $banner_link = &update_help_link(undef,undef,undef,undef,$stayOnPage);
839:
840: my $title = &mt('Get help');
841:
842: return <<"END";
843: $banner_link
844: <a href="$link" title="$title">$text</a>
845: END
846: }
847:
848: sub help_menu_js {
849: my ($text) = @_;
850:
851: my $stayOnPage =
852: ($env{'browser.interface'} eq 'textual' ||
853: $env{'environment.remote'} eq 'off' );
854:
855: my $width = 620;
856: my $height = 600;
857: my $helptopic=&general_help();
858: my $details_link = '/adm/help/'.$helptopic.'.hlp';
859: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
860: my $start_page =
861: &Apache::loncommon::start_page('Help Menu', undef,
862: {'frameset' => 1,
863: 'js_ready' => 1,
864: 'add_entries' => {
865: 'border' => '0',
866: 'rows' => "105,*",},});
867: my $end_page =
868: &Apache::loncommon::end_page({'frameset' => 1,
869: 'js_ready' => 1,});
870:
871: my $template .= <<"ENDTEMPLATE";
872: <script type="text/javascript">
873: // <!-- BEGIN LON-CAPA Internal
874: // <![CDATA[
875: var banner_link = '';
876: function helpMenu(target) {
877: var caller = this;
878: if (target == 'open') {
879: var newWindow = null;
880: try {
881: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
882: }
883: catch(error) {
884: writeHelp(caller);
885: return;
886: }
887: if (newWindow) {
888: caller = newWindow;
889: }
890: }
891: writeHelp(caller);
892: return;
893: }
894: function writeHelp(caller) {
895: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
896: caller.document.close()
897: caller.focus()
898: }
899: // ]]>
900: // END LON-CAPA Internal -->
901: </script>
902: ENDTEMPLATE
903: return $template;
904: }
905:
906: sub help_open_bug {
907: my ($topic, $text, $stayOnPage, $width, $height) = @_;
908: unless ($env{'user.adv'}) { return ''; }
909: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
910: $text = "" if (not defined $text);
911: $stayOnPage = 0 if (not defined $stayOnPage);
912: if ($env{'browser.interface'} eq 'textual' ||
913: $env{'environment.remote'} eq 'off' ) {
914: $stayOnPage=1;
915: }
916: $width = 600 if (not defined $width);
917: $height = 600 if (not defined $height);
918:
919: $topic=~s/\W+/\+/g;
920: my $link='';
921: my $template='';
922: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
923: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
924: if (!$stayOnPage)
925: {
926: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
927: }
928: else
929: {
930: $link = $url;
931: }
932: # Add the text
933: if ($text ne "")
934: {
935: $template .=
936: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
937: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
938: }
939:
940: # Add the graphic
941: my $title = &mt('Report a Bug');
942: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
943: $template .= <<"ENDTEMPLATE";
944: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
945: ENDTEMPLATE
946: if ($text ne '') { $template.='</td></tr></table>' };
947: return $template;
948:
949: }
950:
951: sub help_open_faq {
952: my ($topic, $text, $stayOnPage, $width, $height) = @_;
953: unless ($env{'user.adv'}) { return ''; }
954: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
955: $text = "" if (not defined $text);
956: $stayOnPage = 0 if (not defined $stayOnPage);
957: if ($env{'browser.interface'} eq 'textual' ||
958: $env{'environment.remote'} eq 'off' ) {
959: $stayOnPage=1;
960: }
961: $width = 350 if (not defined $width);
962: $height = 400 if (not defined $height);
963:
964: $topic=~s/\W+/\+/g;
965: my $link='';
966: my $template='';
967: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
968: if (!$stayOnPage)
969: {
970: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
971: }
972: else
973: {
974: $link = $url;
975: }
976:
977: # Add the text
978: if ($text ne "")
979: {
980: $template .=
981: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
982: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
983: }
984:
985: # Add the graphic
986: my $title = &mt('View the FAQ');
987: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
988: $template .= <<"ENDTEMPLATE";
989: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
990: ENDTEMPLATE
991: if ($text ne '') { $template.='</td></tr></table>' };
992: return $template;
993:
994: }
995:
996: ###############################################################
997: ###############################################################
998:
999: =pod
1000:
1001: =item * change_content_javascript():
1002:
1003: This and the next function allow you to create small sections of an
1004: otherwise static HTML page that you can update on the fly with
1005: Javascript, even in Netscape 4.
1006:
1007: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1008: must be written to the HTML page once. It will prove the Javascript
1009: function "change(name, content)". Calling the change function with the
1010: name of the section
1011: you want to update, matching the name passed to C<changable_area>, and
1012: the new content you want to put in there, will put the content into
1013: that area.
1014:
1015: B<Note>: Netscape 4 only reserves enough space for the changable area
1016: to contain room for the original contents. You need to "make space"
1017: for whatever changes you wish to make, and be B<sure> to check your
1018: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1019: it's adequate for updating a one-line status display, but little more.
1020: This script will set the space to 100% width, so you only need to
1021: worry about height in Netscape 4.
1022:
1023: Modern browsers are much less limiting, and if you can commit to the
1024: user not using Netscape 4, this feature may be used freely with
1025: pretty much any HTML.
1026:
1027: =cut
1028:
1029: sub change_content_javascript {
1030: # If we're on Netscape 4, we need to use Layer-based code
1031: if ($env{'browser.type'} eq 'netscape' &&
1032: $env{'browser.version'} =~ /^4\./) {
1033: return (<<NETSCAPE4);
1034: function change(name, content) {
1035: doc = document.layers[name+"___escape"].layers[0].document;
1036: doc.open();
1037: doc.write(content);
1038: doc.close();
1039: }
1040: NETSCAPE4
1041: } else {
1042: # Otherwise, we need to use semi-standards-compliant code
1043: # (technically, "innerHTML" isn't standard but the equivalent
1044: # is really scary, and every useful browser supports it
1045: return (<<DOMBASED);
1046: function change(name, content) {
1047: element = document.getElementById(name);
1048: element.innerHTML = content;
1049: }
1050: DOMBASED
1051: }
1052: }
1053:
1054: =pod
1055:
1056: =item * changable_area($name, $origContent):
1057:
1058: This provides a "changable area" that can be modified on the fly via
1059: the Javascript code provided in C<change_content_javascript>. $name is
1060: the name you will use to reference the area later; do not repeat the
1061: same name on a given HTML page more then once. $origContent is what
1062: the area will originally contain, which can be left blank.
1063:
1064: =cut
1065:
1066: sub changable_area {
1067: my ($name, $origContent) = @_;
1068:
1069: if ($env{'browser.type'} eq 'netscape' &&
1070: $env{'browser.version'} =~ /^4\./) {
1071: # If this is netscape 4, we need to use the Layer tag
1072: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1073: } else {
1074: return "<span id='$name'>$origContent</span>";
1075: }
1076: }
1077:
1078: =pod
1079:
1080: =back
1081:
1082: =head1 Excel and CSV file utility routines
1083:
1084: =over 4
1085:
1086: =cut
1087:
1088: ###############################################################
1089: ###############################################################
1090:
1091: =pod
1092:
1093: =item * csv_translate($text)
1094:
1095: Translate $text to allow it to be output as a 'comma separated values'
1096: format.
1097:
1098: =cut
1099:
1100: ###############################################################
1101: ###############################################################
1102: sub csv_translate {
1103: my $text = shift;
1104: $text =~ s/\"/\"\"/g;
1105: $text =~ s/\n/ /g;
1106: return $text;
1107: }
1108:
1109: ###############################################################
1110: ###############################################################
1111:
1112: =pod
1113:
1114: =item * define_excel_formats
1115:
1116: Define some commonly used Excel cell formats.
1117:
1118: Currently supported formats:
1119:
1120: =over 4
1121:
1122: =item header
1123:
1124: =item bold
1125:
1126: =item h1
1127:
1128: =item h2
1129:
1130: =item h3
1131:
1132: =item h4
1133:
1134: =item i
1135:
1136: =item date
1137:
1138: =back
1139:
1140: Inputs: $workbook
1141:
1142: Returns: $format, a hash reference.
1143:
1144: =cut
1145:
1146: ###############################################################
1147: ###############################################################
1148: sub define_excel_formats {
1149: my ($workbook) = @_;
1150: my $format;
1151: $format->{'header'} = $workbook->add_format(bold => 1,
1152: bottom => 1,
1153: align => 'center');
1154: $format->{'bold'} = $workbook->add_format(bold=>1);
1155: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1156: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1157: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1158: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1159: $format->{'i'} = $workbook->add_format(italic=>1);
1160: $format->{'date'} = $workbook->add_format(num_format=>
1161: 'mm/dd/yyyy hh:mm:ss');
1162: return $format;
1163: }
1164:
1165: ###############################################################
1166: ###############################################################
1167:
1168: =pod
1169:
1170: =item * create_workbook
1171:
1172: Create an Excel worksheet. If it fails, output message on the
1173: request object and return undefs.
1174:
1175: Inputs: Apache request object
1176:
1177: Returns (undef) on failure,
1178: Excel worksheet object, scalar with filename, and formats
1179: from &Apache::loncommon::define_excel_formats on success
1180:
1181: =cut
1182:
1183: ###############################################################
1184: ###############################################################
1185: sub create_workbook {
1186: my ($r) = @_;
1187: #
1188: # Create the excel spreadsheet
1189: my $filename = '/prtspool/'.
1190: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1191: time.'_'.rand(1000000000).'.xls';
1192: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1193: if (! defined($workbook)) {
1194: $r->log_error("Error creating excel spreadsheet $filename: $!");
1195: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1196: "This error has been logged. ".
1197: "Please alert your LON-CAPA administrator").
1198: '</p>');
1199: return (undef);
1200: }
1201: #
1202: $workbook->set_tempdir('/home/httpd/perl/tmp');
1203: #
1204: my $format = &Apache::loncommon::define_excel_formats($workbook);
1205: return ($workbook,$filename,$format);
1206: }
1207:
1208: ###############################################################
1209: ###############################################################
1210:
1211: =pod
1212:
1213: =item * create_text_file
1214:
1215: Create a file to write to and eventually make available to the user.
1216: If file creation fails, outputs an error message on the request object and
1217: return undefs.
1218:
1219: Inputs: Apache request object, and file suffix
1220:
1221: Returns (undef) on failure,
1222: Filehandle and filename on success.
1223:
1224: =cut
1225:
1226: ###############################################################
1227: ###############################################################
1228: sub create_text_file {
1229: my ($r,$suffix) = @_;
1230: if (! defined($suffix)) { $suffix = 'txt'; };
1231: my $fh;
1232: my $filename = '/prtspool/'.
1233: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1234: time.'_'.rand(1000000000).'.'.$suffix;
1235: $fh = Apache::File->new('>/home/httpd'.$filename);
1236: if (! defined($fh)) {
1237: $r->log_error("Couldn't open $filename for output $!");
1238: $r->print("Problems occured in creating the output file. ".
1239: "This error has been logged. ".
1240: "Please alert your LON-CAPA administrator.");
1241: }
1242: return ($fh,$filename)
1243: }
1244:
1245:
1246: =pod
1247:
1248: =back
1249:
1250: =cut
1251:
1252: ###############################################################
1253: ## Home server <option> list generating code ##
1254: ###############################################################
1255:
1256: # ------------------------------------------
1257:
1258: sub domain_select {
1259: my ($name,$value,$multiple)=@_;
1260: my %domains=map {
1261: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1262: } &Apache::lonnet::all_domains();
1263: if ($multiple) {
1264: $domains{''}=&mt('Any domain');
1265: return &multiple_select_form($name,$value,4,\%domains);
1266: } else {
1267: return &select_form($name,$value,%domains);
1268: }
1269: }
1270:
1271: #-------------------------------------------
1272:
1273: =pod
1274:
1275: =head1 Routines for form select boxes
1276:
1277: =over 4
1278:
1279: =cut
1280:
1281: =item * multiple_select_form($name,$value,$size,$hash,$order)
1282:
1283: Returns a string containing a <select> element int multiple mode
1284:
1285:
1286: Args:
1287: $name - name of the <select> element
1288: $value - scalar or array ref of values that should already be selected
1289: $size - number of rows long the select element is
1290: $hash - the elements should be 'option' => 'shown text'
1291: (shown text should already have been &mt())
1292: $order - (optional) array ref of the order to show the elements in
1293:
1294: =cut
1295:
1296: #-------------------------------------------
1297: sub multiple_select_form {
1298: my ($name,$value,$size,$hash,$order)=@_;
1299: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1300: my $output='';
1301: if (! defined($size)) {
1302: $size = 4;
1303: if (scalar(keys(%$hash))<4) {
1304: $size = scalar(keys(%$hash));
1305: }
1306: }
1307: $output.="\n<select name='$name' size='$size' multiple='1'>";
1308: my @order;
1309: if (ref($order) eq 'ARRAY') {
1310: @order = @{$order};
1311: } else {
1312: @order = sort(keys(%$hash));
1313: }
1314: if (exists($$hash{'select_form_order'})) {
1315: @order = @{$$hash{'select_form_order'}};
1316: }
1317:
1318: foreach my $key (@order) {
1319: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1320: $output.='selected="selected" ' if ($selected{$key});
1321: $output.='>'.$hash->{$key}."</option>\n";
1322: }
1323: $output.="</select>\n";
1324: return $output;
1325: }
1326:
1327: #-------------------------------------------
1328:
1329: =pod
1330:
1331: =item * select_form($defdom,$name,%hash)
1332:
1333: Returns a string containing a <select name='$name' size='1'> form to
1334: allow a user to select options from a hash option_name => displayed text.
1335: See lonrights.pm for an example invocation and use.
1336:
1337: =cut
1338:
1339: #-------------------------------------------
1340: sub select_form {
1341: my ($def,$name,%hash) = @_;
1342: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1343: my @keys;
1344: if (exists($hash{'select_form_order'})) {
1345: @keys=@{$hash{'select_form_order'}};
1346: } else {
1347: @keys=sort(keys(%hash));
1348: }
1349: foreach my $key (@keys) {
1350: $selectform.=
1351: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1352: ($key eq $def ? 'selected="selected" ' : '').
1353: ">".&mt($hash{$key})."</option>\n";
1354: }
1355: $selectform.="</select>";
1356: return $selectform;
1357: }
1358:
1359: # For display filters
1360:
1361: sub display_filter {
1362: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1363: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1364: return '<nobr><label>'.&mt('Records [_1]',
1365: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1366: (&mt('all'),10,20,50,100,1000,10000))).
1367: '</label></nobr> <nobr>'.
1368: &mt('Filter [_1]',
1369: &select_form($env{'form.displayfilter'},
1370: 'displayfilter',
1371: ('currentfolder' => 'Current folder/page',
1372: 'containing' => 'Containing phrase',
1373: 'none' => 'None'))).
1374: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1375: }
1376:
1377: sub gradeleveldescription {
1378: my $gradelevel=shift;
1379: my %gradelevels=(0 => 'Not specified',
1380: 1 => 'Grade 1',
1381: 2 => 'Grade 2',
1382: 3 => 'Grade 3',
1383: 4 => 'Grade 4',
1384: 5 => 'Grade 5',
1385: 6 => 'Grade 6',
1386: 7 => 'Grade 7',
1387: 8 => 'Grade 8',
1388: 9 => 'Grade 9',
1389: 10 => 'Grade 10',
1390: 11 => 'Grade 11',
1391: 12 => 'Grade 12',
1392: 13 => 'Grade 13',
1393: 14 => '100 Level',
1394: 15 => '200 Level',
1395: 16 => '300 Level',
1396: 17 => '400 Level',
1397: 18 => 'Graduate Level');
1398: return &mt($gradelevels{$gradelevel});
1399: }
1400:
1401: sub select_level_form {
1402: my ($deflevel,$name)=@_;
1403: unless ($deflevel) { $deflevel=0; }
1404: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1405: for (my $i=0; $i<=18; $i++) {
1406: $selectform.="<option value=\"$i\" ".
1407: ($i==$deflevel ? 'selected="selected" ' : '').
1408: ">".&gradeleveldescription($i)."</option>\n";
1409: }
1410: $selectform.="</select>";
1411: return $selectform;
1412: }
1413:
1414: #-------------------------------------------
1415:
1416: =pod
1417:
1418: =item * select_dom_form($defdom,$name,$includeempty)
1419:
1420: Returns a string containing a <select name='$name' size='1'> form to
1421: allow a user to select the domain to preform an operation in.
1422: See loncreateuser.pm for an example invocation and use.
1423:
1424: If the $includeempty flag is set, it also includes an empty choice ("no domain
1425: selected");
1426:
1427: =cut
1428:
1429: #-------------------------------------------
1430: sub select_dom_form {
1431: my ($defdom,$name,$includeempty) = @_;
1432: my @domains = sort(&Apache::lonnet::all_domains());
1433: if ($includeempty) { @domains=('',@domains); }
1434: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1435: foreach my $dom (@domains) {
1436: $selectdomain.="<option value=\"$dom\" ".
1437: ($dom eq $defdom ? 'selected="selected" ' : '').
1438: ">$dom</option>\n";
1439: }
1440: $selectdomain.="</select>";
1441: return $selectdomain;
1442: }
1443:
1444: #-------------------------------------------
1445:
1446: =pod
1447:
1448: =item * home_server_option_list($domain)
1449:
1450: returns a string which contains an <option> list to be used in a
1451: <select> form input. See loncreateuser.pm for an example.
1452:
1453: =cut
1454:
1455: #-------------------------------------------
1456: sub home_server_option_list {
1457: my $domain = shift;
1458: my %servers = &Apache::lonnet::get_servers($domain,'library');
1459: my $result = '';
1460: foreach my $hostid (sort(keys(%servers))) {
1461: $result.=
1462: '<option value="'.$hostid.'">'.
1463: $hostid.' '.$servers{$hostid}."</option>\n";
1464: }
1465: return $result;
1466: }
1467:
1468: =pod
1469:
1470: =back
1471:
1472: =cut
1473:
1474: ###############################################################
1475: ## Decoding User Agent ##
1476: ###############################################################
1477:
1478: =pod
1479:
1480: =head1 Decoding the User Agent
1481:
1482: =over 4
1483:
1484: =item * &decode_user_agent()
1485:
1486: Inputs: $r
1487:
1488: Outputs:
1489:
1490: =over 4
1491:
1492: =item * $httpbrowser
1493:
1494: =item * $clientbrowser
1495:
1496: =item * $clientversion
1497:
1498: =item * $clientmathml
1499:
1500: =item * $clientunicode
1501:
1502: =item * $clientos
1503:
1504: =back
1505:
1506: =back
1507:
1508: =cut
1509:
1510: ###############################################################
1511: ###############################################################
1512: sub decode_user_agent {
1513: my ($r)=@_;
1514: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1515: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1516: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1517: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1518: my $clientbrowser='unknown';
1519: my $clientversion='0';
1520: my $clientmathml='';
1521: my $clientunicode='0';
1522: for (my $i=0;$i<=$#browsertype;$i++) {
1523: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1524: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1525: $clientbrowser=$bname;
1526: $httpbrowser=~/$vreg/i;
1527: $clientversion=$1;
1528: $clientmathml=($clientversion>=$minv);
1529: $clientunicode=($clientversion>=$univ);
1530: }
1531: }
1532: my $clientos='unknown';
1533: if (($httpbrowser=~/linux/i) ||
1534: ($httpbrowser=~/unix/i) ||
1535: ($httpbrowser=~/ux/i) ||
1536: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1537: if (($httpbrowser=~/vax/i) ||
1538: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1539: if ($httpbrowser=~/next/i) { $clientos='next'; }
1540: if (($httpbrowser=~/mac/i) ||
1541: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1542: if ($httpbrowser=~/win/i) { $clientos='win'; }
1543: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1544: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1545: $clientunicode,$clientos,);
1546: }
1547:
1548: ###############################################################
1549: ## Authentication changing form generation subroutines ##
1550: ###############################################################
1551: ##
1552: ## All of the authform_xxxxxxx subroutines take their inputs in a
1553: ## hash, and have reasonable default values.
1554: ##
1555: ## formname = the name given in the <form> tag.
1556: #-------------------------------------------
1557:
1558: =pod
1559:
1560: =head1 Authentication Routines
1561:
1562: =over 4
1563:
1564: =item * authform_xxxxxx
1565:
1566: The authform_xxxxxx subroutines provide javascript and html forms which
1567: handle some of the conveniences required for authentication forms.
1568: This is not an optimal method, but it works.
1569:
1570: See loncreateuser.pm for invocation and use examples.
1571:
1572: =over 4
1573:
1574: =item * authform_header
1575:
1576: =item * authform_authorwarning
1577:
1578: =item * authform_nochange
1579:
1580: =item * authform_kerberos
1581:
1582: =item * authform_internal
1583:
1584: =item * authform_filesystem
1585:
1586: =back
1587:
1588: =back
1589:
1590: =cut
1591:
1592: #-------------------------------------------
1593: sub authform_header{
1594: my %in = (
1595: formname => 'cu',
1596: kerb_def_dom => '',
1597: @_,
1598: );
1599: $in{'formname'} = 'document.' . $in{'formname'};
1600: my $result='';
1601:
1602: #---------------------------------------------- Code for upper case translation
1603: my $Javascript_toUpperCase;
1604: unless ($in{kerb_def_dom}) {
1605: $Javascript_toUpperCase =<<"END";
1606: switch (choice) {
1607: case 'krb': currentform.elements[choicearg].value =
1608: currentform.elements[choicearg].value.toUpperCase();
1609: break;
1610: default:
1611: }
1612: END
1613: } else {
1614: $Javascript_toUpperCase = "";
1615: }
1616:
1617: my $radioval = "'nochange'";
1618: if (exists($in{'curr_authtype'}) &&
1619: defined($in{'curr_authtype'}) &&
1620: $in{'curr_authtype'} ne '') {
1621: $radioval = "'$in{'curr_authtype'}arg'";
1622: }
1623: my $argfield = 'null';
1624: if ( grep/^mode$/,(keys %in) ) {
1625: if ($in{'mode'} eq 'modifycourse') {
1626: if ( grep/^curr_authtype$/,(keys %in) ) {
1627: $radioval = "'$in{'curr_authtype'}'";
1628: }
1629: if ( grep/^curr_autharg$/,(keys %in) ) {
1630: unless ($in{'curr_autharg'} eq '') {
1631: $argfield = "'$in{'curr_autharg'}'";
1632: }
1633: }
1634: }
1635: }
1636:
1637: $result.=<<"END";
1638: var current = new Object();
1639: current.radiovalue = $radioval;
1640: current.argfield = $argfield;
1641:
1642: function changed_radio(choice,currentform) {
1643: var choicearg = choice + 'arg';
1644: // If a radio button in changed, we need to change the argfield
1645: if (current.radiovalue != choice) {
1646: current.radiovalue = choice;
1647: if (current.argfield != null) {
1648: currentform.elements[current.argfield].value = '';
1649: }
1650: if (choice == 'nochange') {
1651: current.argfield = null;
1652: } else {
1653: current.argfield = choicearg;
1654: switch(choice) {
1655: case 'krb':
1656: currentform.elements[current.argfield].value =
1657: "$in{'kerb_def_dom'}";
1658: break;
1659: default:
1660: break;
1661: }
1662: }
1663: }
1664: return;
1665: }
1666:
1667: function changed_text(choice,currentform) {
1668: var choicearg = choice + 'arg';
1669: if (currentform.elements[choicearg].value !='') {
1670: $Javascript_toUpperCase
1671: // clear old field
1672: if ((current.argfield != choicearg) && (current.argfield != null)) {
1673: currentform.elements[current.argfield].value = '';
1674: }
1675: current.argfield = choicearg;
1676: }
1677: set_auth_radio_buttons(choice,currentform);
1678: return;
1679: }
1680:
1681: function set_auth_radio_buttons(newvalue,currentform) {
1682: var i=0;
1683: while (i < currentform.login.length) {
1684: if (currentform.login[i].value == newvalue) { break; }
1685: i++;
1686: }
1687: if (i == currentform.login.length) {
1688: return;
1689: }
1690: current.radiovalue = newvalue;
1691: currentform.login[i].checked = true;
1692: return;
1693: }
1694: END
1695: return $result;
1696: }
1697:
1698: sub authform_authorwarning{
1699: my $result='';
1700: $result='<i>'.
1701: &mt('As a general rule, only authors or co-authors should be '.
1702: 'filesystem authenticated '.
1703: '(which allows access to the server filesystem).')."</i>\n";
1704: return $result;
1705: }
1706:
1707: sub authform_nochange{
1708: my %in = (
1709: formname => 'document.cu',
1710: kerb_def_dom => 'MSU.EDU',
1711: @_,
1712: );
1713: my $result = '<label>'.&mt('[_1] Do not change login data',
1714: '<input type="radio" name="login" value="nochange" '.
1715: 'checked="checked" onclick="'.
1716: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
1717: '</label>';
1718: return $result;
1719: }
1720:
1721: sub authform_kerberos{
1722: my %in = (
1723: formname => 'document.cu',
1724: kerb_def_dom => 'MSU.EDU',
1725: kerb_def_auth => 'krb4',
1726: @_,
1727: );
1728: my ($check4,$check5,$krbarg);
1729: if ($in{'kerb_def_auth'} eq 'krb5') {
1730: $check5 = " checked=\"on\"";
1731: } else {
1732: $check4 = " checked=\"on\"";
1733: }
1734: $krbarg = $in{'kerb_def_dom'};
1735:
1736: my $krbcheck = "";
1737: if ( grep/^curr_authtype$/,(keys %in) ) {
1738: if ($in{'curr_authtype'} =~ m/^krb/) {
1739: $krbcheck = " checked=\"on\"";
1740: if ( grep/^curr_autharg$/,(keys %in) ) {
1741: $krbarg = $in{'curr_autharg'};
1742: }
1743: }
1744: }
1745:
1746: my $jscall = "javascript:changed_radio('krb',$in{'formname'});";
1747: my $result .= &mt
1748: ('[_1] Kerberos authenticated with domain [_2] '.
1749: '[_3] Version 4 [_4] Version 5 [_5]',
1750: '<label><input type="radio" name="login" value="krb" '.
1751: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.$krbcheck.' />',
1752: '</label><input type="text" size="10" name="krbarg" '.
1753: 'value="'.$krbarg.'" '.
1754: 'onchange="'.$jscall.'" />',
1755: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
1756: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
1757: '</label>');
1758: return $result;
1759: }
1760:
1761: sub authform_internal{
1762: my %args = (
1763: formname => 'document.cu',
1764: kerb_def_dom => 'MSU.EDU',
1765: @_,
1766: );
1767:
1768: my $intcheck = "";
1769: my $intarg = 'value=""';
1770: if ( grep/^curr_authtype$/,(keys %args) ) {
1771: if ($args{'curr_authtype'} eq 'int') {
1772: $intcheck = " checked=\"on\"";
1773: if ( grep/^curr_autharg$/,(keys %args) ) {
1774: $intarg = "value=\"$args{'curr_autharg'}\"";
1775: }
1776: }
1777: }
1778:
1779: my $jscall = "javascript:changed_radio('int',$args{'formname'});";
1780: my $result.=&mt
1781: ('[_1] Internally authenticated (with initial password [_2])',
1782: '<label><input type="radio" name="login" value="int" '.$intcheck.
1783: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1784: '</label><input type="text" size="10" name="intarg" '.$intarg.
1785: ' onchange="'.$jscall.'" />');
1786: return $result;
1787: }
1788:
1789: sub authform_local{
1790: my %in = (
1791: formname => 'document.cu',
1792: kerb_def_dom => 'MSU.EDU',
1793: @_,
1794: );
1795:
1796: my $loccheck = "";
1797: my $locarg = 'value=""';
1798: if ( grep/^curr_authtype$/,(keys %in) ) {
1799: if ($in{'curr_authtype'} eq 'loc') {
1800: $loccheck = " checked=\"on\"";
1801: if ( grep/^curr_autharg$/,(keys %in) ) {
1802: $locarg = "value=\"$in{'curr_autharg'}\"";
1803: }
1804: }
1805: }
1806:
1807: my $jscall = "javascript:changed_radio('loc',$in{'formname'});";
1808: my $result.=&mt('[_1] Local Authentication with argument [_2]',
1809: '<label><input type="radio" name="login" value="loc" '.$loccheck.
1810: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1811: '</label><input type="text" size="10" name="locarg" '.$locarg.
1812: ' onchange="'.$jscall.'" />');
1813: return $result;
1814: }
1815:
1816: sub authform_filesystem{
1817: my %in = (
1818: formname => 'document.cu',
1819: kerb_def_dom => 'MSU.EDU',
1820: @_,
1821: );
1822: my $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
1823: my $result.= &mt
1824: ('[_1] Filesystem Authenticated (with initial password [_2])',
1825: '<label><input type="radio" name="login" value="fsys" '.
1826: 'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1827: '</label><input type="text" size="10" name="fsysarg" value="" '.
1828: 'onchange="'.$jscall.'" />');
1829: return $result;
1830: }
1831:
1832: ###############################################################
1833: ## Get Authentication Defaults for Domain ##
1834: ###############################################################
1835:
1836: =pod
1837:
1838: =head1 Domains and Authentication
1839:
1840: Returns default authentication type and an associated argument as
1841: listed in file 'domain.tab'.
1842:
1843: =over 4
1844:
1845: =item * get_auth_defaults
1846:
1847: get_auth_defaults($target_domain) returns the default authentication
1848: type and an associated argument (initial password or a kerberos domain).
1849: These values are stored in lonTabs/domain.tab
1850:
1851: ($def_auth, $def_arg) = &get_auth_defaults($target_domain);
1852:
1853: If target_domain is not found in domain.tab, returns nothing ('').
1854:
1855: =cut
1856:
1857: #-------------------------------------------
1858: sub get_auth_defaults {
1859: my $domain=shift;
1860: return (&Apache::lonnet::domain($domain,'auth_def'),
1861: &Apache::lonnet::domain($domain,'auth_arg_def'));
1862:
1863: }
1864: ###############################################################
1865: ## End Get Authentication Defaults for Domain ##
1866: ###############################################################
1867:
1868: ###############################################################
1869: ## Get Kerberos Defaults for Domain ##
1870: ###############################################################
1871: ##
1872: ## Returns default kerberos version and an associated argument
1873: ## as listed in file domain.tab. If not listed, provides
1874: ## appropriate default domain and kerberos version.
1875: ##
1876: #-------------------------------------------
1877:
1878: =pod
1879:
1880: =item * get_kerberos_defaults
1881:
1882: get_kerberos_defaults($target_domain) returns the default kerberos
1883: version and domain. If not found in domain.tabs, it defaults to
1884: version 4 and the domain of the server.
1885:
1886: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
1887:
1888: =cut
1889:
1890: #-------------------------------------------
1891: sub get_kerberos_defaults {
1892: my $domain=shift;
1893: my ($krbdef,$krbdefdom) =
1894: &Apache::loncommon::get_auth_defaults($domain);
1895: unless ($krbdef =~/^krb/ && $krbdefdom) {
1896: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
1897: my $krbdefdom=$1;
1898: $krbdefdom=~tr/a-z/A-Z/;
1899: $krbdef = "krb4";
1900: }
1901: return ($krbdef,$krbdefdom);
1902: }
1903:
1904: =pod
1905:
1906: =back
1907:
1908: =cut
1909:
1910: ###############################################################
1911: ## Thesaurus Functions ##
1912: ###############################################################
1913:
1914: =pod
1915:
1916: =head1 Thesaurus Functions
1917:
1918: =over 4
1919:
1920: =item * initialize_keywords
1921:
1922: Initializes the package variable %Keywords if it is empty. Uses the
1923: package variable $thesaurus_db_file.
1924:
1925: =cut
1926:
1927: ###################################################
1928:
1929: sub initialize_keywords {
1930: return 1 if (scalar keys(%Keywords));
1931: # If we are here, %Keywords is empty, so fill it up
1932: # Make sure the file we need exists...
1933: if (! -e $thesaurus_db_file) {
1934: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
1935: " failed because it does not exist");
1936: return 0;
1937: }
1938: # Set up the hash as a database
1939: my %thesaurus_db;
1940: if (! tie(%thesaurus_db,'GDBM_File',
1941: $thesaurus_db_file,&GDBM_READER(),0640)){
1942: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
1943: $thesaurus_db_file);
1944: return 0;
1945: }
1946: # Get the average number of appearances of a word.
1947: my $avecount = $thesaurus_db{'average.count'};
1948: # Put keywords (those that appear > average) into %Keywords
1949: while (my ($word,$data)=each (%thesaurus_db)) {
1950: my ($count,undef) = split /:/,$data;
1951: $Keywords{$word}++ if ($count > $avecount);
1952: }
1953: untie %thesaurus_db;
1954: # Remove special values from %Keywords.
1955: foreach my $value ('total.count','average.count') {
1956: delete($Keywords{$value}) if (exists($Keywords{$value}));
1957: }
1958: return 1;
1959: }
1960:
1961: ###################################################
1962:
1963: =pod
1964:
1965: =item * keyword($word)
1966:
1967: Returns true if $word is a keyword. A keyword is a word that appears more
1968: than the average number of times in the thesaurus database. Calls
1969: &initialize_keywords
1970:
1971: =cut
1972:
1973: ###################################################
1974:
1975: sub keyword {
1976: return if (!&initialize_keywords());
1977: my $word=lc(shift());
1978: $word=~s/\W//g;
1979: return exists($Keywords{$word});
1980: }
1981:
1982: ###############################################################
1983:
1984: =pod
1985:
1986: =item * get_related_words
1987:
1988: Look up a word in the thesaurus. Takes a scalar argument and returns
1989: an array of words. If the keyword is not in the thesaurus, an empty array
1990: will be returned. The order of the words returned is determined by the
1991: database which holds them.
1992:
1993: Uses global $thesaurus_db_file.
1994:
1995: =cut
1996:
1997: ###############################################################
1998: sub get_related_words {
1999: my $keyword = shift;
2000: my %thesaurus_db;
2001: if (! -e $thesaurus_db_file) {
2002: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2003: "failed because the file does not exist");
2004: return ();
2005: }
2006: if (! tie(%thesaurus_db,'GDBM_File',
2007: $thesaurus_db_file,&GDBM_READER(),0640)){
2008: return ();
2009: }
2010: my @Words=();
2011: my $count=0;
2012: if (exists($thesaurus_db{$keyword})) {
2013: # The first element is the number of times
2014: # the word appears. We do not need it now.
2015: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2016: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2017: my $threshold=$mostfrequentcount/10;
2018: foreach my $possibleword (@RelatedWords) {
2019: my ($word,$wordcount)=split(/\,/,$possibleword);
2020: if ($wordcount>$threshold) {
2021: push(@Words,$word);
2022: $count++;
2023: if ($count>10) { last; }
2024: }
2025: }
2026: }
2027: untie %thesaurus_db;
2028: return @Words;
2029: }
2030:
2031: =pod
2032:
2033: =back
2034:
2035: =cut
2036:
2037: # -------------------------------------------------------------- Plaintext name
2038: =pod
2039:
2040: =head1 User Name Functions
2041:
2042: =over 4
2043:
2044: =item * plainname($uname,$udom,$first)
2045:
2046: Takes a users logon name and returns it as a string in
2047: "first middle last generation" form
2048: if $first is set to 'lastname' then it returns it as
2049: 'lastname generation, firstname middlename' if their is a lastname
2050:
2051: =cut
2052:
2053:
2054: ###############################################################
2055: sub plainname {
2056: my ($uname,$udom,$first)=@_;
2057: return if (!defined($uname) || !defined($udom));
2058: my %names=&getnames($uname,$udom);
2059: my $name=&Apache::lonnet::format_name($names{'firstname'},
2060: $names{'middlename'},
2061: $names{'lastname'},
2062: $names{'generation'},$first);
2063: $name=~s/^\s+//;
2064: $name=~s/\s+$//;
2065: $name=~s/\s+/ /g;
2066: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2067: return $name;
2068: }
2069:
2070: # -------------------------------------------------------------------- Nickname
2071: =pod
2072:
2073: =item * nickname($uname,$udom)
2074:
2075: Gets a users name and returns it as a string as
2076:
2077: ""nickname""
2078:
2079: if the user has a nickname or
2080:
2081: "first middle last generation"
2082:
2083: if the user does not
2084:
2085: =cut
2086:
2087: sub nickname {
2088: my ($uname,$udom)=@_;
2089: return if (!defined($uname) || !defined($udom));
2090: my %names=&getnames($uname,$udom);
2091: my $name=$names{'nickname'};
2092: if ($name) {
2093: $name='"'.$name.'"';
2094: } else {
2095: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2096: $names{'lastname'}.' '.$names{'generation'};
2097: $name=~s/\s+$//;
2098: $name=~s/\s+/ /g;
2099: }
2100: return $name;
2101: }
2102:
2103: sub getnames {
2104: my ($uname,$udom)=@_;
2105: return if (!defined($uname) || !defined($udom));
2106: if ($udom eq 'public' && $uname eq 'public') {
2107: return ('lastname' => &mt('Public'));
2108: }
2109: my $id=$uname.':'.$udom;
2110: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2111: if ($cached) {
2112: return %{$names};
2113: } else {
2114: my %loadnames=&Apache::lonnet::get('environment',
2115: ['firstname','middlename','lastname','generation','nickname'],
2116: $udom,$uname);
2117: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2118: return %loadnames;
2119: }
2120: }
2121:
2122: # -------------------------------------------------------------------- getemails
2123: =pod
2124:
2125: =item * getemails($uname,$udom)
2126:
2127: Gets a user's email information and returns it as a hash with keys:
2128: notification, critnotification, permanentemail
2129:
2130: For notification and critnotification, values are comma-separated lists
2131: of e-mail address(es); for permanentemail, value is a single e-mail address.
2132:
2133: =cut
2134:
2135: sub getemails {
2136: my ($uname,$udom)=@_;
2137: if ($udom eq 'public' && $uname eq 'public') {
2138: return;
2139: }
2140: if (!$udom) { $udom=$env{'user.domain'}; }
2141: if (!$uname) { $uname=$env{'user.name'}; }
2142: my $id=$uname.':'.$udom;
2143: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2144: if ($cached) {
2145: return %{$names};
2146: } else {
2147: my %loadnames=&Apache::lonnet::get('environment',
2148: ['notification','critnotification',
2149: 'permanentemail'],
2150: $udom,$uname);
2151: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2152: return %loadnames;
2153: }
2154: }
2155:
2156: # ------------------------------------------------------------------ Screenname
2157:
2158: =pod
2159:
2160: =item * screenname($uname,$udom)
2161:
2162: Gets a users screenname and returns it as a string
2163:
2164: =cut
2165:
2166: sub screenname {
2167: my ($uname,$udom)=@_;
2168: if ($uname eq $env{'user.name'} &&
2169: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2170: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2171: return $names{'screenname'};
2172: }
2173:
2174:
2175: # ------------------------------------------------------------- Message Wrapper
2176:
2177: sub messagewrapper {
2178: my ($link,$username,$domain,$subject,$text)=@_;
2179: return
2180: '<a href="/adm/email?compose=individual&'.
2181: 'recname='.$username.'&recdom='.$domain.
2182: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2183: 'title="'.&mt('Send message').'">'.$link.'</a>';
2184: }
2185: # --------------------------------------------------------------- Notes Wrapper
2186:
2187: sub noteswrapper {
2188: my ($link,$un,$do)=@_;
2189: return
2190: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2191: }
2192: # ------------------------------------------------------------- Aboutme Wrapper
2193:
2194: sub aboutmewrapper {
2195: my ($link,$username,$domain,$target)=@_;
2196: if (!defined($username) && !defined($domain)) {
2197: return;
2198: }
2199: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2200: ($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
2201: }
2202:
2203: # ------------------------------------------------------------ Syllabus Wrapper
2204:
2205:
2206: sub syllabuswrapper {
2207: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
2208: if ($fontcolor) {
2209: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2210: }
2211: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2212: }
2213:
2214: sub track_student_link {
2215: my ($linktext,$sname,$sdom,$target,$start) = @_;
2216: my $link ="/adm/trackstudent?";
2217: my $title = 'View recent activity';
2218: if (defined($sname) && $sname !~ /^\s*$/ &&
2219: defined($sdom) && $sdom !~ /^\s*$/) {
2220: $link .= "selected_student=$sname:$sdom";
2221: $title .= ' of this student';
2222: }
2223: if (defined($target) && $target !~ /^\s*$/) {
2224: $target = qq{target="$target"};
2225: } else {
2226: $target = '';
2227: }
2228: if ($start) { $link.='&start='.$start; }
2229:
2230: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2231: &help_open_topic('View_recent_activity');
2232: }
2233:
2234: # ===================================================== Display a student photo
2235:
2236:
2237: sub student_image_tag {
2238: my ($domain,$user)=@_;
2239: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2240: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2241: return '<img src="'.$imgsrc.'" align="right" />';
2242: } else {
2243: return '';
2244: }
2245: }
2246:
2247: =pod
2248:
2249: =back
2250:
2251: =head1 Access .tab File Data
2252:
2253: =over 4
2254:
2255: =item * languageids()
2256:
2257: returns list of all language ids
2258:
2259: =cut
2260:
2261: sub languageids {
2262: return sort(keys(%language));
2263: }
2264:
2265: =pod
2266:
2267: =item * languagedescription()
2268:
2269: returns description of a specified language id
2270:
2271: =cut
2272:
2273: sub languagedescription {
2274: my $code=shift;
2275: return ($supported_language{$code}?'* ':'').
2276: $language{$code}.
2277: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2278: }
2279:
2280: sub plainlanguagedescription {
2281: my $code=shift;
2282: return $language{$code};
2283: }
2284:
2285: sub supportedlanguagecode {
2286: my $code=shift;
2287: return $supported_language{$code};
2288: }
2289:
2290: =pod
2291:
2292: =item * copyrightids()
2293:
2294: returns list of all copyrights
2295:
2296: =cut
2297:
2298: sub copyrightids {
2299: return sort(keys(%cprtag));
2300: }
2301:
2302: =pod
2303:
2304: =item * copyrightdescription()
2305:
2306: returns description of a specified copyright id
2307:
2308: =cut
2309:
2310: sub copyrightdescription {
2311: return &mt($cprtag{shift(@_)});
2312: }
2313:
2314: =pod
2315:
2316: =item * source_copyrightids()
2317:
2318: returns list of all source copyrights
2319:
2320: =cut
2321:
2322: sub source_copyrightids {
2323: return sort(keys(%scprtag));
2324: }
2325:
2326: =pod
2327:
2328: =item * source_copyrightdescription()
2329:
2330: returns description of a specified source copyright id
2331:
2332: =cut
2333:
2334: sub source_copyrightdescription {
2335: return &mt($scprtag{shift(@_)});
2336: }
2337:
2338: =pod
2339:
2340: =item * filecategories()
2341:
2342: returns list of all file categories
2343:
2344: =cut
2345:
2346: sub filecategories {
2347: return sort(keys(%category_extensions));
2348: }
2349:
2350: =pod
2351:
2352: =item * filecategorytypes()
2353:
2354: returns list of file types belonging to a given file
2355: category
2356:
2357: =cut
2358:
2359: sub filecategorytypes {
2360: my ($cat) = @_;
2361: return @{$category_extensions{lc($cat)}};
2362: }
2363:
2364: =pod
2365:
2366: =item * fileembstyle()
2367:
2368: returns embedding style for a specified file type
2369:
2370: =cut
2371:
2372: sub fileembstyle {
2373: return $fe{lc(shift(@_))};
2374: }
2375:
2376: sub filemimetype {
2377: return $fm{lc(shift(@_))};
2378: }
2379:
2380:
2381: sub filecategoryselect {
2382: my ($name,$value)=@_;
2383: return &select_form($value,$name,
2384: '' => &mt('Any category'),
2385: map { $_,$_ } sort(keys(%category_extensions)));
2386: }
2387:
2388: =pod
2389:
2390: =item * filedescription()
2391:
2392: returns description for a specified file type
2393:
2394: =cut
2395:
2396: sub filedescription {
2397: my $file_description = $fd{lc(shift())};
2398: $file_description =~ s:([\[\]]):~$1:g;
2399: return &mt($file_description);
2400: }
2401:
2402: =pod
2403:
2404: =item * filedescriptionex()
2405:
2406: returns description for a specified file type with
2407: extra formatting
2408:
2409: =cut
2410:
2411: sub filedescriptionex {
2412: my $ex=shift;
2413: my $file_description = $fd{lc($ex)};
2414: $file_description =~ s:([\[\]]):~$1:g;
2415: return '.'.$ex.' '.&mt($file_description);
2416: }
2417:
2418: # End of .tab access
2419: =pod
2420:
2421: =back
2422:
2423: =cut
2424:
2425: # ------------------------------------------------------------------ File Types
2426: sub fileextensions {
2427: return sort(keys(%fe));
2428: }
2429:
2430: # ----------------------------------------------------------- Display Languages
2431: # returns a hash with all desired display languages
2432: #
2433:
2434: sub display_languages {
2435: my %languages=();
2436: foreach my $lang (&preferred_languages()) {
2437: $languages{$lang}=1;
2438: }
2439: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
2440: if ($env{'form.displaylanguage'}) {
2441: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
2442: $languages{$lang}=1;
2443: }
2444: }
2445: return %languages;
2446: }
2447:
2448: sub preferred_languages {
2449: my @languages=();
2450: if ($env{'course.'.$env{'request.course.id'}.'.languages'}) {
2451: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,
2452: $env{'course.'.$env{'request.course.id'}.'.languages'}));
2453: }
2454: if ($env{'environment.languages'}) {
2455: @languages=(@languages,
2456: split(/\s*(\,|\;|\:)\s*/,$env{'environment.languages'}));
2457: }
2458: my $browser=(split(/\;/,$ENV{'HTTP_ACCEPT_LANGUAGE'}))[0];
2459: if ($browser) {
2460: @languages=(@languages,split(/\s*(\,|\;|\:)\s*/,$browser));
2461: }
2462: if (&Apache::lonnet::domain($env{'user.domain'},'lang_def')) {
2463: @languages=(@languages,
2464: &Apache::lonnet::domain($env{'user.domain'},
2465: 'lang_def'));
2466: }
2467: if (&Apache::lonnet::domain($env{'request.role.domain'},'lang_def')) {
2468: @languages=(@languages,
2469: &Apache::lonnet::domain($env{'request.role.domain'},
2470: 'lang_def'));
2471: }
2472: if (&Apache::lonnet::domain($Apache::lonnet::perlvar{'lonDefDomain'},
2473: 'lang_def')) {
2474: @languages=(@languages,
2475: &Apache::lonnet::domain($Apache::lonnet::perlvar{'lonDefDomain'},
2476: 'lang_def'));
2477: }
2478: # turn "en-ca" into "en-ca,en"
2479: my @genlanguages;
2480: foreach my $lang (@languages) {
2481: unless ($lang=~/\w/) { next; }
2482: push (@genlanguages,$lang);
2483: if ($lang=~/(\-|\_)/) {
2484: push(@genlanguages,(split(/(\-|\_)/,$lang))[0]);
2485: }
2486: }
2487: return @genlanguages;
2488: }
2489:
2490: ###############################################################
2491: ## Student Answer Attempts ##
2492: ###############################################################
2493:
2494: =pod
2495:
2496: =head1 Alternate Problem Views
2497:
2498: =over 4
2499:
2500: =item * get_previous_attempt($symb, $username, $domain, $course,
2501: $getattempt, $regexp, $gradesub)
2502:
2503: Return string with previous attempt on problem. Arguments:
2504:
2505: =over 4
2506:
2507: =item * $symb: Problem, including path
2508:
2509: =item * $username: username of the desired student
2510:
2511: =item * $domain: domain of the desired student
2512:
2513: =item * $course: Course ID
2514:
2515: =item * $getattempt: Leave blank for all attempts, otherwise put
2516: something
2517:
2518: =item * $regexp: if string matches this regexp, the string will be
2519: sent to $gradesub
2520:
2521: =item * $gradesub: routine that processes the string if it matches $regexp
2522:
2523: =back
2524:
2525: The output string is a table containing all desired attempts, if any.
2526:
2527: =cut
2528:
2529: sub get_previous_attempt {
2530: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
2531: my $prevattempts='';
2532: no strict 'refs';
2533: if ($symb) {
2534: my (%returnhash)=
2535: &Apache::lonnet::restore($symb,$course,$domain,$username);
2536: if ($returnhash{'version'}) {
2537: my %lasthash=();
2538: my $version;
2539: for ($version=1;$version<=$returnhash{'version'};$version++) {
2540: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
2541: $lasthash{$key}=$returnhash{$version.':'.$key};
2542: }
2543: }
2544: $prevattempts='<table border="0" width="100%"><tr><td bgcolor="#777777">';
2545: $prevattempts.='<table border="0" width="100%"><tr bgcolor="#e6ffff"><td>History</td>';
2546: foreach my $key (sort(keys(%lasthash))) {
2547: my ($ign,@parts) = split(/\./,$key);
2548: if ($#parts > 0) {
2549: my $data=$parts[-1];
2550: pop(@parts);
2551: $prevattempts.='<td>Part '.join('.',@parts).'<br />'.$data.' </td>';
2552: } else {
2553: if ($#parts == 0) {
2554: $prevattempts.='<th>'.$parts[0].'</th>';
2555: } else {
2556: $prevattempts.='<th>'.$ign.'</th>';
2557: }
2558: }
2559: }
2560: if ($getattempt eq '') {
2561: for ($version=1;$version<=$returnhash{'version'};$version++) {
2562: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Transaction '.$version.'</td>';
2563: foreach my $key (sort(keys(%lasthash))) {
2564: my $value;
2565: if ($key =~ /timestamp/) {
2566: $value=scalar(localtime($returnhash{$version.':'.$key}));
2567: } else {
2568: $value=$returnhash{$version.':'.$key};
2569: }
2570: $prevattempts.='<td>'.&unescape($value).' </td>';
2571: }
2572: }
2573: }
2574: $prevattempts.='</tr><tr bgcolor="#ffffe6"><td>Current</td>';
2575: foreach my $key (sort(keys(%lasthash))) {
2576: my $value;
2577: if ($key =~ /timestamp/) {
2578: $value=scalar(localtime($lasthash{$key}));
2579: } else {
2580: $value=$lasthash{$key};
2581: }
2582: $value=&unescape($value);
2583: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
2584: $prevattempts.='<td>'.$value.' </td>';
2585: }
2586: $prevattempts.='</tr></table></td></tr></table>';
2587: } else {
2588: $prevattempts='Nothing submitted - no attempts.';
2589: }
2590: } else {
2591: $prevattempts='No data.';
2592: }
2593: }
2594:
2595: sub relative_to_absolute {
2596: my ($url,$output)=@_;
2597: my $parser=HTML::TokeParser->new(\$output);
2598: my $token;
2599: my $thisdir=$url;
2600: my @rlinks=();
2601: while ($token=$parser->get_token) {
2602: if ($token->[0] eq 'S') {
2603: if ($token->[1] eq 'a') {
2604: if ($token->[2]->{'href'}) {
2605: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
2606: }
2607: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
2608: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
2609: } elsif ($token->[1] eq 'base') {
2610: $thisdir=$token->[2]->{'href'};
2611: }
2612: }
2613: }
2614: $thisdir=~s-/[^/]*$--;
2615: foreach my $link (@rlinks) {
2616: unless (($link=~/^http:\/\//i) ||
2617: ($link=~/^\//) ||
2618: ($link=~/^javascript:/i) ||
2619: ($link=~/^mailto:/i) ||
2620: ($link=~/^\#/)) {
2621: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
2622: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
2623: }
2624: }
2625: # -------------------------------------------------- Deal with Applet codebases
2626: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
2627: return $output;
2628: }
2629:
2630: =pod
2631:
2632: =item * get_student_view
2633:
2634: show a snapshot of what student was looking at
2635:
2636: =cut
2637:
2638: sub get_student_view {
2639: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
2640: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2641: my (%form);
2642: my @elements=('symb','courseid','domain','username');
2643: foreach my $element (@elements) {
2644: $form{'grade_'.$element}=eval '$'.$element #'
2645: }
2646: if (defined($moreenv)) {
2647: %form=(%form,%{$moreenv});
2648: }
2649: if (defined($target)) { $form{'grade_target'} = $target; }
2650: $feedurl=&Apache::lonnet::clutter($feedurl);
2651: my $userview=&Apache::lonnet::ssi_body($feedurl,%form);
2652: $userview=~s/\<body[^\>]*\>//gi;
2653: $userview=~s/\<\/body\>//gi;
2654: $userview=~s/\<html\>//gi;
2655: $userview=~s/\<\/html\>//gi;
2656: $userview=~s/\<head\>//gi;
2657: $userview=~s/\<\/head\>//gi;
2658: $userview=~s/action\s*\=/would_be_action\=/gi;
2659: $userview=&relative_to_absolute($feedurl,$userview);
2660: return $userview;
2661: }
2662:
2663: =pod
2664:
2665: =item * get_student_answers()
2666:
2667: show a snapshot of how student was answering problem
2668:
2669: =cut
2670:
2671: sub get_student_answers {
2672: my ($symb,$username,$domain,$courseid,%form) = @_;
2673: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
2674: my (%moreenv);
2675: my @elements=('symb','courseid','domain','username');
2676: foreach my $element (@elements) {
2677: $moreenv{'grade_'.$element}=eval '$'.$element #'
2678: }
2679: $moreenv{'grade_target'}='answer';
2680: %moreenv=(%form,%moreenv);
2681: $feedurl = &Apache::lonnet::clutter($feedurl);
2682: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
2683: return $userview;
2684: }
2685:
2686: =pod
2687:
2688: =item * &submlink()
2689:
2690: Inputs: $text $uname $udom $symb $target
2691:
2692: Returns: A link to grades.pm such as to see the SUBM view of a student
2693:
2694: =cut
2695:
2696: ###############################################
2697: sub submlink {
2698: my ($text,$uname,$udom,$symb,$target)=@_;
2699: if (!($uname && $udom)) {
2700: (my $cursymb, my $courseid,$udom,$uname)=
2701: &Apache::lonnet::whichuser($symb);
2702: if (!$symb) { $symb=$cursymb; }
2703: }
2704: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2705: $symb=&escape($symb);
2706: if ($target) { $target="target=\"$target\""; }
2707: return '<a href="/adm/grades?&command=submission&'.
2708: 'symb='.$symb.'&student='.$uname.
2709: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
2710: }
2711: ##############################################
2712:
2713: =pod
2714:
2715: =item * &pgrdlink()
2716:
2717: Inputs: $text $uname $udom $symb $target
2718:
2719: Returns: A link to grades.pm such as to see the PGRD view of a student
2720:
2721: =cut
2722:
2723: ###############################################
2724: sub pgrdlink {
2725: my $link=&submlink(@_);
2726: $link=~s/(&command=submission)/$1&showgrading=yes/;
2727: return $link;
2728: }
2729: ##############################################
2730:
2731: =pod
2732:
2733: =item * &pprmlink()
2734:
2735: Inputs: $text $uname $udom $symb $target
2736:
2737: Returns: A link to parmset.pm such as to see the PPRM view of a
2738: student and a specific resource
2739:
2740: =cut
2741:
2742: ###############################################
2743: sub pprmlink {
2744: my ($text,$uname,$udom,$symb,$target)=@_;
2745: if (!($uname && $udom)) {
2746: (my $cursymb, my $courseid,$udom,$uname)=
2747: &Apache::lonnet::whichuser($symb);
2748: if (!$symb) { $symb=$cursymb; }
2749: }
2750: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
2751: $symb=&escape($symb);
2752: if ($target) { $target="target=\"$target\""; }
2753: return '<a href="/adm/parmset?&command=set&'.
2754: 'symb='.$symb.'&uname='.$uname.
2755: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
2756: }
2757: ##############################################
2758:
2759: =pod
2760:
2761: =back
2762:
2763: =cut
2764:
2765: ###############################################
2766:
2767:
2768: sub timehash {
2769: my @ltime=localtime(shift);
2770: return ( 'seconds' => $ltime[0],
2771: 'minutes' => $ltime[1],
2772: 'hours' => $ltime[2],
2773: 'day' => $ltime[3],
2774: 'month' => $ltime[4]+1,
2775: 'year' => $ltime[5]+1900,
2776: 'weekday' => $ltime[6],
2777: 'dayyear' => $ltime[7]+1,
2778: 'dlsav' => $ltime[8] );
2779: }
2780:
2781: sub utc_string {
2782: my ($date)=@_;
2783: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
2784: }
2785:
2786: sub maketime {
2787: my %th=@_;
2788: return POSIX::mktime(
2789: ($th{'seconds'},$th{'minutes'},$th{'hours'},
2790: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
2791: }
2792:
2793: #########################################
2794:
2795: sub findallcourses {
2796: my ($roles,$uname,$udom) = @_;
2797: my %roles;
2798: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
2799: my %courses;
2800: my $now=time;
2801: if (!defined($uname)) {
2802: $uname = $env{'user.name'};
2803: }
2804: if (!defined($udom)) {
2805: $udom = $env{'user.domain'};
2806: }
2807: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
2808: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
2809: if (!%roles) {
2810: %roles = (
2811: cc => 1,
2812: in => 1,
2813: ep => 1,
2814: ta => 1,
2815: cr => 1,
2816: st => 1,
2817: );
2818: }
2819: foreach my $entry (keys(%roleshash)) {
2820: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
2821: if ($trole =~ /^cr/) {
2822: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
2823: } else {
2824: next if (!exists($roles{$trole}));
2825: }
2826: if ($tend) {
2827: next if ($tend < $now);
2828: }
2829: if ($tstart) {
2830: next if ($tstart > $now);
2831: }
2832: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
2833: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
2834: if ($secpart eq '') {
2835: ($cnum,$role) = split(/_/,$cnumpart);
2836: $sec = 'none';
2837: $realsec = '';
2838: } else {
2839: $cnum = $cnumpart;
2840: ($sec,$role) = split(/_/,$secpart);
2841: $realsec = $sec;
2842: }
2843: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
2844: }
2845: } else {
2846: foreach my $key (keys(%env)) {
2847: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
2848: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
2849: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
2850: next if ($role eq 'ca' || $role eq 'aa');
2851: next if (%roles && !exists($roles{$role}));
2852: my ($starttime,$endtime)=split(/\./,$env{$key});
2853: my $active=1;
2854: if ($starttime) {
2855: if ($now<$starttime) { $active=0; }
2856: }
2857: if ($endtime) {
2858: if ($now>$endtime) { $active=0; }
2859: }
2860: if ($active) {
2861: if ($sec eq '') {
2862: $sec = 'none';
2863: }
2864: $courses{$cdom.'_'.$cnum}{$sec} =
2865: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
2866: }
2867: }
2868: }
2869: }
2870: return %courses;
2871: }
2872:
2873: ###############################################
2874:
2875: sub blockcheck {
2876: my ($setters,$activity,$uname,$udom) = @_;
2877:
2878: if (!defined($udom)) {
2879: $udom = $env{'user.domain'};
2880: }
2881: if (!defined($uname)) {
2882: $uname = $env{'user.name'};
2883: }
2884:
2885: # If uname and udom are for a course, check for blocks in the course.
2886:
2887: if (&Apache::lonnet::is_course($udom,$uname)) {
2888: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
2889: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
2890: return ($startblock,$endblock);
2891: }
2892:
2893: my $startblock = 0;
2894: my $endblock = 0;
2895: my %live_courses = &findallcourses(undef,$uname,$udom);
2896:
2897: # If uname is for a user, and activity is course-specific, i.e.,
2898: # boards, chat or groups, check for blocking in current course only.
2899:
2900: if (($activity eq 'boards' || $activity eq 'chat' ||
2901: $activity eq 'groups') && ($env{'request.course.id'})) {
2902: foreach my $key (keys(%live_courses)) {
2903: if ($key ne $env{'request.course.id'}) {
2904: delete($live_courses{$key});
2905: }
2906: }
2907: }
2908:
2909: my $otheruser = 0;
2910: my %own_courses;
2911: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
2912: # Resource belongs to user other than current user.
2913: $otheruser = 1;
2914: # Gather courses for current user
2915: %own_courses =
2916: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
2917: }
2918:
2919: # Gather active course roles - course coordinator, instructor,
2920: # exam proctor, ta, student, or custom role.
2921:
2922: foreach my $course (keys(%live_courses)) {
2923: my ($cdom,$cnum);
2924: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
2925: $cdom = $env{'course.'.$course.'.domain'};
2926: $cnum = $env{'course.'.$course.'.num'};
2927: } else {
2928: ($cdom,$cnum) = split(/_/,$course);
2929: }
2930: my $no_ownblock = 0;
2931: my $no_userblock = 0;
2932: if ($otheruser && $activity ne 'com') {
2933: # Check if current user has 'evb' priv for this
2934: if (defined($own_courses{$course})) {
2935: foreach my $sec (keys(%{$own_courses{$course}})) {
2936: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
2937: if ($sec ne 'none') {
2938: $checkrole .= '/'.$sec;
2939: }
2940: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
2941: $no_ownblock = 1;
2942: last;
2943: }
2944: }
2945: }
2946: # if they have 'evb' priv and are currently not playing student
2947: next if (($no_ownblock) &&
2948: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
2949: }
2950: foreach my $sec (keys(%{$live_courses{$course}})) {
2951: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
2952: if ($sec ne 'none') {
2953: $checkrole .= '/'.$sec;
2954: }
2955: if ($otheruser) {
2956: # Resource belongs to user other than current user.
2957: # Assemble privs for that user, and check for 'evb' priv.
2958: my ($trole,$tdom,$tnum,$tsec);
2959: my $entry = $live_courses{$course}{$sec};
2960: if ($entry =~ /^cr/) {
2961: ($trole,$tdom,$tnum,$tsec) =
2962: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
2963: } else {
2964: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
2965: }
2966: my ($spec,$area,$trest,%allroles,%userroles);
2967: $area = '/'.$tdom.'/'.$tnum;
2968: $trest = $tnum;
2969: if ($tsec ne '') {
2970: $area .= '/'.$tsec;
2971: $trest .= '/'.$tsec;
2972: }
2973: $spec = $trole.'.'.$area;
2974: if ($trole =~ /^cr/) {
2975: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
2976: $tdom,$spec,$trest,$area);
2977: } else {
2978: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
2979: $tdom,$spec,$trest,$area);
2980: }
2981: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
2982: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
2983: if ($1) {
2984: $no_userblock = 1;
2985: last;
2986: }
2987: }
2988: } else {
2989: # Resource belongs to current user
2990: # Check for 'evb' priv via lonnet::allowed().
2991: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
2992: $no_ownblock = 1;
2993: last;
2994: }
2995: }
2996: }
2997: # if they have the evb priv and are currently not playing student
2998: next if (($no_ownblock) &&
2999: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3000: next if ($no_userblock);
3001:
3002: # Retrieve blocking times and identity of blocker for course
3003: # of specified user, unless user has 'evb' privilege.
3004:
3005: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3006: if (($start != 0) &&
3007: (($startblock == 0) || ($startblock > $start))) {
3008: $startblock = $start;
3009: }
3010: if (($end != 0) &&
3011: (($endblock == 0) || ($endblock < $end))) {
3012: $endblock = $end;
3013: }
3014: }
3015: return ($startblock,$endblock);
3016: }
3017:
3018: sub get_blocks {
3019: my ($setters,$activity,$cdom,$cnum) = @_;
3020: my $startblock = 0;
3021: my $endblock = 0;
3022: my $course = $cdom.'_'.$cnum;
3023: $setters->{$course} = {};
3024: $setters->{$course}{'staff'} = [];
3025: $setters->{$course}{'times'} = [];
3026: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3027: foreach my $record (keys(%records)) {
3028: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3029: if ($start <= time && $end >= time) {
3030: my ($staff_name,$staff_dom,$title,$blocks) =
3031: &parse_block_record($records{$record});
3032: if ($blocks->{$activity} eq 'on') {
3033: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3034: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3035: if ( ($startblock == 0) || ($startblock > $start) ) {
3036: $startblock = $start;
3037: }
3038: if ( ($endblock == 0) || ($endblock < $end) ) {
3039: $endblock = $end;
3040: }
3041: }
3042: }
3043: }
3044: return ($startblock,$endblock);
3045: }
3046:
3047: sub parse_block_record {
3048: my ($record) = @_;
3049: my ($setuname,$setudom,$title,$blocks);
3050: if (ref($record) eq 'HASH') {
3051: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3052: $title = &unescape($record->{'event'});
3053: $blocks = $record->{'blocks'};
3054: } else {
3055: my @data = split(/:/,$record,3);
3056: if (scalar(@data) eq 2) {
3057: $title = $data[1];
3058: ($setuname,$setudom) = split(/@/,$data[0]);
3059: } else {
3060: ($setuname,$setudom,$title) = @data;
3061: }
3062: $blocks = { 'com' => 'on' };
3063: }
3064: return ($setuname,$setudom,$title,$blocks);
3065: }
3066:
3067: sub build_block_table {
3068: my ($startblock,$endblock,$setters) = @_;
3069: my %lt = &Apache::lonlocal::texthash(
3070: 'cacb' => 'Currently active communication blocks',
3071: 'cour' => 'Course',
3072: 'dura' => 'Duration',
3073: 'blse' => 'Block set by'
3074: );
3075: my $output;
3076: $output = '<br />'.$lt{'cacb'}.':<br />';
3077: $output .= &start_data_table();
3078: $output .= '
3079: <tr>
3080: <th>'.$lt{'cour'}.'</th>
3081: <th>'.$lt{'dura'}.'</th>
3082: <th>'.$lt{'blse'}.'</th>
3083: </tr>
3084: ';
3085: foreach my $course (keys(%{$setters})) {
3086: my %courseinfo=&Apache::lonnet::coursedescription($course);
3087: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3088: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3089: my $fullname = &plainname($uname,$udom);
3090: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3091: && $env{'user.name'} ne 'public'
3092: && $env{'user.domain'} ne 'public') {
3093: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3094: }
3095: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3096: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3097: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3098: $output .= &Apache::loncommon::start_data_table_row().
3099: '<td>'.$courseinfo{'description'}.'</td>'.
3100: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3101: '<td>'.$fullname.'</td>'.
3102: &Apache::loncommon::end_data_table_row();
3103: }
3104: }
3105: $output .= &end_data_table();
3106: }
3107:
3108: sub blocking_status {
3109: my ($activity,$uname,$udom) = @_;
3110: my %setters;
3111: my ($blocked,$output,$ownitem,$is_course);
3112: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3113: if ($startblock && $endblock) {
3114: $blocked = 1;
3115: if (wantarray) {
3116: my $category;
3117: if ($activity eq 'boards') {
3118: $category = 'Discussion posts in this course';
3119: } elsif ($activity eq 'blogs') {
3120: $category = 'Blogs';
3121: } elsif ($activity eq 'port') {
3122: if (defined($uname) && defined($udom)) {
3123: if ($uname eq $env{'user.name'} &&
3124: $udom eq $env{'user.domain'}) {
3125: $ownitem = 1;
3126: }
3127: }
3128: $is_course = &Apache::lonnet::is_course($udom,$uname);
3129: if ($ownitem) {
3130: $category = 'Your portfolio files';
3131: } elsif ($is_course) {
3132: my $coursedesc;
3133: foreach my $course (keys(%setters)) {
3134: my %courseinfo =
3135: &Apache::lonnet::coursedescription($course);
3136: $coursedesc = $courseinfo{'description'};
3137: }
3138: $category = "Group files in the course '$coursedesc'";
3139: } else {
3140: $category = 'Portfolio files belonging to ';
3141: if ($env{'user.name'} eq 'public' &&
3142: $env{'user.domain'} eq 'public') {
3143: $category .= &plainname($uname,$udom);
3144: } else {
3145: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3146: }
3147: }
3148: } elsif ($activity eq 'groups') {
3149: $category = 'Groups in this course';
3150: }
3151: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
3152: my $showend = &Apache::lonlocal::locallocaltime($endblock);
3153: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
3154: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
3155: $output .= &build_block_table($startblock,$endblock,\%setters);
3156: }
3157: }
3158: }
3159: if (wantarray) {
3160: return ($blocked,$output);
3161: } else {
3162: return $blocked;
3163: }
3164: }
3165:
3166: ###############################################
3167:
3168: =pod
3169:
3170: =head1 Domain Template Functions
3171:
3172: =over 4
3173:
3174: =item * &determinedomain()
3175:
3176: Inputs: $domain (usually will be undef)
3177:
3178: Returns: Determines which domain should be used for designs
3179:
3180: =cut
3181:
3182: ###############################################
3183: sub determinedomain {
3184: my $domain=shift;
3185: if (! $domain) {
3186: # Determine domain if we have not been given one
3187: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3188: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3189: if ($env{'request.role.domain'}) {
3190: $domain=$env{'request.role.domain'};
3191: }
3192: }
3193: return $domain;
3194: }
3195: ###############################################
3196:
3197: sub devalidate_domconfig_cache {
3198: my ($udom)=@_;
3199: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3200: }
3201:
3202: # ---------------------- Get domain configuration for a domain
3203: sub get_domainconf {
3204: my ($udom) = @_;
3205: my $cachetime=1800;
3206: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3207: if (defined($cached)) { return %{$result}; }
3208:
3209: my %domconfig = &Apache::lonnet::get_dom('configuration',
3210: ['login','rolecolors'],$udom);
3211: my %designhash;
3212: if (keys(%domconfig) > 0) {
3213: if (ref($domconfig{'login'}) eq 'HASH') {
3214: foreach my $key (keys(%{$domconfig{'login'}})) {
3215: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3216: }
3217: }
3218: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
3219: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
3220: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
3221: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
3222: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
3223: }
3224: }
3225: }
3226: }
3227: } else {
3228: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
3229: my $designfile = $designdir.'/'.$udom.'.tab';
3230: if (-e $designfile) {
3231: if ( open (my $fh,"<$designfile") ) {
3232: while (my $line = <$fh>) {
3233: next if ($line =~ /^\#/);
3234: chomp($line);
3235: my ($key,$val)=(split(/\=/,$line));
3236: if ($val) { $designhash{$udom.'.'.$key}=$val; }
3237: }
3238: close($fh);
3239: }
3240: }
3241: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
3242: $designhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
3243: }
3244: }
3245: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
3246: $cachetime);
3247: return %designhash;
3248: }
3249:
3250: =pod
3251:
3252: =item * &domainlogo()
3253:
3254: Inputs: $domain (usually will be undef)
3255:
3256: Returns: A link to a domain logo, if the domain logo exists.
3257: If the domain logo does not exist, a description of the domain.
3258:
3259: =cut
3260:
3261: ###############################################
3262: sub domainlogo {
3263: my $domain = &determinedomain(shift);
3264: my %designhash = &get_domainconf($domain);
3265: # See if there is a logo
3266: if ($designhash{$domain.'.login.domlogo'} ne '') {
3267: my $imgsrc = $designhash{$domain.'.login.domlogo'};
3268: if ($imgsrc =~ m{^/(adm|res)/}) {
3269: if ($imgsrc =~ m{^/res/}) {
3270: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
3271: &Apache::lonnet::repcopy($local_name);
3272: }
3273: $imgsrc = &lonhttpdurl($imgsrc);
3274: }
3275: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
3276: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
3277: return &Apache::lonnet::domain($domain,'description');
3278: } else {
3279: return '';
3280: }
3281: }
3282: ##############################################
3283:
3284: =pod
3285:
3286: =item * &designparm()
3287:
3288: Inputs: $which parameter; $domain (usually will be undef)
3289:
3290: Returns: value of designparamter $which
3291:
3292: =cut
3293:
3294:
3295: ##############################################
3296: sub designparm {
3297: my ($which,$domain)=@_;
3298: if ($env{'browser.blackwhite'} eq 'on') {
3299: if ($which=~/\.(font|alink|vlink|link)$/) {
3300: return '#000000';
3301: }
3302: if ($which=~/\.(pgbg|sidebg)$/) {
3303: return '#FFFFFF';
3304: }
3305: if ($which=~/\.tabbg$/) {
3306: return '#CCCCCC';
3307: }
3308: }
3309: if (exists($env{'environment.color.'.$which})) {
3310: return $env{'environment.color.'.$which};
3311: }
3312: $domain=&determinedomain($domain);
3313: my %domdesign = &get_domainconf($domain);
3314: my $output;
3315: if ($domdesign{$domain.'.'.$which} ne '') {
3316: $output = $domdesign{$domain.'.'.$which};
3317: } else {
3318: $output = $defaultdesign{$which};
3319: }
3320: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
3321: ($which =~ /login\.(img|logo|domlogo)/)) {
3322: if ($output =~ m{^/(adm|res)/}) {
3323: if ($output =~ m{^/res/}) {
3324: my $local_name = &Apache::lonnet::filelocation('',$output);
3325: &Apache::lonnet::repcopy($local_name);
3326: }
3327: $output = &lonhttpdurl($output);
3328: }
3329: }
3330: return $output;
3331: }
3332:
3333: ###############################################
3334: ###############################################
3335:
3336: =pod
3337:
3338: =back
3339:
3340: =head1 HTTP Helpers
3341:
3342: =over 4
3343:
3344: =item * &bodytag()
3345:
3346: Returns a uniform header for LON-CAPA web pages.
3347:
3348: Inputs:
3349:
3350: =over 4
3351:
3352: =item * $title, A title to be displayed on the page.
3353:
3354: =item * $function, the current role (can be undef).
3355:
3356: =item * $addentries, extra parameters for the <body> tag.
3357:
3358: =item * $bodyonly, if defined, only return the <body> tag.
3359:
3360: =item * $domain, if defined, force a given domain.
3361:
3362: =item * $forcereg, if page should register as content page (relevant for
3363: text interface only)
3364:
3365: =item * $customtitle, alternate text to use instead of $title
3366: in the title box that appears, this text
3367: is not auto translated like the $title is
3368:
3369: =item * $notopbar, if true, keep the 'what is this' info but remove the
3370: navigational links
3371:
3372: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
3373:
3374: =item * $notitle, if true keep the nav controls, but remove the title bar
3375:
3376: =item * $no_inline_link, if true and in remote mode, don't show the
3377: 'Switch To Inline Menu' link
3378:
3379: =item * $args, optional argument valid values are
3380: no_auto_mt_title -> prevents &mt()ing the title arg
3381:
3382: =back
3383:
3384: Returns: A uniform header for LON-CAPA web pages.
3385: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
3386: If $bodyonly is undef or zero, an html string containing a <body> tag and
3387: other decorations will be returned.
3388:
3389: =cut
3390:
3391: sub bodytag {
3392: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
3393: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
3394:
3395: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
3396:
3397: $function = &get_users_function() if (!$function);
3398: my $img = &designparm($function.'.img',$domain);
3399: my $font = &designparm($function.'.font',$domain);
3400: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
3401:
3402: my %design = ( 'style' => 'margin-top: 0px',
3403: 'bgcolor' => $pgbg,
3404: 'text' => $font,
3405: 'alink' => &designparm($function.'.alink',$domain),
3406: 'vlink' => &designparm($function.'.vlink',$domain),
3407: 'link' => &designparm($function.'.link',$domain),);
3408: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
3409:
3410: # role and realm
3411: my ($role,$realm) = split(/\./,$env{'request.role'},2);
3412: if ($role eq 'ca') {
3413: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
3414: $realm = &plainname($rname,$rdom);
3415: }
3416: # realm
3417: if ($env{'request.course.id'}) {
3418: if ($env{'request.role'} !~ /^cr/) {
3419: $role = &Apache::lonnet::plaintext($role,&course_type());
3420: }
3421: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
3422: } else {
3423: $role = &Apache::lonnet::plaintext($role);
3424: }
3425:
3426: if (!$realm) { $realm=' '; }
3427: # Set messages
3428: my $messages=&domainlogo($domain);
3429: # Port for miniserver
3430: my $lonhttpdPort=$Apache::lonnet::perlvar{'lonhttpdPort'};
3431: if (!defined($lonhttpdPort)) { $lonhttpdPort='8080'; }
3432:
3433: my $extra_body_attr = &make_attr_string($forcereg,\%design);
3434:
3435: # construct main body tag
3436: my $bodytag = "<body $extra_body_attr>".
3437: &Apache::lontexconvert::init_math_support();
3438:
3439: if ($bodyonly) {
3440: return $bodytag;
3441: } elsif ($env{'browser.interface'} eq 'textual') {
3442: # Accessibility
3443:
3444: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
3445: if (!$notitle) {
3446: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
3447: }
3448: return $bodytag;
3449: }
3450:
3451: my $name = &plainname($env{'user.name'},$env{'user.domain'});
3452: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3453: undef($role);
3454: } else {
3455: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
3456: }
3457:
3458: my $roleinfo=(<<ENDROLE);
3459: <td class="LC_title_bar_who">
3460: <div class="LC_title_bar_name">
3461: $name
3462:
3463: </div>
3464: <div class="LC_title_bar_role">
3465: $role
3466: </div>
3467: <div class="LC_title_bar_realm">
3468: $realm
3469: </div>
3470: </td>
3471: ENDROLE
3472:
3473: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
3474: if ($customtitle) {
3475: $titleinfo = $customtitle;
3476: }
3477: #
3478: # Extra info if you are the DC
3479: my $dc_info = '';
3480: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
3481: $env{'course.'.$env{'request.course.id'}.
3482: '.domain'}.'/'})) {
3483: my $cid = $env{'request.course.id'};
3484: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
3485: $dc_info =~ s/\s+$//;
3486: $dc_info = '('.$dc_info.')';
3487: }
3488:
3489: if ($env{'environment.remote'} eq 'off') {
3490: # No Remote
3491: if ($env{'request.state'} eq 'construct') {
3492: $forcereg=1;
3493: }
3494:
3495: if (!$customtitle && $env{'request.state'} eq 'construct') {
3496: # this is for resources; directories have customtitle, and crumbs
3497: # and select recent are created in lonpubdir.pm
3498: my ($uname,$thisdisfn)=
3499: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
3500: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
3501: $formaction=~s/\/+/\//g;
3502:
3503: my $parentpath = '';
3504: my $lastitem = '';
3505: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
3506: $parentpath = $1;
3507: $lastitem = $2;
3508: } else {
3509: $lastitem = $thisdisfn;
3510: }
3511: $titleinfo =
3512: &Apache::loncommon::help_open_menu('','',3,'Authoring').
3513: '<b>Construction Space</b>: '.
3514: '<form name="dirs" method="post" action="'.$formaction
3515: .'" target="_top"><tt><b>'
3516: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
3517: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
3518: .'</form>'
3519: .&Apache::lonmenu::constspaceform();
3520: }
3521:
3522: my $titletable;
3523: if (!$notitle) {
3524: $titletable =
3525: '<table id="LC_title_bar">'.
3526: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
3527: '</tr></table>';
3528: }
3529: if ($notopbar) {
3530: $bodytag .= $titletable;
3531: } else {
3532: if ($env{'request.state'} eq 'construct') {
3533: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
3534: $titletable);
3535: } else {
3536: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
3537: $titletable;
3538: }
3539: }
3540: return $bodytag;
3541: }
3542:
3543: #
3544: # Top frame rendering, Remote is up
3545: #
3546:
3547: my $imgsrc = $img;
3548: if ($img =~ /^\/adm/) {
3549: $imgsrc = 'http://'.$ENV{'HTTP_HOST'}.':'.$lonhttpdPort.$img;
3550: }
3551: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
3552:
3553: # Explicit link to get inline menu
3554: my $menu= ($no_inline_link?''
3555: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
3556: #
3557: if ($notitle) {
3558: return $bodytag;
3559: }
3560: return(<<ENDBODY);
3561: $bodytag
3562: <table id="LC_title_bar" class="LC_with_remote">
3563: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
3564: <td class="LC_title_bar_domain_logo">$messages </td>
3565: </tr>
3566: <tr><td>$titleinfo $dc_info $menu</td>
3567: $roleinfo
3568: </tr>
3569: </table>
3570: ENDBODY
3571: }
3572:
3573: sub make_attr_string {
3574: my ($register,$attr_ref) = @_;
3575:
3576: if ($attr_ref && !ref($attr_ref)) {
3577: die("addentries Must be a hash ref ".
3578: join(':',caller(1))." ".
3579: join(':',caller(0))." ");
3580: }
3581:
3582: if ($register) {
3583: my ($on_load,$on_unload);
3584: foreach my $key (keys(%{$attr_ref})) {
3585: if (lc($key) eq 'onload') {
3586: $on_load.=$attr_ref->{$key}.';';
3587: delete($attr_ref->{$key});
3588:
3589: } elsif (lc($key) eq 'onunload') {
3590: $on_unload.=$attr_ref->{$key}.';';
3591: delete($attr_ref->{$key});
3592: }
3593: }
3594: $attr_ref->{'onload'} =
3595: &Apache::lonmenu::loadevents(). $on_load;
3596: $attr_ref->{'onunload'}=
3597: &Apache::lonmenu::unloadevents().$on_unload;
3598: }
3599:
3600: # Accessibility font enhance
3601: if ($env{'browser.fontenhance'} eq 'on') {
3602: my $style;
3603: foreach my $key (keys(%{$attr_ref})) {
3604: if (lc($key) eq 'style') {
3605: $style.=$attr_ref->{$key}.';';
3606: delete($attr_ref->{$key});
3607: }
3608: }
3609: $attr_ref->{'style'}=$style.'; font-size: x-large;';
3610: }
3611:
3612: if ($env{'browser.blackwhite'} eq 'on') {
3613: delete($attr_ref->{'font'});
3614: delete($attr_ref->{'link'});
3615: delete($attr_ref->{'alink'});
3616: delete($attr_ref->{'vlink'});
3617: delete($attr_ref->{'bgcolor'});
3618: delete($attr_ref->{'background'});
3619: }
3620:
3621: my $attr_string;
3622: foreach my $attr (keys(%$attr_ref)) {
3623: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
3624: }
3625: return $attr_string;
3626: }
3627:
3628:
3629: ###############################################
3630: ###############################################
3631:
3632: =pod
3633:
3634: =back
3635:
3636: =head1 HTML Helpers
3637:
3638: =over 4
3639:
3640: =item * &endbodytag()
3641:
3642: Returns a uniform footer for LON-CAPA web pages.
3643:
3644: Inputs: none
3645:
3646: =back
3647:
3648: =cut
3649:
3650: sub endbodytag {
3651: my $endbodytag='</body>';
3652: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
3653: if ( exists( $env{'internal.head.redirect'} ) ) {
3654: $endbodytag=
3655: "<br /><a href=\"$env{'internal.head.redirect'}\">".
3656: &mt('Continue').'</a>'.
3657: $endbodytag;
3658: }
3659: return $endbodytag;
3660: }
3661:
3662: =pod
3663:
3664: =over 4
3665:
3666: =item * &standard_css()
3667:
3668: Returns a style sheet
3669:
3670: Inputs: (all optional)
3671: domain -> force to color decorate a page for a specific
3672: domain
3673: function -> force usage of a specific rolish color scheme
3674: bgcolor -> override the default page bgcolor
3675:
3676: =back
3677:
3678: =cut
3679:
3680: sub standard_css {
3681: my ($function,$domain,$bgcolor) = @_;
3682: $function = &get_users_function() if (!$function);
3683: my $img = &designparm($function.'.img', $domain);
3684: my $tabbg = &designparm($function.'.tabbg', $domain);
3685: my $font = &designparm($function.'.font', $domain);
3686: my $sidebg = &designparm($function.'.sidebg',$domain);
3687: my $pgbg_or_bgcolor =
3688: $bgcolor ||
3689: &designparm($function.'.pgbg', $domain);
3690: my $pgbg = &designparm($function.'.pgbg', $domain);
3691: my $alink = &designparm($function.'.alink', $domain);
3692: my $vlink = &designparm($function.'.vlink', $domain);
3693: my $link = &designparm($function.'.link', $domain);
3694:
3695: my $sans = 'Arial,Helvetica,sans-serif';
3696: my $mono = 'monospace';
3697: my $data_table_head = $tabbg;
3698: my $data_table_light = '#EEEEEE';
3699: my $data_table_dark = '#DDDDDD';
3700: my $data_table_darker = '#CCCCCC';
3701: my $data_table_highlight = '#FFFF00';
3702: my $mail_new = '#FFBB77';
3703: my $mail_new_hover = '#DD9955';
3704: my $mail_read = '#BBBB77';
3705: my $mail_read_hover = '#999944';
3706: my $mail_replied = '#AAAA88';
3707: my $mail_replied_hover = '#888855';
3708: my $mail_other = '#99BBBB';
3709: my $mail_other_hover = '#669999';
3710: my $table_header = '#DDDDDD';
3711: my $feedback_link_bg = '#BBBBBB';
3712:
3713: my $border = ($env{'browser.type'} eq 'explorer') ? '0px 2px 0px 2px'
3714: : '0px 3px 0px 4px';
3715:
3716:
3717: return <<END;
3718: h1, h2, h3, th { font-family: $sans }
3719: a:focus { color: red; background: yellow }
3720: table.thinborder,
3721:
3722: table.thinborder tr th {
3723: border-style: solid;
3724: border-width: 1px;
3725: background: $tabbg;
3726: }
3727: table.thinborder tr td {
3728: border-style: solid;
3729: border-width: 1px
3730: }
3731:
3732: form, .inline { display: inline; }
3733: .center { text-align: center; }
3734: .LC_filename {font-family: $mono;}
3735: .LC_error {
3736: color: red;
3737: font-size: larger;
3738: }
3739: .LC_warning,
3740: .LC_diff_removed {
3741: color: red;
3742: }
3743:
3744: .LC_info,
3745: .LC_success,
3746: .LC_diff_added {
3747: color: green;
3748: }
3749: .LC_icon {
3750: border: 0px;
3751: }
3752: .LC_indexer_icon {
3753: border: 0px;
3754: height: 22px;
3755: }
3756:
3757: .LC_internal_info {
3758: color: #999;
3759: }
3760:
3761: table.LC_pastsubmission {
3762: border: 1px solid black;
3763: margin: 2px;
3764: }
3765:
3766: table#LC_top_nav, table#LC_menubuttons {
3767: width: 100%;
3768: background: $pgbg;
3769: border: 2px;
3770: border-collapse: separate;
3771: padding: 0px;
3772: }
3773:
3774: table#LC_title_bar, table.LC_breadcrumbs, table#LC_nav_location,
3775: table#LC_title_bar.LC_with_remote {
3776: width: 100%;
3777: border-color: $pgbg;
3778: border-style: solid;
3779: border-width: $border;
3780:
3781: background: $pgbg;
3782: font-family: $sans;
3783: border-collapse: collapse;
3784: padding: 0px;
3785: }
3786:
3787: table.LC_docs_path {
3788: width: 100%;
3789: border: 0;
3790: background: $pgbg;
3791: font-family: $sans;
3792: border-collapse: collapse;
3793: padding: 0px;
3794: }
3795:
3796: table#LC_title_bar td {
3797: background: $tabbg;
3798: }
3799: table#LC_title_bar td.LC_title_bar_who {
3800: background: $tabbg;
3801: color: $font;
3802: font: small $sans;
3803: text-align: right;
3804: }
3805: span.LC_metadata {
3806: font-family: $sans;
3807: }
3808: span.LC_title_bar_title {
3809: font: bold x-large $sans;
3810: }
3811: table#LC_title_bar td.LC_title_bar_domain_logo {
3812: background: $sidebg;
3813: text-align: right;
3814: padding: 0px;
3815: }
3816: table#LC_title_bar td.LC_title_bar_role_logo {
3817: background: $sidebg;
3818: padding: 0px;
3819: }
3820:
3821: table#LC_menubuttons_mainmenu {
3822: width: 100%;
3823: border: 0px;
3824: border-spacing: 1px;
3825: padding: 0px 1px;
3826: margin: 0px;
3827: border-collapse: separate;
3828: }
3829: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
3830: border: 0px;
3831: }
3832: table#LC_top_nav td {
3833: background: $tabbg;
3834: border: 0px;
3835: font-size: small;
3836: }
3837: table#LC_top_nav td a, div#LC_top_nav a {
3838: color: $font;
3839: font-family: $sans;
3840: }
3841: table#LC_top_nav td.LC_top_nav_logo {
3842: background: $tabbg;
3843: text-align: left;
3844: white-space: nowrap;
3845: width: 31px;
3846: }
3847: table#LC_top_nav td.LC_top_nav_logo img {
3848: border: 0px;
3849: vertical-align: bottom;
3850: }
3851: table#LC_top_nav td.LC_top_nav_exit,
3852: table#LC_top_nav td.LC_top_nav_help {
3853: width: 2.0em;
3854: }
3855: table#LC_top_nav td.LC_top_nav_login {
3856: width: 4.0em;
3857: text-align: center;
3858: }
3859: table.LC_breadcrumbs td, table.LC_docs_path td {
3860: background: $tabbg;
3861: color: $font;
3862: font-family: $sans;
3863: font-size: smaller;
3864: }
3865: table.LC_breadcrumbs td.LC_breadcrumbs_component,
3866: table.LC_docs_path td.LC_docs_path_component {
3867: background: $tabbg;
3868: color: $font;
3869: font-family: $sans;
3870: font-size: larger;
3871: text-align: right;
3872: }
3873: td.LC_table_cell_checkbox {
3874: text-align: center;
3875: }
3876:
3877: table#LC_mainmenu td.LC_mainmenu_column {
3878: vertical-align: top;
3879: }
3880:
3881: .LC_menubuttons_inline_text {
3882: color: $font;
3883: font-family: $sans;
3884: font-size: smaller;
3885: }
3886:
3887: .LC_menubuttons_link {
3888: text-decoration: none;
3889: }
3890:
3891: .LC_menubuttons_category {
3892: color: $font;
3893: background: $pgbg;
3894: font-family: $sans;
3895: font-size: larger;
3896: font-weight: bold;
3897: }
3898:
3899: td.LC_menubuttons_text {
3900: width: 90%;
3901: color: $font;
3902: font-family: $sans;
3903: }
3904:
3905: td.LC_menubuttons_img {
3906: }
3907:
3908: .LC_current_location {
3909: font-family: $sans;
3910: background: $tabbg;
3911: }
3912: .LC_new_mail {
3913: font-family: $sans;
3914: font-weight: bold;
3915: }
3916:
3917: .LC_rolesmenu_is {
3918: font-family: $sans;
3919: }
3920:
3921: .LC_rolesmenu_selected {
3922: font-family: $sans;
3923: }
3924:
3925: .LC_rolesmenu_future {
3926: font-family: $sans;
3927: }
3928:
3929:
3930: .LC_rolesmenu_will {
3931: font-family: $sans;
3932: }
3933:
3934: .LC_rolesmenu_will_not {
3935: font-family: $sans;
3936: }
3937:
3938: .LC_rolesmenu_expired {
3939: font-family: $sans;
3940: }
3941:
3942: .LC_rolesinfo {
3943: font-family: $sans;
3944: }
3945:
3946: .LC_dropadd_labeltext {
3947: font-family: $sans;
3948: text-align: right;
3949: }
3950:
3951: .LC_preferences_labeltext {
3952: font-family: $sans;
3953: text-align: right;
3954: }
3955:
3956: table.LC_aboutme_port {
3957: border: 0px;
3958: border-collapse: collapse;
3959: border-spacing: 0px;
3960: }
3961: table.LC_data_table, table.LC_mail_list {
3962: border: 1px solid #000000;
3963: border-collapse: separate;
3964: border-spacing: 1px;
3965: }
3966: .LC_data_table_dense {
3967: font-size: small;
3968: }
3969: table.LC_nested_outer {
3970: border: 1px solid #000000;
3971: border-collapse: separate;
3972: border-spacing: 0px;
3973: width: 100%;
3974: }
3975: table.LC_nested {
3976: border: 0px;
3977: border-collapse: separate;
3978: border-spacing: 0px;
3979: width: 100%;
3980: }
3981: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
3982: table.LC_prior_tries tr th {
3983: font-weight: bold;
3984: background-color: $data_table_head;
3985: font-size: smaller;
3986: }
3987: table.LC_data_table tr td,
3988: table.LC_aboutme_port tr td {
3989: background-color: $data_table_light;
3990: padding: 2px;
3991: }
3992: table.LC_data_table tr.LC_even_row td,
3993: table.LC_aboutme_port tr.LC_even_row td {
3994: background-color: $data_table_dark;
3995: }
3996: table.LC_data_table tr.LC_data_table_highlight td {
3997: background-color: $data_table_darker;
3998: }
3999: table.LC_data_table tr.LC_empty_row td,
4000: table.LC_nested tr.LC_empty_row td {
4001: background-color: #FFFFFF;
4002: font-weight: bold;
4003: font-style: italic;
4004: text-align: center;
4005: padding: 8px;
4006: }
4007: table.LC_nested tr.LC_empty_row td {
4008: padding: 4ex
4009: }
4010: table.LC_nested_outer tr th {
4011: font-weight: bold;
4012: background-color: $data_table_head;
4013: font-size: smaller;
4014: border-bottom: 1px solid #000000;
4015: }
4016: table.LC_nested_outer tr td.LC_subheader {
4017: background-color: $data_table_head;
4018: font-weight: bold;
4019: font-size: small;
4020: border-bottom: 1px solid #000000;
4021: text-align: right;
4022: }
4023: table.LC_nested tr.LC_info_row td {
4024: background-color: #CCC;
4025: font-weight: bold;
4026: font-size: small;
4027: text-align: center;
4028: }
4029: table.LC_nested tr.LC_info_row td.LC_left_item {
4030: text-align: left;
4031: }
4032: table.LC_nested td {
4033: background-color: #FFF;
4034: font-size: small;
4035: }
4036: table.LC_nested_outer tr th.LC_right_item,
4037: table.LC_nested tr.LC_info_row td.LC_right_item,
4038: table.LC_nested tr.LC_odd_row td.LC_right_item,
4039: table.LC_nested tr td.LC_right_item {
4040: text-align: right;
4041: }
4042:
4043: table.LC_nested tr.LC_odd_row td {
4044: background-color: #EEE;
4045: }
4046:
4047: table.LC_createuser {
4048: }
4049:
4050: table.LC_createuser tr.LC_section_row td {
4051: font-size: smaller;
4052: }
4053:
4054: table.LC_createuser tr.LC_info_row td {
4055: background-color: #CCC;
4056: font-weight: bold;
4057: text-align: center;
4058: }
4059:
4060: table.LC_calendar {
4061: border: 1px solid #000000;
4062: border-collapse: collapse;
4063: }
4064: table.LC_calendar_pickdate {
4065: font-size: xx-small;
4066: }
4067: table.LC_calendar tr td {
4068: border: 1px solid #000000;
4069: vertical-align: top;
4070: }
4071: table.LC_calendar tr td.LC_calendar_day_empty {
4072: background-color: $data_table_dark;
4073: }
4074: table.LC_calendar tr td.LC_calendar_day_current {
4075: background-color: $data_table_highlight;
4076: }
4077:
4078: table.LC_mail_list tr.LC_mail_new {
4079: background-color: $mail_new;
4080: }
4081: table.LC_mail_list tr.LC_mail_new:hover {
4082: background-color: $mail_new_hover;
4083: }
4084: table.LC_mail_list tr.LC_mail_read {
4085: background-color: $mail_read;
4086: }
4087: table.LC_mail_list tr.LC_mail_read:hover {
4088: background-color: $mail_read_hover;
4089: }
4090: table.LC_mail_list tr.LC_mail_replied {
4091: background-color: $mail_replied;
4092: }
4093: table.LC_mail_list tr.LC_mail_replied:hover {
4094: background-color: $mail_replied_hover;
4095: }
4096: table.LC_mail_list tr.LC_mail_other {
4097: background-color: $mail_other;
4098: }
4099: table.LC_mail_list tr.LC_mail_other:hover {
4100: background-color: $mail_other_hover;
4101: }
4102: table.LC_mail_list tr.LC_mail_even {
4103: }
4104: table.LC_mail_list tr.LC_mail_odd {
4105: }
4106:
4107:
4108: table#LC_portfolio_actions {
4109: width: auto;
4110: background: $pgbg;
4111: border: 0px;
4112: border-spacing: 2px 2px;
4113: padding: 0px;
4114: margin: 0px;
4115: border-collapse: separate;
4116: }
4117: table#LC_portfolio_actions td.LC_label {
4118: background: $tabbg;
4119: text-align: right;
4120: }
4121: table#LC_portfolio_actions td.LC_value {
4122: background: $tabbg;
4123: }
4124:
4125: table#LC_cstr_controls {
4126: width: 100%;
4127: border-collapse: collapse;
4128: }
4129: table#LC_cstr_controls tr td {
4130: border: 4px solid $pgbg;
4131: padding: 4px;
4132: text-align: center;
4133: background: $tabbg;
4134: }
4135: table#LC_cstr_controls tr th {
4136: border: 4px solid $pgbg;
4137: background: $table_header;
4138: text-align: center;
4139: font-family: $sans;
4140: font-size: smaller;
4141: }
4142:
4143: table#LC_browser {
4144:
4145: }
4146: table#LC_browser tr th {
4147: background: $table_header;
4148: }
4149: table#LC_browser tr td {
4150: padding: 2px;
4151: }
4152: table#LC_browser tr.LC_browser_file,
4153: table#LC_browser tr.LC_browser_file_published {
4154: background: #CCFF88;
4155: }
4156: table#LC_browser tr.LC_browser_file_locked,
4157: table#LC_browser tr.LC_browser_file_unpublished {
4158: background: #FFAA99;
4159: }
4160: table#LC_browser tr.LC_browser_file_obsolete {
4161: background: #AAAAAA;
4162: }
4163: table#LC_browser tr.LC_browser_file_modified,
4164: table#LC_browser tr.LC_browser_file_metamodified {
4165: background: #FFFF77;
4166: }
4167: table#LC_browser tr.LC_browser_folder {
4168: background: #CCCCFF;
4169: }
4170: span.LC_current_location {
4171: font-size: x-large;
4172: background: $pgbg;
4173: }
4174:
4175: span.LC_parm_menu_item {
4176: font-size: larger;
4177: font-family: $sans;
4178: }
4179: span.LC_parm_scope_all {
4180: color: red;
4181: }
4182: span.LC_parm_scope_folder {
4183: color: green;
4184: }
4185: span.LC_parm_scope_resource {
4186: color: orange;
4187: }
4188: span.LC_parm_part {
4189: color: blue;
4190: }
4191: span.LC_parm_folder, span.LC_parm_symb {
4192: font-size: x-small;
4193: font-family: $mono;
4194: color: #AAAAAA;
4195: }
4196:
4197: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
4198: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
4199: border: 1px solid black;
4200: border-collapse: collapse;
4201: }
4202: table.LC_parm_overview_restrictions td {
4203: border-width: 1px 4px 1px 4px;
4204: border-style: solid;
4205: border-color: $pgbg;
4206: text-align: center;
4207: }
4208: table.LC_parm_overview_restrictions th {
4209: background: $tabbg;
4210: border-width: 1px 4px 1px 4px;
4211: border-style: solid;
4212: border-color: $pgbg;
4213: }
4214: table#LC_helpmenu {
4215: border: 0px;
4216: height: 55px;
4217: border-spacing: 0px;
4218: }
4219:
4220: table#LC_helpmenu fieldset legend {
4221: font-size: larger;
4222: font-weight: bold;
4223: }
4224: table#LC_helpmenu_links {
4225: width: 100%;
4226: border: 1px solid black;
4227: background: $pgbg;
4228: padding: 0px;
4229: border-spacing: 1px;
4230: }
4231: table#LC_helpmenu_links tr td {
4232: padding: 1px;
4233: background: $tabbg;
4234: text-align: center;
4235: font-weight: bold;
4236: }
4237:
4238: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
4239: table#LC_helpmenu_links a:active {
4240: text-decoration: none;
4241: color: $font;
4242: }
4243: table#LC_helpmenu_links a:hover {
4244: text-decoration: underline;
4245: color: $vlink;
4246: }
4247:
4248: .LC_chrt_popup_exists {
4249: border: 1px solid #339933;
4250: margin: -1px;
4251: }
4252: .LC_chrt_popup_up {
4253: border: 1px solid yellow;
4254: margin: -1px;
4255: }
4256: .LC_chrt_popup {
4257: border: 1px solid #8888FF;
4258: background: #CCCCFF;
4259: }
4260:
4261: table.LC_pick_box {
4262: width: 100%;
4263: border-collapse: separate;
4264: background: white;
4265: border: 1px solid black;
4266: border-spacing: 1px;
4267: }
4268: table.LC_pick_box td.LC_pick_box_title {
4269: background: $tabbg;
4270: font-weight: bold;
4271: text-align: right;
4272: width: 184px;
4273: padding: 8px;
4274: }
4275: table.LC_pick_box td.LC_pick_box_separator {
4276: padding: 0px;
4277: height: 1px;
4278: background: black;
4279: }
4280: table.LC_pick_box td.LC_pick_box_submit {
4281: text-align: right;
4282: }
4283:
4284: table.LC_group_priv_box {
4285: background: white;
4286: border: 1px solid black;
4287: border-spacing: 1px;
4288: }
4289: table.LC_group_priv_box td.LC_pick_box_title {
4290: background: $tabbg;
4291: font-weight: bold;
4292: text-align: right;
4293: width: 184px;
4294: }
4295: table.LC_group_priv_box td.LC_groups_fixed {
4296: background: $data_table_light;
4297: text-align: center;
4298: }
4299: table.LC_group_priv_box td.LC_groups_optional {
4300: background: $data_table_dark;
4301: text-align: center;
4302: }
4303: table.LC_group_priv_box td.LC_groups_functionality {
4304: background: $data_table_darker;
4305: text-align: center;
4306: font-weight: bold;
4307: }
4308: table.LC_group_priv td {
4309: text-align: left;
4310: padding: 0px;
4311: }
4312:
4313: table.LC_notify_front_page {
4314: background: white;
4315: border: 1px solid black;
4316: padding: 8px;
4317: }
4318: table.LC_notify_front_page td {
4319: padding: 8px;
4320: }
4321: .LC_navbuttons {
4322: margin: 2ex 0ex 2ex 0ex;
4323: }
4324: .LC_topic_bar {
4325: font-family: $sans;
4326: font-weight: bold;
4327: width: 100%;
4328: background: $tabbg;
4329: vertical-align: middle;
4330: margin: 2ex 0ex 2ex 0ex;
4331: }
4332: .LC_topic_bar span {
4333: vertical-align: middle;
4334: }
4335: .LC_topic_bar img {
4336: vertical-align: bottom;
4337: }
4338: table.LC_course_group_status {
4339: margin: 20px;
4340: }
4341: table.LC_status_selector td {
4342: vertical-align: top;
4343: text-align: center;
4344: padding: 4px;
4345: }
4346: table.LC_descriptive_input td.LC_description {
4347: vertical-align: top;
4348: text-align: right;
4349: font-weight: bold;
4350: }
4351: table.LC_feedback_link {
4352: background: $feedback_link_bg;
4353: }
4354: span.LC_feedback_link {
4355: background: $feedback_link_bg;
4356: font-size: larger;
4357: }
4358:
4359: table.LC_prior_tries {
4360: border: 1px solid #000000;
4361: border-collapse: separate;
4362: border-spacing: 1px;
4363: }
4364:
4365: table.LC_prior_tries td {
4366: padding: 2px;
4367: }
4368:
4369: .LC_answer_correct {
4370: background: #AAFFAA;
4371: color: black;
4372: }
4373: .LC_answer_charged_try {
4374: background: #FFAAAA ! important;
4375: color: black;
4376: }
4377: .LC_answer_not_charged_try,
4378: .LC_answer_no_grade,
4379: .LC_answer_late {
4380: background: #FFFFAA;
4381: color: black;
4382: }
4383: .LC_answer_previous {
4384: background: #AAAAFF;
4385: color: black;
4386: }
4387: .LC_answer_no_message {
4388: background: #FFFFFF;
4389: color: black;
4390: }
4391: .LC_answer_unknown {
4392: background: orange;
4393: color: black;
4394: }
4395:
4396:
4397: span.LC_prior_numerical,
4398: span.LC_prior_string,
4399: span.LC_prior_custom,
4400: span.LC_prior_reaction,
4401: span.LC_prior_math {
4402: font-family: monospace;
4403: white-space: pre;
4404: }
4405:
4406: span.LC_prior_string {
4407: font-family: monospace;
4408: white-space: pre;
4409: }
4410:
4411: table.LC_prior_option {
4412: width: 100%;
4413: border-collapse: collapse;
4414: }
4415: table.LC_prior_rank, table.LC_prior_match {
4416: border-collapse: collapse;
4417: }
4418: table.LC_prior_option tr td,
4419: table.LC_prior_rank tr td,
4420: table.LC_prior_match tr td {
4421: border: 1px solid #000000;
4422: }
4423:
4424: span.LC_nobreak {
4425: white-space: nowrap;
4426: }
4427:
4428: END
4429: }
4430:
4431: =pod
4432:
4433: =over 4
4434:
4435: =item * &headtag()
4436:
4437: Returns a uniform footer for LON-CAPA web pages.
4438:
4439: Inputs: $title - optional title for the head
4440: $head_extra - optional extra HTML to put inside the <head>
4441: $args - optional arguments
4442: force_register - if is true call registerurl so the remote is
4443: informed
4444: redirect -> array ref of
4445: 1- seconds before redirect occurs
4446: 2- url to redirect to
4447: 3- whether the side effect should occur
4448: (side effect of setting
4449: $env{'internal.head.redirect'} to the url
4450: redirected too)
4451: domain -> force to color decorate a page for a specific
4452: domain
4453: function -> force usage of a specific rolish color scheme
4454: bgcolor -> override the default page bgcolor
4455: no_auto_mt_title
4456: -> prevent &mt()ing the title arg
4457:
4458: =back
4459:
4460: =cut
4461:
4462: sub headtag {
4463: my ($title,$head_extra,$args) = @_;
4464:
4465: my $function = $args->{'function'} || &get_users_function();
4466: my $domain = $args->{'domain'} || &determinedomain();
4467: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
4468: my $url = join(':',$env{'user.name'},$env{'user.domain'},
4469: $Apache::lonnet::perlvar{'lonVersion'},
4470: #time(),
4471: $env{'environment.color.timestamp'},
4472: $function,$domain,$bgcolor);
4473:
4474: $url = '/adm/css/'.&escape($url).'.css';
4475:
4476: my $result =
4477: '<head>'.
4478: &font_settings();
4479:
4480: if (!$args->{'frameset'}) {
4481: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
4482: }
4483: if ($args->{'force_register'}) {
4484: $result .= &Apache::lonmenu::registerurl(1);
4485: }
4486: if (!$args->{'no_nav_bar'}
4487: && !$args->{'only_body'}
4488: && !$args->{'frameset'}) {
4489: $result .= &help_menu_js();
4490: }
4491:
4492: if (ref($args->{'redirect'})) {
4493: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
4494: $url = &Apache::lonenc::check_encrypt($url);
4495: if (!$inhibit_continue) {
4496: $env{'internal.head.redirect'} = $url;
4497: }
4498: $result.=<<ADDMETA
4499: <meta http-equiv="pragma" content="no-cache" />
4500: <meta http-equiv="Refresh" content="$time; url=$url" />
4501: ADDMETA
4502: }
4503: if (!defined($title)) {
4504: $title = 'The LearningOnline Network with CAPA';
4505: }
4506: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4507: $result .= '<title> LON-CAPA '.$title.'</title>'
4508: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
4509: .$head_extra;
4510: return $result;
4511: }
4512:
4513: =pod
4514:
4515: =over 4
4516:
4517: =item * &font_settings()
4518:
4519: Returns neccessary <meta> to set the proper encoding
4520:
4521: Inputs: none
4522:
4523: =back
4524:
4525: =cut
4526:
4527: sub font_settings {
4528: my $headerstring='';
4529: if (($env{'browser.os'} eq 'mac') && (!$env{'browser.mathml'})) {
4530: $headerstring.=
4531: '<meta Content-Type="text/html; charset=x-mac-roman" />';
4532: } elsif (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
4533: $headerstring.=
4534: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
4535: }
4536: return $headerstring;
4537: }
4538:
4539: =pod
4540:
4541: =over 4
4542:
4543: =item * &xml_begin()
4544:
4545: Returns the needed doctype and <html>
4546:
4547: Inputs: none
4548:
4549: =back
4550:
4551: =cut
4552:
4553: sub xml_begin {
4554: my $output='';
4555:
4556: &Apache::lonhtmlcommon::init_htmlareafields();
4557:
4558: if ($env{'browser.mathml'}) {
4559: $output='<?xml version="1.0"?>'
4560: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
4561: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
4562:
4563: # .'<!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">] >'
4564: .'<!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">'
4565: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
4566: .'xmlns="http://www.w3.org/1999/xhtml">';
4567: } else {
4568: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
4569: }
4570: return $output;
4571: }
4572:
4573: =pod
4574:
4575: =over 4
4576:
4577: =item * &endheadtag()
4578:
4579: Returns a uniform </head> for LON-CAPA web pages.
4580:
4581: Inputs: none
4582:
4583: =back
4584:
4585: =cut
4586:
4587: sub endheadtag {
4588: return '</head>';
4589: }
4590:
4591: =pod
4592:
4593: =over 4
4594:
4595: =item * &head()
4596:
4597: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
4598:
4599: Inputs: $title - optional title for the page
4600: $head_extra - optional extra HTML to put inside the <head>
4601:
4602: =back
4603:
4604: =cut
4605:
4606: sub head {
4607: my ($title,$head_extra,$args) = @_;
4608: return &headtag($title,$head_extra,$args).&endheadtag();
4609: }
4610:
4611: =pod
4612:
4613: =over 4
4614:
4615: =item * &start_page()
4616:
4617: Returns a complete <html> .. <body> section for LON-CAPA web pages.
4618:
4619: Inputs: $title - optional title for the page
4620: $head_extra - optional extra HTML to incude inside the <head>
4621: $args - additional optional args supported are:
4622: only_body -> is true will set &bodytag() onlybodytag
4623: arg on
4624: no_nav_bar -> is true will set &bodytag() notopbar arg on
4625: add_entries -> additional attributes to add to the <body>
4626: domain -> force to color decorate a page for a
4627: specific domain
4628: function -> force usage of a specific rolish color
4629: scheme
4630: redirect -> see &headtag()
4631: bgcolor -> override the default page bg color
4632: js_ready -> return a string ready for being used in
4633: a javascript writeln
4634: html_encode -> return a string ready for being used in
4635: a html attribute
4636: force_register -> if is true will turn on the &bodytag()
4637: $forcereg arg
4638: body_title -> alternate text to use instead of $title
4639: in the title box that appears, this text
4640: is not auto translated like the $title is
4641: frameset -> if true will start with a <frameset>
4642: rather than <body>
4643: no_title -> if true the title bar won't be shown
4644: skip_phases -> hash ref of
4645: head -> skip the <html><head> generation
4646: body -> skip all <body> generation
4647:
4648: no_inline_link -> if true and in remote mode, don't show the
4649: 'Switch To Inline Menu' link
4650:
4651: no_auto_mt_title -> prevent &mt()ing the title arg
4652:
4653: =back
4654:
4655: =cut
4656:
4657: sub start_page {
4658: my ($title,$head_extra,$args) = @_;
4659: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
4660: my %head_args;
4661: foreach my $arg ('redirect','force_register','domain','function',
4662: 'bgcolor','frameset','no_nav_bar','only_body',
4663: 'no_auto_mt_title') {
4664: if (defined($args->{$arg})) {
4665: $head_args{$arg} = $args->{$arg};
4666: }
4667: }
4668:
4669: $env{'internal.start_page'}++;
4670: my $result;
4671: if (! exists($args->{'skip_phases'}{'head'}) ) {
4672: $result.=
4673: &xml_begin().
4674: &headtag($title,$head_extra,\%head_args).&endheadtag();
4675: }
4676:
4677: if (! exists($args->{'skip_phases'}{'body'}) ) {
4678: if ($args->{'frameset'}) {
4679: my $attr_string = &make_attr_string($args->{'force_register'},
4680: $args->{'add_entries'});
4681: $result .= "\n<frameset $attr_string>\n";
4682: } else {
4683: $result .=
4684: &bodytag($title,
4685: $args->{'function'}, $args->{'add_entries'},
4686: $args->{'only_body'}, $args->{'domain'},
4687: $args->{'force_register'}, $args->{'body_title'},
4688: $args->{'no_nav_bar'}, $args->{'bgcolor'},
4689: $args->{'no_title'}, $args->{'no_inline_link'},
4690: $args);
4691: }
4692: }
4693:
4694: if ($args->{'js_ready'}) {
4695: $result = &js_ready($result);
4696: }
4697: if ($args->{'html_encode'}) {
4698: $result = &html_encode($result);
4699: }
4700: return $result;
4701: }
4702:
4703:
4704: =pod
4705:
4706: =over 4
4707:
4708: =item * &head()
4709:
4710: Returns a complete </body></html> section for LON-CAPA web pages.
4711:
4712: Inputs: $args - additional optional args supported are:
4713: js_ready -> return a string ready for being used in
4714: a javascript writeln
4715: html_encode -> return a string ready for being used in
4716: a html attribute
4717: frameset -> if true will start with a <frameset>
4718: rather than <body>
4719: dicsussion -> if true will get discussion from
4720: lonxml::xmlend
4721: (you can pass the target and parser arguments
4722: through optional 'target' and 'parser' args
4723: to this routine)
4724:
4725: =cut
4726:
4727: sub end_page {
4728: my ($args) = @_;
4729: $env{'internal.end_page'}++;
4730: my $result;
4731: if ($args->{'discussion'}) {
4732: my ($target,$parser);
4733: if (ref($args->{'discussion'})) {
4734: ($target,$parser) =($args->{'discussion'}{'target'},
4735: $args->{'discussion'}{'parser'});
4736: }
4737: $result .= &Apache::lonxml::xmlend($target,$parser);
4738: }
4739:
4740: if ($args->{'frameset'}) {
4741: $result .= '</frameset>';
4742: } else {
4743: $result .= &endbodytag();
4744: }
4745: $result .= "\n</html>";
4746:
4747: if ($args->{'js_ready'}) {
4748: $result = &js_ready($result);
4749: }
4750:
4751: if ($args->{'html_encode'}) {
4752: $result = &html_encode($result);
4753: }
4754:
4755: return $result;
4756: }
4757:
4758: sub html_encode {
4759: my ($result) = @_;
4760:
4761: $result = &HTML::Entities::encode($result,'<>&"');
4762:
4763: return $result;
4764: }
4765: sub js_ready {
4766: my ($result) = @_;
4767:
4768: $result =~ s/[\n\r]/ /xmsg;
4769: $result =~ s/\\/\\\\/xmsg;
4770: $result =~ s/'/\\'/xmsg;
4771: $result =~ s{</}{<\\/}xmsg;
4772:
4773: return $result;
4774: }
4775:
4776: sub validate_page {
4777: if ( exists($env{'internal.start_page'})
4778: && $env{'internal.start_page'} > 1) {
4779: &Apache::lonnet::logthis('start_page called multiple times '.
4780: $env{'internal.start_page'}.' '.
4781: $ENV{'request.filename'});
4782: }
4783: if ( exists($env{'internal.end_page'})
4784: && $env{'internal.end_page'} > 1) {
4785: &Apache::lonnet::logthis('end_page called multiple times '.
4786: $env{'internal.end_page'}.' '.
4787: $env{'request.filename'});
4788: }
4789: if ( exists($env{'internal.start_page'})
4790: && ! exists($env{'internal.end_page'})) {
4791: &Apache::lonnet::logthis('start_page called without end_page '.
4792: $env{'request.filename'});
4793: }
4794: if ( ! exists($env{'internal.start_page'})
4795: && exists($env{'internal.end_page'})) {
4796: &Apache::lonnet::logthis('end_page called without start_page'.
4797: $env{'request.filename'});
4798: }
4799: }
4800:
4801: sub simple_error_page {
4802: my ($r,$title,$msg) = @_;
4803: my $page =
4804: &Apache::loncommon::start_page($title).
4805: &mt($msg).
4806: &Apache::loncommon::end_page();
4807: if (ref($r)) {
4808: $r->print($page);
4809: return;
4810: }
4811: return $page;
4812: }
4813:
4814: {
4815: my $row_count;
4816: sub start_data_table {
4817: my ($add_class) = @_;
4818: my $css_class = (join(' ','LC_data_table',$add_class));
4819: undef($row_count);
4820: return '<table class="'.$css_class.'">'."\n";
4821: }
4822:
4823: sub end_data_table {
4824: undef($row_count);
4825: return '</table>'."\n";;
4826: }
4827:
4828: sub start_data_table_row {
4829: my ($add_class) = @_;
4830: $row_count++;
4831: my $css_class = ($row_count % 2)?'':'LC_even_row';
4832: $css_class = (join(' ',$css_class,$add_class));
4833: return '<tr class="'.$css_class.'">'."\n";;
4834: }
4835:
4836: sub continue_data_table_row {
4837: my ($add_class) = @_;
4838: my $css_class = ($row_count % 2)?'':'LC_even_row';
4839: $css_class = (join(' ',$css_class,$add_class));
4840: return '<tr class="'.$css_class.'">'."\n";;
4841: }
4842:
4843: sub end_data_table_row {
4844: return '</tr>'."\n";;
4845: }
4846:
4847: sub start_data_table_empty_row {
4848: $row_count++;
4849: return '<tr class="LC_empty_row" >'."\n";;
4850: }
4851:
4852: sub end_data_table_empty_row {
4853: return '</tr>'."\n";;
4854: }
4855:
4856: sub start_data_table_header_row {
4857: return '<tr class="LC_header_row">'."\n";;
4858: }
4859:
4860: sub end_data_table_header_row {
4861: return '</tr>'."\n";;
4862: }
4863: }
4864:
4865: ###############################################
4866:
4867: =pod
4868:
4869: =item * &get_users_function()
4870:
4871: Used by &bodytag to determine the current users primary role.
4872: Returns either 'student','coordinator','admin', or 'author'.
4873:
4874: =cut
4875:
4876: ###############################################
4877: sub get_users_function {
4878: my $function = 'student';
4879: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
4880: $function='coordinator';
4881: }
4882: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
4883: $function='admin';
4884: }
4885: if (($env{'request.role'}=~/^(au|ca)/) ||
4886: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
4887: $function='author';
4888: }
4889: return $function;
4890: }
4891:
4892: ###############################################
4893:
4894: =pod
4895:
4896: =item * &check_user_status()
4897:
4898: Determines current status of supplied role for a
4899: specific user. Roles can be active, previous or future.
4900:
4901: Inputs:
4902: user's domain, user's username, course's domain,
4903: course's number, optional section ID.
4904:
4905: Outputs:
4906: role status: active, previous or future.
4907:
4908: =cut
4909:
4910: sub check_user_status {
4911: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
4912: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
4913: my @uroles = keys %userinfo;
4914: my $srchstr;
4915: my $active_chk = 'none';
4916: my $now = time;
4917: if (@uroles > 0) {
4918: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
4919: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
4920: } else {
4921: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
4922: }
4923: if (grep/^\Q$srchstr\E$/,@uroles) {
4924: my $role_end = 0;
4925: my $role_start = 0;
4926: $active_chk = 'active';
4927: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
4928: $role_end = $1;
4929: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
4930: $role_start = $1;
4931: }
4932: }
4933: if ($role_start > 0) {
4934: if ($now < $role_start) {
4935: $active_chk = 'future';
4936: }
4937: }
4938: if ($role_end > 0) {
4939: if ($now > $role_end) {
4940: $active_chk = 'previous';
4941: }
4942: }
4943: }
4944: }
4945: return $active_chk;
4946: }
4947:
4948: ###############################################
4949:
4950: =pod
4951:
4952: =item * &get_sections()
4953:
4954: Determines all the sections for a course including
4955: sections with students and sections containing other roles.
4956: Incoming parameters:
4957:
4958: 1. domain
4959: 2. course number
4960: 3. reference to array containing roles for which sections should
4961: be gathered (optional).
4962: 4. reference to array containing status types for which sections
4963: should be gathered (optional).
4964:
4965: If the third argument is undefined, sections are gathered for any role.
4966: If the fourth argument is undefined, sections are gathered for any status.
4967: Permissible values are 'active' or 'future' or 'previous'.
4968:
4969: Returns section hash (keys are section IDs, values are
4970: number of users in each section), subject to the
4971: optional roles filter, optional status filter
4972:
4973: =cut
4974:
4975: ###############################################
4976: sub get_sections {
4977: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
4978: if (!defined($cdom) || !defined($cnum)) {
4979: my $cid = $env{'request.course.id'};
4980:
4981: return if (!defined($cid));
4982:
4983: $cdom = $env{'course.'.$cid.'.domain'};
4984: $cnum = $env{'course.'.$cid.'.num'};
4985: }
4986:
4987: my %sectioncount;
4988: my $now = time;
4989:
4990: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
4991: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
4992: my $sec_index = &Apache::loncoursedata::CL_SECTION();
4993: my $status_index = &Apache::loncoursedata::CL_STATUS();
4994: my $start_index = &Apache::loncoursedata::CL_START();
4995: my $end_index = &Apache::loncoursedata::CL_END();
4996: my $status;
4997: while (my ($student,$data) = each(%$classlist)) {
4998: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
4999: $data->[$status_index],
5000: $data->[$start_index],
5001: $data->[$end_index]);
5002: if ($stu_status eq 'Active') {
5003: $status = 'active';
5004: } elsif ($end < $now) {
5005: $status = 'previous';
5006: } elsif ($start > $now) {
5007: $status = 'future';
5008: }
5009: if ($section ne '-1' && $section !~ /^\s*$/) {
5010: if ((!defined($possible_status)) || (($status ne '') &&
5011: (grep/^\Q$status\E$/,@{$possible_status}))) {
5012: $sectioncount{$section}++;
5013: }
5014: }
5015: }
5016: }
5017: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
5018: foreach my $user (sort(keys(%courseroles))) {
5019: if ($user !~ /^(\w{2})/) { next; }
5020: my ($role) = ($user =~ /^(\w{2})/);
5021: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
5022: my ($section,$status);
5023: if ($role eq 'cr' &&
5024: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
5025: $section=$1;
5026: }
5027: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
5028: if (!defined($section) || $section eq '-1') { next; }
5029: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
5030: if ($end == -1 && $start == -1) {
5031: next; #deleted role
5032: }
5033: if (!defined($possible_status)) {
5034: $sectioncount{$section}++;
5035: } else {
5036: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
5037: $status = 'active';
5038: } elsif ($end < $now) {
5039: $status = 'future';
5040: } elsif ($start > $now) {
5041: $status = 'previous';
5042: }
5043: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
5044: $sectioncount{$section}++;
5045: }
5046: }
5047: }
5048: return %sectioncount;
5049: }
5050:
5051: ###############################################
5052:
5053: =pod
5054:
5055: =item * &get_course_users()
5056:
5057: Retrieves usernames:domains for users in the specified course
5058: with specific role(s), and access status.
5059:
5060: Incoming parameters:
5061: 1. course domain
5062: 2. course number
5063: 3. access status: users must have - either active,
5064: previous, future, or all.
5065: 4. reference to array of permissible roles
5066: 5. reference to array of section restrictions (optional)
5067: 6. reference to results object (hash of hashes).
5068: 7. reference to optional userdata hash
5069: Keys of top level hash are roles.
5070: Keys of inner hashes are username:domain, with
5071: values set to access type.
5072: Optional userdata hash returns an array with arguments in the
5073: same order as loncoursedata::get_classlist() for student data.
5074:
5075: Entries for end, start, section and status are blank because
5076: of the possibility of multiple values for non-student roles.
5077:
5078: =cut
5079:
5080: ###############################################
5081:
5082: sub get_course_users {
5083: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata) = @_;
5084: my %idx = ();
5085: my %seclists;
5086:
5087: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
5088: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
5089: $idx{end} = &Apache::loncoursedata::CL_END();
5090: $idx{start} = &Apache::loncoursedata::CL_START();
5091: $idx{id} = &Apache::loncoursedata::CL_ID();
5092: $idx{section} = &Apache::loncoursedata::CL_SECTION();
5093: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
5094: $idx{status} = &Apache::loncoursedata::CL_STATUS();
5095:
5096: if (grep(/^st$/,@{$roles})) {
5097: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
5098: my $now = time;
5099: foreach my $student (keys(%{$classlist})) {
5100: my $match = 0;
5101: my $secmatch = 0;
5102: my $section = $$classlist{$student}[$idx{section}];
5103: if ($section eq '') {
5104: $section = 'none';
5105: }
5106: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
5107: if (grep(/^all$/,@{$sections})) {
5108: $secmatch = 1;
5109: } elsif ($$classlist{$student}[$idx{section}] eq '') {
5110: if (grep(/^none$/,@{$sections})) {
5111: $secmatch = 1;
5112: }
5113: } else {
5114: if (grep(/^\Q$section\E$/,@{$sections})) {
5115: $secmatch = 1;
5116: }
5117: }
5118: if (!$secmatch) {
5119: next;
5120: }
5121: }
5122: push(@{$seclists{$student}},$section);
5123: if (defined($$types{'active'})) {
5124: if ($$classlist{$student}[$idx{status}] eq 'Active') {
5125: push(@{$$users{st}{$student}},'active');
5126: $match = 1;
5127: }
5128: }
5129: if (defined($$types{'previous'})) {
5130: if ($$classlist{$student}[$idx{end}] <= $now) {
5131: push(@{$$users{st}{$student}},'previous');
5132: $match = 1;
5133: }
5134: }
5135: if (defined($$types{'future'})) {
5136: if (($$classlist{$student}[$idx{start}] > $now) && ($$classlist{$student}[$idx{end}] > $now) || ($$classlist{$student}[$idx{end}] == 0) || ($$classlist{$student}[$idx{end}] eq '')) {
5137: push(@{$$users{st}{$student}},'future');
5138: $match = 1;
5139: }
5140: }
5141: if ($match && ref($userdata) eq 'HASH') {
5142: $$userdata{$student} = $$classlist{$student};
5143: }
5144: }
5145: }
5146: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
5147: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
5148: my $now = time;
5149: foreach my $person (sort(keys(%coursepersonnel))) {
5150: my $match = 0;
5151: my $secmatch = 0;
5152: my $status;
5153: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
5154: $user =~ s/:$//;
5155: my ($end,$start) = split(/:/,$coursepersonnel{$person});
5156: if ($end == -1 || $start == -1) {
5157: next;
5158: }
5159: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
5160: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
5161: my ($uname,$udom) = split(/:/,$user);
5162: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
5163: if (grep(/^all$/,@{$sections})) {
5164: $secmatch = 1;
5165: } elsif ($usec eq '') {
5166: if (grep(/^none$/,@{$sections})) {
5167: $secmatch = 1;
5168: }
5169: } else {
5170: if (grep(/^\Q$usec\E$/,@{$sections})) {
5171: $secmatch = 1;
5172: }
5173: }
5174: if (!$secmatch) {
5175: next;
5176: }
5177: }
5178: if ($usec eq '') {
5179: $usec = 'none';
5180: }
5181: if ($uname ne '' && $udom ne '') {
5182: if ($end > 0 && $end < $now) {
5183: $status = 'previous';
5184: } elsif ($start > $now) {
5185: $status = 'future';
5186: } else {
5187: $status = 'active';
5188: }
5189: foreach my $type (keys(%{$types})) {
5190: if ($status eq $type) {
5191: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
5192: push(@{$$users{$role}{$user}},$type);
5193: }
5194: $match = 1;
5195: }
5196: }
5197: if (($match) && (ref($userdata) eq 'HASH')) {
5198: if (!exists($$userdata{$uname.':'.$udom})) {
5199: &get_user_info($udom,$uname,\%idx,$userdata);
5200: }
5201: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
5202: push(@{$seclists{$uname.':'.$udom}},$usec);
5203: }
5204: }
5205: }
5206: }
5207: }
5208: if (grep(/^ow$/,@{$roles})) {
5209: if ((defined($cdom)) && (defined($cnum))) {
5210: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
5211: if ( defined($csettings{'internal.courseowner'}) ) {
5212: my $owner = $csettings{'internal.courseowner'};
5213: if ($owner !~ /^[^:]+:[^:]+$/) {
5214: $owner = $owner.':'.$cdom;
5215: }
5216: @{$$users{'ow'}{$owner}} = 'any';
5217: if (defined($userdata) &&
5218: !exists($$userdata{$owner.':'.$cdom})) {
5219: &get_user_info($cdom,$owner,\%idx,$userdata);
5220: if (!grep(/^none$/,@{$seclists{$owner.':'.$cdom}})) {
5221: push(@{$seclists{$owner.':'.$cdom}},'none');
5222: }
5223: }
5224: }
5225: }
5226: }
5227: foreach my $user (keys(%seclists)) {
5228: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
5229: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
5230: }
5231: }
5232: return;
5233: }
5234:
5235: sub get_user_info {
5236: my ($udom,$uname,$idx,$userdata) = @_;
5237: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
5238: &plainname($uname,$udom,'lastname');
5239: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
5240: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
5241: return;
5242: }
5243:
5244: ###############################################
5245:
5246: =pod
5247:
5248: =item * &get_user_quota()
5249:
5250: Retrieves quota assigned for storage of portfolio files for a user
5251:
5252: Incoming parameters:
5253: 1. user's username
5254: 2. user's domain
5255:
5256: Returns:
5257: 1. Disk quota (in Mb) assigned to student.
5258: 2. (Optional) Type of setting: custom or default
5259: (individually assigned or default for user's
5260: institutional status).
5261: 3. (Optional) - User's institutional status (e.g., faculty, staff
5262: or student - types as defined in localenroll::inst_usertypes
5263: for user's domain, which determines default quota for user.
5264: 4. (Optional) - Default quota which would apply to the user.
5265:
5266: If a value has been stored in the user's environment,
5267: it will return that, otherwise it returns the maximal default
5268: defined for the user's instituional status(es) in the domain.
5269:
5270: =cut
5271:
5272: ###############################################
5273:
5274:
5275: sub get_user_quota {
5276: my ($uname,$udom) = @_;
5277: my ($quota,$quotatype,$settingstatus,$defquota);
5278: if (!defined($udom)) {
5279: $udom = $env{'user.domain'};
5280: }
5281: if (!defined($uname)) {
5282: $uname = $env{'user.name'};
5283: }
5284: if (($udom eq '' || $uname eq '') ||
5285: ($udom eq 'public') && ($uname eq 'public')) {
5286: $quota = 0;
5287: $quotatype = 'default';
5288: $defquota = 0;
5289: } else {
5290: my $inststatus;
5291: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
5292: $quota = $env{'environment.portfolioquota'};
5293: $inststatus = $env{'environment.inststatus'};
5294: } else {
5295: my %userenv =
5296: &Apache::lonnet::get('environment',['portfolioquota',
5297: 'inststatus'],$udom,$uname);
5298: my ($tmp) = keys(%userenv);
5299: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
5300: $quota = $userenv{'portfolioquota'};
5301: $inststatus = $userenv{'inststatus'};
5302: } else {
5303: undef(%userenv);
5304: }
5305: }
5306: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
5307: if ($quota eq '') {
5308: $quota = $defquota;
5309: $quotatype = 'default';
5310: } else {
5311: $quotatype = 'custom';
5312: }
5313: }
5314: if (wantarray) {
5315: return ($quota,$quotatype,$settingstatus,$defquota);
5316: } else {
5317: return $quota;
5318: }
5319: }
5320:
5321: ###############################################
5322:
5323: =pod
5324:
5325: =item * &default_quota()
5326:
5327: Retrieves default quota assigned for storage of user portfolio files,
5328: given an (optional) user's institutional status.
5329:
5330: Incoming parameters:
5331: 1. domain
5332: 2. (Optional) institutional status(es). This is a : separated list of
5333: status types (e.g., faculty, staff, student etc.)
5334: which apply to the user for whom the default is being retrieved.
5335: If the institutional status string in undefined, the domain
5336: default quota will be returned.
5337:
5338: Returns:
5339: 1. Default disk quota (in Mb) for user portfolios in the domain.
5340: 2. (Optional) institutional type which determined the value of the
5341: default quota.
5342:
5343: If a value has been stored in the domain's configuration db,
5344: it will return that, otherwise it returns 20 (for backwards
5345: compatibility with domains which have not set up a configuration
5346: db file; the original statically defined portfolio quota was 20 Mb).
5347:
5348: If the user's status includes multiple types (e.g., staff and student),
5349: the largest default quota which applies to the user determines the
5350: default quota returned.
5351:
5352: =cut
5353:
5354: ###############################################
5355:
5356:
5357: sub default_quota {
5358: my ($udom,$inststatus) = @_;
5359: my ($defquota,$settingstatus);
5360: my %quotahash = &Apache::lonnet::get_dom('configuration',
5361: ['quota'],$udom);
5362: if (ref($quotahash{'quota'}) eq 'HASH') {
5363: if ($inststatus ne '') {
5364: my @statuses = split(/:/,$inststatus);
5365: foreach my $item (@statuses) {
5366: if ($quotahash{'quota'}{$item} ne '') {
5367: if ($defquota eq '') {
5368: $defquota = $quotahash{'quota'}{$item};
5369: $settingstatus = $item;
5370: } elsif ($quotahash{'quota'}{$item} > $defquota) {
5371: $defquota = $quotahash{'quota'}{$item};
5372: $settingstatus = $item;
5373: }
5374: }
5375: }
5376: }
5377: if ($defquota eq '') {
5378: $defquota = $quotahash{'quota'}{'default'};
5379: $settingstatus = 'default';
5380: }
5381: } else {
5382: $settingstatus = 'default';
5383: $defquota = 20;
5384: }
5385: if (wantarray) {
5386: return ($defquota,$settingstatus);
5387: } else {
5388: return $defquota;
5389: }
5390: }
5391:
5392: sub get_secgrprole_info {
5393: my ($cdom,$cnum,$needroles,$type) = @_;
5394: my %sections_count = &get_sections($cdom,$cnum);
5395: my @sections = (sort {$a <=> $b} keys(%sections_count));
5396: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
5397: my @groups = sort(keys(%curr_groups));
5398: my $allroles = [];
5399: my $rolehash;
5400: my $accesshash = {
5401: active => 'Currently has access',
5402: future => 'Will have future access',
5403: previous => 'Previously had access',
5404: };
5405: if ($needroles) {
5406: $rolehash = {'all' => 'all'};
5407: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
5408: if (&Apache::lonnet::error(%user_roles)) {
5409: undef(%user_roles);
5410: }
5411: foreach my $item (keys(%user_roles)) {
5412: my ($role)=split(/\:/,$item,2);
5413: if ($role eq 'cr') { next; }
5414: if ($role =~ /^cr/) {
5415: $$rolehash{$role} = (split('/',$role))[3];
5416: } else {
5417: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
5418: }
5419: }
5420: foreach my $key (sort(keys(%{$rolehash}))) {
5421: push(@{$allroles},$key);
5422: }
5423: push (@{$allroles},'st');
5424: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
5425: }
5426: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
5427: }
5428:
5429: =pod
5430:
5431: =item * get_unprocessed_cgi($query,$possible_names)
5432:
5433: Modify the %env hash to contain unprocessed CGI form parameters held in
5434: $query. The parameters listed in $possible_names (an array reference),
5435: will be set in $env{'form.name'} if they do not already exist.
5436:
5437: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
5438: $possible_names is an ref to an array of form element names. As an example:
5439: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
5440: will result in $env{'form.uname'} and $env{'form.udom'} being set.
5441:
5442: =cut
5443:
5444: sub get_unprocessed_cgi {
5445: my ($query,$possible_names)= @_;
5446: # $Apache::lonxml::debug=1;
5447: foreach my $pair (split(/&/,$query)) {
5448: my ($name, $value) = split(/=/,$pair);
5449: $name = &unescape($name);
5450: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
5451: $value =~ tr/+/ /;
5452: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
5453: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
5454: }
5455: }
5456: }
5457:
5458: =pod
5459:
5460: =item * cacheheader()
5461:
5462: returns cache-controlling header code
5463:
5464: =cut
5465:
5466: sub cacheheader {
5467: unless ($env{'request.method'} eq 'GET') { return ''; }
5468: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
5469: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
5470: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
5471: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
5472: return $output;
5473: }
5474:
5475: =pod
5476:
5477: =item * no_cache($r)
5478:
5479: specifies header code to not have cache
5480:
5481: =cut
5482:
5483: sub no_cache {
5484: my ($r) = @_;
5485: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
5486: $env{'request.method'} ne 'GET') { return ''; }
5487: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
5488: $r->no_cache(1);
5489: $r->header_out("Expires" => $date);
5490: $r->header_out("Pragma" => "no-cache");
5491: }
5492:
5493: sub content_type {
5494: my ($r,$type,$charset) = @_;
5495: if ($r) {
5496: # Note that printout.pl calls this with undef for $r.
5497: &no_cache($r);
5498: }
5499: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
5500: unless ($charset) {
5501: $charset=&Apache::lonlocal::current_encoding;
5502: }
5503: if ($charset) { $type.='; charset='.$charset; }
5504: if ($r) {
5505: $r->content_type($type);
5506: } else {
5507: print("Content-type: $type\n\n");
5508: }
5509: }
5510:
5511: =pod
5512:
5513: =item * add_to_env($name,$value)
5514:
5515: adds $name to the %env hash with value
5516: $value, if $name already exists, the entry is converted to an array
5517: reference and $value is added to the array.
5518:
5519: =cut
5520:
5521: sub add_to_env {
5522: my ($name,$value)=@_;
5523: if (defined($env{$name})) {
5524: if (ref($env{$name})) {
5525: #already have multiple values
5526: push(@{ $env{$name} },$value);
5527: } else {
5528: #first time seeing multiple values, convert hash entry to an arrayref
5529: my $first=$env{$name};
5530: undef($env{$name});
5531: push(@{ $env{$name} },$first,$value);
5532: }
5533: } else {
5534: $env{$name}=$value;
5535: }
5536: }
5537:
5538: =pod
5539:
5540: =item * get_env_multiple($name)
5541:
5542: gets $name from the %env hash, it seemlessly handles the cases where multiple
5543: values may be defined and end up as an array ref.
5544:
5545: returns an array of values
5546:
5547: =cut
5548:
5549: sub get_env_multiple {
5550: my ($name) = @_;
5551: my @values;
5552: if (defined($env{$name})) {
5553: # exists is it an array
5554: if (ref($env{$name})) {
5555: @values=@{ $env{$name} };
5556: } else {
5557: $values[0]=$env{$name};
5558: }
5559: }
5560: return(@values);
5561: }
5562:
5563:
5564: =pod
5565:
5566: =back
5567:
5568: =head1 CSV Upload/Handling functions
5569:
5570: =over 4
5571:
5572: =item * upfile_store($r)
5573:
5574: Store uploaded file, $r should be the HTTP Request object,
5575: needs $env{'form.upfile'}
5576: returns $datatoken to be put into hidden field
5577:
5578: =cut
5579:
5580: sub upfile_store {
5581: my $r=shift;
5582: $env{'form.upfile'}=~s/\r/\n/gs;
5583: $env{'form.upfile'}=~s/\f/\n/gs;
5584: $env{'form.upfile'}=~s/\n+/\n/gs;
5585: $env{'form.upfile'}=~s/\n+$//gs;
5586:
5587: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
5588: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
5589: {
5590: my $datafile = $r->dir_config('lonDaemons').
5591: '/tmp/'.$datatoken.'.tmp';
5592: if ( open(my $fh,">$datafile") ) {
5593: print $fh $env{'form.upfile'};
5594: close($fh);
5595: }
5596: }
5597: return $datatoken;
5598: }
5599:
5600: =pod
5601:
5602: =item * load_tmp_file($r)
5603:
5604: Load uploaded file from tmp, $r should be the HTTP Request object,
5605: needs $env{'form.datatoken'},
5606: sets $env{'form.upfile'} to the contents of the file
5607:
5608: =cut
5609:
5610: sub load_tmp_file {
5611: my $r=shift;
5612: my @studentdata=();
5613: {
5614: my $studentfile = $r->dir_config('lonDaemons').
5615: '/tmp/'.$env{'form.datatoken'}.'.tmp';
5616: if ( open(my $fh,"<$studentfile") ) {
5617: @studentdata=<$fh>;
5618: close($fh);
5619: }
5620: }
5621: $env{'form.upfile'}=join('',@studentdata);
5622: }
5623:
5624: =pod
5625:
5626: =item * upfile_record_sep()
5627:
5628: Separate uploaded file into records
5629: returns array of records,
5630: needs $env{'form.upfile'} and $env{'form.upfiletype'}
5631:
5632: =cut
5633:
5634: sub upfile_record_sep {
5635: if ($env{'form.upfiletype'} eq 'xml') {
5636: } else {
5637: my @records;
5638: foreach my $line (split(/\n/,$env{'form.upfile'})) {
5639: if ($line=~/^\s*$/) { next; }
5640: push(@records,$line);
5641: }
5642: return @records;
5643: }
5644: }
5645:
5646: =pod
5647:
5648: =item * record_sep($record)
5649:
5650: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
5651:
5652: =cut
5653:
5654: sub takeleft {
5655: my $index=shift;
5656: return substr('0000'.$index,-4,4);
5657: }
5658:
5659: sub record_sep {
5660: my $record=shift;
5661: my %components=();
5662: if ($env{'form.upfiletype'} eq 'xml') {
5663: } elsif ($env{'form.upfiletype'} eq 'space') {
5664: my $i=0;
5665: foreach my $field (split(/\s+/,$record)) {
5666: $field=~s/^(\"|\')//;
5667: $field=~s/(\"|\')$//;
5668: $components{&takeleft($i)}=$field;
5669: $i++;
5670: }
5671: } elsif ($env{'form.upfiletype'} eq 'tab') {
5672: my $i=0;
5673: foreach my $field (split(/\t/,$record)) {
5674: $field=~s/^(\"|\')//;
5675: $field=~s/(\"|\')$//;
5676: $components{&takeleft($i)}=$field;
5677: $i++;
5678: }
5679: } else {
5680: my @allfields;
5681: if ($env{'form.upfiletype'} eq 'semisv') {
5682: @allfields=split(/;/,$record,-1);
5683: } else {
5684: @allfields=split(/\,/,$record,-1);
5685: }
5686: my $i=0;
5687: my $j;
5688: for ($j=0;$j<=$#allfields;$j++) {
5689: my $field=$allfields[$j];
5690: if ($field=~/^\s*(\"|\')/) {
5691: my $delimiter=$1;
5692: while (($field!~/$delimiter$/) && ($j<$#allfields)) {
5693: $j++;
5694: $field.=','.$allfields[$j];
5695: }
5696: $field=~s/^\s*$delimiter//;
5697: $field=~s/$delimiter\s*$//;
5698: }
5699: $components{&takeleft($i)}=$field;
5700: $i++;
5701: }
5702: }
5703: return %components;
5704: }
5705:
5706: ######################################################
5707: ######################################################
5708:
5709: =pod
5710:
5711: =item * upfile_select_html()
5712:
5713: Return HTML code to select a file from the users machine and specify
5714: the file type.
5715:
5716: =cut
5717:
5718: ######################################################
5719: ######################################################
5720: sub upfile_select_html {
5721: my %Types = (
5722: csv => &mt('CSV (comma separated values, spreadsheet)'),
5723: semisv => &mt('Semicolon separated values'),
5724: space => &mt('Space separated'),
5725: tab => &mt('Tabulator separated'),
5726: # xml => &mt('HTML/XML'),
5727: );
5728: my $Str = '<input type="file" name="upfile" size="50" />'.
5729: '<br />Type: <select name="upfiletype">';
5730: foreach my $type (sort(keys(%Types))) {
5731: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
5732: }
5733: $Str .= "</select>\n";
5734: return $Str;
5735: }
5736:
5737: sub get_samples {
5738: my ($records,$toget) = @_;
5739: my @samples=({});
5740: my $got=0;
5741: foreach my $rec (@$records) {
5742: my %temp = &record_sep($rec);
5743: if (! grep(/\S/, values(%temp))) { next; }
5744: if (%temp) {
5745: $samples[$got]=\%temp;
5746: $got++;
5747: if ($got == $toget) { last; }
5748: }
5749: }
5750: return \@samples;
5751: }
5752:
5753: ######################################################
5754: ######################################################
5755:
5756: =pod
5757:
5758: =item * csv_print_samples($r,$records)
5759:
5760: Prints a table of sample values from each column uploaded $r is an
5761: Apache Request ref, $records is an arrayref from
5762: &Apache::loncommon::upfile_record_sep
5763:
5764: =cut
5765:
5766: ######################################################
5767: ######################################################
5768: sub csv_print_samples {
5769: my ($r,$records) = @_;
5770: my $samples = &get_samples($records,3);
5771:
5772: $r->print(&mt('Samples').'<br /><table border="2"><tr>');
5773: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5774: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
5775: $r->print('</tr>');
5776: foreach my $hash (@$samples) {
5777: $r->print('<tr>');
5778: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5779: $r->print('<td>');
5780: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
5781: $r->print('</td>');
5782: }
5783: $r->print('</tr>');
5784: }
5785: $r->print('</tr></table><br />'."\n");
5786: }
5787:
5788: ######################################################
5789: ######################################################
5790:
5791: =pod
5792:
5793: =item * csv_print_select_table($r,$records,$d)
5794:
5795: Prints a table to create associations between values and table columns.
5796:
5797: $r is an Apache Request ref,
5798: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
5799: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
5800:
5801: =cut
5802:
5803: ######################################################
5804: ######################################################
5805: sub csv_print_select_table {
5806: my ($r,$records,$d) = @_;
5807: my $i=0;
5808: my $samples = &get_samples($records,1);
5809: $r->print(&mt('Associate columns with student attributes.')."\n".
5810: '<table border="2"><tr>'.
5811: '<th>'.&mt('Attribute').'</th>'.
5812: '<th>'.&mt('Column').'</th></tr>'."\n");
5813: foreach my $array_ref (@$d) {
5814: my ($value,$display,$defaultcol)=@{ $array_ref };
5815: $r->print('<tr><td>'.$display.'</td>');
5816:
5817: $r->print('<td><select name=f'.$i.
5818: ' onchange="javascript:flip(this.form,'.$i.');">');
5819: $r->print('<option value="none"></option>');
5820: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
5821: $r->print('<option value="'.$sample.'"'.
5822: ($sample eq $defaultcol ? ' selected="selected" ' : '').
5823: '>Column '.($sample+1).'</option>');
5824: }
5825: $r->print('</select></td></tr>'."\n");
5826: $i++;
5827: }
5828: $i--;
5829: return $i;
5830: }
5831:
5832: ######################################################
5833: ######################################################
5834:
5835: =pod
5836:
5837: =item * csv_samples_select_table($r,$records,$d)
5838:
5839: Prints a table of sample values from the upload and can make associate samples to internal names.
5840:
5841: $r is an Apache Request ref,
5842: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
5843: $d is an array of 2 element arrays (internal name, displayed name)
5844:
5845: =cut
5846:
5847: ######################################################
5848: ######################################################
5849: sub csv_samples_select_table {
5850: my ($r,$records,$d) = @_;
5851: my $i=0;
5852: #
5853: my $samples = &get_samples($records,3);
5854: $r->print('<table border=2><tr><th>'.
5855: &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
5856:
5857: foreach my $key (sort(keys(%{ $samples->[0] }))) {
5858: $r->print('<tr><td><select name="f'.$i.'"'.
5859: ' onchange="javascript:flip(this.form,'.$i.');">');
5860: foreach my $option (@$d) {
5861: my ($value,$display,$defaultcol)=@{ $option };
5862: $r->print('<option value="'.$value.'"'.
5863: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
5864: $display.'</option>');
5865: }
5866: $r->print('</select></td><td>');
5867: foreach my $line (0..2) {
5868: if (defined($samples->[$line]{$key})) {
5869: $r->print($samples->[$line]{$key}."<br />\n");
5870: }
5871: }
5872: $r->print('</td></tr>');
5873: $i++;
5874: }
5875: $i--;
5876: return($i);
5877: }
5878:
5879: ######################################################
5880: ######################################################
5881:
5882: =pod
5883:
5884: =item clean_excel_name($name)
5885:
5886: Returns a replacement for $name which does not contain any illegal characters.
5887:
5888: =cut
5889:
5890: ######################################################
5891: ######################################################
5892: sub clean_excel_name {
5893: my ($name) = @_;
5894: $name =~ s/[:\*\?\/\\]//g;
5895: if (length($name) > 31) {
5896: $name = substr($name,0,31);
5897: }
5898: return $name;
5899: }
5900:
5901: =pod
5902:
5903: =item * check_if_partid_hidden($id,$symb,$udom,$uname)
5904:
5905: Returns either 1 or undef
5906:
5907: 1 if the part is to be hidden, undef if it is to be shown
5908:
5909: Arguments are:
5910:
5911: $id the id of the part to be checked
5912: $symb, optional the symb of the resource to check
5913: $udom, optional the domain of the user to check for
5914: $uname, optional the username of the user to check for
5915:
5916: =cut
5917:
5918: sub check_if_partid_hidden {
5919: my ($id,$symb,$udom,$uname) = @_;
5920: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
5921: $symb,$udom,$uname);
5922: my $truth=1;
5923: #if the string starts with !, then the list is the list to show not hide
5924: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
5925: my @hiddenlist=split(/,/,$hiddenparts);
5926: foreach my $checkid (@hiddenlist) {
5927: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
5928: }
5929: return !$truth;
5930: }
5931:
5932:
5933: ############################################################
5934: ############################################################
5935:
5936: =pod
5937:
5938: =back
5939:
5940: =head1 cgi-bin script and graphing routines
5941:
5942: =over 4
5943:
5944: =item get_cgi_id
5945:
5946: Inputs: none
5947:
5948: Returns an id which can be used to pass environment variables
5949: to various cgi-bin scripts. These environment variables will
5950: be removed from the users environment after a given time by
5951: the routine &Apache::lonnet::transfer_profile_to_env.
5952:
5953: =cut
5954:
5955: ############################################################
5956: ############################################################
5957: my $uniq=0;
5958: sub get_cgi_id {
5959: $uniq=($uniq+1)%100000;
5960: return (time.'_'.$$.'_'.$uniq);
5961: }
5962:
5963: ############################################################
5964: ############################################################
5965:
5966: =pod
5967:
5968: =item DrawBarGraph
5969:
5970: Facilitates the plotting of data in a (stacked) bar graph.
5971: Puts plot definition data into the users environment in order for
5972: graph.png to plot it. Returns an <img> tag for the plot.
5973: The bars on the plot are labeled '1','2',...,'n'.
5974:
5975: Inputs:
5976:
5977: =over 4
5978:
5979: =item $Title: string, the title of the plot
5980:
5981: =item $xlabel: string, text describing the X-axis of the plot
5982:
5983: =item $ylabel: string, text describing the Y-axis of the plot
5984:
5985: =item $Max: scalar, the maximum Y value to use in the plot
5986: If $Max is < any data point, the graph will not be rendered.
5987:
5988: =item $colors: array ref holding the colors to be used for the data sets when
5989: they are plotted. If undefined, default values will be used.
5990:
5991: =item $labels: array ref holding the labels to use on the x-axis for the bars.
5992:
5993: =item @Values: An array of array references. Each array reference holds data
5994: to be plotted in a stacked bar chart.
5995:
5996: =item If the final element of @Values is a hash reference the key/value
5997: pairs will be added to the graph definition.
5998:
5999: =back
6000:
6001: Returns:
6002:
6003: An <img> tag which references graph.png and the appropriate identifying
6004: information for the plot.
6005:
6006: =cut
6007:
6008: ############################################################
6009: ############################################################
6010: sub DrawBarGraph {
6011: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
6012: #
6013: if (! defined($colors)) {
6014: $colors = ['#33ff00',
6015: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
6016: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
6017: ];
6018: }
6019: my $extra_settings = {};
6020: if (ref($Values[-1]) eq 'HASH') {
6021: $extra_settings = pop(@Values);
6022: }
6023: #
6024: my $identifier = &get_cgi_id();
6025: my $id = 'cgi.'.$identifier;
6026: if (! @Values || ref($Values[0]) ne 'ARRAY') {
6027: return '';
6028: }
6029: #
6030: my @Labels;
6031: if (defined($labels)) {
6032: @Labels = @$labels;
6033: } else {
6034: for (my $i=0;$i<@{$Values[0]};$i++) {
6035: push (@Labels,$i+1);
6036: }
6037: }
6038: #
6039: my $NumBars = scalar(@{$Values[0]});
6040: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
6041: my %ValuesHash;
6042: my $NumSets=1;
6043: foreach my $array (@Values) {
6044: next if (! ref($array));
6045: $ValuesHash{$id.'.data.'.$NumSets++} =
6046: join(',',@$array);
6047: }
6048: #
6049: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
6050: if ($NumBars < 3) {
6051: $width = 120+$NumBars*32;
6052: $xskip = 1;
6053: $bar_width = 30;
6054: } elsif ($NumBars < 5) {
6055: $width = 120+$NumBars*20;
6056: $xskip = 1;
6057: $bar_width = 20;
6058: } elsif ($NumBars < 10) {
6059: $width = 120+$NumBars*15;
6060: $xskip = 1;
6061: $bar_width = 15;
6062: } elsif ($NumBars <= 25) {
6063: $width = 120+$NumBars*11;
6064: $xskip = 5;
6065: $bar_width = 8;
6066: } elsif ($NumBars <= 50) {
6067: $width = 120+$NumBars*8;
6068: $xskip = 5;
6069: $bar_width = 4;
6070: } else {
6071: $width = 120+$NumBars*8;
6072: $xskip = 5;
6073: $bar_width = 4;
6074: }
6075: #
6076: $Max = 1 if ($Max < 1);
6077: if ( int($Max) < $Max ) {
6078: $Max++;
6079: $Max = int($Max);
6080: }
6081: $Title = '' if (! defined($Title));
6082: $xlabel = '' if (! defined($xlabel));
6083: $ylabel = '' if (! defined($ylabel));
6084: $ValuesHash{$id.'.title'} = &escape($Title);
6085: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
6086: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
6087: $ValuesHash{$id.'.y_max_value'} = $Max;
6088: $ValuesHash{$id.'.NumBars'} = $NumBars;
6089: $ValuesHash{$id.'.NumSets'} = $NumSets;
6090: $ValuesHash{$id.'.PlotType'} = 'bar';
6091: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
6092: $ValuesHash{$id.'.height'} = $height;
6093: $ValuesHash{$id.'.width'} = $width;
6094: $ValuesHash{$id.'.xskip'} = $xskip;
6095: $ValuesHash{$id.'.bar_width'} = $bar_width;
6096: $ValuesHash{$id.'.labels'} = join(',',@Labels);
6097: #
6098: # Deal with other parameters
6099: while (my ($key,$value) = each(%$extra_settings)) {
6100: $ValuesHash{$id.'.'.$key} = $value;
6101: }
6102: #
6103: &Apache::lonnet::appenv(%ValuesHash);
6104: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
6105: }
6106:
6107: ############################################################
6108: ############################################################
6109:
6110: =pod
6111:
6112: =item DrawXYGraph
6113:
6114: Facilitates the plotting of data in an XY graph.
6115: Puts plot definition data into the users environment in order for
6116: graph.png to plot it. Returns an <img> tag for the plot.
6117:
6118: Inputs:
6119:
6120: =over 4
6121:
6122: =item $Title: string, the title of the plot
6123:
6124: =item $xlabel: string, text describing the X-axis of the plot
6125:
6126: =item $ylabel: string, text describing the Y-axis of the plot
6127:
6128: =item $Max: scalar, the maximum Y value to use in the plot
6129: If $Max is < any data point, the graph will not be rendered.
6130:
6131: =item $colors: Array ref containing the hex color codes for the data to be
6132: plotted in. If undefined, default values will be used.
6133:
6134: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
6135:
6136: =item $Ydata: Array ref containing Array refs.
6137: Each of the contained arrays will be plotted as a separate curve.
6138:
6139: =item %Values: hash indicating or overriding any default values which are
6140: passed to graph.png.
6141: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
6142:
6143: =back
6144:
6145: Returns:
6146:
6147: An <img> tag which references graph.png and the appropriate identifying
6148: information for the plot.
6149:
6150: =cut
6151:
6152: ############################################################
6153: ############################################################
6154: sub DrawXYGraph {
6155: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
6156: #
6157: # Create the identifier for the graph
6158: my $identifier = &get_cgi_id();
6159: my $id = 'cgi.'.$identifier;
6160: #
6161: $Title = '' if (! defined($Title));
6162: $xlabel = '' if (! defined($xlabel));
6163: $ylabel = '' if (! defined($ylabel));
6164: my %ValuesHash =
6165: (
6166: $id.'.title' => &escape($Title),
6167: $id.'.xlabel' => &escape($xlabel),
6168: $id.'.ylabel' => &escape($ylabel),
6169: $id.'.y_max_value'=> $Max,
6170: $id.'.labels' => join(',',@$Xlabels),
6171: $id.'.PlotType' => 'XY',
6172: );
6173: #
6174: if (defined($colors) && ref($colors) eq 'ARRAY') {
6175: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
6176: }
6177: #
6178: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
6179: return '';
6180: }
6181: my $NumSets=1;
6182: foreach my $array (@{$Ydata}){
6183: next if (! ref($array));
6184: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
6185: }
6186: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
6187: #
6188: # Deal with other parameters
6189: while (my ($key,$value) = each(%Values)) {
6190: $ValuesHash{$id.'.'.$key} = $value;
6191: }
6192: #
6193: &Apache::lonnet::appenv(%ValuesHash);
6194: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
6195: }
6196:
6197: ############################################################
6198: ############################################################
6199:
6200: =pod
6201:
6202: =item DrawXYYGraph
6203:
6204: Facilitates the plotting of data in an XY graph with two Y axes.
6205: Puts plot definition data into the users environment in order for
6206: graph.png to plot it. Returns an <img> tag for the plot.
6207:
6208: Inputs:
6209:
6210: =over 4
6211:
6212: =item $Title: string, the title of the plot
6213:
6214: =item $xlabel: string, text describing the X-axis of the plot
6215:
6216: =item $ylabel: string, text describing the Y-axis of the plot
6217:
6218: =item $colors: Array ref containing the hex color codes for the data to be
6219: plotted in. If undefined, default values will be used.
6220:
6221: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
6222:
6223: =item $Ydata1: The first data set
6224:
6225: =item $Min1: The minimum value of the left Y-axis
6226:
6227: =item $Max1: The maximum value of the left Y-axis
6228:
6229: =item $Ydata2: The second data set
6230:
6231: =item $Min2: The minimum value of the right Y-axis
6232:
6233: =item $Max2: The maximum value of the left Y-axis
6234:
6235: =item %Values: hash indicating or overriding any default values which are
6236: passed to graph.png.
6237: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
6238:
6239: =back
6240:
6241: Returns:
6242:
6243: An <img> tag which references graph.png and the appropriate identifying
6244: information for the plot.
6245:
6246: =cut
6247:
6248: ############################################################
6249: ############################################################
6250: sub DrawXYYGraph {
6251: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
6252: $Ydata2,$Min2,$Max2,%Values)=@_;
6253: #
6254: # Create the identifier for the graph
6255: my $identifier = &get_cgi_id();
6256: my $id = 'cgi.'.$identifier;
6257: #
6258: $Title = '' if (! defined($Title));
6259: $xlabel = '' if (! defined($xlabel));
6260: $ylabel = '' if (! defined($ylabel));
6261: my %ValuesHash =
6262: (
6263: $id.'.title' => &escape($Title),
6264: $id.'.xlabel' => &escape($xlabel),
6265: $id.'.ylabel' => &escape($ylabel),
6266: $id.'.labels' => join(',',@$Xlabels),
6267: $id.'.PlotType' => 'XY',
6268: $id.'.NumSets' => 2,
6269: $id.'.two_axes' => 1,
6270: $id.'.y1_max_value' => $Max1,
6271: $id.'.y1_min_value' => $Min1,
6272: $id.'.y2_max_value' => $Max2,
6273: $id.'.y2_min_value' => $Min2,
6274: );
6275: #
6276: if (defined($colors) && ref($colors) eq 'ARRAY') {
6277: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
6278: }
6279: #
6280: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
6281: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
6282: return '';
6283: }
6284: my $NumSets=1;
6285: foreach my $array ($Ydata1,$Ydata2){
6286: next if (! ref($array));
6287: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
6288: }
6289: #
6290: # Deal with other parameters
6291: while (my ($key,$value) = each(%Values)) {
6292: $ValuesHash{$id.'.'.$key} = $value;
6293: }
6294: #
6295: &Apache::lonnet::appenv(%ValuesHash);
6296: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
6297: }
6298:
6299: ############################################################
6300: ############################################################
6301:
6302: =pod
6303:
6304: =back
6305:
6306: =head1 Statistics helper routines?
6307:
6308: Bad place for them but what the hell.
6309:
6310: =over 4
6311:
6312: =item &chartlink
6313:
6314: Returns a link to the chart for a specific student.
6315:
6316: Inputs:
6317:
6318: =over 4
6319:
6320: =item $linktext: The text of the link
6321:
6322: =item $sname: The students username
6323:
6324: =item $sdomain: The students domain
6325:
6326: =back
6327:
6328: =back
6329:
6330: =cut
6331:
6332: ############################################################
6333: ############################################################
6334: sub chartlink {
6335: my ($linktext, $sname, $sdomain) = @_;
6336: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
6337: '&SelectedStudent='.&escape($sname.':'.$sdomain).
6338: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
6339: '">'.$linktext.'</a>';
6340: }
6341:
6342: #######################################################
6343: #######################################################
6344:
6345: =pod
6346:
6347: =head1 Course Environment Routines
6348:
6349: =over 4
6350:
6351: =item &restore_course_settings
6352:
6353: =item &store_course_settings
6354:
6355: Restores/Store indicated form parameters from the course environment.
6356: Will not overwrite existing values of the form parameters.
6357:
6358: Inputs:
6359: a scalar describing the data (e.g. 'chart', 'problem_analysis')
6360:
6361: a hash ref describing the data to be stored. For example:
6362:
6363: %Save_Parameters = ('Status' => 'scalar',
6364: 'chartoutputmode' => 'scalar',
6365: 'chartoutputdata' => 'scalar',
6366: 'Section' => 'array',
6367: 'Group' => 'array',
6368: 'StudentData' => 'array',
6369: 'Maps' => 'array');
6370:
6371: Returns: both routines return nothing
6372:
6373: =cut
6374:
6375: #######################################################
6376: #######################################################
6377: sub store_course_settings {
6378: return &store_settings($env{'request.course.id'},@_);
6379: }
6380:
6381: sub store_settings {
6382: # save to the environment
6383: # appenv the same items, just to be safe
6384: my $udom = $env{'user.domain'};
6385: my $uname = $env{'user.name'};
6386: my ($context,$prefix,$Settings) = @_;
6387: my %SaveHash;
6388: my %AppHash;
6389: while (my ($setting,$type) = each(%$Settings)) {
6390: my $basename = join('.','internal',$context,$prefix,$setting);
6391: my $envname = 'environment.'.$basename;
6392: if (exists($env{'form.'.$setting})) {
6393: # Save this value away
6394: if ($type eq 'scalar' &&
6395: (! exists($env{$envname}) ||
6396: $env{$envname} ne $env{'form.'.$setting})) {
6397: $SaveHash{$basename} = $env{'form.'.$setting};
6398: $AppHash{$envname} = $env{'form.'.$setting};
6399: } elsif ($type eq 'array') {
6400: my $stored_form;
6401: if (ref($env{'form.'.$setting})) {
6402: $stored_form = join(',',
6403: map {
6404: &escape($_);
6405: } sort(@{$env{'form.'.$setting}}));
6406: } else {
6407: $stored_form =
6408: &escape($env{'form.'.$setting});
6409: }
6410: # Determine if the array contents are the same.
6411: if ($stored_form ne $env{$envname}) {
6412: $SaveHash{$basename} = $stored_form;
6413: $AppHash{$envname} = $stored_form;
6414: }
6415: }
6416: }
6417: }
6418: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
6419: $udom,$uname);
6420: if ($put_result !~ /^(ok|delayed)/) {
6421: &Apache::lonnet::logthis('unable to save form parameters, '.
6422: 'got error:'.$put_result);
6423: }
6424: # Make sure these settings stick around in this session, too
6425: &Apache::lonnet::appenv(%AppHash);
6426: return;
6427: }
6428:
6429: sub restore_course_settings {
6430: return &restore_settings($env{'request.course.id'},@_);
6431: }
6432:
6433: sub restore_settings {
6434: my ($context,$prefix,$Settings) = @_;
6435: while (my ($setting,$type) = each(%$Settings)) {
6436: next if (exists($env{'form.'.$setting}));
6437: my $envname = 'environment.internal.'.$context.'.'.$prefix.
6438: '.'.$setting;
6439: if (exists($env{$envname})) {
6440: if ($type eq 'scalar') {
6441: $env{'form.'.$setting} = $env{$envname};
6442: } elsif ($type eq 'array') {
6443: $env{'form.'.$setting} = [
6444: map {
6445: &unescape($_);
6446: } split(',',$env{$envname})
6447: ];
6448: }
6449: }
6450: }
6451: }
6452:
6453: ############################################################
6454: ############################################################
6455:
6456: sub commit_customrole {
6457: my ($udom,$uname,$url,$three,$four,$five,$start,$end) = @_;
6458: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.'@'.$three.' in '.$url.
6459: ($start?', '.&mt('starting').' '.localtime($start):'').
6460: ($end?', ending '.localtime($end):'').': <b>'.
6461: &Apache::lonnet::assigncustomrole(
6462: $udom,$uname,$url,$three,$four,$five,$end,$start).
6463: '</b><br />';
6464: return $output;
6465: }
6466:
6467: sub commit_standardrole {
6468: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
6469: my ($output,$logmsg,$linefeed);
6470: if ($context eq 'auto') {
6471: $linefeed = "\n";
6472: } else {
6473: $linefeed = "<br />\n";
6474: }
6475: if ($three eq 'st') {
6476: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
6477: $one,$two,$sec,$context);
6478: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
6479: ($result eq 'unknown_course')) {
6480: $output = "Error: $result\n";
6481: } else {
6482: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
6483: ($start?', '.&mt('starting').' '.localtime($start):'').
6484: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
6485: if ($context eq 'auto') {
6486: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
6487: } else {
6488: $output .= '<b>'.$result.'</b>'.$linefeed.
6489: &mt('Add to classlist').': <b>ok</b>';
6490: }
6491: $output .= $linefeed;
6492: }
6493: } else {
6494: $output = &mt('Assigning').' '.$three.' in '.$url.
6495: ($start?', '.&mt('starting').' '.localtime($start):'').
6496: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
6497: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start);
6498: if ($context eq 'auto') {
6499: $output .= $result.$linefeed;
6500: } else {
6501: $output .= '<b>'.$result.'</b>'.$linefeed;
6502: }
6503: }
6504: return $output;
6505: }
6506:
6507: sub commit_studentrole {
6508: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
6509: my ($result,$linefeed);
6510: if ($context eq 'auto') {
6511: $linefeed = "\n";
6512: } else {
6513: $linefeed = '<br />'."\n";
6514: }
6515: if (defined($one) && defined($two)) {
6516: my $cid=$one.'_'.$two;
6517: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
6518: my $secchange = 0;
6519: my $expire_role_result;
6520: my $modify_section_result;
6521: unless ($oldsec eq '-1') {
6522: unless ($sec eq $oldsec) {
6523: $secchange = 1;
6524: my $uurl='/'.$cid;
6525: $uurl=~s/\_/\//g;
6526: if ($oldsec) {
6527: $uurl.='/'.$oldsec;
6528: }
6529: $expire_role_result = &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',time);
6530: $result = $expire_role_result;
6531: }
6532: }
6533: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
6534: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid);
6535: if ($modify_section_result =~ /^ok/) {
6536: if ($secchange == 1) {
6537: $$logmsg .= "Section for $uname switched from old section: $oldsec to new section: $sec".$linefeed;
6538: } elsif ($oldsec eq '-1') {
6539: $$logmsg .= "New student role for $uname in section $sec in course $cid".$linefeed;
6540: } else {
6541: $$logmsg .= "Student $uname assigned to unchanged section $sec in course $cid".$linefeed;
6542: }
6543: } else {
6544: $$logmsg .= "Error when attempting section change for $uname from old section $oldsec to new section: $sec in course $cid -error: $modify_section_result".$linefeed;
6545: }
6546: $result = $modify_section_result;
6547: } elsif ($secchange == 1) {
6548: $$logmsg .= "Error when attempting to expire role for $uname in old section $oldsec in course $cid -error: $expire_role_result".$linefeed;
6549: }
6550: } else {
6551: $$logmsg .= "Incomplete course id defined. Addition of user $uname from domain $udom to course $one\_$two, section $sec not completed.$linefeed";
6552: $result = "error: incomplete course id\n";
6553: }
6554: return $result;
6555: }
6556:
6557: ############################################################
6558: ############################################################
6559:
6560: sub construct_course {
6561: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
6562: my $outcome;
6563: my $linefeed = '<br />'."\n";
6564: if ($context eq 'auto') {
6565: $linefeed = "\n";
6566: }
6567: #
6568: # Open course
6569: #
6570: my $crstype = lc($args->{'crstype'});
6571: my %cenv=();
6572: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
6573: $args->{'cdescr'},
6574: $args->{'curl'},
6575: $args->{'course_home'},
6576: $args->{'nonstandard'},
6577: $args->{'crscode'},
6578: $args->{'ccuname'}.':'.
6579: $args->{'ccdomain'},
6580: $args->{'crstype'});
6581:
6582: # Note: The testing routines depend on this being output; see
6583: # Utils::Course. This needs to at least be output as a comment
6584: # if anyone ever decides to not show this, and Utils::Course::new
6585: # will need to be suitably modified.
6586: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
6587:
6588: #
6589: # Check if created correctly
6590: #
6591: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
6592: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
6593: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
6594: #
6595: # Are we cloning?
6596: #
6597: my $cloneid='';
6598: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
6599: my $can_clone = 0;
6600: $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
6601: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
6602: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
6603: my $clonemsg;
6604: if ($clonehome eq 'no_host') {
6605: $clonemsg = &mt('Attempting to clone non-existing [_1]',$crstype);
6606: if ($context eq 'auto') {
6607: $outcome .= $clonemsg;
6608: } else {
6609: $outcome .= '<font color="red">'.$clonemsg.'</font>';
6610: }
6611: $outcome .= $linefeed;
6612: } else {
6613: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
6614: if ($env{'request.role.domain'} eq $args->{'form.clonedomain'}) {
6615: $can_clone = 1;
6616: } else {
6617: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
6618: $args->{'clonedomain'},$args->{'clonecourse'});
6619: my @cloners = split(/,/,$clonehash{'cloners'});
6620: my %roleshash =
6621: &Apache::lonnet::get_my_roles($args->{'ccuname'},
6622: $args->{'ccdomain'},'userroles',['active'],['cc'],
6623: [$args->{'clonedomain'}]);
6624: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
6625: $can_clone = 1;
6626: } else {
6627: $clonemsg = &mt('The new course was not cloned from an existing course because the course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
6628: if ($context eq 'auto') {
6629: $outcome .= $clonemsg;
6630: } else {
6631: $outcome .= '<font color="red">'.$clonemsg.'</font>';
6632: }
6633: $outcome .= $linefeed;
6634: }
6635: }
6636: }
6637: if ($can_clone) {
6638: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
6639: if ($context eq 'auto') {
6640: $outcome = $clonemsg;
6641: } else {
6642: $outcome .= '<font color="green">'.$clonemsg.'</font>';
6643: }
6644: $outcome .= $linefeed;
6645: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
6646: # Copy all files
6647: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid);
6648: # Restore URL
6649: $cenv{'url'}=$oldcenv{'url'};
6650: # Restore title
6651: $cenv{'description'}=$oldcenv{'description'};
6652: # restore grading mode
6653: if (defined($oldcenv{'grading'})) {
6654: $cenv{'grading'}=$oldcenv{'grading'};
6655: }
6656: # Mark as cloned
6657: $cenv{'clonedfrom'}=$cloneid;
6658: delete($cenv{'default_enrollment_start_date'});
6659: delete($cenv{'default_enrollment_end_date'});
6660: }
6661: }
6662: #
6663: # Set environment (will override cloned, if existing)
6664: #
6665: my @sections = ();
6666: my @xlists = ();
6667: if ($args->{'crstype'}) {
6668: $cenv{'type'}=$args->{'crstype'};
6669: }
6670: if ($args->{'crsid'}) {
6671: $cenv{'courseid'}=$args->{'crsid'};
6672: }
6673: if ($args->{'crscode'}) {
6674: $cenv{'internal.coursecode'}=$args->{'crscode'};
6675: }
6676: if ($args->{'crsquota'} ne '') {
6677: $cenv{'internal.coursequota'}=$args->{'crsquota'};
6678: } else {
6679: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
6680: }
6681: if ($args->{'ccuname'}) {
6682: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
6683: ':'.$args->{'ccdomain'};
6684: } else {
6685: $cenv{'internal.courseowner'} = $args->{'curruser'};
6686: }
6687:
6688: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
6689: if ($args->{'crssections'}) {
6690: $cenv{'internal.sectionnums'} = '';
6691: if ($args->{'crssections'} =~ m/,/) {
6692: @sections = split/,/,$args->{'crssections'};
6693: } else {
6694: $sections[0] = $args->{'crssections'};
6695: }
6696: if (@sections > 0) {
6697: foreach my $item (@sections) {
6698: my ($sec,$gp) = split/:/,$item;
6699: my $class = $args->{'crscode'}.$sec;
6700: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
6701: $cenv{'internal.sectionnums'} .= $item.',';
6702: unless ($addcheck eq 'ok') {
6703: push @badclasses, $class;
6704: }
6705: }
6706: $cenv{'internal.sectionnums'} =~ s/,$//;
6707: }
6708: }
6709: # do not hide course coordinator from staff listing,
6710: # even if privileged
6711: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6712: # add crosslistings
6713: if ($args->{'crsxlist'}) {
6714: $cenv{'internal.crosslistings'}='';
6715: if ($args->{'crsxlist'} =~ m/,/) {
6716: @xlists = split/,/,$args->{'crsxlist'};
6717: } else {
6718: $xlists[0] = $args->{'crsxlist'};
6719: }
6720: if (@xlists > 0) {
6721: foreach my $item (@xlists) {
6722: my ($xl,$gp) = split/:/,$item;
6723: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
6724: $cenv{'internal.crosslistings'} .= $item.',';
6725: unless ($addcheck eq 'ok') {
6726: push @badclasses, $xl;
6727: }
6728: }
6729: $cenv{'internal.crosslistings'} =~ s/,$//;
6730: }
6731: }
6732: if ($args->{'autoadds'}) {
6733: $cenv{'internal.autoadds'}=$args->{'autoadds'};
6734: }
6735: if ($args->{'autodrops'}) {
6736: $cenv{'internal.autodrops'}=$args->{'autodrops'};
6737: }
6738: # check for notification of enrollment changes
6739: my @notified = ();
6740: if ($args->{'notify_owner'}) {
6741: if ($args->{'ccuname'} ne '') {
6742: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
6743: }
6744: }
6745: if ($args->{'notify_dc'}) {
6746: if ($uname ne '') {
6747: push(@notified,$uname.'@'.$udom);
6748: }
6749: }
6750: if (@notified > 0) {
6751: my $notifylist;
6752: if (@notified > 1) {
6753: $notifylist = join(',',@notified);
6754: } else {
6755: $notifylist = $notified[0];
6756: }
6757: $cenv{'internal.notifylist'} = $notifylist;
6758: }
6759: if (@badclasses > 0) {
6760: my %lt=&Apache::lonlocal::texthash(
6761: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
6762: 'dnhr' => 'does not have rights to access enrollment in these classes',
6763: 'adby' => 'as determined by the policies of your institution on access to official classlists'
6764: );
6765: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
6766: ' ('.$lt{'adby'}.')';
6767: if ($context eq 'auto') {
6768: $outcome .= $badclass_msg.$linefeed;
6769: $outcome .= '<font color="red">'.$badclass_msg.$linefeed.'<ul>'."\n";
6770: foreach my $item (@badclasses) {
6771: if ($context eq 'auto') {
6772: $outcome .= " - $item\n";
6773: } else {
6774: $outcome .= "<li>$item</li>\n";
6775: }
6776: }
6777: if ($context eq 'auto') {
6778: $outcome .= $linefeed;
6779: } else {
6780: $outcome .= "</ul><br /><br /></font>\n";
6781: }
6782: }
6783: }
6784: if ($args->{'no_end_date'}) {
6785: $args->{'endaccess'} = 0;
6786: }
6787: $cenv{'internal.autostart'}=$args->{'enrollstart'};
6788: $cenv{'internal.autoend'}=$args->{'enrollend'};
6789: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
6790: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
6791: if ($args->{'showphotos'}) {
6792: $cenv{'internal.showphotos'}=$args->{'showphotos'};
6793: }
6794: $cenv{'internal.authtype'} = $args->{'authtype'};
6795: $cenv{'internal.autharg'} = $args->{'autharg'};
6796: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
6797: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
6798: my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student');
6799: if ($context eq 'auto') {
6800: $outcome .= $krb_msg;
6801: } else {
6802: $outcome .= '<font color="red" size="+1">'.$krb_msg.'</font>';
6803: }
6804: $outcome .= $linefeed;
6805: }
6806: }
6807: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
6808: if ($args->{'setpolicy'}) {
6809: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6810: }
6811: if ($args->{'setcontent'}) {
6812: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
6813: }
6814: }
6815: if ($args->{'reshome'}) {
6816: $cenv{'reshome'}=$args->{'reshome'}.'/';
6817: $cenv{'reshome'}=~s/\/+$/\//;
6818: }
6819: #
6820: # course has keyed access
6821: #
6822: if ($args->{'setkeys'}) {
6823: $cenv{'keyaccess'}='yes';
6824: }
6825: # if specified, key authority is not course, but user
6826: # only active if keyaccess is yes
6827: if ($args->{'keyauth'}) {
6828: my ($user,$domain) = split(':',$args->{'keyauth'});
6829: $user = &LONCAPA::clean_username($user);
6830: $domain = &LONCAPA::clean_username($domain);
6831: if ($user ne '' && $domain ne '') {
6832: $cenv{'keyauth'}=$user.':'.$domain;
6833: }
6834: }
6835:
6836: if ($args->{'disresdis'}) {
6837: $cenv{'pch.roles.denied'}='st';
6838: }
6839: if ($args->{'disablechat'}) {
6840: $cenv{'plc.roles.denied'}='st';
6841: }
6842:
6843: # Record we've not yet viewed the Course Initialization Helper for this
6844: # course
6845: $cenv{'course.helper.not.run'} = 1;
6846: #
6847: # Use new Randomseed
6848: #
6849: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
6850: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
6851: #
6852: # The encryption code and receipt prefix for this course
6853: #
6854: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
6855: $cenv{'internal.encpref'}=100+int(9*rand(99));
6856: #
6857: # By default, use standard grading
6858: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
6859:
6860: $outcome .= $linefeed.&mt('Setting environment').': '.
6861: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
6862: #
6863: # Open all assignments
6864: #
6865: if ($args->{'openall'}) {
6866: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
6867: my %storecontent = ($storeunder => time,
6868: $storeunder.'.type' => 'date_start');
6869:
6870: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
6871: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
6872: }
6873: #
6874: # Set first page
6875: #
6876: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
6877: || ($cloneid)) {
6878: use LONCAPA::map;
6879: $outcome .= &mt('Setting first resource').': ';
6880:
6881: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
6882: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
6883:
6884: $outcome .= ($fatal?$errtext:'read ok').' - ';
6885: my $title; my $url;
6886: if ($args->{'firstres'} eq 'syl') {
6887: $title='Syllabus';
6888: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
6889: } else {
6890: $title='Navigate Contents';
6891: $url='/adm/navmaps';
6892: }
6893:
6894: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
6895: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
6896:
6897: if ($errtext) { $fatal=2; }
6898: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
6899: }
6900: return $outcome;
6901: }
6902:
6903: ############################################################
6904: ############################################################
6905:
6906: sub course_type {
6907: my ($cid) = @_;
6908: if (!defined($cid)) {
6909: $cid = $env{'request.course.id'};
6910: }
6911: if (defined($env{'course.'.$cid.'.type'})) {
6912: return $env{'course.'.$cid.'.type'};
6913: } else {
6914: return 'Course';
6915: }
6916: }
6917:
6918: sub group_term {
6919: my $crstype = &course_type();
6920: my %names = (
6921: 'Course' => 'group',
6922: 'Group' => 'team',
6923: );
6924: return $names{$crstype};
6925: }
6926:
6927: sub icon {
6928: my ($file)=@_;
6929: my $curfext = lc((split(/\./,$file))[-1]);
6930: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
6931: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
6932: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
6933: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
6934: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
6935: $curfext.".gif") {
6936: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
6937: $curfext.".gif";
6938: }
6939: }
6940: return &lonhttpdurl($iconname);
6941: }
6942:
6943: sub lonhttpdurl {
6944: my ($url)=@_;
6945: my $lonhttpd_port=$Apache::lonnet::perlvar{'lonhttpdPort'};
6946: if (!defined($lonhttpd_port)) { $lonhttpd_port='8080'; }
6947: return 'http://'.$ENV{'SERVER_NAME'}.':'.$lonhttpd_port.$url;
6948: }
6949:
6950: sub connection_aborted {
6951: my ($r)=@_;
6952: $r->print(" ");$r->rflush();
6953: my $c = $r->connection;
6954: return $c->aborted();
6955: }
6956:
6957: # Escapes strings that may have embedded 's that will be put into
6958: # strings as 'strings'.
6959: sub escape_single {
6960: my ($input) = @_;
6961: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
6962: $input =~ s/\'/\\\'/g; # Esacpe the 's....
6963: return $input;
6964: }
6965:
6966: # Same as escape_single, but escape's "'s This
6967: # can be used for "strings"
6968: sub escape_double {
6969: my ($input) = @_;
6970: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
6971: $input =~ s/\"/\\\"/g; # Esacpe the "s....
6972: return $input;
6973: }
6974:
6975: # Escapes the last element of a full URL.
6976: sub escape_url {
6977: my ($url) = @_;
6978: my @urlslices = split(/\//, $url,-1);
6979: my $lastitem = &escape(pop(@urlslices));
6980: return join('/',@urlslices).'/'.$lastitem;
6981: }
6982:
6983: # -------------------------------------------------------- Initliaze user login
6984: sub init_user_environment {
6985: my ($r, $username, $domain, $authhost, $form, $args) = @_;
6986: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
6987:
6988: my $public=($username eq 'public' && $domain eq 'public');
6989:
6990: # See if old ID present, if so, remove
6991:
6992: my ($filename,$cookie,$userroles);
6993: my $now=time;
6994:
6995: if ($public) {
6996: my $max_public=100;
6997: my $oldest;
6998: my $oldest_time=0;
6999: for(my $next=1;$next<=$max_public;$next++) {
7000: if (-e $lonids."/publicuser_$next.id") {
7001: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
7002: if ($mtime<$oldest_time || !$oldest_time) {
7003: $oldest_time=$mtime;
7004: $oldest=$next;
7005: }
7006: } else {
7007: $cookie="publicuser_$next";
7008: last;
7009: }
7010: }
7011: if (!$cookie) { $cookie="publicuser_$oldest"; }
7012: } else {
7013: # if this isn't a robot, kill any existing non-robot sessions
7014: if (!$args->{'robot'}) {
7015: opendir(DIR,$lonids);
7016: while ($filename=readdir(DIR)) {
7017: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
7018: unlink($lonids.'/'.$filename);
7019: }
7020: }
7021: closedir(DIR);
7022: }
7023: # Give them a new cookie
7024: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
7025: : $now);
7026: $cookie="$username\_$id\_$domain\_$authhost";
7027:
7028: # Initialize roles
7029:
7030: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
7031: }
7032: # ------------------------------------ Check browser type and MathML capability
7033:
7034: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
7035: $clientunicode,$clientos) = &decode_user_agent($r);
7036:
7037: # -------------------------------------- Any accessibility options to remember?
7038: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
7039: foreach my $option ('imagesuppress','appletsuppress',
7040: 'embedsuppress','fontenhance','blackwhite') {
7041: if ($form->{$option} eq 'true') {
7042: &Apache::lonnet::put('environment',{$option => 'on'},
7043: $domain,$username);
7044: } else {
7045: &Apache::lonnet::del('environment',[$option],
7046: $domain,$username);
7047: }
7048: }
7049: }
7050: # ------------------------------------------------------------- Get environment
7051:
7052: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
7053: my ($tmp) = keys(%userenv);
7054: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7055: # default remote control to off
7056: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
7057: } else {
7058: undef(%userenv);
7059: }
7060: if (($userenv{'interface'}) && (!$form->{'interface'})) {
7061: $form->{'interface'}=$userenv{'interface'};
7062: }
7063: $env{'environment.remote'}=$userenv{'remote'};
7064: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
7065:
7066: # --------------- Do not trust query string to be put directly into environment
7067: foreach my $option ('imagesuppress','appletsuppress',
7068: 'embedsuppress','fontenhance','blackwhite',
7069: 'interface','localpath','localres') {
7070: $form->{$option}=~s/[\n\r\=]//gs;
7071: }
7072: # --------------------------------------------------------- Write first profile
7073:
7074: {
7075: my %initial_env =
7076: ("user.name" => $username,
7077: "user.domain" => $domain,
7078: "user.home" => $authhost,
7079: "browser.type" => $clientbrowser,
7080: "browser.version" => $clientversion,
7081: "browser.mathml" => $clientmathml,
7082: "browser.unicode" => $clientunicode,
7083: "browser.os" => $clientos,
7084: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
7085: "request.course.fn" => '',
7086: "request.course.uri" => '',
7087: "request.course.sec" => '',
7088: "request.role" => 'cm',
7089: "request.role.adv" => $env{'user.adv'},
7090: "request.host" => $ENV{'REMOTE_ADDR'},);
7091:
7092: if ($form->{'localpath'}) {
7093: $initial_env{"browser.localpath"} = $form->{'localpath'};
7094: $initial_env{"browser.localres"} = $form->{'localres'};
7095: }
7096:
7097: if ($public) {
7098: $initial_env{"environment.remote"} = "off";
7099: }
7100: if ($form->{'interface'}) {
7101: $form->{'interface'}=~s/\W//gs;
7102: $initial_env{"browser.interface"} = $form->{'interface'};
7103: $env{'browser.interface'}=$form->{'interface'};
7104: foreach my $option ('imagesuppress','appletsuppress',
7105: 'embedsuppress','fontenhance','blackwhite') {
7106: if (($form->{$option} eq 'true') ||
7107: ($userenv{$option} eq 'on')) {
7108: $initial_env{"browser.$option"} = "on";
7109: }
7110: }
7111: }
7112:
7113: $env{'user.environment'} = "$lonids/$cookie.id";
7114:
7115: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
7116: &GDBM_WRCREAT(),0640)) {
7117: &_add_to_env(\%disk_env,\%initial_env);
7118: &_add_to_env(\%disk_env,\%userenv,'environment.');
7119: &_add_to_env(\%disk_env,$userroles);
7120: if (ref($args->{'extra_env'})) {
7121: &_add_to_env(\%disk_env,$args->{'extra_env'});
7122: }
7123: untie(%disk_env);
7124: } else {
7125: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
7126: 'Could not create environment storage in lonauth: '.$!.'</font>');
7127: return 'error: '.$!;
7128: }
7129: }
7130: $env{'request.role'}='cm';
7131: $env{'request.role.adv'}=$env{'user.adv'};
7132: $env{'browser.type'}=$clientbrowser;
7133:
7134: return $cookie;
7135:
7136: }
7137:
7138: sub _add_to_env {
7139: my ($idf,$env_data,$prefix) = @_;
7140: while (my ($key,$value) = each(%$env_data)) {
7141: $idf->{$prefix.$key} = $value;
7142: $env{$prefix.$key} = $value;
7143: }
7144: }
7145:
7146:
7147: =pod
7148:
7149: =back
7150:
7151: =cut
7152:
7153: 1;
7154: __END__;
7155:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>