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