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