File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.710:
download - view:
text,
annotated -
select for diffs
Mon Dec 8 18:25:07 2008 UTC (15 years, 10 months ago) by
bisitz
Branches:
MAIN
CVS tags:
HEAD
Optimized/standarized screen output for first grading screen ("Manual Grading/View Submissions"):
- Replaced special styles with standard fieldsets
- Removed now unused styles from loncommon.pm
- Excluded section preselection from output
These changes also restore the screen layout for the radiobuttons which have moved right to the selection boxes due to new styles.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.710 2008/12/08 18:25:07 bisitz Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use LONCAPA qw(:DEFAULT :match);
71: use DateTime::TimeZone;
72: use DateTime::Locale::Catalog;
73:
74: # ---------------------------------------------- Designs
75: use vars qw(%defaultdesign);
76:
77: my $readit;
78:
79:
80: ##
81: ## Global Variables
82: ##
83:
84:
85: # ----------------------------------------------- SSI with retries:
86: #
87:
88: =pod
89:
90: =head1 Server Side include with retries:
91:
92: =over 4
93:
94: =item * &ssi_with_retries(resource,retries form)
95:
96: Performs an ssi with some number of retries. Retries continue either
97: until the result is ok or until the retry count supplied by the
98: caller is exhausted.
99:
100: Inputs:
101:
102: =over 4
103:
104: resource - Identifies the resource to insert.
105:
106: retries - Count of the number of retries allowed.
107:
108: form - Hash that identifies the rendering options.
109:
110: =back
111:
112: Returns:
113:
114: =over 4
115:
116: content - The content of the response. If retries were exhausted this is empty.
117:
118: response - The response from the last attempt (which may or may not have been successful.
119:
120: =back
121:
122: =back
123:
124: =cut
125:
126: sub ssi_with_retries {
127: my ($resource, $retries, %form) = @_;
128:
129:
130: my $ok = 0; # True if we got a good response.
131: my $content;
132: my $response;
133:
134: # Try to get the ssi done. within the retries count:
135:
136: do {
137: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
138: $ok = $response->is_success;
139: if (!$ok) {
140: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
141: }
142: $retries--;
143: } while (!$ok && ($retries > 0));
144:
145: if (!$ok) {
146: $content = ''; # On error return an empty content.
147: }
148: return ($content, $response);
149:
150: }
151:
152:
153:
154: # ----------------------------------------------- Filetypes/Languages/Copyright
155: my %language;
156: my %supported_language;
157: my %cprtag;
158: my %scprtag;
159: my %fe; my %fd; my %fm;
160: my %category_extensions;
161:
162: # ---------------------------------------------- Thesaurus variables
163: #
164: # %Keywords:
165: # A hash used by &keyword to determine if a word is considered a keyword.
166: # $thesaurus_db_file
167: # Scalar containing the full path to the thesaurus database.
168:
169: my %Keywords;
170: my $thesaurus_db_file;
171:
172: #
173: # Initialize values from language.tab, copyright.tab, filetypes.tab,
174: # thesaurus.tab, and filecategories.tab.
175: #
176: BEGIN {
177: # Variable initialization
178: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
179: #
180: unless ($readit) {
181: # ------------------------------------------------------------------- languages
182: {
183: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
184: '/language.tab';
185: if ( open(my $fh,"<$langtabfile") ) {
186: while (my $line = <$fh>) {
187: next if ($line=~/^\#/);
188: chomp($line);
189: my ($key,$two,$country,$three,$enc,$val,$sup)=(split(/\t/,$line));
190: $language{$key}=$val.' - '.$enc;
191: if ($sup) {
192: $supported_language{$key}=$sup;
193: }
194: }
195: close($fh);
196: }
197: }
198: # ------------------------------------------------------------------ copyrights
199: {
200: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
201: '/copyright.tab';
202: if ( open (my $fh,"<$copyrightfile") ) {
203: while (my $line = <$fh>) {
204: next if ($line=~/^\#/);
205: chomp($line);
206: my ($key,$val)=(split(/\s+/,$line,2));
207: $cprtag{$key}=$val;
208: }
209: close($fh);
210: }
211: }
212: # ----------------------------------------------------------- source copyrights
213: {
214: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
215: '/source_copyright.tab';
216: if ( open (my $fh,"<$sourcecopyrightfile") ) {
217: while (my $line = <$fh>) {
218: next if ($line =~ /^\#/);
219: chomp($line);
220: my ($key,$val)=(split(/\s+/,$line,2));
221: $scprtag{$key}=$val;
222: }
223: close($fh);
224: }
225: }
226:
227: # -------------------------------------------------------------- default domain designs
228: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
229: my $designfile = $designdir.'/default.tab';
230: if ( open (my $fh,"<$designfile") ) {
231: while (my $line = <$fh>) {
232: next if ($line =~ /^\#/);
233: chomp($line);
234: my ($key,$val)=(split(/\=/,$line));
235: if ($val) { $defaultdesign{$key}=$val; }
236: }
237: close($fh);
238: }
239:
240: # ------------------------------------------------------------- file categories
241: {
242: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
243: '/filecategories.tab';
244: if ( open (my $fh,"<$categoryfile") ) {
245: while (my $line = <$fh>) {
246: next if ($line =~ /^\#/);
247: chomp($line);
248: my ($extension,$category)=(split(/\s+/,$line,2));
249: push @{$category_extensions{lc($category)}},$extension;
250: }
251: close($fh);
252: }
253:
254: }
255: # ------------------------------------------------------------------ file types
256: {
257: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
258: '/filetypes.tab';
259: if ( open (my $fh,"<$typesfile") ) {
260: while (my $line = <$fh>) {
261: next if ($line =~ /^\#/);
262: chomp($line);
263: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
264: if ($descr ne '') {
265: $fe{$ending}=lc($emb);
266: $fd{$ending}=$descr;
267: if ($mime ne 'unk') { $fm{$ending}=$mime; }
268: }
269: }
270: close($fh);
271: }
272: }
273: &Apache::lonnet::logthis(
274: "<span style='color:yellow;'>INFO: Read file types</span>");
275: $readit=1;
276: } # end of unless($readit)
277:
278: }
279:
280: ###############################################################
281: ## HTML and Javascript Helper Functions ##
282: ###############################################################
283:
284: =pod
285:
286: =head1 HTML and Javascript Functions
287:
288: =over 4
289:
290: =item * &browser_and_searcher_javascript()
291:
292: X<browsing, javascript>X<searching, javascript>Returns a string
293: containing javascript with two functions, C<openbrowser> and
294: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
295: tags.
296:
297: =item * &openbrowser(formname,elementname,only,omit) [javascript]
298:
299: inputs: formname, elementname, only, omit
300:
301: formname and elementname indicate the name of the html form and name of
302: the element that the results of the browsing selection are to be placed in.
303:
304: Specifying 'only' will restrict the browser to displaying only files
305: with the given extension. Can be a comma separated list.
306:
307: Specifying 'omit' will restrict the browser to NOT displaying files
308: with the given extension. Can be a comma separated list.
309:
310: =item * &opensearcher(formname,elementname) [javascript]
311:
312: Inputs: formname, elementname
313:
314: formname and elementname specify the name of the html form and the name
315: of the element the selection from the search results will be placed in.
316:
317: =cut
318:
319: sub browser_and_searcher_javascript {
320: my ($mode)=@_;
321: if (!defined($mode)) { $mode='edit'; }
322: my $resurl=&escape_single(&lastresurl());
323: return <<END;
324: // <!-- BEGIN LON-CAPA Internal
325: var editbrowser = null;
326: function openbrowser(formname,elementname,only,omit,titleelement) {
327: var url = '$resurl/?';
328: if (editbrowser == null) {
329: url += 'launch=1&';
330: }
331: url += 'catalogmode=interactive&';
332: url += 'mode=$mode&';
333: url += 'inhibitmenu=yes&';
334: url += 'form=' + formname + '&';
335: if (only != null) {
336: url += 'only=' + only + '&';
337: } else {
338: url += 'only=&';
339: }
340: if (omit != null) {
341: url += 'omit=' + omit + '&';
342: } else {
343: url += 'omit=&';
344: }
345: if (titleelement != null) {
346: url += 'titleelement=' + titleelement + '&';
347: } else {
348: url += 'titleelement=&';
349: }
350: url += 'element=' + elementname + '';
351: var title = 'Browser';
352: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
353: options += ',width=700,height=600';
354: editbrowser = open(url,title,options,'1');
355: editbrowser.focus();
356: }
357: var editsearcher;
358: function opensearcher(formname,elementname,titleelement) {
359: var url = '/adm/searchcat?';
360: if (editsearcher == null) {
361: url += 'launch=1&';
362: }
363: url += 'catalogmode=interactive&';
364: url += 'mode=$mode&';
365: url += 'form=' + formname + '&';
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Search';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editsearcher = open(url,title,options,'1');
376: editsearcher.focus();
377: }
378: // END LON-CAPA Internal -->
379: END
380: }
381:
382: sub lastresurl {
383: if ($env{'environment.lastresurl'}) {
384: return $env{'environment.lastresurl'}
385: } else {
386: return '/res';
387: }
388: }
389:
390: sub storeresurl {
391: my $resurl=&Apache::lonnet::clutter(shift);
392: unless ($resurl=~/^\/res/) { return 0; }
393: $resurl=~s/\/$//;
394: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
395: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
396: return 1;
397: }
398:
399: sub studentbrowser_javascript {
400: unless (
401: (($env{'request.course.id'}) &&
402: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
403: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
404: '/'.$env{'request.course.sec'})
405: ))
406: || ($env{'request.role'}=~/^(au|dc|su)/)
407: ) { return ''; }
408: return (<<'ENDSTDBRW');
409: <script type="text/javascript" language="Javascript" >
410: var stdeditbrowser;
411: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter) {
412: var url = '/adm/pickstudent?';
413: var filter;
414: if (!ignorefilter) {
415: eval('filter=document.'+formname+'.'+uname+'.value;');
416: }
417: if (filter != null) {
418: if (filter != '') {
419: url += 'filter='+filter+'&';
420: }
421: }
422: url += 'form=' + formname + '&unameelement='+uname+
423: '&udomelement='+udom;
424: if (roleflag) { url+="&roles=1"; }
425: var title = 'Student_Browser';
426: var options = 'scrollbars=1,resizable=1,menubar=0';
427: options += ',width=700,height=600';
428: stdeditbrowser = open(url,title,options,'1');
429: stdeditbrowser.focus();
430: }
431: </script>
432: ENDSTDBRW
433: }
434:
435: sub selectstudent_link {
436: my ($form,$unameele,$udomele)=@_;
437: if ($env{'request.course.id'}) {
438: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
439: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
440: '/'.$env{'request.course.sec'})) {
441: return '';
442: }
443: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
444: '","'.$udomele.'");'."'>".&mt('Select User')."</a>";
445: }
446: if ($env{'request.role'}=~/^(au|dc|su)/) {
447: return "<a href='".'javascript:openstdbrowser("'.$form.'","'.$unameele.
448: '","'.$udomele.'",1);'."'>".&mt('Select User')."</a>";
449: }
450: return '';
451: }
452:
453: sub authorbrowser_javascript {
454: return <<"ENDAUTHORBRW";
455: <script type="text/javascript">
456: var stdeditbrowser;
457:
458: function openauthorbrowser(formname,udom) {
459: var url = '/adm/pickauthor?';
460: url += 'form='+formname+'&roledom='+udom;
461: var title = 'Author_Browser';
462: var options = 'scrollbars=1,resizable=1,menubar=0';
463: options += ',width=700,height=600';
464: stdeditbrowser = open(url,title,options,'1');
465: stdeditbrowser.focus();
466: }
467:
468: </script>
469: ENDAUTHORBRW
470: }
471:
472: sub coursebrowser_javascript {
473: my ($domainfilter,$sec_element,$formname)=@_;
474: 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');
475: my $output = '
476: <script type="text/javascript">
477: var stdeditbrowser;'."\n";
478: $output .= <<"ENDSTDBRW";
479: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,crstype) {
480: var url = '/adm/pickcourse?';
481: var domainfilter = '';
482: var formid = getFormIdByName(formname);
483: if (formid > -1) {
484: var domid = getIndexByName(formid,udom);
485: if (domid > -1) {
486: if (document.forms[formid].elements[domid].type == 'select-one') {
487: domainfilter=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
488: }
489: if (document.forms[formid].elements[domid].type == 'hidden') {
490: domainfilter=document.forms[formid].elements[domid].value;
491: }
492: }
493: }
494: if (domainfilter != null) {
495: if (domainfilter != '') {
496: url += 'domainfilter='+domainfilter+'&';
497: }
498: }
499: url += 'form=' + formname + '&cnumelement='+uname+
500: '&cdomelement='+udom+
501: '&cnameelement='+desc;
502: if (extra_element !=null && extra_element != '') {
503: if (formname == 'rolechoice' || formname == 'studentform') {
504: url += '&roleelement='+extra_element;
505: if (domainfilter == null || domainfilter == '') {
506: url += '&domainfilter='+extra_element;
507: }
508: }
509: else {
510: if (formname == 'portform') {
511: url += '&setroles='+extra_element;
512: }
513: }
514: }
515: if (multflag !=null && multflag != '') {
516: url += '&multiple='+multflag;
517: }
518: if (crstype == 'Course/Group') {
519: if (formname == 'cu') {
520: crstype = document.cu.crstype.options[document.cu.crstype.selectedIndex].value;
521: if (crstype == "") {
522: alert("$crs_or_grp_alert");
523: return;
524: }
525: }
526: }
527: if (crstype !=null && crstype != '') {
528: url += '&type='+crstype;
529: }
530: var title = 'Course_Browser';
531: var options = 'scrollbars=1,resizable=1,menubar=0';
532: options += ',width=700,height=600';
533: stdeditbrowser = open(url,title,options,'1');
534: stdeditbrowser.focus();
535: }
536:
537: function getFormIdByName(formname) {
538: for (var i=0;i<document.forms.length;i++) {
539: if (document.forms[i].name == formname) {
540: return i;
541: }
542: }
543: return -1;
544: }
545:
546: function getIndexByName(formid,item) {
547: for (var i=0;i<document.forms[formid].elements.length;i++) {
548: if (document.forms[formid].elements[i].name == item) {
549: return i;
550: }
551: }
552: return -1;
553: }
554: ENDSTDBRW
555: if ($sec_element ne '') {
556: $output .= &setsec_javascript($sec_element,$formname);
557: }
558: $output .= '
559: </script>';
560: return $output;
561: }
562:
563: sub setsec_javascript {
564: my ($sec_element,$formname) = @_;
565: my $setsections = qq|
566: function setSect(sectionlist) {
567: var sectionsArray = new Array();
568: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
569: sectionsArray = sectionlist.split(",");
570: }
571: var numSections = sectionsArray.length;
572: document.$formname.$sec_element.length = 0;
573: if (numSections == 0) {
574: document.$formname.$sec_element.multiple=false;
575: document.$formname.$sec_element.size=1;
576: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
577: } else {
578: if (numSections == 1) {
579: document.$formname.$sec_element.multiple=false;
580: document.$formname.$sec_element.size=1;
581: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
582: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
583: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
584: } else {
585: for (var i=0; i<numSections; i++) {
586: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
587: }
588: document.$formname.$sec_element.multiple=true
589: if (numSections < 3) {
590: document.$formname.$sec_element.size=numSections;
591: } else {
592: document.$formname.$sec_element.size=3;
593: }
594: document.$formname.$sec_element.options[0].selected = false
595: }
596: }
597: }
598: |;
599: return $setsections;
600: }
601:
602:
603: sub selectcourse_link {
604: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype)=@_;
605: return "<a href='".'javascript:opencrsbrowser("'.$form.'","'.$unameele.
606: '","'.$udomele.'","'.$desc.'","'.$extra_element.'","'.$multflag.'","'.$selecttype.'");'."'>".&mt('Select Course')."</a>";
607: }
608:
609: sub selectauthor_link {
610: my ($form,$udom)=@_;
611: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
612: &mt('Select Author').'</a>';
613: }
614:
615: sub check_uncheck_jscript {
616: my $jscript = <<"ENDSCRT";
617: function checkAll(field) {
618: if (field.length > 0) {
619: for (i = 0; i < field.length; i++) {
620: field[i].checked = true ;
621: }
622: } else {
623: field.checked = true
624: }
625: }
626:
627: function uncheckAll(field) {
628: if (field.length > 0) {
629: for (i = 0; i < field.length; i++) {
630: field[i].checked = false ;
631: }
632: } else {
633: field.checked = false ;
634: }
635: }
636: ENDSCRT
637: return $jscript;
638: }
639:
640: sub select_timezone {
641: my ($name,$selected,$onchange,$includeempty)=@_;
642: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
643: if ($includeempty) {
644: $output .= '<option value=""';
645: if (($selected eq '') || ($selected eq 'local')) {
646: $output .= ' selected="selected" ';
647: }
648: $output .= '> </option>';
649: }
650: my @timezones = DateTime::TimeZone->all_names;
651: foreach my $tzone (@timezones) {
652: $output.= '<option value="'.$tzone.'"';
653: if ($tzone eq $selected) {
654: $output.=' selected="selected"';
655: }
656: $output.=">$tzone</option>\n";
657: }
658: $output.="</select>";
659: return $output;
660: }
661:
662: sub select_datelocale {
663: my ($name,$selected,$onchange,$includeempty)=@_;
664: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
665: if ($includeempty) {
666: $output .= '<option value=""';
667: if ($selected eq '') {
668: $output .= ' selected="selected" ';
669: }
670: $output .= '> </option>';
671: }
672: my (@possibles,%locale_names);
673: my @locales = DateTime::Locale::Catalog::Locales;
674: foreach my $locale (@locales) {
675: if (ref($locale) eq 'HASH') {
676: my $id = $locale->{'id'};
677: if ($id ne '') {
678: my $en_terr = $locale->{'en_territory'};
679: my $native_terr = $locale->{'native_territory'};
680: my @languages = &Apache::lonlocal::preferred_languages();
681: if (grep(/^en$/,@languages) || !@languages) {
682: if ($en_terr ne '') {
683: $locale_names{$id} = '('.$en_terr.')';
684: } elsif ($native_terr ne '') {
685: $locale_names{$id} = $native_terr;
686: }
687: } else {
688: if ($native_terr ne '') {
689: $locale_names{$id} = $native_terr.' ';
690: } elsif ($en_terr ne '') {
691: $locale_names{$id} = '('.$en_terr.')';
692: }
693: }
694: push (@possibles,$id);
695: }
696: }
697: }
698: foreach my $item (sort(@possibles)) {
699: $output.= '<option value="'.$item.'"';
700: if ($item eq $selected) {
701: $output.=' selected="selected"';
702: }
703: $output.=">$item";
704: if ($locale_names{$item} ne '') {
705: $output.=" $locale_names{$item}</option>\n";
706: }
707: $output.="</option>\n";
708: }
709: $output.="</select>";
710: return $output;
711: }
712:
713: =pod
714:
715: =item * &linked_select_forms(...)
716:
717: linked_select_forms returns a string containing a <script></script> block
718: and html for two <select> menus. The select menus will be linked in that
719: changing the value of the first menu will result in new values being placed
720: in the second menu. The values in the select menu will appear in alphabetical
721: order unless a defined order is provided.
722:
723: linked_select_forms takes the following ordered inputs:
724:
725: =over 4
726:
727: =item * $formname, the name of the <form> tag
728:
729: =item * $middletext, the text which appears between the <select> tags
730:
731: =item * $firstdefault, the default value for the first menu
732:
733: =item * $firstselectname, the name of the first <select> tag
734:
735: =item * $secondselectname, the name of the second <select> tag
736:
737: =item * $hashref, a reference to a hash containing the data for the menus.
738:
739: =item * $menuorder, the order of values in the first menu
740:
741: =back
742:
743: Below is an example of such a hash. Only the 'text', 'default', and
744: 'select2' keys must appear as stated. keys(%menu) are the possible
745: values for the first select menu. The text that coincides with the
746: first menu value is given in $menu{$choice1}->{'text'}. The values
747: and text for the second menu are given in the hash pointed to by
748: $menu{$choice1}->{'select2'}.
749:
750: my %menu = ( A1 => { text =>"Choice A1" ,
751: default => "B3",
752: select2 => {
753: B1 => "Choice B1",
754: B2 => "Choice B2",
755: B3 => "Choice B3",
756: B4 => "Choice B4"
757: },
758: order => ['B4','B3','B1','B2'],
759: },
760: A2 => { text =>"Choice A2" ,
761: default => "C2",
762: select2 => {
763: C1 => "Choice C1",
764: C2 => "Choice C2",
765: C3 => "Choice C3"
766: },
767: order => ['C2','C1','C3'],
768: },
769: A3 => { text =>"Choice A3" ,
770: default => "D6",
771: select2 => {
772: D1 => "Choice D1",
773: D2 => "Choice D2",
774: D3 => "Choice D3",
775: D4 => "Choice D4",
776: D5 => "Choice D5",
777: D6 => "Choice D6",
778: D7 => "Choice D7"
779: },
780: order => ['D4','D3','D2','D1','D7','D6','D5'],
781: }
782: );
783:
784: =cut
785:
786: sub linked_select_forms {
787: my ($formname,
788: $middletext,
789: $firstdefault,
790: $firstselectname,
791: $secondselectname,
792: $hashref,
793: $menuorder,
794: ) = @_;
795: my $second = "document.$formname.$secondselectname";
796: my $first = "document.$formname.$firstselectname";
797: # output the javascript to do the changing
798: my $result = '';
799: $result.="<script type=\"text/javascript\">\n";
800: $result.="var select2data = new Object();\n";
801: $" = '","';
802: my $debug = '';
803: foreach my $s1 (sort(keys(%$hashref))) {
804: $result.="select2data.d_$s1 = new Object();\n";
805: $result.="select2data.d_$s1.def = new String('".
806: $hashref->{$s1}->{'default'}."');\n";
807: $result.="select2data.d_$s1.values = new Array(";
808: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
809: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
810: @s2values = @{$hashref->{$s1}->{'order'}};
811: }
812: $result.="\"@s2values\");\n";
813: $result.="select2data.d_$s1.texts = new Array(";
814: my @s2texts;
815: foreach my $value (@s2values) {
816: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
817: }
818: $result.="\"@s2texts\");\n";
819: }
820: $"=' ';
821: $result.= <<"END";
822:
823: function select1_changed() {
824: // Determine new choice
825: var newvalue = "d_" + $first.value;
826: // update select2
827: var values = select2data[newvalue].values;
828: var texts = select2data[newvalue].texts;
829: var select2def = select2data[newvalue].def;
830: var i;
831: // out with the old
832: for (i = 0; i < $second.options.length; i++) {
833: $second.options[i] = null;
834: }
835: // in with the nuclear
836: for (i=0;i<values.length; i++) {
837: $second.options[i] = new Option(values[i]);
838: $second.options[i].value = values[i];
839: $second.options[i].text = texts[i];
840: if (values[i] == select2def) {
841: $second.options[i].selected = true;
842: }
843: }
844: }
845: </script>
846: END
847: # output the initial values for the selection lists
848: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
849: my @order = sort(keys(%{$hashref}));
850: if (ref($menuorder) eq 'ARRAY') {
851: @order = @{$menuorder};
852: }
853: foreach my $value (@order) {
854: $result.=" <option value=\"$value\" ";
855: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
856: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
857: }
858: $result .= "</select>\n";
859: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
860: $result .= $middletext;
861: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
862: my $seconddefault = $hashref->{$firstdefault}->{'default'};
863:
864: my @secondorder = sort(keys(%select2));
865: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
866: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
867: }
868: foreach my $value (@secondorder) {
869: $result.=" <option value=\"$value\" ";
870: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
871: $result.=">".&mt($select2{$value})."</option>\n";
872: }
873: $result .= "</select>\n";
874: # return $debug;
875: return $result;
876: } # end of sub linked_select_forms {
877:
878: =pod
879:
880: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
881:
882: Returns a string corresponding to an HTML link to the given help
883: $topic, where $topic corresponds to the name of a .tex file in
884: /home/httpd/html/adm/help/tex, with underscores replaced by
885: spaces.
886:
887: $text will optionally be linked to the same topic, allowing you to
888: link text in addition to the graphic. If you do not want to link
889: text, but wish to specify one of the later parameters, pass an
890: empty string.
891:
892: $stayOnPage is a value that will be interpreted as a boolean. If true,
893: the link will not open a new window. If false, the link will open
894: a new window using Javascript. (Default is false.)
895:
896: $width and $height are optional numerical parameters that will
897: override the width and height of the popped up window, which may
898: be useful for certain help topics with big pictures included.
899:
900: =cut
901:
902: sub help_open_topic {
903: my ($topic, $text, $stayOnPage, $width, $height) = @_;
904: $text = "" if (not defined $text);
905: $stayOnPage = 0 if (not defined $stayOnPage);
906: if ($env{'browser.interface'} eq 'textual') {
907: $stayOnPage=1;
908: }
909: $width = 350 if (not defined $width);
910: $height = 400 if (not defined $height);
911: my $filename = $topic;
912: $filename =~ s/ /_/g;
913:
914: my $template = "";
915: my $link;
916:
917: $topic=~s/\W/\_/g;
918:
919: if (!$stayOnPage) {
920: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
921: } else {
922: $link = "/adm/help/${filename}.hlp";
923: }
924:
925: # Add the text
926: if ($text ne "") {
927: $template .=
928: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
929: "<td bgcolor='#5555FF'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
930: }
931:
932: # Add the graphic
933: my $title = &mt('Online Help');
934: my $helpicon=&lonhttpdurl("/adm/help/help.png");
935: $template .= <<"ENDTEMPLATE";
936: <a target="_top" href="$link" title="$title"><img src="$helpicon" border="0" alt="(Help: $topic)" /></a>
937: ENDTEMPLATE
938: if ($text ne '') { $template.='</td></tr></table>' };
939: return $template;
940:
941: }
942:
943: # This is a quicky function for Latex cheatsheet editing, since it
944: # appears in at least four places
945: sub helpLatexCheatsheet {
946: my $other = shift;
947: my $addOther = '';
948: if ($other) {
949: $addOther = Apache::loncommon::help_open_topic($other, shift,
950: undef, undef, 600) .
951: '</td><td>';
952: }
953: return '<table><tr><td>'.
954: $addOther .
955: &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
956: undef,undef,600)
957: .'</td><td>'.
958: &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
959: undef,undef,600)
960: .'</td><td>'.
961: &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
962: undef,undef,600)
963: .'</td></tr></table>';
964: }
965:
966: sub general_help {
967: my $helptopic='Student_Intro';
968: if ($env{'request.role'}=~/^(ca|au)/) {
969: $helptopic='Authoring_Intro';
970: } elsif ($env{'request.role'}=~/^cc/) {
971: $helptopic='Course_Coordination_Intro';
972: } elsif ($env{'request.role'}=~/^dc/) {
973: $helptopic='Domain_Coordination_Intro';
974: }
975: return $helptopic;
976: }
977:
978: sub update_help_link {
979: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
980: my $origurl = $ENV{'REQUEST_URI'};
981: $origurl=~s|^/~|/priv/|;
982: my $timestamp = time;
983: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
984: $$datum = &escape($$datum);
985: }
986:
987: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
988: my $output .= <<"ENDOUTPUT";
989: <script type="text/javascript">
990: banner_link = '$banner_link';
991: </script>
992: ENDOUTPUT
993: return $output;
994: }
995:
996: # now just updates the help link and generates a blue icon
997: sub help_open_menu {
998: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
999: = @_;
1000: $stayOnPage = 0 if (not defined $stayOnPage);
1001: # only use pop-up help (stayOnPage == 0)
1002: # if environment.remote is on (using remote control UI)
1003: if ($env{'browser.interface'} eq 'textual' ||
1004: $env{'environment.remote'} eq 'off' ) {
1005: $stayOnPage=1;
1006: }
1007: my $output;
1008: if ($component_help) {
1009: if (!$text) {
1010: $output=&help_open_topic($component_help,undef,$stayOnPage,
1011: $width,$height);
1012: } else {
1013: my $help_text;
1014: $help_text=&unescape($topic);
1015: $output='<table><tr><td>'.
1016: &help_open_topic($component_help,$help_text,$stayOnPage,
1017: $width,$height).'</td></tr></table>';
1018: }
1019: }
1020: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1021: return $output.$banner_link;
1022: }
1023:
1024: sub top_nav_help {
1025: my ($text) = @_;
1026: $text = &mt($text);
1027: my $stay_on_page =
1028: ($env{'browser.interface'} eq 'textual' ||
1029: $env{'environment.remote'} eq 'off' );
1030: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1031: : "javascript:helpMenu('open')";
1032: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1033:
1034: my $title = &mt('Get help');
1035:
1036: return <<"END";
1037: $banner_link
1038: <a href="$link" title="$title">$text</a>
1039: END
1040: }
1041:
1042: sub help_menu_js {
1043: my ($text) = @_;
1044:
1045: my $stayOnPage =
1046: ($env{'browser.interface'} eq 'textual' ||
1047: $env{'environment.remote'} eq 'off' );
1048:
1049: my $width = 620;
1050: my $height = 600;
1051: my $helptopic=&general_help();
1052: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1053: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1054: my $start_page =
1055: &Apache::loncommon::start_page('Help Menu', undef,
1056: {'frameset' => 1,
1057: 'js_ready' => 1,
1058: 'add_entries' => {
1059: 'border' => '0',
1060: 'rows' => "110,*",},});
1061: my $end_page =
1062: &Apache::loncommon::end_page({'frameset' => 1,
1063: 'js_ready' => 1,});
1064:
1065: my $template .= <<"ENDTEMPLATE";
1066: <script type="text/javascript">
1067: // <!-- BEGIN LON-CAPA Internal
1068: // <![CDATA[
1069: var banner_link = '';
1070: function helpMenu(target) {
1071: var caller = this;
1072: if (target == 'open') {
1073: var newWindow = null;
1074: try {
1075: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1076: }
1077: catch(error) {
1078: writeHelp(caller);
1079: return;
1080: }
1081: if (newWindow) {
1082: caller = newWindow;
1083: }
1084: }
1085: writeHelp(caller);
1086: return;
1087: }
1088: function writeHelp(caller) {
1089: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1090: caller.document.close()
1091: caller.focus()
1092: }
1093: // ]]>
1094: // END LON-CAPA Internal -->
1095: </script>
1096: ENDTEMPLATE
1097: return $template;
1098: }
1099:
1100: sub help_open_bug {
1101: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1102: unless ($env{'user.adv'}) { return ''; }
1103: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1104: $text = "" if (not defined $text);
1105: $stayOnPage = 0 if (not defined $stayOnPage);
1106: if ($env{'browser.interface'} eq 'textual' ||
1107: $env{'environment.remote'} eq 'off' ) {
1108: $stayOnPage=1;
1109: }
1110: $width = 600 if (not defined $width);
1111: $height = 600 if (not defined $height);
1112:
1113: $topic=~s/\W+/\+/g;
1114: my $link='';
1115: my $template='';
1116: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1117: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1118: if (!$stayOnPage)
1119: {
1120: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1121: }
1122: else
1123: {
1124: $link = $url;
1125: }
1126: # Add the text
1127: if ($text ne "")
1128: {
1129: $template .=
1130: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1131: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1132: }
1133:
1134: # Add the graphic
1135: my $title = &mt('Report a Bug');
1136: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1137: $template .= <<"ENDTEMPLATE";
1138: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1139: ENDTEMPLATE
1140: if ($text ne '') { $template.='</td></tr></table>' };
1141: return $template;
1142:
1143: }
1144:
1145: sub help_open_faq {
1146: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1147: unless ($env{'user.adv'}) { return ''; }
1148: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1149: $text = "" if (not defined $text);
1150: $stayOnPage = 0 if (not defined $stayOnPage);
1151: if ($env{'browser.interface'} eq 'textual' ||
1152: $env{'environment.remote'} eq 'off' ) {
1153: $stayOnPage=1;
1154: }
1155: $width = 350 if (not defined $width);
1156: $height = 400 if (not defined $height);
1157:
1158: $topic=~s/\W+/\+/g;
1159: my $link='';
1160: my $template='';
1161: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1162: if (!$stayOnPage)
1163: {
1164: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1165: }
1166: else
1167: {
1168: $link = $url;
1169: }
1170:
1171: # Add the text
1172: if ($text ne "")
1173: {
1174: $template .=
1175: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1176: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1177: }
1178:
1179: # Add the graphic
1180: my $title = &mt('View the FAQ');
1181: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1182: $template .= <<"ENDTEMPLATE";
1183: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1184: ENDTEMPLATE
1185: if ($text ne '') { $template.='</td></tr></table>' };
1186: return $template;
1187:
1188: }
1189:
1190: ###############################################################
1191: ###############################################################
1192:
1193: =pod
1194:
1195: =item * &change_content_javascript():
1196:
1197: This and the next function allow you to create small sections of an
1198: otherwise static HTML page that you can update on the fly with
1199: Javascript, even in Netscape 4.
1200:
1201: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1202: must be written to the HTML page once. It will prove the Javascript
1203: function "change(name, content)". Calling the change function with the
1204: name of the section
1205: you want to update, matching the name passed to C<changable_area>, and
1206: the new content you want to put in there, will put the content into
1207: that area.
1208:
1209: B<Note>: Netscape 4 only reserves enough space for the changable area
1210: to contain room for the original contents. You need to "make space"
1211: for whatever changes you wish to make, and be B<sure> to check your
1212: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1213: it's adequate for updating a one-line status display, but little more.
1214: This script will set the space to 100% width, so you only need to
1215: worry about height in Netscape 4.
1216:
1217: Modern browsers are much less limiting, and if you can commit to the
1218: user not using Netscape 4, this feature may be used freely with
1219: pretty much any HTML.
1220:
1221: =cut
1222:
1223: sub change_content_javascript {
1224: # If we're on Netscape 4, we need to use Layer-based code
1225: if ($env{'browser.type'} eq 'netscape' &&
1226: $env{'browser.version'} =~ /^4\./) {
1227: return (<<NETSCAPE4);
1228: function change(name, content) {
1229: doc = document.layers[name+"___escape"].layers[0].document;
1230: doc.open();
1231: doc.write(content);
1232: doc.close();
1233: }
1234: NETSCAPE4
1235: } else {
1236: # Otherwise, we need to use semi-standards-compliant code
1237: # (technically, "innerHTML" isn't standard but the equivalent
1238: # is really scary, and every useful browser supports it
1239: return (<<DOMBASED);
1240: function change(name, content) {
1241: element = document.getElementById(name);
1242: element.innerHTML = content;
1243: }
1244: DOMBASED
1245: }
1246: }
1247:
1248: =pod
1249:
1250: =item * &changable_area($name,$origContent):
1251:
1252: This provides a "changable area" that can be modified on the fly via
1253: the Javascript code provided in C<change_content_javascript>. $name is
1254: the name you will use to reference the area later; do not repeat the
1255: same name on a given HTML page more then once. $origContent is what
1256: the area will originally contain, which can be left blank.
1257:
1258: =cut
1259:
1260: sub changable_area {
1261: my ($name, $origContent) = @_;
1262:
1263: if ($env{'browser.type'} eq 'netscape' &&
1264: $env{'browser.version'} =~ /^4\./) {
1265: # If this is netscape 4, we need to use the Layer tag
1266: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1267: } else {
1268: return "<span id='$name'>$origContent</span>";
1269: }
1270: }
1271:
1272: =pod
1273:
1274: =item * &viewport_geometry_js
1275:
1276: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1277:
1278: =cut
1279:
1280:
1281: sub viewport_geometry_js {
1282: return <<"GEOMETRY";
1283: var Geometry = {};
1284: function init_geometry() {
1285: if (Geometry.init) { return };
1286: Geometry.init=1;
1287: if (window.innerHeight) {
1288: Geometry.getViewportHeight = function() { return window.innerHeight; };
1289: Geometry.getViewportWidth = function() { return window.innerWidth; };
1290: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1291: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1292: }
1293: else if (document.documentElement && document.documentElement.clientHeight) {
1294: Geometry.getViewportHeight =
1295: function() { return document.documentElement.clientHeight; };
1296: Geometry.getViewportWidth =
1297: function() { return document.documentElement.clientWidth; };
1298:
1299: Geometry.getHorizontalScroll =
1300: function() { return document.documentElement.scrollLeft; };
1301: Geometry.getVerticalScroll =
1302: function() { return document.documentElement.scrollTop; };
1303: }
1304: else if (document.body.clientHeight) {
1305: Geometry.getViewportHeight =
1306: function() { return document.body.clientHeight; };
1307: Geometry.getViewportWidth =
1308: function() { return document.body.clientWidth; };
1309: Geometry.getHorizontalScroll =
1310: function() { return document.body.scrollLeft; };
1311: Geometry.getVerticalScroll =
1312: function() { return document.body.scrollTop; };
1313: }
1314: }
1315:
1316: GEOMETRY
1317: }
1318:
1319: =pod
1320:
1321: =item * &viewport_size_js()
1322:
1323: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window.
1324:
1325: =cut
1326:
1327: sub viewport_size_js {
1328: my $geometry = &viewport_geometry_js();
1329: return <<"DIMS";
1330:
1331: $geometry
1332:
1333: function getViewportDims(width,height) {
1334: init_geometry();
1335: width.value = Geometry.getViewportWidth();
1336: height.value = Geometry.getViewportHeight();
1337: return;
1338: }
1339:
1340: DIMS
1341: }
1342:
1343: =pod
1344:
1345: =item * &resize_textarea_js()
1346:
1347: emits the needed javascript to resize a textarea to be as big as possible
1348:
1349: creates a function resize_textrea that takes two IDs first should be
1350: the id of the element to resize, second should be the id of a div that
1351: surrounds everything that comes after the textarea, this routine needs
1352: to be attached to the <body> for the onload and onresize events.
1353:
1354: =back
1355:
1356: =cut
1357:
1358: sub resize_textarea_js {
1359: my $geometry = &viewport_geometry_js();
1360: return <<"RESIZE";
1361: <script type="text/javascript">
1362: $geometry
1363:
1364: function getX(element) {
1365: var x = 0;
1366: while (element) {
1367: x += element.offsetLeft;
1368: element = element.offsetParent;
1369: }
1370: return x;
1371: }
1372: function getY(element) {
1373: var y = 0;
1374: while (element) {
1375: y += element.offsetTop;
1376: element = element.offsetParent;
1377: }
1378: return y;
1379: }
1380:
1381:
1382: function resize_textarea(textarea_id,bottom_id) {
1383: init_geometry();
1384: var textarea = document.getElementById(textarea_id);
1385: //alert(textarea);
1386:
1387: var textarea_top = getY(textarea);
1388: var textarea_height = textarea.offsetHeight;
1389: var bottom = document.getElementById(bottom_id);
1390: var bottom_top = getY(bottom);
1391: var bottom_height = bottom.offsetHeight;
1392: var window_height = Geometry.getViewportHeight();
1393: var fudge = 23;
1394: var new_height = window_height-fudge-textarea_top-bottom_height;
1395: if (new_height < 300) {
1396: new_height = 300;
1397: }
1398: textarea.style.height=new_height+'px';
1399: }
1400: </script>
1401: RESIZE
1402:
1403: }
1404:
1405: =pod
1406:
1407: =head1 Excel and CSV file utility routines
1408:
1409: =over 4
1410:
1411: =cut
1412:
1413: ###############################################################
1414: ###############################################################
1415:
1416: =pod
1417:
1418: =item * &csv_translate($text)
1419:
1420: Translate $text to allow it to be output as a 'comma separated values'
1421: format.
1422:
1423: =cut
1424:
1425: ###############################################################
1426: ###############################################################
1427: sub csv_translate {
1428: my $text = shift;
1429: $text =~ s/\"/\"\"/g;
1430: $text =~ s/\n/ /g;
1431: return $text;
1432: }
1433:
1434: ###############################################################
1435: ###############################################################
1436:
1437: =pod
1438:
1439: =item * &define_excel_formats()
1440:
1441: Define some commonly used Excel cell formats.
1442:
1443: Currently supported formats:
1444:
1445: =over 4
1446:
1447: =item header
1448:
1449: =item bold
1450:
1451: =item h1
1452:
1453: =item h2
1454:
1455: =item h3
1456:
1457: =item h4
1458:
1459: =item i
1460:
1461: =item date
1462:
1463: =back
1464:
1465: Inputs: $workbook
1466:
1467: Returns: $format, a hash reference.
1468:
1469: =cut
1470:
1471: ###############################################################
1472: ###############################################################
1473: sub define_excel_formats {
1474: my ($workbook) = @_;
1475: my $format;
1476: $format->{'header'} = $workbook->add_format(bold => 1,
1477: bottom => 1,
1478: align => 'center');
1479: $format->{'bold'} = $workbook->add_format(bold=>1);
1480: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1481: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1482: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1483: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1484: $format->{'i'} = $workbook->add_format(italic=>1);
1485: $format->{'date'} = $workbook->add_format(num_format=>
1486: 'mm/dd/yyyy hh:mm:ss');
1487: return $format;
1488: }
1489:
1490: ###############################################################
1491: ###############################################################
1492:
1493: =pod
1494:
1495: =item * &create_workbook()
1496:
1497: Create an Excel worksheet. If it fails, output message on the
1498: request object and return undefs.
1499:
1500: Inputs: Apache request object
1501:
1502: Returns (undef) on failure,
1503: Excel worksheet object, scalar with filename, and formats
1504: from &Apache::loncommon::define_excel_formats on success
1505:
1506: =cut
1507:
1508: ###############################################################
1509: ###############################################################
1510: sub create_workbook {
1511: my ($r) = @_;
1512: #
1513: # Create the excel spreadsheet
1514: my $filename = '/prtspool/'.
1515: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1516: time.'_'.rand(1000000000).'.xls';
1517: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1518: if (! defined($workbook)) {
1519: $r->log_error("Error creating excel spreadsheet $filename: $!");
1520: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1521: "This error has been logged. ".
1522: "Please alert your LON-CAPA administrator").
1523: '</p>');
1524: return (undef);
1525: }
1526: #
1527: $workbook->set_tempdir('/home/httpd/perl/tmp');
1528: #
1529: my $format = &Apache::loncommon::define_excel_formats($workbook);
1530: return ($workbook,$filename,$format);
1531: }
1532:
1533: ###############################################################
1534: ###############################################################
1535:
1536: =pod
1537:
1538: =item * &create_text_file()
1539:
1540: Create a file to write to and eventually make available to the user.
1541: If file creation fails, outputs an error message on the request object and
1542: return undefs.
1543:
1544: Inputs: Apache request object, and file suffix
1545:
1546: Returns (undef) on failure,
1547: Filehandle and filename on success.
1548:
1549: =cut
1550:
1551: ###############################################################
1552: ###############################################################
1553: sub create_text_file {
1554: my ($r,$suffix) = @_;
1555: if (! defined($suffix)) { $suffix = 'txt'; };
1556: my $fh;
1557: my $filename = '/prtspool/'.
1558: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1559: time.'_'.rand(1000000000).'.'.$suffix;
1560: $fh = Apache::File->new('>/home/httpd'.$filename);
1561: if (! defined($fh)) {
1562: $r->log_error("Couldn't open $filename for output $!");
1563: $r->print(&mt('Problems occurred in creating the output file. '
1564: .'This error has been logged. '
1565: .'Please alert your LON-CAPA administrator.'));
1566: }
1567: return ($fh,$filename)
1568: }
1569:
1570:
1571: =pod
1572:
1573: =back
1574:
1575: =cut
1576:
1577: ###############################################################
1578: ## Home server <option> list generating code ##
1579: ###############################################################
1580:
1581: # ------------------------------------------
1582:
1583: sub domain_select {
1584: my ($name,$value,$multiple)=@_;
1585: my %domains=map {
1586: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1587: } &Apache::lonnet::all_domains();
1588: if ($multiple) {
1589: $domains{''}=&mt('Any domain');
1590: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1591: return &multiple_select_form($name,$value,4,\%domains);
1592: } else {
1593: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1594: return &select_form($name,$value,%domains);
1595: }
1596: }
1597:
1598: #-------------------------------------------
1599:
1600: =pod
1601:
1602: =head1 Routines for form select boxes
1603:
1604: =over 4
1605:
1606: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1607:
1608: Returns a string containing a <select> element int multiple mode
1609:
1610:
1611: Args:
1612: $name - name of the <select> element
1613: $value - scalar or array ref of values that should already be selected
1614: $size - number of rows long the select element is
1615: $hash - the elements should be 'option' => 'shown text'
1616: (shown text should already have been &mt())
1617: $order - (optional) array ref of the order to show the elements in
1618:
1619: =cut
1620:
1621: #-------------------------------------------
1622: sub multiple_select_form {
1623: my ($name,$value,$size,$hash,$order)=@_;
1624: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1625: my $output='';
1626: if (! defined($size)) {
1627: $size = 4;
1628: if (scalar(keys(%$hash))<4) {
1629: $size = scalar(keys(%$hash));
1630: }
1631: }
1632: $output.="\n<select name='$name' size='$size' multiple='1'>";
1633: my @order;
1634: if (ref($order) eq 'ARRAY') {
1635: @order = @{$order};
1636: } else {
1637: @order = sort(keys(%$hash));
1638: }
1639: if (exists($$hash{'select_form_order'})) {
1640: @order = @{$$hash{'select_form_order'}};
1641: }
1642:
1643: foreach my $key (@order) {
1644: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1645: $output.='selected="selected" ' if ($selected{$key});
1646: $output.='>'.$hash->{$key}."</option>\n";
1647: }
1648: $output.="</select>\n";
1649: return $output;
1650: }
1651:
1652: #-------------------------------------------
1653:
1654: =pod
1655:
1656: =item * &select_form($defdom,$name,%hash)
1657:
1658: Returns a string containing a <select name='$name' size='1'> form to
1659: allow a user to select options from a hash option_name => displayed text.
1660: See lonrights.pm for an example invocation and use.
1661:
1662: =cut
1663:
1664: #-------------------------------------------
1665: sub select_form {
1666: my ($def,$name,%hash) = @_;
1667: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1668: my @keys;
1669: if (exists($hash{'select_form_order'})) {
1670: @keys=@{$hash{'select_form_order'}};
1671: } else {
1672: @keys=sort(keys(%hash));
1673: }
1674: foreach my $key (@keys) {
1675: $selectform.=
1676: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1677: ($key eq $def ? 'selected="selected" ' : '').
1678: ">".&mt($hash{$key})."</option>\n";
1679: }
1680: $selectform.="</select>";
1681: return $selectform;
1682: }
1683:
1684: # For display filters
1685:
1686: sub display_filter {
1687: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1688: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1689: return '<nobr><label>'.&mt('Records [_1]',
1690: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1691: (&mt('all'),10,20,50,100,1000,10000))).
1692: '</label></nobr> <nobr>'.
1693: &mt('Filter [_1]',
1694: &select_form($env{'form.displayfilter'},
1695: 'displayfilter',
1696: ('currentfolder' => 'Current folder/page',
1697: 'containing' => 'Containing phrase',
1698: 'none' => 'None'))).
1699: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></nobr>';
1700: }
1701:
1702: sub gradeleveldescription {
1703: my $gradelevel=shift;
1704: my %gradelevels=(0 => 'Not specified',
1705: 1 => 'Grade 1',
1706: 2 => 'Grade 2',
1707: 3 => 'Grade 3',
1708: 4 => 'Grade 4',
1709: 5 => 'Grade 5',
1710: 6 => 'Grade 6',
1711: 7 => 'Grade 7',
1712: 8 => 'Grade 8',
1713: 9 => 'Grade 9',
1714: 10 => 'Grade 10',
1715: 11 => 'Grade 11',
1716: 12 => 'Grade 12',
1717: 13 => 'Grade 13',
1718: 14 => '100 Level',
1719: 15 => '200 Level',
1720: 16 => '300 Level',
1721: 17 => '400 Level',
1722: 18 => 'Graduate Level');
1723: return &mt($gradelevels{$gradelevel});
1724: }
1725:
1726: sub select_level_form {
1727: my ($deflevel,$name)=@_;
1728: unless ($deflevel) { $deflevel=0; }
1729: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1730: for (my $i=0; $i<=18; $i++) {
1731: $selectform.="<option value=\"$i\" ".
1732: ($i==$deflevel ? 'selected="selected" ' : '').
1733: ">".&gradeleveldescription($i)."</option>\n";
1734: }
1735: $selectform.="</select>";
1736: return $selectform;
1737: }
1738:
1739: #-------------------------------------------
1740:
1741: =pod
1742:
1743: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc)
1744:
1745: Returns a string containing a <select name='$name' size='1'> form to
1746: allow a user to select the domain to preform an operation in.
1747: See loncreateuser.pm for an example invocation and use.
1748:
1749: If the $includeempty flag is set, it also includes an empty choice ("no domain
1750: selected");
1751:
1752: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1753:
1754: =cut
1755:
1756: #-------------------------------------------
1757: sub select_dom_form {
1758: my ($defdom,$name,$includeempty,$showdomdesc) = @_;
1759: my @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1760: if ($includeempty) { @domains=('',@domains); }
1761: my $selectdomain = "<select name=\"$name\" size=\"1\">\n";
1762: foreach my $dom (@domains) {
1763: $selectdomain.="<option value=\"$dom\" ".
1764: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1765: if ($showdomdesc) {
1766: if ($dom ne '') {
1767: my $domdesc = &Apache::lonnet::domain($dom,'description');
1768: if ($domdesc ne '') {
1769: $selectdomain .= ' ('.$domdesc.')';
1770: }
1771: }
1772: }
1773: $selectdomain .= "</option>\n";
1774: }
1775: $selectdomain.="</select>";
1776: return $selectdomain;
1777: }
1778:
1779: #-------------------------------------------
1780:
1781: =pod
1782:
1783: =item * &home_server_form_item($domain,$name,$defaultflag)
1784:
1785: input: 4 arguments (two required, two optional) -
1786: $domain - domain of new user
1787: $name - name of form element
1788: $default - Value of 'default' causes a default item to be first
1789: option, and selected by default.
1790: $hide - Value of 'hide' causes hiding of the name of the server,
1791: if 1 server found, or default, if 0 found.
1792: output: returns 2 items:
1793: (a) form element which contains either:
1794: (i) <select name="$name">
1795: <option value="$hostid1">$hostid $servers{$hostid}</option>
1796: <option value="$hostid2">$hostid $servers{$hostid}</option>
1797: </select>
1798: form item if there are multiple library servers in $domain, or
1799: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
1800: if there is only one library server in $domain.
1801:
1802: (b) number of library servers found.
1803:
1804: See loncreateuser.pm for example of use.
1805:
1806: =cut
1807:
1808: #-------------------------------------------
1809: sub home_server_form_item {
1810: my ($domain,$name,$default,$hide) = @_;
1811: my %servers = &Apache::lonnet::get_servers($domain,'library');
1812: my $result;
1813: my $numlib = keys(%servers);
1814: if ($numlib > 1) {
1815: $result .= '<select name="'.$name.'" />'."\n";
1816: if ($default) {
1817: $result .= '<option value="default" selected>'.&mt('default').
1818: '</option>'."\n";
1819: }
1820: foreach my $hostid (sort(keys(%servers))) {
1821: $result.= '<option value="'.$hostid.'">'.
1822: $hostid.' '.$servers{$hostid}."</option>\n";
1823: }
1824: $result .= '</select>'."\n";
1825: } elsif ($numlib == 1) {
1826: my $hostid;
1827: foreach my $item (keys(%servers)) {
1828: $hostid = $item;
1829: }
1830: $result .= '<input type="hidden" name="'.$name.'" value="'.
1831: $hostid.'" />';
1832: if (!$hide) {
1833: $result .= $hostid.' '.$servers{$hostid};
1834: }
1835: $result .= "\n";
1836: } elsif ($default) {
1837: $result .= '<input type="hidden" name="'.$name.
1838: '" value="default" />';
1839: if (!$hide) {
1840: $result .= &mt('default');
1841: }
1842: $result .= "\n";
1843: }
1844: return ($result,$numlib);
1845: }
1846:
1847: =pod
1848:
1849: =back
1850:
1851: =cut
1852:
1853: ###############################################################
1854: ## Decoding User Agent ##
1855: ###############################################################
1856:
1857: =pod
1858:
1859: =head1 Decoding the User Agent
1860:
1861: =over 4
1862:
1863: =item * &decode_user_agent()
1864:
1865: Inputs: $r
1866:
1867: Outputs:
1868:
1869: =over 4
1870:
1871: =item * $httpbrowser
1872:
1873: =item * $clientbrowser
1874:
1875: =item * $clientversion
1876:
1877: =item * $clientmathml
1878:
1879: =item * $clientunicode
1880:
1881: =item * $clientos
1882:
1883: =back
1884:
1885: =back
1886:
1887: =cut
1888:
1889: ###############################################################
1890: ###############################################################
1891: sub decode_user_agent {
1892: my ($r)=@_;
1893: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
1894: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
1895: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1896: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1897: my $clientbrowser='unknown';
1898: my $clientversion='0';
1899: my $clientmathml='';
1900: my $clientunicode='0';
1901: for (my $i=0;$i<=$#browsertype;$i++) {
1902: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
1903: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
1904: $clientbrowser=$bname;
1905: $httpbrowser=~/$vreg/i;
1906: $clientversion=$1;
1907: $clientmathml=($clientversion>=$minv);
1908: $clientunicode=($clientversion>=$univ);
1909: }
1910: }
1911: my $clientos='unknown';
1912: if (($httpbrowser=~/linux/i) ||
1913: ($httpbrowser=~/unix/i) ||
1914: ($httpbrowser=~/ux/i) ||
1915: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
1916: if (($httpbrowser=~/vax/i) ||
1917: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
1918: if ($httpbrowser=~/next/i) { $clientos='next'; }
1919: if (($httpbrowser=~/mac/i) ||
1920: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1921: if ($httpbrowser=~/win/i) { $clientos='win'; }
1922: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1923: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1924: $clientunicode,$clientos,);
1925: }
1926:
1927: ###############################################################
1928: ## Authentication changing form generation subroutines ##
1929: ###############################################################
1930: ##
1931: ## All of the authform_xxxxxxx subroutines take their inputs in a
1932: ## hash, and have reasonable default values.
1933: ##
1934: ## formname = the name given in the <form> tag.
1935: #-------------------------------------------
1936:
1937: =pod
1938:
1939: =head1 Authentication Routines
1940:
1941: =over 4
1942:
1943: =item * &authform_xxxxxx()
1944:
1945: The authform_xxxxxx subroutines provide javascript and html forms which
1946: handle some of the conveniences required for authentication forms.
1947: This is not an optimal method, but it works.
1948:
1949: =over 4
1950:
1951: =item * authform_header
1952:
1953: =item * authform_authorwarning
1954:
1955: =item * authform_nochange
1956:
1957: =item * authform_kerberos
1958:
1959: =item * authform_internal
1960:
1961: =item * authform_filesystem
1962:
1963: =back
1964:
1965: See loncreateuser.pm for invocation and use examples.
1966:
1967: =cut
1968:
1969: #-------------------------------------------
1970: sub authform_header{
1971: my %in = (
1972: formname => 'cu',
1973: kerb_def_dom => '',
1974: @_,
1975: );
1976: $in{'formname'} = 'document.' . $in{'formname'};
1977: my $result='';
1978:
1979: #---------------------------------------------- Code for upper case translation
1980: my $Javascript_toUpperCase;
1981: unless ($in{kerb_def_dom}) {
1982: $Javascript_toUpperCase =<<"END";
1983: switch (choice) {
1984: case 'krb': currentform.elements[choicearg].value =
1985: currentform.elements[choicearg].value.toUpperCase();
1986: break;
1987: default:
1988: }
1989: END
1990: } else {
1991: $Javascript_toUpperCase = "";
1992: }
1993:
1994: my $radioval = "'nochange'";
1995: if (defined($in{'curr_authtype'})) {
1996: if ($in{'curr_authtype'} ne '') {
1997: $radioval = "'".$in{'curr_authtype'}."arg'";
1998: }
1999: }
2000: my $argfield = 'null';
2001: if (defined($in{'mode'})) {
2002: if ($in{'mode'} eq 'modifycourse') {
2003: if (defined($in{'curr_autharg'})) {
2004: if ($in{'curr_autharg'} ne '') {
2005: $argfield = "'$in{'curr_autharg'}'";
2006: }
2007: }
2008: }
2009: }
2010:
2011: $result.=<<"END";
2012: var current = new Object();
2013: current.radiovalue = $radioval;
2014: current.argfield = $argfield;
2015:
2016: function changed_radio(choice,currentform) {
2017: var choicearg = choice + 'arg';
2018: // If a radio button in changed, we need to change the argfield
2019: if (current.radiovalue != choice) {
2020: current.radiovalue = choice;
2021: if (current.argfield != null) {
2022: currentform.elements[current.argfield].value = '';
2023: }
2024: if (choice == 'nochange') {
2025: current.argfield = null;
2026: } else {
2027: current.argfield = choicearg;
2028: switch(choice) {
2029: case 'krb':
2030: currentform.elements[current.argfield].value =
2031: "$in{'kerb_def_dom'}";
2032: break;
2033: default:
2034: break;
2035: }
2036: }
2037: }
2038: return;
2039: }
2040:
2041: function changed_text(choice,currentform) {
2042: var choicearg = choice + 'arg';
2043: if (currentform.elements[choicearg].value !='') {
2044: $Javascript_toUpperCase
2045: // clear old field
2046: if ((current.argfield != choicearg) && (current.argfield != null)) {
2047: currentform.elements[current.argfield].value = '';
2048: }
2049: current.argfield = choicearg;
2050: }
2051: set_auth_radio_buttons(choice,currentform);
2052: return;
2053: }
2054:
2055: function set_auth_radio_buttons(newvalue,currentform) {
2056: var i=0;
2057: while (i < currentform.login.length) {
2058: if (currentform.login[i].value == newvalue) { break; }
2059: i++;
2060: }
2061: if (i == currentform.login.length) {
2062: return;
2063: }
2064: current.radiovalue = newvalue;
2065: currentform.login[i].checked = true;
2066: return;
2067: }
2068: END
2069: return $result;
2070: }
2071:
2072: sub authform_authorwarning{
2073: my $result='';
2074: $result='<i>'.
2075: &mt('As a general rule, only authors or co-authors should be '.
2076: 'filesystem authenticated '.
2077: '(which allows access to the server filesystem).')."</i>\n";
2078: return $result;
2079: }
2080:
2081: sub authform_nochange{
2082: my %in = (
2083: formname => 'document.cu',
2084: kerb_def_dom => 'MSU.EDU',
2085: @_,
2086: );
2087: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2088: my $result;
2089: if (keys(%can_assign) == 0) {
2090: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2091: } else {
2092: $result = '<label>'.&mt('[_1] Do not change login data',
2093: '<input type="radio" name="login" value="nochange" '.
2094: 'checked="checked" onclick="'.
2095: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2096: '</label>';
2097: }
2098: return $result;
2099: }
2100:
2101: sub authform_kerberos {
2102: my %in = (
2103: formname => 'document.cu',
2104: kerb_def_dom => 'MSU.EDU',
2105: kerb_def_auth => 'krb4',
2106: @_,
2107: );
2108: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2109: $autharg,$jscall);
2110: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2111: if ($in{'kerb_def_auth'} eq 'krb5') {
2112: $check5 = ' checked="on"';
2113: } else {
2114: $check4 = ' checked="on"';
2115: }
2116: $krbarg = $in{'kerb_def_dom'};
2117: if (defined($in{'curr_authtype'})) {
2118: if ($in{'curr_authtype'} eq 'krb') {
2119: $krbcheck = ' checked="on"';
2120: if (defined($in{'mode'})) {
2121: if ($in{'mode'} eq 'modifyuser') {
2122: $krbcheck = '';
2123: }
2124: }
2125: if (defined($in{'curr_kerb_ver'})) {
2126: if ($in{'curr_krb_ver'} eq '5') {
2127: $check5 = ' checked="on"';
2128: $check4 = '';
2129: } else {
2130: $check4 = ' checked="on"';
2131: $check5 = '';
2132: }
2133: }
2134: if (defined($in{'curr_autharg'})) {
2135: $krbarg = $in{'curr_autharg'};
2136: }
2137: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2138: if (defined($in{'curr_autharg'})) {
2139: $result =
2140: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2141: $in{'curr_autharg'},$krbver);
2142: } else {
2143: $result =
2144: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2145: }
2146: return $result;
2147: }
2148: }
2149: } else {
2150: if ($authnum == 1) {
2151: $authtype = '<input type="hidden" name="login" value="krb">';
2152: }
2153: }
2154: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2155: return;
2156: } elsif ($authtype eq '') {
2157: if (defined($in{'mode'})) {
2158: if ($in{'mode'} eq 'modifycourse') {
2159: if ($authnum == 1) {
2160: $authtype = '<input type="hidden" name="login" value="krb">';
2161: }
2162: }
2163: }
2164: }
2165: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2166: if ($authtype eq '') {
2167: $authtype = '<input type="radio" name="login" value="krb" '.
2168: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2169: $krbcheck.' />';
2170: }
2171: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2172: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2173: $in{'curr_authtype'} eq 'krb5') ||
2174: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2175: $in{'curr_authtype'} eq 'krb4')) {
2176: $result .= &mt
2177: ('[_1] Kerberos authenticated with domain [_2] '.
2178: '[_3] Version 4 [_4] Version 5 [_5]',
2179: '<label>'.$authtype,
2180: '</label><input type="text" size="10" name="krbarg" '.
2181: 'value="'.$krbarg.'" '.
2182: 'onchange="'.$jscall.'" />',
2183: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2184: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2185: '</label>');
2186: } elsif ($can_assign{'krb4'}) {
2187: $result .= &mt
2188: ('[_1] Kerberos authenticated with domain [_2] '.
2189: '[_3] Version 4 [_4]',
2190: '<label>'.$authtype,
2191: '</label><input type="text" size="10" name="krbarg" '.
2192: 'value="'.$krbarg.'" '.
2193: 'onchange="'.$jscall.'" />',
2194: '<label><input type="hidden" name="krbver" value="4" />',
2195: '</label>');
2196: } elsif ($can_assign{'krb5'}) {
2197: $result .= &mt
2198: ('[_1] Kerberos authenticated with domain [_2] '.
2199: '[_3] Version 5 [_4]',
2200: '<label>'.$authtype,
2201: '</label><input type="text" size="10" name="krbarg" '.
2202: 'value="'.$krbarg.'" '.
2203: 'onchange="'.$jscall.'" />',
2204: '<label><input type="hidden" name="krbver" value="5" />',
2205: '</label>');
2206: }
2207: return $result;
2208: }
2209:
2210: sub authform_internal{
2211: my %in = (
2212: formname => 'document.cu',
2213: kerb_def_dom => 'MSU.EDU',
2214: @_,
2215: );
2216: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2217: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2218: if (defined($in{'curr_authtype'})) {
2219: if ($in{'curr_authtype'} eq 'int') {
2220: if ($can_assign{'int'}) {
2221: $intcheck = 'checked="on" ';
2222: if (defined($in{'mode'})) {
2223: if ($in{'mode'} eq 'modifyuser') {
2224: $intcheck = '';
2225: }
2226: }
2227: if (defined($in{'curr_autharg'})) {
2228: $intarg = $in{'curr_autharg'};
2229: }
2230: } else {
2231: $result = &mt('Currently internally authenticated.');
2232: return $result;
2233: }
2234: }
2235: } else {
2236: if ($authnum == 1) {
2237: $authtype = '<input type="hidden" name="login" value="int">';
2238: }
2239: }
2240: if (!$can_assign{'int'}) {
2241: return;
2242: } elsif ($authtype eq '') {
2243: if (defined($in{'mode'})) {
2244: if ($in{'mode'} eq 'modifycourse') {
2245: if ($authnum == 1) {
2246: $authtype = '<input type="hidden" name="login" value="int">';
2247: }
2248: }
2249: }
2250: }
2251: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2252: if ($authtype eq '') {
2253: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2254: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2255: }
2256: $autharg = '<input type="password" size="10" name="intarg" value="'.
2257: $intarg.'" onchange="'.$jscall.'" />';
2258: $result = &mt
2259: ('[_1] Internally authenticated (with initial password [_2])',
2260: '<label>'.$authtype,'</label>'.$autharg);
2261: $result.="<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
2262: return $result;
2263: }
2264:
2265: sub authform_local{
2266: my %in = (
2267: formname => 'document.cu',
2268: kerb_def_dom => 'MSU.EDU',
2269: @_,
2270: );
2271: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2272: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2273: if (defined($in{'curr_authtype'})) {
2274: if ($in{'curr_authtype'} eq 'loc') {
2275: if ($can_assign{'loc'}) {
2276: $loccheck = 'checked="on" ';
2277: if (defined($in{'mode'})) {
2278: if ($in{'mode'} eq 'modifyuser') {
2279: $loccheck = '';
2280: }
2281: }
2282: if (defined($in{'curr_autharg'})) {
2283: $locarg = $in{'curr_autharg'};
2284: }
2285: } else {
2286: $result = &mt('Currently using local (institutional) authentication.');
2287: return $result;
2288: }
2289: }
2290: } else {
2291: if ($authnum == 1) {
2292: $authtype = '<input type="hidden" name="login" value="loc">';
2293: }
2294: }
2295: if (!$can_assign{'loc'}) {
2296: return;
2297: } elsif ($authtype eq '') {
2298: if (defined($in{'mode'})) {
2299: if ($in{'mode'} eq 'modifycourse') {
2300: if ($authnum == 1) {
2301: $authtype = '<input type="hidden" name="login" value="loc">';
2302: }
2303: }
2304: }
2305: }
2306: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2307: if ($authtype eq '') {
2308: $authtype = '<input type="radio" name="login" value="loc" '.
2309: $loccheck.' onchange="'.$jscall.'" onclick="'.
2310: $jscall.'" />';
2311: }
2312: $autharg = '<input type="text" size="10" name="locarg" value="'.
2313: $locarg.'" onchange="'.$jscall.'" />';
2314: $result = &mt('[_1] Local Authentication with argument [_2]',
2315: '<label>'.$authtype,'</label>'.$autharg);
2316: return $result;
2317: }
2318:
2319: sub authform_filesystem{
2320: my %in = (
2321: formname => 'document.cu',
2322: kerb_def_dom => 'MSU.EDU',
2323: @_,
2324: );
2325: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2326: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2327: if (defined($in{'curr_authtype'})) {
2328: if ($in{'curr_authtype'} eq 'fsys') {
2329: if ($can_assign{'fsys'}) {
2330: $fsyscheck = 'checked="on" ';
2331: if (defined($in{'mode'})) {
2332: if ($in{'mode'} eq 'modifyuser') {
2333: $fsyscheck = '';
2334: }
2335: }
2336: } else {
2337: $result = &mt('Currently Filesystem Authenticated.');
2338: return $result;
2339: }
2340: }
2341: } else {
2342: if ($authnum == 1) {
2343: $authtype = '<input type="hidden" name="login" value="fsys">';
2344: }
2345: }
2346: if (!$can_assign{'fsys'}) {
2347: return;
2348: } elsif ($authtype eq '') {
2349: if (defined($in{'mode'})) {
2350: if ($in{'mode'} eq 'modifycourse') {
2351: if ($authnum == 1) {
2352: $authtype = '<input type="hidden" name="login" value="fsys">';
2353: }
2354: }
2355: }
2356: }
2357: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2358: if ($authtype eq '') {
2359: $authtype = '<input type="radio" name="login" value="fsys" '.
2360: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2361: $jscall.'" />';
2362: }
2363: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2364: ' onchange="'.$jscall.'" />';
2365: $result = &mt
2366: ('[_1] Filesystem Authenticated (with initial password [_2])',
2367: '<label><input type="radio" name="login" value="fsys" '.
2368: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2369: '</label><input type="password" size="10" name="fsysarg" value="" '.
2370: 'onchange="'.$jscall.'" />');
2371: return $result;
2372: }
2373:
2374: sub get_assignable_auth {
2375: my ($dom) = @_;
2376: if ($dom eq '') {
2377: $dom = $env{'request.role.domain'};
2378: }
2379: my %can_assign = (
2380: krb4 => 1,
2381: krb5 => 1,
2382: int => 1,
2383: loc => 1,
2384: );
2385: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2386: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2387: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2388: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2389: my $context;
2390: if ($env{'request.role'} =~ /^au/) {
2391: $context = 'author';
2392: } elsif ($env{'request.role'} =~ /^dc/) {
2393: $context = 'domain';
2394: } elsif ($env{'request.course.id'}) {
2395: $context = 'course';
2396: }
2397: if ($context) {
2398: if (ref($authhash->{$context}) eq 'HASH') {
2399: %can_assign = %{$authhash->{$context}};
2400: }
2401: }
2402: }
2403: }
2404: my $authnum = 0;
2405: foreach my $key (keys(%can_assign)) {
2406: if ($can_assign{$key}) {
2407: $authnum ++;
2408: }
2409: }
2410: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2411: $authnum --;
2412: }
2413: return ($authnum,%can_assign);
2414: }
2415:
2416: ###############################################################
2417: ## Get Kerberos Defaults for Domain ##
2418: ###############################################################
2419: ##
2420: ## Returns default kerberos version and an associated argument
2421: ## as listed in file domain.tab. If not listed, provides
2422: ## appropriate default domain and kerberos version.
2423: ##
2424: #-------------------------------------------
2425:
2426: =pod
2427:
2428: =item * &get_kerberos_defaults()
2429:
2430: get_kerberos_defaults($target_domain) returns the default kerberos
2431: version and domain. If not found, it defaults to version 4 and the
2432: domain of the server.
2433:
2434: =over 4
2435:
2436: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2437:
2438: =back
2439:
2440: =back
2441:
2442: =cut
2443:
2444: #-------------------------------------------
2445: sub get_kerberos_defaults {
2446: my $domain=shift;
2447: my ($krbdef,$krbdefdom);
2448: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2449: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2450: $krbdef = $domdefaults{'auth_def'};
2451: $krbdefdom = $domdefaults{'auth_arg_def'};
2452: } else {
2453: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2454: my $krbdefdom=$1;
2455: $krbdefdom=~tr/a-z/A-Z/;
2456: $krbdef = "krb4";
2457: }
2458: return ($krbdef,$krbdefdom);
2459: }
2460:
2461:
2462: ###############################################################
2463: ## Thesaurus Functions ##
2464: ###############################################################
2465:
2466: =pod
2467:
2468: =head1 Thesaurus Functions
2469:
2470: =over 4
2471:
2472: =item * &initialize_keywords()
2473:
2474: Initializes the package variable %Keywords if it is empty. Uses the
2475: package variable $thesaurus_db_file.
2476:
2477: =cut
2478:
2479: ###################################################
2480:
2481: sub initialize_keywords {
2482: return 1 if (scalar keys(%Keywords));
2483: # If we are here, %Keywords is empty, so fill it up
2484: # Make sure the file we need exists...
2485: if (! -e $thesaurus_db_file) {
2486: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2487: " failed because it does not exist");
2488: return 0;
2489: }
2490: # Set up the hash as a database
2491: my %thesaurus_db;
2492: if (! tie(%thesaurus_db,'GDBM_File',
2493: $thesaurus_db_file,&GDBM_READER(),0640)){
2494: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2495: $thesaurus_db_file);
2496: return 0;
2497: }
2498: # Get the average number of appearances of a word.
2499: my $avecount = $thesaurus_db{'average.count'};
2500: # Put keywords (those that appear > average) into %Keywords
2501: while (my ($word,$data)=each (%thesaurus_db)) {
2502: my ($count,undef) = split /:/,$data;
2503: $Keywords{$word}++ if ($count > $avecount);
2504: }
2505: untie %thesaurus_db;
2506: # Remove special values from %Keywords.
2507: foreach my $value ('total.count','average.count') {
2508: delete($Keywords{$value}) if (exists($Keywords{$value}));
2509: }
2510: return 1;
2511: }
2512:
2513: ###################################################
2514:
2515: =pod
2516:
2517: =item * &keyword($word)
2518:
2519: Returns true if $word is a keyword. A keyword is a word that appears more
2520: than the average number of times in the thesaurus database. Calls
2521: &initialize_keywords
2522:
2523: =cut
2524:
2525: ###################################################
2526:
2527: sub keyword {
2528: return if (!&initialize_keywords());
2529: my $word=lc(shift());
2530: $word=~s/\W//g;
2531: return exists($Keywords{$word});
2532: }
2533:
2534: ###############################################################
2535:
2536: =pod
2537:
2538: =item * &get_related_words()
2539:
2540: Look up a word in the thesaurus. Takes a scalar argument and returns
2541: an array of words. If the keyword is not in the thesaurus, an empty array
2542: will be returned. The order of the words returned is determined by the
2543: database which holds them.
2544:
2545: Uses global $thesaurus_db_file.
2546:
2547: =cut
2548:
2549: ###############################################################
2550: sub get_related_words {
2551: my $keyword = shift;
2552: my %thesaurus_db;
2553: if (! -e $thesaurus_db_file) {
2554: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2555: "failed because the file does not exist");
2556: return ();
2557: }
2558: if (! tie(%thesaurus_db,'GDBM_File',
2559: $thesaurus_db_file,&GDBM_READER(),0640)){
2560: return ();
2561: }
2562: my @Words=();
2563: my $count=0;
2564: if (exists($thesaurus_db{$keyword})) {
2565: # The first element is the number of times
2566: # the word appears. We do not need it now.
2567: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2568: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2569: my $threshold=$mostfrequentcount/10;
2570: foreach my $possibleword (@RelatedWords) {
2571: my ($word,$wordcount)=split(/\,/,$possibleword);
2572: if ($wordcount>$threshold) {
2573: push(@Words,$word);
2574: $count++;
2575: if ($count>10) { last; }
2576: }
2577: }
2578: }
2579: untie %thesaurus_db;
2580: return @Words;
2581: }
2582:
2583: =pod
2584:
2585: =back
2586:
2587: =cut
2588:
2589: # -------------------------------------------------------------- Plaintext name
2590: =pod
2591:
2592: =head1 User Name Functions
2593:
2594: =over 4
2595:
2596: =item * &plainname($uname,$udom,$first)
2597:
2598: Takes a users logon name and returns it as a string in
2599: "first middle last generation" form
2600: if $first is set to 'lastname' then it returns it as
2601: 'lastname generation, firstname middlename' if their is a lastname
2602:
2603: =cut
2604:
2605:
2606: ###############################################################
2607: sub plainname {
2608: my ($uname,$udom,$first)=@_;
2609: return if (!defined($uname) || !defined($udom));
2610: my %names=&getnames($uname,$udom);
2611: my $name=&Apache::lonnet::format_name($names{'firstname'},
2612: $names{'middlename'},
2613: $names{'lastname'},
2614: $names{'generation'},$first);
2615: $name=~s/^\s+//;
2616: $name=~s/\s+$//;
2617: $name=~s/\s+/ /g;
2618: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2619: return $name;
2620: }
2621:
2622: # -------------------------------------------------------------------- Nickname
2623: =pod
2624:
2625: =item * &nickname($uname,$udom)
2626:
2627: Gets a users name and returns it as a string as
2628:
2629: ""nickname""
2630:
2631: if the user has a nickname or
2632:
2633: "first middle last generation"
2634:
2635: if the user does not
2636:
2637: =cut
2638:
2639: sub nickname {
2640: my ($uname,$udom)=@_;
2641: return if (!defined($uname) || !defined($udom));
2642: my %names=&getnames($uname,$udom);
2643: my $name=$names{'nickname'};
2644: if ($name) {
2645: $name='"'.$name.'"';
2646: } else {
2647: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2648: $names{'lastname'}.' '.$names{'generation'};
2649: $name=~s/\s+$//;
2650: $name=~s/\s+/ /g;
2651: }
2652: return $name;
2653: }
2654:
2655: sub getnames {
2656: my ($uname,$udom)=@_;
2657: return if (!defined($uname) || !defined($udom));
2658: if ($udom eq 'public' && $uname eq 'public') {
2659: return ('lastname' => &mt('Public'));
2660: }
2661: my $id=$uname.':'.$udom;
2662: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2663: if ($cached) {
2664: return %{$names};
2665: } else {
2666: my %loadnames=&Apache::lonnet::get('environment',
2667: ['firstname','middlename','lastname','generation','nickname'],
2668: $udom,$uname);
2669: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2670: return %loadnames;
2671: }
2672: }
2673:
2674: # -------------------------------------------------------------------- getemails
2675:
2676: =pod
2677:
2678: =item * &getemails($uname,$udom)
2679:
2680: Gets a user's email information and returns it as a hash with keys:
2681: notification, critnotification, permanentemail
2682:
2683: For notification and critnotification, values are comma-separated lists
2684: of e-mail addresses; for permanentemail, value is a single e-mail address.
2685:
2686:
2687: =cut
2688:
2689:
2690: sub getemails {
2691: my ($uname,$udom)=@_;
2692: if ($udom eq 'public' && $uname eq 'public') {
2693: return;
2694: }
2695: if (!$udom) { $udom=$env{'user.domain'}; }
2696: if (!$uname) { $uname=$env{'user.name'}; }
2697: my $id=$uname.':'.$udom;
2698: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2699: if ($cached) {
2700: return %{$names};
2701: } else {
2702: my %loadnames=&Apache::lonnet::get('environment',
2703: ['notification','critnotification',
2704: 'permanentemail'],
2705: $udom,$uname);
2706: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2707: return %loadnames;
2708: }
2709: }
2710:
2711: sub flush_email_cache {
2712: my ($uname,$udom)=@_;
2713: if (!$udom) { $udom =$env{'user.domain'}; }
2714: if (!$uname) { $uname=$env{'user.name'}; }
2715: return if ($udom eq 'public' && $uname eq 'public');
2716: my $id=$uname.':'.$udom;
2717: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2718: }
2719:
2720: # ------------------------------------------------------------------ Screenname
2721:
2722: =pod
2723:
2724: =item * &screenname($uname,$udom)
2725:
2726: Gets a users screenname and returns it as a string
2727:
2728: =cut
2729:
2730: sub screenname {
2731: my ($uname,$udom)=@_;
2732: if ($uname eq $env{'user.name'} &&
2733: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2734: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2735: return $names{'screenname'};
2736: }
2737:
2738:
2739: # ------------------------------------------------------------- Message Wrapper
2740:
2741: sub messagewrapper {
2742: my ($link,$username,$domain,$subject,$text)=@_;
2743: return
2744: '<a href="/adm/email?compose=individual&'.
2745: 'recname='.$username.'&recdom='.$domain.
2746: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
2747: 'title="'.&mt('Send message').'">'.$link.'</a>';
2748: }
2749: # --------------------------------------------------------------- Notes Wrapper
2750:
2751: sub noteswrapper {
2752: my ($link,$un,$do)=@_;
2753: return
2754: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
2755: }
2756: # ------------------------------------------------------------- Aboutme Wrapper
2757:
2758: sub aboutmewrapper {
2759: my ($link,$username,$domain,$target)=@_;
2760: if (!defined($username) && !defined($domain)) {
2761: return;
2762: }
2763: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
2764: ($target?' target="$target"':'').' title="'.&mt("View this user's personal page").'">'.$link.'</a>';
2765: }
2766:
2767: # ------------------------------------------------------------ Syllabus Wrapper
2768:
2769:
2770: sub syllabuswrapper {
2771: my ($linktext,$coursedir,$domain)=@_;
2772: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2773: }
2774:
2775: sub track_student_link {
2776: my ($linktext,$sname,$sdom,$target,$start) = @_;
2777: my $link ="/adm/trackstudent?";
2778: my $title = 'View recent activity';
2779: if (defined($sname) && $sname !~ /^\s*$/ &&
2780: defined($sdom) && $sdom !~ /^\s*$/) {
2781: $link .= "selected_student=$sname:$sdom";
2782: $title .= ' of this student';
2783: }
2784: if (defined($target) && $target !~ /^\s*$/) {
2785: $target = qq{target="$target"};
2786: } else {
2787: $target = '';
2788: }
2789: if ($start) { $link.='&start='.$start; }
2790: $title = &mt($title);
2791: $linktext = &mt($linktext);
2792: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2793: &help_open_topic('View_recent_activity');
2794: }
2795:
2796: # ===================================================== Display a student photo
2797:
2798:
2799: sub student_image_tag {
2800: my ($domain,$user)=@_;
2801: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2802: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2803: return '<img src="'.$imgsrc.'" align="right" />';
2804: } else {
2805: return '';
2806: }
2807: }
2808:
2809: =pod
2810:
2811: =back
2812:
2813: =head1 Access .tab File Data
2814:
2815: =over 4
2816:
2817: =item * &languageids()
2818:
2819: returns list of all language ids
2820:
2821: =cut
2822:
2823: sub languageids {
2824: return sort(keys(%language));
2825: }
2826:
2827: =pod
2828:
2829: =item * &languagedescription()
2830:
2831: returns description of a specified language id
2832:
2833: =cut
2834:
2835: sub languagedescription {
2836: my $code=shift;
2837: return ($supported_language{$code}?'* ':'').
2838: $language{$code}.
2839: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2840: }
2841:
2842: sub plainlanguagedescription {
2843: my $code=shift;
2844: return $language{$code};
2845: }
2846:
2847: sub supportedlanguagecode {
2848: my $code=shift;
2849: return $supported_language{$code};
2850: }
2851:
2852: =pod
2853:
2854: =item * ©rightids()
2855:
2856: returns list of all copyrights
2857:
2858: =cut
2859:
2860: sub copyrightids {
2861: return sort(keys(%cprtag));
2862: }
2863:
2864: =pod
2865:
2866: =item * ©rightdescription()
2867:
2868: returns description of a specified copyright id
2869:
2870: =cut
2871:
2872: sub copyrightdescription {
2873: return &mt($cprtag{shift(@_)});
2874: }
2875:
2876: =pod
2877:
2878: =item * &source_copyrightids()
2879:
2880: returns list of all source copyrights
2881:
2882: =cut
2883:
2884: sub source_copyrightids {
2885: return sort(keys(%scprtag));
2886: }
2887:
2888: =pod
2889:
2890: =item * &source_copyrightdescription()
2891:
2892: returns description of a specified source copyright id
2893:
2894: =cut
2895:
2896: sub source_copyrightdescription {
2897: return &mt($scprtag{shift(@_)});
2898: }
2899:
2900: =pod
2901:
2902: =item * &filecategories()
2903:
2904: returns list of all file categories
2905:
2906: =cut
2907:
2908: sub filecategories {
2909: return sort(keys(%category_extensions));
2910: }
2911:
2912: =pod
2913:
2914: =item * &filecategorytypes()
2915:
2916: returns list of file types belonging to a given file
2917: category
2918:
2919: =cut
2920:
2921: sub filecategorytypes {
2922: my ($cat) = @_;
2923: return @{$category_extensions{lc($cat)}};
2924: }
2925:
2926: =pod
2927:
2928: =item * &fileembstyle()
2929:
2930: returns embedding style for a specified file type
2931:
2932: =cut
2933:
2934: sub fileembstyle {
2935: return $fe{lc(shift(@_))};
2936: }
2937:
2938: sub filemimetype {
2939: return $fm{lc(shift(@_))};
2940: }
2941:
2942:
2943: sub filecategoryselect {
2944: my ($name,$value)=@_;
2945: return &select_form($value,$name,
2946: '' => &mt('Any category'),
2947: map { $_,$_ } sort(keys(%category_extensions)));
2948: }
2949:
2950: =pod
2951:
2952: =item * &filedescription()
2953:
2954: returns description for a specified file type
2955:
2956: =cut
2957:
2958: sub filedescription {
2959: my $file_description = $fd{lc(shift())};
2960: $file_description =~ s:([\[\]]):~$1:g;
2961: return &mt($file_description);
2962: }
2963:
2964: =pod
2965:
2966: =item * &filedescriptionex()
2967:
2968: returns description for a specified file type with
2969: extra formatting
2970:
2971: =cut
2972:
2973: sub filedescriptionex {
2974: my $ex=shift;
2975: my $file_description = $fd{lc($ex)};
2976: $file_description =~ s:([\[\]]):~$1:g;
2977: return '.'.$ex.' '.&mt($file_description);
2978: }
2979:
2980: # End of .tab access
2981: =pod
2982:
2983: =back
2984:
2985: =cut
2986:
2987: # ------------------------------------------------------------------ File Types
2988: sub fileextensions {
2989: return sort(keys(%fe));
2990: }
2991:
2992: # ----------------------------------------------------------- Display Languages
2993: # returns a hash with all desired display languages
2994: #
2995:
2996: sub display_languages {
2997: my %languages=();
2998: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
2999: $languages{$lang}=1;
3000: }
3001: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3002: if ($env{'form.displaylanguage'}) {
3003: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3004: $languages{$lang}=1;
3005: }
3006: }
3007: return %languages;
3008: }
3009:
3010: sub languages {
3011: my ($possible_langs) = @_;
3012: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3013: if (!ref($possible_langs)) {
3014: if( wantarray ) {
3015: return @preferred_langs;
3016: } else {
3017: return $preferred_langs[0];
3018: }
3019: }
3020: my %possibilities = map { $_ => 1 } (@$possible_langs);
3021: my @preferred_possibilities;
3022: foreach my $preferred_lang (@preferred_langs) {
3023: if (exists($possibilities{$preferred_lang})) {
3024: push(@preferred_possibilities, $preferred_lang);
3025: }
3026: }
3027: if( wantarray ) {
3028: return @preferred_possibilities;
3029: }
3030: return $preferred_possibilities[0];
3031: }
3032:
3033: ###############################################################
3034: ## Student Answer Attempts ##
3035: ###############################################################
3036:
3037: =pod
3038:
3039: =head1 Alternate Problem Views
3040:
3041: =over 4
3042:
3043: =item * &get_previous_attempt($symb, $username, $domain, $course,
3044: $getattempt, $regexp, $gradesub)
3045:
3046: Return string with previous attempt on problem. Arguments:
3047:
3048: =over 4
3049:
3050: =item * $symb: Problem, including path
3051:
3052: =item * $username: username of the desired student
3053:
3054: =item * $domain: domain of the desired student
3055:
3056: =item * $course: Course ID
3057:
3058: =item * $getattempt: Leave blank for all attempts, otherwise put
3059: something
3060:
3061: =item * $regexp: if string matches this regexp, the string will be
3062: sent to $gradesub
3063:
3064: =item * $gradesub: routine that processes the string if it matches $regexp
3065:
3066: =back
3067:
3068: The output string is a table containing all desired attempts, if any.
3069:
3070: =cut
3071:
3072: sub get_previous_attempt {
3073: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3074: my $prevattempts='';
3075: no strict 'refs';
3076: if ($symb) {
3077: my (%returnhash)=
3078: &Apache::lonnet::restore($symb,$course,$domain,$username);
3079: if ($returnhash{'version'}) {
3080: my %lasthash=();
3081: my $version;
3082: for ($version=1;$version<=$returnhash{'version'};$version++) {
3083: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3084: $lasthash{$key}=$returnhash{$version.':'.$key};
3085: }
3086: }
3087: $prevattempts=&start_data_table().&start_data_table_header_row();
3088: $prevattempts.='<th>'.&mt('History').'</th>';
3089: foreach my $key (sort(keys(%lasthash))) {
3090: my ($ign,@parts) = split(/\./,$key);
3091: if ($#parts > 0) {
3092: my $data=$parts[-1];
3093: pop(@parts);
3094: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3095: } else {
3096: if ($#parts == 0) {
3097: $prevattempts.='<th>'.$parts[0].'</th>';
3098: } else {
3099: $prevattempts.='<th>'.$ign.'</th>';
3100: }
3101: }
3102: }
3103: $prevattempts.=&end_data_table_header_row();
3104: if ($getattempt eq '') {
3105: for ($version=1;$version<=$returnhash{'version'};$version++) {
3106: $prevattempts.=&start_data_table_row().
3107: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3108: foreach my $key (sort(keys(%lasthash))) {
3109: my $value = &format_previous_attempt_value($key,
3110: $returnhash{$version.':'.$key});
3111: $prevattempts.='<td>'.$value.' </td>';
3112: }
3113: $prevattempts.=&end_data_table_row();
3114: }
3115: }
3116: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3117: foreach my $key (sort(keys(%lasthash))) {
3118: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3119: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3120: $prevattempts.='<td>'.$value.' </td>';
3121: }
3122: $prevattempts.= &end_data_table_row().&end_data_table();
3123: } else {
3124: $prevattempts=
3125: &start_data_table().&start_data_table_row().
3126: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3127: &end_data_table_row().&end_data_table();
3128: }
3129: } else {
3130: $prevattempts=
3131: &start_data_table().&start_data_table_row().
3132: '<td>'.&mt('No data.').'</td>'.
3133: &end_data_table_row().&end_data_table();
3134: }
3135: }
3136:
3137: sub format_previous_attempt_value {
3138: my ($key,$value) = @_;
3139: if ($key =~ /timestamp/) {
3140: $value = &Apache::lonlocal::locallocaltime($value);
3141: } elsif (ref($value) eq 'ARRAY') {
3142: $value = '('.join(', ', @{ $value }).')';
3143: } else {
3144: $value = &unescape($value);
3145: }
3146: return $value;
3147: }
3148:
3149:
3150: sub relative_to_absolute {
3151: my ($url,$output)=@_;
3152: my $parser=HTML::TokeParser->new(\$output);
3153: my $token;
3154: my $thisdir=$url;
3155: my @rlinks=();
3156: while ($token=$parser->get_token) {
3157: if ($token->[0] eq 'S') {
3158: if ($token->[1] eq 'a') {
3159: if ($token->[2]->{'href'}) {
3160: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3161: }
3162: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3163: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3164: } elsif ($token->[1] eq 'base') {
3165: $thisdir=$token->[2]->{'href'};
3166: }
3167: }
3168: }
3169: $thisdir=~s-/[^/]*$--;
3170: foreach my $link (@rlinks) {
3171: unless (($link=~/^http:\/\//i) ||
3172: ($link=~/^\//) ||
3173: ($link=~/^javascript:/i) ||
3174: ($link=~/^mailto:/i) ||
3175: ($link=~/^\#/)) {
3176: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3177: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3178: }
3179: }
3180: # -------------------------------------------------- Deal with Applet codebases
3181: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3182: return $output;
3183: }
3184:
3185: =pod
3186:
3187: =item * &get_student_view()
3188:
3189: show a snapshot of what student was looking at
3190:
3191: =cut
3192:
3193: sub get_student_view {
3194: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3195: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3196: my (%form);
3197: my @elements=('symb','courseid','domain','username');
3198: foreach my $element (@elements) {
3199: $form{'grade_'.$element}=eval '$'.$element #'
3200: }
3201: if (defined($moreenv)) {
3202: %form=(%form,%{$moreenv});
3203: }
3204: if (defined($target)) { $form{'grade_target'} = $target; }
3205: $feedurl=&Apache::lonnet::clutter($feedurl);
3206: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3207: $userview=~s/\<body[^\>]*\>//gi;
3208: $userview=~s/\<\/body\>//gi;
3209: $userview=~s/\<html\>//gi;
3210: $userview=~s/\<\/html\>//gi;
3211: $userview=~s/\<head\>//gi;
3212: $userview=~s/\<\/head\>//gi;
3213: $userview=~s/action\s*\=/would_be_action\=/gi;
3214: $userview=&relative_to_absolute($feedurl,$userview);
3215: if (wantarray) {
3216: return ($userview,$response);
3217: } else {
3218: return $userview;
3219: }
3220: }
3221:
3222: sub get_student_view_with_retries {
3223: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3224:
3225: my $ok = 0; # True if we got a good response.
3226: my $content;
3227: my $response;
3228:
3229: # Try to get the student_view done. within the retries count:
3230:
3231: do {
3232: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3233: $ok = $response->is_success;
3234: if (!$ok) {
3235: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3236: }
3237: $retries--;
3238: } while (!$ok && ($retries > 0));
3239:
3240: if (!$ok) {
3241: $content = ''; # On error return an empty content.
3242: }
3243: if (wantarray) {
3244: return ($content, $response);
3245: } else {
3246: return $content;
3247: }
3248: }
3249:
3250: =pod
3251:
3252: =item * &get_student_answers()
3253:
3254: show a snapshot of how student was answering problem
3255:
3256: =cut
3257:
3258: sub get_student_answers {
3259: my ($symb,$username,$domain,$courseid,%form) = @_;
3260: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3261: my (%moreenv);
3262: my @elements=('symb','courseid','domain','username');
3263: foreach my $element (@elements) {
3264: $moreenv{'grade_'.$element}=eval '$'.$element #'
3265: }
3266: $moreenv{'grade_target'}='answer';
3267: %moreenv=(%form,%moreenv);
3268: $feedurl = &Apache::lonnet::clutter($feedurl);
3269: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3270: return $userview;
3271: }
3272:
3273: =pod
3274:
3275: =item * &submlink()
3276:
3277: Inputs: $text $uname $udom $symb $target
3278:
3279: Returns: A link to grades.pm such as to see the SUBM view of a student
3280:
3281: =cut
3282:
3283: ###############################################
3284: sub submlink {
3285: my ($text,$uname,$udom,$symb,$target)=@_;
3286: if (!($uname && $udom)) {
3287: (my $cursymb, my $courseid,$udom,$uname)=
3288: &Apache::lonnet::whichuser($symb);
3289: if (!$symb) { $symb=$cursymb; }
3290: }
3291: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3292: $symb=&escape($symb);
3293: if ($target) { $target="target=\"$target\""; }
3294: return '<a href="/adm/grades?&command=submission&'.
3295: 'symb='.$symb.'&student='.$uname.
3296: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3297: }
3298: ##############################################
3299:
3300: =pod
3301:
3302: =item * &pgrdlink()
3303:
3304: Inputs: $text $uname $udom $symb $target
3305:
3306: Returns: A link to grades.pm such as to see the PGRD view of a student
3307:
3308: =cut
3309:
3310: ###############################################
3311: sub pgrdlink {
3312: my $link=&submlink(@_);
3313: $link=~s/(&command=submission)/$1&showgrading=yes/;
3314: return $link;
3315: }
3316: ##############################################
3317:
3318: =pod
3319:
3320: =item * &pprmlink()
3321:
3322: Inputs: $text $uname $udom $symb $target
3323:
3324: Returns: A link to parmset.pm such as to see the PPRM view of a
3325: student and a specific resource
3326:
3327: =cut
3328:
3329: ###############################################
3330: sub pprmlink {
3331: my ($text,$uname,$udom,$symb,$target)=@_;
3332: if (!($uname && $udom)) {
3333: (my $cursymb, my $courseid,$udom,$uname)=
3334: &Apache::lonnet::whichuser($symb);
3335: if (!$symb) { $symb=$cursymb; }
3336: }
3337: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3338: $symb=&escape($symb);
3339: if ($target) { $target="target=\"$target\""; }
3340: return '<a href="/adm/parmset?command=set&'.
3341: 'symb='.$symb.'&uname='.$uname.
3342: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3343: }
3344: ##############################################
3345:
3346: =pod
3347:
3348: =back
3349:
3350: =cut
3351:
3352: ###############################################
3353:
3354:
3355: sub timehash {
3356: my ($thistime) = @_;
3357: my $timezone = &Apache::lonlocal::gettimezone();
3358: my $dt = DateTime->from_epoch(epoch => $thistime)
3359: ->set_time_zone($timezone);
3360: my $wday = $dt->day_of_week();
3361: if ($wday == 7) { $wday = 0; }
3362: return ( 'second' => $dt->second(),
3363: 'minute' => $dt->minute(),
3364: 'hour' => $dt->hour(),
3365: 'day' => $dt->day_of_month(),
3366: 'month' => $dt->month(),
3367: 'year' => $dt->year(),
3368: 'weekday' => $wday,
3369: 'dayyear' => $dt->day_of_year(),
3370: 'dlsav' => $dt->is_dst() );
3371: }
3372:
3373: sub utc_string {
3374: my ($date)=@_;
3375: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3376: }
3377:
3378: sub maketime {
3379: my %th=@_;
3380: my ($epoch_time,$timezone,$dt);
3381: $timezone = &Apache::lonlocal::gettimezone();
3382: eval {
3383: $dt = DateTime->new( year => $th{'year'},
3384: month => $th{'month'},
3385: day => $th{'day'},
3386: hour => $th{'hour'},
3387: minute => $th{'minute'},
3388: second => $th{'second'},
3389: time_zone => $timezone,
3390: );
3391: };
3392: if (!$@) {
3393: $epoch_time = $dt->epoch;
3394: if ($epoch_time) {
3395: return $epoch_time;
3396: }
3397: }
3398: return POSIX::mktime(
3399: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3400: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3401: }
3402:
3403: #########################################
3404:
3405: sub findallcourses {
3406: my ($roles,$uname,$udom) = @_;
3407: my %roles;
3408: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3409: my %courses;
3410: my $now=time;
3411: if (!defined($uname)) {
3412: $uname = $env{'user.name'};
3413: }
3414: if (!defined($udom)) {
3415: $udom = $env{'user.domain'};
3416: }
3417: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3418: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3419: if (!%roles) {
3420: %roles = (
3421: cc => 1,
3422: in => 1,
3423: ep => 1,
3424: ta => 1,
3425: cr => 1,
3426: st => 1,
3427: );
3428: }
3429: foreach my $entry (keys(%roleshash)) {
3430: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3431: if ($trole =~ /^cr/) {
3432: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3433: } else {
3434: next if (!exists($roles{$trole}));
3435: }
3436: if ($tend) {
3437: next if ($tend < $now);
3438: }
3439: if ($tstart) {
3440: next if ($tstart > $now);
3441: }
3442: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3443: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3444: if ($secpart eq '') {
3445: ($cnum,$role) = split(/_/,$cnumpart);
3446: $sec = 'none';
3447: $realsec = '';
3448: } else {
3449: $cnum = $cnumpart;
3450: ($sec,$role) = split(/_/,$secpart);
3451: $realsec = $sec;
3452: }
3453: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3454: }
3455: } else {
3456: foreach my $key (keys(%env)) {
3457: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3458: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3459: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3460: next if ($role eq 'ca' || $role eq 'aa');
3461: next if (%roles && !exists($roles{$role}));
3462: my ($starttime,$endtime)=split(/\./,$env{$key});
3463: my $active=1;
3464: if ($starttime) {
3465: if ($now<$starttime) { $active=0; }
3466: }
3467: if ($endtime) {
3468: if ($now>$endtime) { $active=0; }
3469: }
3470: if ($active) {
3471: if ($sec eq '') {
3472: $sec = 'none';
3473: }
3474: $courses{$cdom.'_'.$cnum}{$sec} =
3475: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3476: }
3477: }
3478: }
3479: }
3480: return %courses;
3481: }
3482:
3483: ###############################################
3484:
3485: sub blockcheck {
3486: my ($setters,$activity,$uname,$udom) = @_;
3487:
3488: if (!defined($udom)) {
3489: $udom = $env{'user.domain'};
3490: }
3491: if (!defined($uname)) {
3492: $uname = $env{'user.name'};
3493: }
3494:
3495: # If uname and udom are for a course, check for blocks in the course.
3496:
3497: if (&Apache::lonnet::is_course($udom,$uname)) {
3498: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3499: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3500: return ($startblock,$endblock);
3501: }
3502:
3503: my $startblock = 0;
3504: my $endblock = 0;
3505: my %live_courses = &findallcourses(undef,$uname,$udom);
3506:
3507: # If uname is for a user, and activity is course-specific, i.e.,
3508: # boards, chat or groups, check for blocking in current course only.
3509:
3510: if (($activity eq 'boards' || $activity eq 'chat' ||
3511: $activity eq 'groups') && ($env{'request.course.id'})) {
3512: foreach my $key (keys(%live_courses)) {
3513: if ($key ne $env{'request.course.id'}) {
3514: delete($live_courses{$key});
3515: }
3516: }
3517: }
3518:
3519: my $otheruser = 0;
3520: my %own_courses;
3521: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3522: # Resource belongs to user other than current user.
3523: $otheruser = 1;
3524: # Gather courses for current user
3525: %own_courses =
3526: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3527: }
3528:
3529: # Gather active course roles - course coordinator, instructor,
3530: # exam proctor, ta, student, or custom role.
3531:
3532: foreach my $course (keys(%live_courses)) {
3533: my ($cdom,$cnum);
3534: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3535: $cdom = $env{'course.'.$course.'.domain'};
3536: $cnum = $env{'course.'.$course.'.num'};
3537: } else {
3538: ($cdom,$cnum) = split(/_/,$course);
3539: }
3540: my $no_ownblock = 0;
3541: my $no_userblock = 0;
3542: if ($otheruser && $activity ne 'com') {
3543: # Check if current user has 'evb' priv for this
3544: if (defined($own_courses{$course})) {
3545: foreach my $sec (keys(%{$own_courses{$course}})) {
3546: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3547: if ($sec ne 'none') {
3548: $checkrole .= '/'.$sec;
3549: }
3550: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3551: $no_ownblock = 1;
3552: last;
3553: }
3554: }
3555: }
3556: # if they have 'evb' priv and are currently not playing student
3557: next if (($no_ownblock) &&
3558: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3559: }
3560: foreach my $sec (keys(%{$live_courses{$course}})) {
3561: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3562: if ($sec ne 'none') {
3563: $checkrole .= '/'.$sec;
3564: }
3565: if ($otheruser) {
3566: # Resource belongs to user other than current user.
3567: # Assemble privs for that user, and check for 'evb' priv.
3568: my ($trole,$tdom,$tnum,$tsec);
3569: my $entry = $live_courses{$course}{$sec};
3570: if ($entry =~ /^cr/) {
3571: ($trole,$tdom,$tnum,$tsec) =
3572: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3573: } else {
3574: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3575: }
3576: my ($spec,$area,$trest,%allroles,%userroles);
3577: $area = '/'.$tdom.'/'.$tnum;
3578: $trest = $tnum;
3579: if ($tsec ne '') {
3580: $area .= '/'.$tsec;
3581: $trest .= '/'.$tsec;
3582: }
3583: $spec = $trole.'.'.$area;
3584: if ($trole =~ /^cr/) {
3585: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3586: $tdom,$spec,$trest,$area);
3587: } else {
3588: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3589: $tdom,$spec,$trest,$area);
3590: }
3591: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3592: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3593: if ($1) {
3594: $no_userblock = 1;
3595: last;
3596: }
3597: }
3598: } else {
3599: # Resource belongs to current user
3600: # Check for 'evb' priv via lonnet::allowed().
3601: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3602: $no_ownblock = 1;
3603: last;
3604: }
3605: }
3606: }
3607: # if they have the evb priv and are currently not playing student
3608: next if (($no_ownblock) &&
3609: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3610: next if ($no_userblock);
3611:
3612: # Retrieve blocking times and identity of blocker for course
3613: # of specified user, unless user has 'evb' privilege.
3614:
3615: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3616: if (($start != 0) &&
3617: (($startblock == 0) || ($startblock > $start))) {
3618: $startblock = $start;
3619: }
3620: if (($end != 0) &&
3621: (($endblock == 0) || ($endblock < $end))) {
3622: $endblock = $end;
3623: }
3624: }
3625: return ($startblock,$endblock);
3626: }
3627:
3628: sub get_blocks {
3629: my ($setters,$activity,$cdom,$cnum) = @_;
3630: my $startblock = 0;
3631: my $endblock = 0;
3632: my $course = $cdom.'_'.$cnum;
3633: $setters->{$course} = {};
3634: $setters->{$course}{'staff'} = [];
3635: $setters->{$course}{'times'} = [];
3636: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3637: foreach my $record (keys(%records)) {
3638: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3639: if ($start <= time && $end >= time) {
3640: my ($staff_name,$staff_dom,$title,$blocks) =
3641: &parse_block_record($records{$record});
3642: if ($blocks->{$activity} eq 'on') {
3643: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3644: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3645: if ( ($startblock == 0) || ($startblock > $start) ) {
3646: $startblock = $start;
3647: }
3648: if ( ($endblock == 0) || ($endblock < $end) ) {
3649: $endblock = $end;
3650: }
3651: }
3652: }
3653: }
3654: return ($startblock,$endblock);
3655: }
3656:
3657: sub parse_block_record {
3658: my ($record) = @_;
3659: my ($setuname,$setudom,$title,$blocks);
3660: if (ref($record) eq 'HASH') {
3661: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3662: $title = &unescape($record->{'event'});
3663: $blocks = $record->{'blocks'};
3664: } else {
3665: my @data = split(/:/,$record,3);
3666: if (scalar(@data) eq 2) {
3667: $title = $data[1];
3668: ($setuname,$setudom) = split(/@/,$data[0]);
3669: } else {
3670: ($setuname,$setudom,$title) = @data;
3671: }
3672: $blocks = { 'com' => 'on' };
3673: }
3674: return ($setuname,$setudom,$title,$blocks);
3675: }
3676:
3677: sub build_block_table {
3678: my ($startblock,$endblock,$setters) = @_;
3679: my %lt = &Apache::lonlocal::texthash(
3680: 'cacb' => 'Currently active communication blocks',
3681: 'cour' => 'Course',
3682: 'dura' => 'Duration',
3683: 'blse' => 'Block set by'
3684: );
3685: my $output;
3686: $output = '<br />'.$lt{'cacb'}.':<br />';
3687: $output .= &start_data_table();
3688: $output .= '
3689: <tr>
3690: <th>'.$lt{'cour'}.'</th>
3691: <th>'.$lt{'dura'}.'</th>
3692: <th>'.$lt{'blse'}.'</th>
3693: </tr>
3694: ';
3695: foreach my $course (keys(%{$setters})) {
3696: my %courseinfo=&Apache::lonnet::coursedescription($course);
3697: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3698: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3699: my $fullname = &plainname($uname,$udom);
3700: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3701: && $env{'user.name'} ne 'public'
3702: && $env{'user.domain'} ne 'public') {
3703: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3704: }
3705: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3706: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3707: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3708: $output .= &Apache::loncommon::start_data_table_row().
3709: '<td>'.$courseinfo{'description'}.'</td>'.
3710: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3711: '<td>'.$fullname.'</td>'.
3712: &Apache::loncommon::end_data_table_row();
3713: }
3714: }
3715: $output .= &end_data_table();
3716: }
3717:
3718: sub blocking_status {
3719: my ($activity,$uname,$udom) = @_;
3720: my %setters;
3721: my ($blocked,$output,$ownitem,$is_course);
3722: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3723: if ($startblock && $endblock) {
3724: $blocked = 1;
3725: if (wantarray) {
3726: my $category;
3727: if ($activity eq 'boards') {
3728: $category = 'Discussion posts in this course';
3729: } elsif ($activity eq 'blogs') {
3730: $category = 'Blogs';
3731: } elsif ($activity eq 'port') {
3732: if (defined($uname) && defined($udom)) {
3733: if ($uname eq $env{'user.name'} &&
3734: $udom eq $env{'user.domain'}) {
3735: $ownitem = 1;
3736: }
3737: }
3738: $is_course = &Apache::lonnet::is_course($udom,$uname);
3739: if ($ownitem) {
3740: $category = 'Your portfolio files';
3741: } elsif ($is_course) {
3742: my $coursedesc;
3743: foreach my $course (keys(%setters)) {
3744: my %courseinfo =
3745: &Apache::lonnet::coursedescription($course);
3746: $coursedesc = $courseinfo{'description'};
3747: }
3748: $category = "Group files in the course '$coursedesc'";
3749: } else {
3750: $category = 'Portfolio files belonging to ';
3751: if ($env{'user.name'} eq 'public' &&
3752: $env{'user.domain'} eq 'public') {
3753: $category .= &plainname($uname,$udom);
3754: } else {
3755: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3756: }
3757: }
3758: } elsif ($activity eq 'groups') {
3759: $category = 'Groups in this course';
3760: }
3761: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
3762: my $showend = &Apache::lonlocal::locallocaltime($endblock);
3763: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
3764: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
3765: $output .= &build_block_table($startblock,$endblock,\%setters);
3766: }
3767: }
3768: }
3769: if (wantarray) {
3770: return ($blocked,$output);
3771: } else {
3772: return $blocked;
3773: }
3774: }
3775:
3776: ###############################################
3777:
3778: sub check_ip_acc {
3779: my ($acc)=@_;
3780: &Apache::lonxml::debug("acc is $acc");
3781: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
3782: return 1;
3783: }
3784: my $allowed=0;
3785: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
3786:
3787: my $name;
3788: foreach my $pattern (split(',',$acc)) {
3789: $pattern =~ s/^\s*//;
3790: $pattern =~ s/\s*$//;
3791: if ($pattern =~ /\*$/) {
3792: #35.8.*
3793: $pattern=~s/\*//;
3794: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3795: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
3796: #35.8.3.[34-56]
3797: my $low=$2;
3798: my $high=$3;
3799: $pattern=$1;
3800: if ($ip =~ /^\Q$pattern\E/) {
3801: my $last=(split(/\./,$ip))[3];
3802: if ($last <=$high && $last >=$low) { $allowed=1; }
3803: }
3804: } elsif ($pattern =~ /^\*/) {
3805: #*.msu.edu
3806: $pattern=~s/\*//;
3807: if (!defined($name)) {
3808: use Socket;
3809: my $netaddr=inet_aton($ip);
3810: ($name)=gethostbyaddr($netaddr,AF_INET);
3811: }
3812: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3813: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
3814: #127.0.0.1
3815: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3816: } else {
3817: #some.name.com
3818: if (!defined($name)) {
3819: use Socket;
3820: my $netaddr=inet_aton($ip);
3821: ($name)=gethostbyaddr($netaddr,AF_INET);
3822: }
3823: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3824: }
3825: if ($allowed) { last; }
3826: }
3827: return $allowed;
3828: }
3829:
3830: ###############################################
3831:
3832: =pod
3833:
3834: =head1 Domain Template Functions
3835:
3836: =over 4
3837:
3838: =item * &determinedomain()
3839:
3840: Inputs: $domain (usually will be undef)
3841:
3842: Returns: Determines which domain should be used for designs
3843:
3844: =cut
3845:
3846: ###############################################
3847: sub determinedomain {
3848: my $domain=shift;
3849: if (! $domain) {
3850: # Determine domain if we have not been given one
3851: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3852: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3853: if ($env{'request.role.domain'}) {
3854: $domain=$env{'request.role.domain'};
3855: }
3856: }
3857: return $domain;
3858: }
3859: ###############################################
3860:
3861: sub devalidate_domconfig_cache {
3862: my ($udom)=@_;
3863: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3864: }
3865:
3866: # ---------------------- Get domain configuration for a domain
3867: sub get_domainconf {
3868: my ($udom) = @_;
3869: my $cachetime=1800;
3870: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3871: if (defined($cached)) { return %{$result}; }
3872:
3873: my %domconfig = &Apache::lonnet::get_dom('configuration',
3874: ['login','rolecolors'],$udom);
3875: my (%designhash,%legacy);
3876: if (keys(%domconfig) > 0) {
3877: if (ref($domconfig{'login'}) eq 'HASH') {
3878: if (keys(%{$domconfig{'login'}})) {
3879: foreach my $key (keys(%{$domconfig{'login'}})) {
3880: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
3881: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
3882: $designhash{$udom.'.login.'.$key.'_'.$img} =
3883: $domconfig{'login'}{$key}{$img};
3884: }
3885: } else {
3886: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3887: }
3888: }
3889: } else {
3890: $legacy{'login'} = 1;
3891: }
3892: } else {
3893: $legacy{'login'} = 1;
3894: }
3895: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
3896: if (keys(%{$domconfig{'rolecolors'}})) {
3897: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
3898: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
3899: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
3900: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
3901: }
3902: }
3903: }
3904: } else {
3905: $legacy{'rolecolors'} = 1;
3906: }
3907: } else {
3908: $legacy{'rolecolors'} = 1;
3909: }
3910: if (keys(%legacy) > 0) {
3911: my %legacyhash = &get_legacy_domconf($udom);
3912: foreach my $item (keys(%legacyhash)) {
3913: if ($item =~ /^\Q$udom\E\.login/) {
3914: if ($legacy{'login'}) {
3915: $designhash{$item} = $legacyhash{$item};
3916: }
3917: } else {
3918: if ($legacy{'rolecolors'}) {
3919: $designhash{$item} = $legacyhash{$item};
3920: }
3921: }
3922: }
3923: }
3924: } else {
3925: %designhash = &get_legacy_domconf($udom);
3926: }
3927: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
3928: $cachetime);
3929: return %designhash;
3930: }
3931:
3932: sub get_legacy_domconf {
3933: my ($udom) = @_;
3934: my %legacyhash;
3935: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
3936: my $designfile = $designdir.'/'.$udom.'.tab';
3937: if (-e $designfile) {
3938: if ( open (my $fh,"<$designfile") ) {
3939: while (my $line = <$fh>) {
3940: next if ($line =~ /^\#/);
3941: chomp($line);
3942: my ($key,$val)=(split(/\=/,$line));
3943: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
3944: }
3945: close($fh);
3946: }
3947: }
3948: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
3949: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
3950: }
3951: return %legacyhash;
3952: }
3953:
3954: =pod
3955:
3956: =item * &domainlogo()
3957:
3958: Inputs: $domain (usually will be undef)
3959:
3960: Returns: A link to a domain logo, if the domain logo exists.
3961: If the domain logo does not exist, a description of the domain.
3962:
3963: =cut
3964:
3965: ###############################################
3966: sub domainlogo {
3967: my $domain = &determinedomain(shift);
3968: my %designhash = &get_domainconf($domain);
3969: # See if there is a logo
3970: if ($designhash{$domain.'.login.domlogo'} ne '') {
3971: my $imgsrc = $designhash{$domain.'.login.domlogo'};
3972: if ($imgsrc =~ m{^/(adm|res)/}) {
3973: if ($imgsrc =~ m{^/res/}) {
3974: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
3975: &Apache::lonnet::repcopy($local_name);
3976: }
3977: $imgsrc = &lonhttpdurl($imgsrc);
3978: }
3979: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
3980: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
3981: return &Apache::lonnet::domain($domain,'description');
3982: } else {
3983: return '';
3984: }
3985: }
3986: ##############################################
3987:
3988: =pod
3989:
3990: =item * &designparm()
3991:
3992: Inputs: $which parameter; $domain (usually will be undef)
3993:
3994: Returns: value of designparamter $which
3995:
3996: =cut
3997:
3998:
3999: ##############################################
4000: sub designparm {
4001: my ($which,$domain)=@_;
4002: if ($env{'browser.blackwhite'} eq 'on') {
4003: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
4004: return '#000000';
4005: }
4006: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
4007: return '#FFFFFF';
4008: }
4009: if ($which=~/\.tabbg$/) {
4010: return '#CCCCCC';
4011: }
4012: }
4013: if (exists($env{'environment.color.'.$which})) {
4014: return $env{'environment.color.'.$which};
4015: }
4016: $domain=&determinedomain($domain);
4017: my %domdesign = &get_domainconf($domain);
4018: my $output;
4019: if ($domdesign{$domain.'.'.$which} ne '') {
4020: $output = $domdesign{$domain.'.'.$which};
4021: } else {
4022: $output = $defaultdesign{$which};
4023: }
4024: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4025: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4026: if ($output =~ m{^/(adm|res)/}) {
4027: if ($output =~ m{^/res/}) {
4028: my $local_name = &Apache::lonnet::filelocation('',$output);
4029: &Apache::lonnet::repcopy($local_name);
4030: }
4031: $output = &lonhttpdurl($output);
4032: }
4033: }
4034: return $output;
4035: }
4036:
4037: ###############################################
4038: ###############################################
4039:
4040: =pod
4041:
4042: =back
4043:
4044: =head1 HTML Helpers
4045:
4046: =over 4
4047:
4048: =item * &bodytag()
4049:
4050: Returns a uniform header for LON-CAPA web pages.
4051:
4052: Inputs:
4053:
4054: =over 4
4055:
4056: =item * $title, A title to be displayed on the page.
4057:
4058: =item * $function, the current role (can be undef).
4059:
4060: =item * $addentries, extra parameters for the <body> tag.
4061:
4062: =item * $bodyonly, if defined, only return the <body> tag.
4063:
4064: =item * $domain, if defined, force a given domain.
4065:
4066: =item * $forcereg, if page should register as content page (relevant for
4067: text interface only)
4068:
4069: =item * $customtitle, alternate text to use instead of $title
4070: in the title box that appears, this text
4071: is not auto translated like the $title is
4072:
4073: =item * $notopbar, if true, keep the 'what is this' info but remove the
4074: navigational links
4075:
4076: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4077:
4078: =item * $notitle, if true keep the nav controls, but remove the title bar
4079:
4080: =item * $no_inline_link, if true and in remote mode, don't show the
4081: 'Switch To Inline Menu' link
4082:
4083: =item * $args, optional argument valid values are
4084: no_auto_mt_title -> prevents &mt()ing the title arg
4085: inherit_jsmath -> when creating popup window in a page,
4086: should it have jsmath forced on by the
4087: current page
4088:
4089: =back
4090:
4091: Returns: A uniform header for LON-CAPA web pages.
4092: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4093: If $bodyonly is undef or zero, an html string containing a <body> tag and
4094: other decorations will be returned.
4095:
4096: =cut
4097:
4098: sub bodytag {
4099: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
4100: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
4101:
4102: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4103:
4104: $function = &get_users_function() if (!$function);
4105: my $img = &designparm($function.'.img',$domain);
4106: my $font = &designparm($function.'.font',$domain);
4107: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4108:
4109: my %design = ( 'style' => 'margin-top: 0px',
4110: 'bgcolor' => $pgbg,
4111: 'text' => $font,
4112: 'alink' => &designparm($function.'.alink',$domain),
4113: 'vlink' => &designparm($function.'.vlink',$domain),
4114: 'link' => &designparm($function.'.link',$domain),);
4115: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4116:
4117: # role and realm
4118: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4119: if ($role eq 'ca') {
4120: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4121: $realm = &plainname($rname,$rdom);
4122: }
4123: # realm
4124: if ($env{'request.course.id'}) {
4125: if ($env{'request.role'} !~ /^cr/) {
4126: $role = &Apache::lonnet::plaintext($role,&course_type());
4127: }
4128: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4129: } else {
4130: $role = &Apache::lonnet::plaintext($role);
4131: }
4132:
4133: if (!$realm) { $realm=' '; }
4134: # Set messages
4135: my $messages=&domainlogo($domain);
4136:
4137: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4138:
4139: # construct main body tag
4140: my $bodytag = "<body $extra_body_attr>".
4141: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4142:
4143: if ($bodyonly) {
4144: return $bodytag;
4145: } elsif ($env{'browser.interface'} eq 'textual') {
4146: # Accessibility
4147:
4148: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4149: if (!$notitle) {
4150: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4151: }
4152: return $bodytag;
4153: }
4154:
4155: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4156: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4157: undef($role);
4158: } else {
4159: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4160: }
4161:
4162: my $roleinfo=(<<ENDROLE);
4163: <td class="LC_title_bar_who">
4164: <div class="LC_title_bar_name">
4165: $name
4166:
4167: </div>
4168: <div class="LC_title_bar_role">
4169: $role
4170: </div>
4171: <div class="LC_title_bar_realm">
4172: $realm
4173: </div>
4174: </td>
4175: ENDROLE
4176:
4177: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4178: if ($customtitle) {
4179: $titleinfo = $customtitle;
4180: }
4181: #
4182: # Extra info if you are the DC
4183: my $dc_info = '';
4184: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4185: $env{'course.'.$env{'request.course.id'}.
4186: '.domain'}.'/'})) {
4187: my $cid = $env{'request.course.id'};
4188: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4189: $dc_info =~ s/\s+$//;
4190: $dc_info = '('.$dc_info.')';
4191: }
4192:
4193: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4194: # No Remote
4195: if ($env{'request.state'} eq 'construct') {
4196: $forcereg=1;
4197: }
4198:
4199: if (!$customtitle && $env{'request.state'} eq 'construct') {
4200: # this is for resources; directories have customtitle, and crumbs
4201: # and select recent are created in lonpubdir.pm
4202: my ($uname,$thisdisfn)=
4203: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4204: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4205: $formaction=~s/\/+/\//g;
4206:
4207: my $parentpath = '';
4208: my $lastitem = '';
4209: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4210: $parentpath = $1;
4211: $lastitem = $2;
4212: } else {
4213: $lastitem = $thisdisfn;
4214: }
4215: $titleinfo =
4216: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4217: .'<b>'.&mt('Construction Space').'</b>: '
4218: .'<form name="dirs" method="post" action="'.$formaction
4219: .'" target="_top"><tt><b>'
4220: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<span class=\"LC_fontsize_big\">$lastitem</span></b></tt><br />"
4221: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4222: .'</form>'
4223: .&Apache::lonmenu::constspaceform();
4224: }
4225:
4226: my $titletable;
4227: if (!$notitle) {
4228: $titletable =
4229: '<table id="LC_title_bar">'.
4230: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4231: '</tr></table>';
4232: }
4233: if ($notopbar) {
4234: $bodytag .= $titletable;
4235: } else {
4236: if ($env{'request.state'} eq 'construct') {
4237: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4238: $titletable);
4239: } else {
4240: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4241: $titletable;
4242: }
4243: }
4244: return $bodytag;
4245: }
4246:
4247: #
4248: # Top frame rendering, Remote is up
4249: #
4250:
4251: my $imgsrc = $img;
4252: if ($img =~ /^\/adm/) {
4253: $imgsrc = &lonhttpdurl($img);
4254: }
4255: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4256:
4257: # Explicit link to get inline menu
4258: my $menu= ($no_inline_link?''
4259: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4260: #
4261: if ($notitle) {
4262: return $bodytag;
4263: }
4264: return(<<ENDBODY);
4265: $bodytag
4266: <table id="LC_title_bar" class="LC_with_remote">
4267: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4268: <td class="LC_title_bar_domain_logo">$messages </td>
4269: </tr>
4270: <tr><td>$titleinfo $dc_info $menu</td>
4271: $roleinfo
4272: </tr>
4273: </table>
4274: ENDBODY
4275: }
4276:
4277: sub make_attr_string {
4278: my ($register,$attr_ref) = @_;
4279:
4280: if ($attr_ref && !ref($attr_ref)) {
4281: die("addentries Must be a hash ref ".
4282: join(':',caller(1))." ".
4283: join(':',caller(0))." ");
4284: }
4285:
4286: if ($register) {
4287: my ($on_load,$on_unload);
4288: foreach my $key (keys(%{$attr_ref})) {
4289: if (lc($key) eq 'onload') {
4290: $on_load.=$attr_ref->{$key}.';';
4291: delete($attr_ref->{$key});
4292:
4293: } elsif (lc($key) eq 'onunload') {
4294: $on_unload.=$attr_ref->{$key}.';';
4295: delete($attr_ref->{$key});
4296: }
4297: }
4298: $attr_ref->{'onload'} =
4299: &Apache::lonmenu::loadevents(). $on_load;
4300: $attr_ref->{'onunload'}=
4301: &Apache::lonmenu::unloadevents().$on_unload;
4302: }
4303:
4304: # Accessibility font enhance
4305: if ($env{'browser.fontenhance'} eq 'on') {
4306: my $style;
4307: foreach my $key (keys(%{$attr_ref})) {
4308: if (lc($key) eq 'style') {
4309: $style.=$attr_ref->{$key}.';';
4310: delete($attr_ref->{$key});
4311: }
4312: }
4313: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4314: }
4315:
4316: if ($env{'browser.blackwhite'} eq 'on') {
4317: delete($attr_ref->{'font'});
4318: delete($attr_ref->{'link'});
4319: delete($attr_ref->{'alink'});
4320: delete($attr_ref->{'vlink'});
4321: delete($attr_ref->{'bgcolor'});
4322: delete($attr_ref->{'background'});
4323: }
4324:
4325: my $attr_string;
4326: foreach my $attr (keys(%$attr_ref)) {
4327: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4328: }
4329: return $attr_string;
4330: }
4331:
4332:
4333: ###############################################
4334: ###############################################
4335:
4336: =pod
4337:
4338: =item * &endbodytag()
4339:
4340: Returns a uniform footer for LON-CAPA web pages.
4341:
4342: Inputs: 1 - optional reference to an args hash
4343: If in the hash, key for noredirectlink has a value which evaluates to true,
4344: a 'Continue' link is not displayed if the page contains an
4345: internal redirect in the <head></head> section,
4346: i.e., $env{'internal.head.redirect'} exists
4347:
4348: =cut
4349:
4350: sub endbodytag {
4351: my ($args) = @_;
4352: my $endbodytag='</body>';
4353: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4354: if ( exists( $env{'internal.head.redirect'} ) ) {
4355: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4356: $endbodytag=
4357: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4358: &mt('Continue').'</a>'.
4359: $endbodytag;
4360: }
4361: }
4362: return $endbodytag;
4363: }
4364:
4365: =pod
4366:
4367: =item * &standard_css()
4368:
4369: Returns a style sheet
4370:
4371: Inputs: (all optional)
4372: domain -> force to color decorate a page for a specific
4373: domain
4374: function -> force usage of a specific rolish color scheme
4375: bgcolor -> override the default page bgcolor
4376:
4377: =cut
4378:
4379: sub standard_css {
4380: my ($function,$domain,$bgcolor) = @_;
4381: $function = &get_users_function() if (!$function);
4382: my $img = &designparm($function.'.img', $domain);
4383: my $tabbg = &designparm($function.'.tabbg', $domain);
4384: my $font = &designparm($function.'.font', $domain);
4385: my $sidebg = &designparm($function.'.sidebg',$domain);
4386: my $pgbg_or_bgcolor =
4387: $bgcolor ||
4388: &designparm($function.'.pgbg', $domain);
4389: my $pgbg = &designparm($function.'.pgbg', $domain);
4390: my $alink = &designparm($function.'.alink', $domain);
4391: my $vlink = &designparm($function.'.vlink', $domain);
4392: my $link = &designparm($function.'.link', $domain);
4393:
4394: my $loginbg = &designparm('login.sidebg',$domain);
4395:
4396: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4397: my $mono = 'monospace';
4398: my $data_table_head = $tabbg;
4399: my $data_table_light = '#EEEEEE';
4400: my $data_table_dark = '#DDDDDD';
4401: my $data_table_darker = '#CCCCCC';
4402: my $data_table_highlight = '#FFFF00';
4403: my $mail_new = '#FFBB77';
4404: my $mail_new_hover = '#DD9955';
4405: my $mail_read = '#BBBB77';
4406: my $mail_read_hover = '#999944';
4407: my $mail_replied = '#AAAA88';
4408: my $mail_replied_hover = '#888855';
4409: my $mail_other = '#99BBBB';
4410: my $mail_other_hover = '#669999';
4411: my $table_header = '#DDDDDD';
4412: my $feedback_link_bg = '#BBBBBB';
4413: my $lg_border_color = '#C8C8C8';
4414:
4415: my $border = ($env{'browser.type'} eq 'explorer' ||
4416: $env{'browser.type'} eq 'safari' ) ? '0px 2px 0px 2px'
4417: : '0px 3px 0px 4px';
4418:
4419:
4420: return <<END;
4421: body{
4422: font-family: $sans;
4423: line-height:130%;
4424: font-size:0.83em;
4425: color:$font;
4426: }
4427: a:link, a:visited { font-size:100%; }
4428:
4429: a:focus { color: red; background: yellow }
4430: table.thinborder,
4431: table.thinborder tr th {
4432: border-style: solid;
4433: border-width: 1px;
4434: border-color: $lg_border_color;
4435: background: $tabbg;
4436: }
4437: table.thinborder tr td {
4438: border-style: solid;
4439: border-width: 1px;
4440: border-color: $lg_border_color;
4441: }
4442:
4443: form, .inline { display: inline; }
4444: .center { text-align: center; }
4445: .left { text-align:left; }
4446: .right {text-align:right;}
4447: .middle {vertical-align:middle;}
4448: .top {vertical-align:top;}
4449: .bottom {vertical-align:bottom;}
4450: .LC_filename {font-family: $mono; white-space:pre;}
4451: .LC_error {
4452: color: red;
4453: font-size: larger;
4454: }
4455: .LC_warning,
4456: .LC_diff_removed {
4457: color: red;
4458: }
4459:
4460: .LC_info,
4461: .LC_success,
4462: .LC_diff_added {
4463: color: green;
4464: }
4465: .LC_unknown {
4466: color: yellow;
4467: }
4468:
4469: .LC_icon {
4470: border: 0px;
4471: }
4472: .LC_indexer_icon {
4473: border: 0px;
4474: height: 22px;
4475: }
4476: .LC_docs_spacer {
4477: width: 25px;
4478: height: 1px;
4479: border: 0px;
4480: }
4481:
4482: .LC_internal_info {
4483: color: #999;
4484: }
4485:
4486: table.LC_pastsubmission {
4487: border: 1px solid black;
4488: margin: 2px;
4489: }
4490:
4491: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4492: width: 100%;
4493: background: $pgbg;
4494: border: 2px;
4495: border-collapse: separate;
4496: padding: 0px;
4497: }
4498:
4499: table#LC_title_bar, table.LC_breadcrumbs,
4500: table#LC_title_bar.LC_with_remote {
4501: width: 100%;
4502: border-color: $pgbg;
4503: border-style: solid;
4504: border-width: $border;
4505:
4506: background: $pgbg;
4507: font-family: $sans;
4508: border-collapse: collapse;
4509: padding: 0px;
4510: }
4511: table.LC_docs_path {
4512: width: 100%;
4513: border: 0;
4514: background: $pgbg;
4515: font-family: $sans;
4516: border-collapse: collapse;
4517: padding: 0px;
4518: }
4519:
4520: table#LC_title_bar td {
4521: background: $tabbg;
4522: }
4523: table#LC_title_bar td.LC_title_bar_who {
4524: background: $tabbg;
4525: color: $font;
4526: font: small $sans;
4527: text-align: right;
4528: }
4529: span.LC_metadata {
4530: font-family: $sans;
4531: }
4532: span.LC_title_bar_title {
4533: font: bold x-large $sans;
4534: }
4535: table#LC_title_bar td.LC_title_bar_domain_logo {
4536: background: $sidebg;
4537: text-align: right;
4538: padding: 0px;
4539: }
4540: table#LC_title_bar td.LC_title_bar_role_logo {
4541: background: $sidebg;
4542: padding: 0px;
4543: }
4544:
4545: table#LC_menubuttons img{
4546: border: 0px;
4547: }
4548: table#LC_top_nav td {
4549: background: $tabbg;
4550: border: 0px;
4551: font-size: small;
4552: vertical-align:top;
4553: padding:2px 5px 2px 5px;
4554: }
4555: table#LC_top_nav td a, div#LC_top_nav a {
4556: color: $font;
4557: font-family: $sans;
4558: }
4559: table#LC_top_nav td.LC_top_nav_logo {
4560: background: $tabbg;
4561: text-align: left;
4562: white-space: nowrap;
4563: width: 31px;
4564: }
4565: table#LC_top_nav td.LC_top_nav_logo img {
4566: border: 0px;
4567: vertical-align: bottom;
4568: }
4569: table#LC_top_nav td.LC_top_nav_exit,
4570: table#LC_top_nav td.LC_top_nav_help {
4571: width: 2.0em;
4572: }
4573: table#LC_top_nav td.LC_top_nav_login {
4574: width: 4.0em;
4575: text-align: center;
4576: }
4577: table.LC_breadcrumbs td, table.LC_docs_path td {
4578: background: $tabbg;
4579: color: $font;
4580: font-family: $sans;
4581: font-size: smaller;
4582: }
4583: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4584: table.LC_docs_path td.LC_docs_path_component {
4585: background: $tabbg;
4586: color: $font;
4587: font-family: $sans;
4588: font-size: larger;
4589: text-align: right;
4590: }
4591: td.LC_table_cell_checkbox {
4592: text-align: center;
4593: }
4594: table#LC_mainmenu td.LC_mainmenu_column {
4595: vertical-align: top;
4596: }
4597:
4598: .LC_fontsize_small
4599: {
4600: font-size: 70%;
4601: }
4602:
4603: .LC_fontsize_medium
4604: {
4605: font-size: 85%;
4606: }
4607:
4608: .LC_fontsize_large
4609: {
4610: font-size: 120%;
4611: }
4612:
4613: .LC_fontcolor_red
4614: {
4615: color: #FF0000;
4616: }
4617:
4618: .LC_menubuttons_inline_text {
4619: color: $font;
4620: font-family: $sans;
4621: font-size: 90%;
4622: padding-left:3px;
4623: }
4624:
4625: .LC_menubuttons_link {
4626: text-decoration: none;
4627: }
4628: /*2008--9-5: new menu style sheet.Changed category*/
4629: .LC_menubuttons_category {
4630: color: $font;
4631: background: $pgbg;
4632: font-family: $sans;
4633: font-size: larger;
4634: font-weight: bold;
4635: }
4636:
4637: td.LC_menubuttons_text {
4638: color: $font;
4639: }
4640:
4641:
4642:
4643: .LC_current_location {
4644: font-family: $sans;
4645: background: $tabbg;
4646: }
4647: .LC_new_mail {
4648: font-family: $sans;
4649: background: $tabbg;
4650: font-weight: bold;
4651: }
4652:
4653:
4654: .LC_dropadd_labeltext {
4655: font-family: $sans;
4656: text-align: right;
4657: }
4658:
4659: .LC_preferences_labeltext {
4660: font-family: $sans;
4661: text-align: right;
4662: }
4663:
4664: .LC_roleslog_note {
4665: font-size: small;
4666: }
4667:
4668: table.LC_aboutme_port {
4669: border: 0px;
4670: border-collapse: collapse;
4671: border-spacing: 0px;
4672: }
4673: table.LC_data_table, table.LC_mail_list {
4674: border: 1px solid #000000;
4675: border-collapse: separate;
4676: border-spacing: 1px;
4677: background: $pgbg;
4678: }
4679: .LC_data_table_dense {
4680: font-size: small;
4681: }
4682: table.LC_nested_outer {
4683: border: 1px solid #000000;
4684: border-collapse: collapse;
4685: border-spacing: 0px;
4686: width: 100%;
4687: }
4688: table.LC_nested {
4689: border: 0px;
4690: border-collapse: collapse;
4691: border-spacing: 0px;
4692: width: 100%;
4693: }
4694: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
4695: table.LC_prior_tries tr th {
4696: font-weight: bold;
4697: background-color: $data_table_head;
4698: font-size:90%;
4699: }
4700: table.LC_data_table tr.LC_odd_row > td,
4701: table.LC_pick_box tr > td.LC_odd_row,
4702: table.LC_aboutme_port tr td {
4703: background-color: $data_table_light;
4704: padding: 2px;
4705: }
4706: table.LC_data_table tr.LC_even_row > td,
4707: table.LC_pick_box tr > td.LC_even_row,
4708: table.LC_aboutme_port tr.LC_even_row td {
4709: background-color: $data_table_dark;
4710: padding: 2px;
4711: }
4712: table.LC_data_table tr.LC_data_table_highlight td {
4713: background-color: $data_table_darker;
4714: }
4715: table.LC_data_table tr td.LC_leftcol_header {
4716: background-color: $data_table_head;
4717: font-weight: bold;
4718: }
4719: table.LC_data_table tr.LC_empty_row td,
4720: table.LC_nested tr.LC_empty_row td {
4721: background-color: #FFFFFF;
4722: font-weight: bold;
4723: font-style: italic;
4724: text-align: center;
4725: padding: 8px;
4726: }
4727: table.LC_nested tr.LC_empty_row td {
4728: padding: 4ex
4729: }
4730: table.LC_nested_outer tr th {
4731: font-weight: bold;
4732: background-color: $data_table_head;
4733: font-size: small;
4734: border-bottom: 1px solid #000000;
4735: }
4736: table.LC_nested_outer tr td.LC_subheader {
4737: background-color: $data_table_head;
4738: font-weight: bold;
4739: font-size: small;
4740: border-bottom: 1px solid #000000;
4741: text-align: right;
4742: }
4743: table.LC_nested tr.LC_info_row td {
4744: background-color: #CCC;
4745: font-weight: bold;
4746: font-size: small;
4747: text-align: center;
4748: }
4749: table.LC_nested tr.LC_info_row td.LC_left_item,
4750: table.LC_nested_outer tr th.LC_left_item {
4751: text-align: left;
4752: }
4753: table.LC_nested td {
4754: background-color: #FFF;
4755: font-size: small;
4756: }
4757: table.LC_nested_outer tr th.LC_right_item,
4758: table.LC_nested tr.LC_info_row td.LC_right_item,
4759: table.LC_nested tr.LC_odd_row td.LC_right_item,
4760: table.LC_nested tr td.LC_right_item {
4761: text-align: right;
4762: }
4763:
4764: table.LC_nested tr.LC_odd_row td {
4765: background-color: #EEE;
4766: }
4767:
4768: table.LC_createuser {
4769: }
4770:
4771: table.LC_createuser tr.LC_section_row td {
4772: font-size: small;
4773: }
4774:
4775: table.LC_createuser tr.LC_info_row td {
4776: background-color: #CCC;
4777: font-weight: bold;
4778: text-align: center;
4779: }
4780:
4781: table.LC_calendar {
4782: border: 1px solid #000000;
4783: border-collapse: collapse;
4784: }
4785: table.LC_calendar_pickdate {
4786: font-size: xx-small;
4787: }
4788: table.LC_calendar tr td {
4789: border: 1px solid #000000;
4790: vertical-align: top;
4791: }
4792: table.LC_calendar tr td.LC_calendar_day_empty {
4793: background-color: $data_table_dark;
4794: }
4795: table.LC_calendar tr td.LC_calendar_day_current {
4796: background-color: $data_table_highlight;
4797: }
4798:
4799: table.LC_mail_list tr.LC_mail_new {
4800: background-color: $mail_new;
4801: }
4802: table.LC_mail_list tr.LC_mail_new:hover {
4803: background-color: $mail_new_hover;
4804: }
4805: table.LC_mail_list tr.LC_mail_read {
4806: background-color: $mail_read;
4807: }
4808: table.LC_mail_list tr.LC_mail_read:hover {
4809: background-color: $mail_read_hover;
4810: }
4811: table.LC_mail_list tr.LC_mail_replied {
4812: background-color: $mail_replied;
4813: }
4814: table.LC_mail_list tr.LC_mail_replied:hover {
4815: background-color: $mail_replied_hover;
4816: }
4817: table.LC_mail_list tr.LC_mail_other {
4818: background-color: $mail_other;
4819: }
4820: table.LC_mail_list tr.LC_mail_other:hover {
4821: background-color: $mail_other_hover;
4822: }
4823: table.LC_mail_list tr.LC_mail_even {
4824: }
4825: table.LC_mail_list tr.LC_mail_odd {
4826: }
4827:
4828: table.LC_data_table tr > td.LC_browser_file,
4829: table.LC_data_table tr > td.LC_browser_file_published {
4830: background: #CCFF88;
4831: }
4832: table.LC_data_table tr > td.LC_browser_file_locked,
4833: table.LC_data_table tr > td.LC_browser_file_unpublished {
4834: background: #FFAA99;
4835: }
4836: table.LC_data_table tr > td.LC_browser_file_obsolete {
4837: background: #AAAAAA;
4838: }
4839: table.LC_data_table tr > td.LC_browser_file_modified,
4840: table.LC_data_table tr > td.LC_browser_file_metamodified {
4841: background: #FFFF77;
4842: }
4843: table.LC_data_table tr.LC_browser_folder > td {
4844: background: #CCCCFF;
4845: }
4846:
4847: table.LC_data_table tr > td.LC_roles_is {
4848: /* background: #77FF77; */
4849: }
4850: table.LC_data_table tr > td.LC_roles_future {
4851: background: #FFFF77;
4852: }
4853: table.LC_data_table tr > td.LC_roles_will {
4854: background: #FFAA77;
4855: }
4856: table.LC_data_table tr > td.LC_roles_expired {
4857: background: #FF7777;
4858: }
4859: table.LC_data_table tr > td.LC_roles_will_not {
4860: background: #AAFF77;
4861: }
4862: table.LC_data_table tr > td.LC_roles_selected {
4863: background: #11CC55;
4864: }
4865:
4866: span.LC_current_location {
4867: font-size:larger;
4868: background: $pgbg;
4869: }
4870:
4871: span.LC_parm_menu_item {
4872: font-size: larger;
4873: font-family: $sans;
4874: }
4875: span.LC_parm_scope_all {
4876: color: red;
4877: }
4878: span.LC_parm_scope_folder {
4879: color: green;
4880: }
4881: span.LC_parm_scope_resource {
4882: color: orange;
4883: }
4884: span.LC_parm_part {
4885: color: blue;
4886: }
4887: span.LC_parm_folder, span.LC_parm_symb {
4888: font-size: x-small;
4889: font-family: $mono;
4890: color: #AAAAAA;
4891: }
4892:
4893: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
4894: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
4895: border: 1px solid black;
4896: border-collapse: collapse;
4897: }
4898: table.LC_parm_overview_restrictions td {
4899: border-width: 1px 4px 1px 4px;
4900: border-style: solid;
4901: border-color: $pgbg;
4902: text-align: center;
4903: }
4904: table.LC_parm_overview_restrictions th {
4905: background: $tabbg;
4906: border-width: 1px 4px 1px 4px;
4907: border-style: solid;
4908: border-color: $pgbg;
4909: }
4910: table#LC_helpmenu {
4911: border: 0px;
4912: height: 55px;
4913: border-spacing: 0px;
4914: }
4915:
4916: table#LC_helpmenu fieldset legend {
4917: font-size: larger;
4918: font-weight: bold;
4919: }
4920: table#LC_helpmenu_links {
4921: width: 100%;
4922: border: 1px solid black;
4923: background: $pgbg;
4924: padding: 0px;
4925: border-spacing: 1px;
4926: }
4927: table#LC_helpmenu_links tr td {
4928: padding: 1px;
4929: background: $tabbg;
4930: text-align: center;
4931: font-weight: bold;
4932: }
4933:
4934: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
4935: table#LC_helpmenu_links a:active {
4936: text-decoration: none;
4937: color: $font;
4938: }
4939: table#LC_helpmenu_links a:hover {
4940: text-decoration: underline;
4941: color: $vlink;
4942: }
4943:
4944: .LC_chrt_popup_exists {
4945: border: 1px solid #339933;
4946: margin: -1px;
4947: }
4948: .LC_chrt_popup_up {
4949: border: 1px solid yellow;
4950: margin: -1px;
4951: }
4952: .LC_chrt_popup {
4953: border: 1px solid #8888FF;
4954: background: #CCCCFF;
4955: }
4956: table.LC_pick_box {
4957: border-collapse: separate;
4958: background: white;
4959: border: 1px solid black;
4960: border-spacing: 1px;
4961: }
4962: table.LC_pick_box td.LC_pick_box_title {
4963: background: $tabbg;
4964: font-weight: bold;
4965: text-align: right;
4966: width: 184px;
4967: padding: 8px;
4968: }
4969: table.LC_pick_box td.LC_selfenroll_pick_box_title {
4970: background: $tabbg;
4971: font-weight: bold;
4972: text-align: right;
4973: width: 350px;
4974: padding: 8px;
4975: }
4976:
4977: table.LC_pick_box td.LC_pick_box_value {
4978: text-align: left;
4979: padding: 8px;
4980: }
4981: table.LC_pick_box td.LC_pick_box_select {
4982: text-align: left;
4983: padding: 8px;
4984: }
4985: table.LC_pick_box td.LC_pick_box_separator {
4986: padding: 0px;
4987: height: 1px;
4988: background: black;
4989: }
4990: table.LC_pick_box td.LC_pick_box_submit {
4991: text-align: right;
4992: }
4993: table.LC_pick_box td.LC_evenrow_value {
4994: text-align: left;
4995: padding: 8px;
4996: background-color: $data_table_light;
4997: }
4998: table.LC_pick_box td.LC_oddrow_value {
4999: text-align: left;
5000: padding: 8px;
5001: background-color: $data_table_light;
5002: }
5003: table.LC_helpform_receipt {
5004: width: 620px;
5005: border-collapse: separate;
5006: background: white;
5007: border: 1px solid black;
5008: border-spacing: 1px;
5009: }
5010: table.LC_helpform_receipt td.LC_pick_box_title {
5011: background: $tabbg;
5012: font-weight: bold;
5013: text-align: right;
5014: width: 184px;
5015: padding: 8px;
5016: }
5017: table.LC_helpform_receipt td.LC_evenrow_value {
5018: text-align: left;
5019: padding: 8px;
5020: background-color: $data_table_light;
5021: }
5022: table.LC_helpform_receipt td.LC_oddrow_value {
5023: text-align: left;
5024: padding: 8px;
5025: background-color: $data_table_light;
5026: }
5027: table.LC_helpform_receipt td.LC_pick_box_separator {
5028: padding: 0px;
5029: height: 1px;
5030: background: black;
5031: }
5032: span.LC_helpform_receipt_cat {
5033: font-weight: bold;
5034: }
5035: table.LC_group_priv_box {
5036: background: white;
5037: border: 1px solid black;
5038: border-spacing: 1px;
5039: }
5040: table.LC_group_priv_box td.LC_pick_box_title {
5041: background: $tabbg;
5042: font-weight: bold;
5043: text-align: right;
5044: width: 184px;
5045: }
5046: table.LC_group_priv_box td.LC_groups_fixed {
5047: background: $data_table_light;
5048: text-align: center;
5049: }
5050: table.LC_group_priv_box td.LC_groups_optional {
5051: background: $data_table_dark;
5052: text-align: center;
5053: }
5054: table.LC_group_priv_box td.LC_groups_functionality {
5055: background: $data_table_darker;
5056: text-align: center;
5057: font-weight: bold;
5058: }
5059: table.LC_group_priv td {
5060: text-align: left;
5061: padding: 0px;
5062: }
5063:
5064: table.LC_notify_front_page {
5065: background: white;
5066: border: 1px solid black;
5067: padding: 8px;
5068: }
5069: table.LC_notify_front_page td {
5070: padding: 8px;
5071: }
5072: .LC_navbuttons {
5073: margin: 2ex 0ex 2ex 0ex;
5074: }
5075: .LC_topic_bar {
5076: font-family: $sans;
5077: font-weight: bold;
5078: width: 100%;
5079: background: $tabbg;
5080: vertical-align: middle;
5081: margin: 2ex 0ex 2ex 0ex;
5082: }
5083: .LC_topic_bar span {
5084: vertical-align: middle;
5085: }
5086: .LC_topic_bar img {
5087: vertical-align: bottom;
5088: }
5089: table.LC_course_group_status {
5090: margin: 20px;
5091: }
5092: table.LC_status_selector td {
5093: vertical-align: top;
5094: text-align: center;
5095: padding: 4px;
5096: }
5097: table.LC_descriptive_input td.LC_description {
5098: vertical-align: top;
5099: text-align: right;
5100: font-weight: bold;
5101: }
5102: div.LC_feedback_link {
5103: clear: both;
5104: background: white;
5105: width: 100%;
5106: }
5107: span.LC_feedback_link {
5108: background: $feedback_link_bg;
5109: font-size: larger;
5110: }
5111: span.LC_message_link {
5112: background: $feedback_link_bg;
5113: font-size: larger;
5114: position: absolute;
5115: right: 1em;
5116: }
5117:
5118: table.LC_prior_tries {
5119: border: 1px solid #000000;
5120: border-collapse: separate;
5121: border-spacing: 1px;
5122: }
5123:
5124: table.LC_prior_tries td {
5125: padding: 2px;
5126: }
5127:
5128: .LC_answer_correct {
5129: background: #AAFFAA;
5130: color: black;
5131: }
5132: .LC_answer_charged_try {
5133: background: #FFAAAA ! important;
5134: color: black;
5135: }
5136: .LC_answer_not_charged_try,
5137: .LC_answer_no_grade,
5138: .LC_answer_late {
5139: background: #FFFFAA;
5140: color: black;
5141: }
5142: .LC_answer_previous {
5143: background: #AAAAFF;
5144: color: black;
5145: }
5146: .LC_answer_no_message {
5147: background: #FFFFFF;
5148: color: black;
5149: }
5150: .LC_answer_unknown {
5151: background: orange;
5152: color: black;
5153: }
5154:
5155:
5156: span.LC_prior_numerical,
5157: span.LC_prior_string,
5158: span.LC_prior_custom,
5159: span.LC_prior_reaction,
5160: span.LC_prior_math {
5161: font-family: monospace;
5162: white-space: pre;
5163: }
5164:
5165: span.LC_prior_string {
5166: font-family: monospace;
5167: white-space: pre;
5168: }
5169:
5170: table.LC_prior_option {
5171: width: 100%;
5172: border-collapse: collapse;
5173: }
5174: table.LC_prior_rank, table.LC_prior_match {
5175: border-collapse: collapse;
5176: }
5177: table.LC_prior_option tr td,
5178: table.LC_prior_rank tr td,
5179: table.LC_prior_match tr td {
5180: border: 1px solid #000000;
5181: }
5182:
5183: span.LC_nobreak {
5184: white-space: nowrap;
5185: }
5186:
5187: span.LC_cusr_emph {
5188: font-style: italic;
5189: }
5190:
5191: span.LC_cusr_subheading {
5192: font-weight: normal;
5193: font-size: 85%;
5194: }
5195:
5196: table.LC_docs_documents {
5197: background: #BBBBBB;
5198: border-width: 0px;
5199: border-collapse: collapse;
5200: }
5201:
5202: table.LC_docs_documents td.LC_docs_document {
5203: border: 2px solid black;
5204: padding: 4px;
5205: }
5206:
5207: .LC_docs_course_commands div {
5208: float: left;
5209: border: 4px solid #AAAAAA;
5210: padding: 4px;
5211: background: #DDDDCC;
5212: }
5213:
5214: .LC_docs_entry_move {
5215: border: 0px;
5216: border-collapse: collapse;
5217: }
5218:
5219: .LC_docs_entry_move td {
5220: border: 2px solid #BBBBBB;
5221: background: #DDDDDD;
5222: }
5223:
5224: .LC_docs_editor td.LC_docs_entry_commands {
5225: background: #DDDDDD;
5226: font-size: x-small;
5227: }
5228: .LC_docs_copy {
5229: color: #000099;
5230: }
5231: .LC_docs_cut {
5232: color: #550044;
5233: }
5234: .LC_docs_rename {
5235: color: #009900;
5236: }
5237: .LC_docs_remove {
5238: color: #990000;
5239: }
5240:
5241: .LC_docs_reinit_warn,
5242: .LC_docs_ext_edit {
5243: font-size: x-small;
5244: }
5245:
5246: .LC_docs_editor td.LC_docs_entry_title,
5247: .LC_docs_editor td.LC_docs_entry_icon {
5248: background: #FFFFBB;
5249: }
5250: .LC_docs_editor td.LC_docs_entry_parameter {
5251: background: #BBBBFF;
5252: font-size: x-small;
5253: white-space: nowrap;
5254: }
5255:
5256: table.LC_docs_adddocs td,
5257: table.LC_docs_adddocs th {
5258: border: 1px solid #BBBBBB;
5259: padding: 4px;
5260: background: #DDDDDD;
5261: }
5262:
5263: table.LC_sty_begin {
5264: background: #BBFFBB;
5265: }
5266: table.LC_sty_end {
5267: background: #FFBBBB;
5268: }
5269:
5270: table.LC_double_column {
5271: border-width: 0px;
5272: border-collapse: collapse;
5273: width: 100%;
5274: padding: 2px;
5275: }
5276:
5277: table.LC_double_column tr td.LC_left_col {
5278: top: 2px;
5279: left: 2px;
5280: width: 47%;
5281: vertical-align: top;
5282: }
5283:
5284: table.LC_double_column tr td.LC_right_col {
5285: top: 2px;
5286: right: 2px;
5287: width: 47%;
5288: vertical-align: top;
5289: }
5290:
5291: span.LC_role_level {
5292: font-weight: bold;
5293: }
5294:
5295: div.LC_left_float {
5296: float: left;
5297: padding-right: 5%;
5298: padding-bottom: 4px;
5299: }
5300:
5301: div.LC_clear_float_header {
5302: padding-bottom: 2px;
5303: }
5304:
5305: div.LC_clear_float_footer {
5306: padding-top: 10px;
5307: clear: both;
5308: }
5309:
5310:
5311: div.LC_grade_show_user {
5312: margin-top: 20px;
5313: border: 1px solid black;
5314: }
5315: div.LC_grade_user_name {
5316: background: #DDDDEE;
5317: border-bottom: 1px solid black;
5318: font-weight: bold;
5319: font-size: large;
5320: }
5321: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5322: background: #DDEEDD;
5323: }
5324:
5325: div.LC_grade_show_problem,
5326: div.LC_grade_submissions,
5327: div.LC_grade_message_center,
5328: div.LC_grade_info_links,
5329: div.LC_grade_assign {
5330: margin: 5px;
5331: width: 99%;
5332: background: #FFFFFF;
5333: }
5334: div.LC_grade_show_problem_header,
5335: div.LC_grade_submissions_header,
5336: div.LC_grade_message_center_header,
5337: div.LC_grade_assign_header {
5338: font-weight: bold;
5339: font-size: large;
5340: }
5341: div.LC_grade_show_problem_problem,
5342: div.LC_grade_submissions_body,
5343: div.LC_grade_message_center_body,
5344: div.LC_grade_assign_body {
5345: border: 1px solid black;
5346: width: 99%;
5347: background: #FFFFFF;
5348: }
5349: span.LC_grade_check_note {
5350: font-weight: normal;
5351: font-size: medium;
5352: display: inline;
5353: position: absolute;
5354: right: 1em;
5355: }
5356:
5357: table.LC_scantron_action {
5358: width: 100%;
5359: }
5360: table.LC_scantron_action tr th {
5361: font-weight:bold;
5362: font-style:normal;
5363: }
5364: .LC_edit_problem_header,
5365: div.LC_edit_problem_footer {
5366: font-weight: normal;
5367: font-size: medium;
5368: margin: 2px;
5369: }
5370: div.LC_edit_problem_header,
5371: div.LC_edit_problem_header div,
5372: div.LC_edit_problem_footer,
5373: div.LC_edit_problem_footer div,
5374: div.LC_edit_problem_editxml_header,
5375: div.LC_edit_problem_editxml_header div {
5376: margin-top: 5px;
5377: }
5378: div.LC_edit_problem_header_edit_row {
5379: background: $tabbg;
5380: padding: 3px;
5381: margin-bottom: 5px;
5382: }
5383: div.LC_edit_problem_header_title {
5384: font-weight: bold;
5385: font-size: larger;
5386: background: $tabbg;
5387: padding: 3px;
5388: }
5389: table.LC_edit_problem_header_title {
5390: font-size: larger;
5391: font-weight: bold;
5392: width: 100%;
5393: border-color: $pgbg;
5394: border-style: solid;
5395: border-width: $border;
5396:
5397: background: $tabbg;
5398: border-collapse: collapse;
5399: padding: 0px
5400: }
5401:
5402: div.LC_edit_problem_discards {
5403: float: left;
5404: padding-bottom: 5px;
5405: }
5406: div.LC_edit_problem_saves {
5407: float: right;
5408: padding-bottom: 5px;
5409: }
5410: hr.LC_edit_problem_divide {
5411: clear: both;
5412: color: $tabbg;
5413: background-color: $tabbg;
5414: height: 3px;
5415: border: 0px;
5416: }
5417: img.stift{
5418: border-width:0;
5419: vertical-align:middle;
5420: }
5421:
5422: table#LC_mainmenu{
5423: margin-top:10px;
5424: width:80%;
5425:
5426: }
5427:
5428: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5429: vertical-align: top;
5430: width: 45%;
5431: }
5432: .LC_mainmenu_fieldset_category {
5433: color: $font;
5434: background: $pgbg;
5435: font-family: $sans;
5436: font-size: small;
5437: font-weight: bold;
5438: }
5439:
5440: /* ---- Remove when done ----
5441: # The following styles is part of the redesign of LON-CAPA and are
5442: # subject to change during this project.
5443: # Don't rely on their current functionality as they might be
5444: # changed or removed.
5445: # --------------------------*/
5446:
5447: a:hover,
5448: ol.smallMenu a:hover,
5449: ol#MenuBreadcrumbs a:hover,
5450: ul#TabMainMenuContent a:hover,
5451: .FormSectionClearButton input:hover{
5452: color:#BF2317;
5453: text-decoration:none;
5454: }
5455:
5456: h1 {
5457: padding:5px 10px 5px 0px;
5458: line-height:130%;
5459: }
5460:
5461: h2,h3,h4,h5,h6
5462: {
5463: margin:5px 0px 5px 0px;
5464: line-height:130%;
5465: }
5466: .hcell{
5467: padding:3px 15px 3px 15px;
5468: margin:0px;
5469: background-color:$tabbg;
5470: border-bottom:solid 1px $lg_border_color;
5471: }
5472: .noBorder {
5473: border:0px;
5474: }
5475: /*
5476: .bgLightGrey { background:URL(images/TabMenuBG.png) repeat-x left top; }
5477: .bgLightGreyYellow {background-color:#EFECE0;}
5478: */
5479:
5480:
5481: /* Main Header with discription of Person, Course, etc. */
5482: .HeadRight {
5483: text-align: right;
5484: float: right;
5485: margin: 0px;
5486: padding: 0px;
5487: right:0;
5488: position:absolute;
5489: overflow:hidden;
5490: }
5491:
5492: p {
5493: padding: 10px;
5494:
5495: }
5496: .FormSectionClearButton input {
5497: background-color:transparent;
5498: border:0px;
5499: cursor:pointer;
5500: text-decoration:underline;
5501: }
5502:
5503:
5504: dl,ul,div,fieldset {
5505: margin: 10px 10px 10px 0px;
5506: overflow:hidden;
5507: }
5508: ol.smallMenu {
5509: margin: 0px;
5510: }
5511:
5512: ol.smallMenu li {
5513: display: inline;
5514: padding: 5px 5px 0px 10px;
5515: vertical-align: top;
5516: }
5517:
5518: ol.smallMenu li img {
5519: vertical-align: bottom;
5520: }
5521:
5522: ol.smallMenu a {
5523: font-size: 90%;
5524: color: RGB(80, 80, 80);
5525: text-decoration: none;
5526: }
5527:
5528: ol#TabMainMenuContent {
5529:
5530: margin: 0px 0px 10px 0px;
5531: padding: 0px;
5532: }
5533:
5534: ol#TabMainMenuContent li {
5535: display: inline;
5536: vertical-align: bottom;
5537: border-bottom: solid 1px RGB(175, 175, 175);
5538: border-right: solid 1px RGB(175, 175, 175);
5539: padding: 5px 15px 5px 15px;
5540: margin-right:4px;
5541: line-height: 140%;
5542: font-weight: bold;
5543: overflow:hidden;
5544: /* background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left top;*/
5545: }
5546:
5547: ol#TabMainMenuContent li a{
5548: color: RGB(47, 47, 47);
5549: text-decoration: none;
5550: }
5551:
5552: ol#TabMainMenuContent div.columnSection {
5553: margin-bottom: 0px;
5554: }
5555:
5556: ol#MenuBreadcrumbs, ol#PathBreadcrumbs {
5557: border-top: solid 1px RGB(255, 255, 255);
5558: height: 20px;
5559: line-height: 20px;
5560: vertical-align: bottom;
5561: margin: 0px 0px 30px 0px;
5562: padding-left: 10px;
5563: list-style-position: inside;
5564: /* background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left
5565: top;*/
5566: }
5567:
5568: ol#MenuBreadcrumbs li, ol#PathBreadcrumbs li {
5569: /* background: url(images/pfeil_white.png) no-repeat left center;*/
5570: display: inline;
5571: padding: 0px 0px 0px 10px;
5572: vertical-align: bottom;
5573: overflow:hidden;
5574: }
5575:
5576: ol#MenuBreadcrumbs li a {
5577: text-decoration: none;
5578: font-size:90%;
5579: }
5580: ol#PathBreadcrumbs li a{
5581: text-decoration:none;
5582: font-size:100%;
5583: font-weight:bold;
5584: }
5585:
5586: .ContentBoxSpecial
5587: {
5588: border: solid 1px $lg_border_color;
5589: }
5590: .ContentBox {
5591: padding:10px;
5592: }
5593: .PopUp
5594: {
5595: padding:10px;
5596: border-left:solid 1px $lg_border_color;
5597: border-top:solid 1px $lg_border_color;
5598: border-bottom:outset 1px $lg_border_color;
5599: border-right:outset 1px $lg_border_color;
5600: display:none;
5601: position:absolute;
5602: right:0;
5603: background-color:white;
5604: z-index:5;
5605: }
5606:
5607: dl.ListStyleClean dt {
5608: padding-right: 5px;
5609: display: table-header-group;
5610: }
5611:
5612: dl.ListStyleClean dd {
5613: display: table-row;
5614: }
5615:
5616: .ListStyleClean,
5617: .ListStyleSimple,
5618: .ListStyleNormal,
5619: .ListStyleNormal_Border,
5620: .ListStyleSpecial
5621: {
5622: /*display:block; */
5623: list-style-position: inside;
5624: list-style-type: none;
5625: overflow: hidden;
5626: padding: 0px;
5627: }
5628:
5629: .ListStyleSimple li,
5630: .ListStyleSimple dd,
5631: .ListStyleNormal li,
5632: .ListStyleNormal dd,
5633: .ListStyleSpecial li,
5634: .ListStyleSpecial dd
5635: {
5636: margin: 0px;
5637: padding: 5px 5px 5px 10px;
5638: clear: both;
5639: }
5640:
5641: .ListStyleClean li,
5642: .ListStyleClean dd {
5643: padding-top: 0px;
5644: padding-bottom: 0px;
5645: }
5646:
5647: .ListStyleSimple dd,
5648: .ListStyleSimple li{
5649: border-bottom: solid 1px $lg_border_color;
5650: }
5651:
5652: .ListStyleSpecial li,
5653: .ListStyleSpecial dd {
5654: list-style-type: none;
5655: background-color: RGB(220, 220, 220);
5656: margin-bottom: 4px;
5657: }
5658:
5659: table.SimpleTable {
5660: margin:5px;
5661: border:solid 1px $lg_border_color;
5662: }
5663:
5664: table.SimpleTable tr {
5665: padding:0px;
5666: border:solid 1px $lg_border_color;
5667: }
5668: table.SimpleTable thead{
5669: background:rgb(220,220,220);
5670: }
5671:
5672: div.columnSection {
5673: display: block;
5674: clear: both;
5675: overflow: hidden;
5676: margin:0px;
5677: }
5678:
5679: div.columnSection>* {
5680: float: left;
5681: margin: 10px 20px 10px 0px;
5682: overflow:hidden;
5683: }
5684: div.columnSection > .ContentBox,
5685: div.columnSection > .ContentBoxSpecial
5686: {
5687: width: 400px;
5688:
5689: }
5690:
5691: .LC_loginpage_container {
5692: text-align:left;
5693: margin : 0 auto;
5694: width:65%;
5695: padding: 10px;
5696: height: auto;
5697: # background-color:#FFFFFF;
5698: background-color:$loginbg;
5699: border:1px solid #CCCCCC;
5700: }
5701:
5702:
5703: .LC_loginpage_loginContainer {
5704: float:left;
5705: width:60%;
5706: }
5707:
5708: .LC_loginpage_loginInfo {
5709: margin-top:20px;
5710: margin-left:20px;
5711: float:left;
5712: width:30%;
5713: border:1px solid #CCCCCC;
5714: padding:10px;
5715: }
5716:
5717: .LC_loginpage_space {
5718: clear:both;
5719: margin-bottom:20px;
5720: border-bottom: 1px solid #CCCCCC;
5721: }
5722:
5723: .LC_loginpage_fieldset{
5724: border: 1px solid #CCCCCC;
5725: margin: 0 auto;
5726: }
5727:
5728: .LC_loginpage_legend{
5729: padding: 2px;
5730: margin: 0px;
5731: font-size:14px;
5732: font-weight:bold;
5733: }
5734:
5735:
5736:
5737: END
5738: }
5739:
5740: =pod
5741:
5742: =item * &headtag()
5743:
5744: Returns a uniform footer for LON-CAPA web pages.
5745:
5746: Inputs: $title - optional title for the head
5747: $head_extra - optional extra HTML to put inside the <head>
5748: $args - optional arguments
5749: force_register - if is true call registerurl so the remote is
5750: informed
5751: redirect -> array ref of
5752: 1- seconds before redirect occurs
5753: 2- url to redirect to
5754: 3- whether the side effect should occur
5755: (side effect of setting
5756: $env{'internal.head.redirect'} to the url
5757: redirected too)
5758: domain -> force to color decorate a page for a specific
5759: domain
5760: function -> force usage of a specific rolish color scheme
5761: bgcolor -> override the default page bgcolor
5762: no_auto_mt_title
5763: -> prevent &mt()ing the title arg
5764:
5765: =cut
5766:
5767: sub headtag {
5768: my ($title,$head_extra,$args) = @_;
5769:
5770: my $function = $args->{'function'} || &get_users_function();
5771: my $domain = $args->{'domain'} || &determinedomain();
5772: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5773: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5774: $Apache::lonnet::perlvar{'lonVersion'},
5775: #time(),
5776: $env{'environment.color.timestamp'},
5777: $function,$domain,$bgcolor);
5778:
5779: $url = '/adm/css/'.&escape($url).'.css';
5780:
5781: my $result =
5782: '<head>'.
5783: &font_settings();
5784:
5785: if (!$args->{'frameset'}) {
5786: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5787: }
5788: if ($args->{'force_register'}) {
5789: $result .= &Apache::lonmenu::registerurl(1);
5790: }
5791: if (!$args->{'no_nav_bar'}
5792: && !$args->{'only_body'}
5793: && !$args->{'frameset'}) {
5794: $result .= &help_menu_js();
5795: }
5796:
5797: if (ref($args->{'redirect'})) {
5798: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5799: $url = &Apache::lonenc::check_encrypt($url);
5800: if (!$inhibit_continue) {
5801: $env{'internal.head.redirect'} = $url;
5802: }
5803: $result.=<<ADDMETA
5804: <meta http-equiv="pragma" content="no-cache" />
5805: <meta http-equiv="Refresh" content="$time; url=$url" />
5806: ADDMETA
5807: }
5808: if (!defined($title)) {
5809: $title = 'The LearningOnline Network with CAPA';
5810: }
5811: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5812: $result .= '<title> LON-CAPA '.$title.'</title>'
5813: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5814: .$head_extra;
5815: return $result;
5816: }
5817:
5818: =pod
5819:
5820: =item * &font_settings()
5821:
5822: Returns neccessary <meta> to set the proper encoding
5823:
5824: Inputs: none
5825:
5826: =cut
5827:
5828: sub font_settings {
5829: my $headerstring='';
5830: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5831: $headerstring.=
5832: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5833: }
5834: return $headerstring;
5835: }
5836:
5837: =pod
5838:
5839: =item * &xml_begin()
5840:
5841: Returns the needed doctype and <html>
5842:
5843: Inputs: none
5844:
5845: =cut
5846:
5847: sub xml_begin {
5848: my $output='';
5849:
5850: if ($env{'internal.start_page'}==1) {
5851: &Apache::lonhtmlcommon::init_htmlareafields();
5852: }
5853:
5854: if ($env{'browser.mathml'}) {
5855: $output='<?xml version="1.0"?>'
5856: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5857: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5858:
5859: # .'<!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">] >'
5860: .'<!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">'
5861: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5862: .'xmlns="http://www.w3.org/1999/xhtml">';
5863: } else {
5864: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
5865: }
5866: return $output;
5867: }
5868:
5869: =pod
5870:
5871: =item * &endheadtag()
5872:
5873: Returns a uniform </head> for LON-CAPA web pages.
5874:
5875: Inputs: none
5876:
5877: =cut
5878:
5879: sub endheadtag {
5880: return '</head>';
5881: }
5882:
5883: =pod
5884:
5885: =item * &head()
5886:
5887: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
5888:
5889: Inputs:
5890:
5891: =over 4
5892:
5893: $title - optional title for the page
5894:
5895: $head_extra - optional extra HTML to put inside the <head>
5896:
5897: =back
5898:
5899: =cut
5900:
5901: sub head {
5902: my ($title,$head_extra,$args) = @_;
5903: return &headtag($title,$head_extra,$args).&endheadtag();
5904: }
5905:
5906: =pod
5907:
5908: =item * &start_page()
5909:
5910: Returns a complete <html> .. <body> section for LON-CAPA web pages.
5911:
5912: Inputs:
5913:
5914: =over 4
5915:
5916: $title - optional title for the page
5917:
5918: $head_extra - optional extra HTML to incude inside the <head>
5919:
5920: $args - additional optional args supported are:
5921:
5922: =over 8
5923:
5924: only_body -> is true will set &bodytag() onlybodytag
5925: arg on
5926: no_nav_bar -> is true will set &bodytag() notopbar arg on
5927: add_entries -> additional attributes to add to the <body>
5928: domain -> force to color decorate a page for a
5929: specific domain
5930: function -> force usage of a specific rolish color
5931: scheme
5932: redirect -> see &headtag()
5933: bgcolor -> override the default page bg color
5934: js_ready -> return a string ready for being used in
5935: a javascript writeln
5936: html_encode -> return a string ready for being used in
5937: a html attribute
5938: force_register -> if is true will turn on the &bodytag()
5939: $forcereg arg
5940: body_title -> alternate text to use instead of $title
5941: in the title box that appears, this text
5942: is not auto translated like the $title is
5943: frameset -> if true will start with a <frameset>
5944: rather than <body>
5945: no_title -> if true the title bar won't be shown
5946: skip_phases -> hash ref of
5947: head -> skip the <html><head> generation
5948: body -> skip all <body> generation
5949: no_inline_link -> if true and in remote mode, don't show the
5950: 'Switch To Inline Menu' link
5951: no_auto_mt_title -> prevent &mt()ing the title arg
5952: inherit_jsmath -> when creating popup window in a page,
5953: should it have jsmath forced on by the
5954: current page
5955:
5956: =back
5957:
5958: =back
5959:
5960: =cut
5961:
5962: sub start_page {
5963: my ($title,$head_extra,$args) = @_;
5964: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
5965: my %head_args;
5966: foreach my $arg ('redirect','force_register','domain','function',
5967: 'bgcolor','frameset','no_nav_bar','only_body',
5968: 'no_auto_mt_title') {
5969: if (defined($args->{$arg})) {
5970: $head_args{$arg} = $args->{$arg};
5971: }
5972: }
5973:
5974: $env{'internal.start_page'}++;
5975: my $result;
5976: if (! exists($args->{'skip_phases'}{'head'}) ) {
5977: $result.=
5978: &xml_begin().
5979: &headtag($title,$head_extra,\%head_args).&endheadtag();
5980: }
5981:
5982: if (! exists($args->{'skip_phases'}{'body'}) ) {
5983: if ($args->{'frameset'}) {
5984: my $attr_string = &make_attr_string($args->{'force_register'},
5985: $args->{'add_entries'});
5986: $result .= "\n<frameset $attr_string>\n";
5987: } else {
5988: $result .=
5989: &bodytag($title,
5990: $args->{'function'}, $args->{'add_entries'},
5991: $args->{'only_body'}, $args->{'domain'},
5992: $args->{'force_register'}, $args->{'body_title'},
5993: $args->{'no_nav_bar'}, $args->{'bgcolor'},
5994: $args->{'no_title'}, $args->{'no_inline_link'},
5995: $args);
5996: }
5997: }
5998:
5999: if ($args->{'js_ready'}) {
6000: $result = &js_ready($result);
6001: }
6002: if ($args->{'html_encode'}) {
6003: $result = &html_encode($result);
6004: }
6005: return $result;
6006: }
6007:
6008:
6009: =pod
6010:
6011: =item * &head()
6012:
6013: Returns a complete </body></html> section for LON-CAPA web pages.
6014:
6015: Inputs: $args - additional optional args supported are:
6016: js_ready -> return a string ready for being used in
6017: a javascript writeln
6018: html_encode -> return a string ready for being used in
6019: a html attribute
6020: frameset -> if true will start with a <frameset>
6021: rather than <body>
6022: dicsussion -> if true will get discussion from
6023: lonxml::xmlend
6024: (you can pass the target and parser arguments
6025: through optional 'target' and 'parser' args
6026: to this routine)
6027:
6028: =cut
6029:
6030: sub end_page {
6031: my ($args) = @_;
6032: $env{'internal.end_page'}++;
6033: my $result;
6034: if ($args->{'discussion'}) {
6035: my ($target,$parser);
6036: if (ref($args->{'discussion'})) {
6037: ($target,$parser) =($args->{'discussion'}{'target'},
6038: $args->{'discussion'}{'parser'});
6039: }
6040: $result .= &Apache::lonxml::xmlend($target,$parser);
6041: }
6042:
6043: if ($args->{'frameset'}) {
6044: $result .= '</frameset>';
6045: } else {
6046: $result .= &endbodytag($args);
6047: }
6048: $result .= "\n</html>";
6049:
6050: if ($args->{'js_ready'}) {
6051: $result = &js_ready($result);
6052: }
6053:
6054: if ($args->{'html_encode'}) {
6055: $result = &html_encode($result);
6056: }
6057:
6058: return $result;
6059: }
6060:
6061: sub html_encode {
6062: my ($result) = @_;
6063:
6064: $result = &HTML::Entities::encode($result,'<>&"');
6065:
6066: return $result;
6067: }
6068: sub js_ready {
6069: my ($result) = @_;
6070:
6071: $result =~ s/[\n\r]/ /xmsg;
6072: $result =~ s/\\/\\\\/xmsg;
6073: $result =~ s/'/\\'/xmsg;
6074: $result =~ s{</}{<\\/}xmsg;
6075:
6076: return $result;
6077: }
6078:
6079: sub validate_page {
6080: if ( exists($env{'internal.start_page'})
6081: && $env{'internal.start_page'} > 1) {
6082: &Apache::lonnet::logthis('start_page called multiple times '.
6083: $env{'internal.start_page'}.' '.
6084: $ENV{'request.filename'});
6085: }
6086: if ( exists($env{'internal.end_page'})
6087: && $env{'internal.end_page'} > 1) {
6088: &Apache::lonnet::logthis('end_page called multiple times '.
6089: $env{'internal.end_page'}.' '.
6090: $env{'request.filename'});
6091: }
6092: if ( exists($env{'internal.start_page'})
6093: && ! exists($env{'internal.end_page'})) {
6094: &Apache::lonnet::logthis('start_page called without end_page '.
6095: $env{'request.filename'});
6096: }
6097: if ( ! exists($env{'internal.start_page'})
6098: && exists($env{'internal.end_page'})) {
6099: &Apache::lonnet::logthis('end_page called without start_page'.
6100: $env{'request.filename'});
6101: }
6102: }
6103:
6104: sub simple_error_page {
6105: my ($r,$title,$msg) = @_;
6106: my $page =
6107: &Apache::loncommon::start_page($title).
6108: &mt($msg).
6109: &Apache::loncommon::end_page();
6110: if (ref($r)) {
6111: $r->print($page);
6112: return;
6113: }
6114: return $page;
6115: }
6116:
6117: {
6118: my @row_count;
6119: sub start_data_table {
6120: my ($add_class) = @_;
6121: my $css_class = (join(' ','LC_data_table',$add_class));
6122: unshift(@row_count,0);
6123: return '<table class="'.$css_class.'">'."\n";
6124: }
6125:
6126: sub end_data_table {
6127: shift(@row_count);
6128: return '</table>'."\n";;
6129: }
6130:
6131: sub start_data_table_row {
6132: my ($add_class) = @_;
6133: $row_count[0]++;
6134: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6135: $css_class = (join(' ',$css_class,$add_class));
6136: return '<tr class="'.$css_class.'">'."\n";;
6137: }
6138:
6139: sub continue_data_table_row {
6140: my ($add_class) = @_;
6141: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6142: $css_class = (join(' ',$css_class,$add_class));
6143: return '<tr class="'.$css_class.'">'."\n";;
6144: }
6145:
6146: sub end_data_table_row {
6147: return '</tr>'."\n";;
6148: }
6149:
6150: sub start_data_table_empty_row {
6151: # $row_count[0]++;
6152: return '<tr class="LC_empty_row" >'."\n";;
6153: }
6154:
6155: sub end_data_table_empty_row {
6156: return '</tr>'."\n";;
6157: }
6158:
6159: sub start_data_table_header_row {
6160: return '<tr class="LC_header_row">'."\n";;
6161: }
6162:
6163: sub end_data_table_header_row {
6164: return '</tr>'."\n";;
6165: }
6166: }
6167:
6168: =pod
6169:
6170: =item * &inhibit_menu_check($arg)
6171:
6172: Checks for a inhibitmenu state and generates output to preserve it
6173:
6174: Inputs: $arg - can be any of
6175: - undef - in which case the return value is a string
6176: to add into arguments list of a uri
6177: - 'input' - in which case the return value is a HTML
6178: <form> <input> field of type hidden to
6179: preserve the value
6180: - a url - in which case the return value is the url with
6181: the neccesary cgi args added to preserve the
6182: inhibitmenu state
6183: - a ref to a url - no return value, but the string is
6184: updated to include the neccessary cgi
6185: args to preserve the inhibitmenu state
6186:
6187: =cut
6188:
6189: sub inhibit_menu_check {
6190: my ($arg) = @_;
6191: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6192: if ($arg eq 'input') {
6193: if ($env{'form.inhibitmenu'}) {
6194: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6195: } else {
6196: return
6197: }
6198: }
6199: if ($env{'form.inhibitmenu'}) {
6200: if (ref($arg)) {
6201: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6202: } elsif ($arg eq '') {
6203: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6204: } else {
6205: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6206: }
6207: }
6208: if (!ref($arg)) {
6209: return $arg;
6210: }
6211: }
6212:
6213: ###############################################
6214:
6215: =pod
6216:
6217: =back
6218:
6219: =head1 User Information Routines
6220:
6221: =over 4
6222:
6223: =item * &get_users_function()
6224:
6225: Used by &bodytag to determine the current users primary role.
6226: Returns either 'student','coordinator','admin', or 'author'.
6227:
6228: =cut
6229:
6230: ###############################################
6231: sub get_users_function {
6232: my $function = 'student';
6233: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
6234: $function='coordinator';
6235: }
6236: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6237: $function='admin';
6238: }
6239: if (($env{'request.role'}=~/^(au|ca)/) ||
6240: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6241: $function='author';
6242: }
6243: return $function;
6244: }
6245:
6246: ###############################################
6247:
6248: =pod
6249:
6250: =item * &check_user_status()
6251:
6252: Determines current status of supplied role for a
6253: specific user. Roles can be active, previous or future.
6254:
6255: Inputs:
6256: user's domain, user's username, course's domain,
6257: course's number, optional section ID.
6258:
6259: Outputs:
6260: role status: active, previous or future.
6261:
6262: =cut
6263:
6264: sub check_user_status {
6265: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6266: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6267: my @uroles = keys %userinfo;
6268: my $srchstr;
6269: my $active_chk = 'none';
6270: my $now = time;
6271: if (@uroles > 0) {
6272: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
6273: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6274: } else {
6275: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6276: }
6277: if (grep/^\Q$srchstr\E$/,@uroles) {
6278: my $role_end = 0;
6279: my $role_start = 0;
6280: $active_chk = 'active';
6281: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6282: $role_end = $1;
6283: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6284: $role_start = $1;
6285: }
6286: }
6287: if ($role_start > 0) {
6288: if ($now < $role_start) {
6289: $active_chk = 'future';
6290: }
6291: }
6292: if ($role_end > 0) {
6293: if ($now > $role_end) {
6294: $active_chk = 'previous';
6295: }
6296: }
6297: }
6298: }
6299: return $active_chk;
6300: }
6301:
6302: ###############################################
6303:
6304: =pod
6305:
6306: =item * &get_sections()
6307:
6308: Determines all the sections for a course including
6309: sections with students and sections containing other roles.
6310: Incoming parameters:
6311:
6312: 1. domain
6313: 2. course number
6314: 3. reference to array containing roles for which sections should
6315: be gathered (optional).
6316: 4. reference to array containing status types for which sections
6317: should be gathered (optional).
6318:
6319: If the third argument is undefined, sections are gathered for any role.
6320: If the fourth argument is undefined, sections are gathered for any status.
6321: Permissible values are 'active' or 'future' or 'previous'.
6322:
6323: Returns section hash (keys are section IDs, values are
6324: number of users in each section), subject to the
6325: optional roles filter, optional status filter
6326:
6327: =cut
6328:
6329: ###############################################
6330: sub get_sections {
6331: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6332: if (!defined($cdom) || !defined($cnum)) {
6333: my $cid = $env{'request.course.id'};
6334:
6335: return if (!defined($cid));
6336:
6337: $cdom = $env{'course.'.$cid.'.domain'};
6338: $cnum = $env{'course.'.$cid.'.num'};
6339: }
6340:
6341: my %sectioncount;
6342: my $now = time;
6343:
6344: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6345: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6346: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6347: my $status_index = &Apache::loncoursedata::CL_STATUS();
6348: my $start_index = &Apache::loncoursedata::CL_START();
6349: my $end_index = &Apache::loncoursedata::CL_END();
6350: my $status;
6351: while (my ($student,$data) = each(%$classlist)) {
6352: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6353: $data->[$status_index],
6354: $data->[$start_index],
6355: $data->[$end_index]);
6356: if ($stu_status eq 'Active') {
6357: $status = 'active';
6358: } elsif ($end < $now) {
6359: $status = 'previous';
6360: } elsif ($start > $now) {
6361: $status = 'future';
6362: }
6363: if ($section ne '-1' && $section !~ /^\s*$/) {
6364: if ((!defined($possible_status)) || (($status ne '') &&
6365: (grep/^\Q$status\E$/,@{$possible_status}))) {
6366: $sectioncount{$section}++;
6367: }
6368: }
6369: }
6370: }
6371: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6372: foreach my $user (sort(keys(%courseroles))) {
6373: if ($user !~ /^(\w{2})/) { next; }
6374: my ($role) = ($user =~ /^(\w{2})/);
6375: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6376: my ($section,$status);
6377: if ($role eq 'cr' &&
6378: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6379: $section=$1;
6380: }
6381: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6382: if (!defined($section) || $section eq '-1') { next; }
6383: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6384: if ($end == -1 && $start == -1) {
6385: next; #deleted role
6386: }
6387: if (!defined($possible_status)) {
6388: $sectioncount{$section}++;
6389: } else {
6390: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6391: $status = 'active';
6392: } elsif ($end < $now) {
6393: $status = 'future';
6394: } elsif ($start > $now) {
6395: $status = 'previous';
6396: }
6397: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6398: $sectioncount{$section}++;
6399: }
6400: }
6401: }
6402: return %sectioncount;
6403: }
6404:
6405: ###############################################
6406:
6407: =pod
6408:
6409: =item * &get_course_users()
6410:
6411: Retrieves usernames:domains for users in the specified course
6412: with specific role(s), and access status.
6413:
6414: Incoming parameters:
6415: 1. course domain
6416: 2. course number
6417: 3. access status: users must have - either active,
6418: previous, future, or all.
6419: 4. reference to array of permissible roles
6420: 5. reference to array of section restrictions (optional)
6421: 6. reference to results object (hash of hashes).
6422: 7. reference to optional userdata hash
6423: 8. reference to optional statushash
6424: 9. flag if privileged users (except those set to unhide in
6425: course settings) should be excluded
6426: Keys of top level results hash are roles.
6427: Keys of inner hashes are username:domain, with
6428: values set to access type.
6429: Optional userdata hash returns an array with arguments in the
6430: same order as loncoursedata::get_classlist() for student data.
6431:
6432: Optional statushash returns
6433:
6434: Entries for end, start, section and status are blank because
6435: of the possibility of multiple values for non-student roles.
6436:
6437: =cut
6438:
6439: ###############################################
6440:
6441: sub get_course_users {
6442: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6443: my %idx = ();
6444: my %seclists;
6445:
6446: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6447: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6448: $idx{end} = &Apache::loncoursedata::CL_END();
6449: $idx{start} = &Apache::loncoursedata::CL_START();
6450: $idx{id} = &Apache::loncoursedata::CL_ID();
6451: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6452: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6453: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6454:
6455: if (grep(/^st$/,@{$roles})) {
6456: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6457: my $now = time;
6458: foreach my $student (keys(%{$classlist})) {
6459: my $match = 0;
6460: my $secmatch = 0;
6461: my $section = $$classlist{$student}[$idx{section}];
6462: my $status = $$classlist{$student}[$idx{status}];
6463: if ($section eq '') {
6464: $section = 'none';
6465: }
6466: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6467: if (grep(/^all$/,@{$sections})) {
6468: $secmatch = 1;
6469: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6470: if (grep(/^none$/,@{$sections})) {
6471: $secmatch = 1;
6472: }
6473: } else {
6474: if (grep(/^\Q$section\E$/,@{$sections})) {
6475: $secmatch = 1;
6476: }
6477: }
6478: if (!$secmatch) {
6479: next;
6480: }
6481: }
6482: if (defined($$types{'active'})) {
6483: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6484: push(@{$$users{st}{$student}},'active');
6485: $match = 1;
6486: }
6487: }
6488: if (defined($$types{'previous'})) {
6489: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6490: push(@{$$users{st}{$student}},'previous');
6491: $match = 1;
6492: }
6493: }
6494: if (defined($$types{'future'})) {
6495: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6496: push(@{$$users{st}{$student}},'future');
6497: $match = 1;
6498: }
6499: }
6500: if ($match) {
6501: push(@{$seclists{$student}},$section);
6502: if (ref($userdata) eq 'HASH') {
6503: $$userdata{$student} = $$classlist{$student};
6504: }
6505: if (ref($statushash) eq 'HASH') {
6506: $statushash->{$student}{'st'}{$section} = $status;
6507: }
6508: }
6509: }
6510: }
6511: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6512: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6513: my $now = time;
6514: my %displaystatus = ( previous => 'Expired',
6515: active => 'Active',
6516: future => 'Future',
6517: );
6518: my %nothide;
6519: if ($hidepriv) {
6520: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6521: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6522: if ($user !~ /:/) {
6523: $nothide{join(':',split(/[\@]/,$user))}=1;
6524: } else {
6525: $nothide{$user} = 1;
6526: }
6527: }
6528: }
6529: foreach my $person (sort(keys(%coursepersonnel))) {
6530: my $match = 0;
6531: my $secmatch = 0;
6532: my $status;
6533: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6534: $user =~ s/:$//;
6535: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6536: if ($end == -1 || $start == -1) {
6537: next;
6538: }
6539: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6540: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6541: my ($uname,$udom) = split(/:/,$user);
6542: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6543: if (grep(/^all$/,@{$sections})) {
6544: $secmatch = 1;
6545: } elsif ($usec eq '') {
6546: if (grep(/^none$/,@{$sections})) {
6547: $secmatch = 1;
6548: }
6549: } else {
6550: if (grep(/^\Q$usec\E$/,@{$sections})) {
6551: $secmatch = 1;
6552: }
6553: }
6554: if (!$secmatch) {
6555: next;
6556: }
6557: }
6558: if ($usec eq '') {
6559: $usec = 'none';
6560: }
6561: if ($uname ne '' && $udom ne '') {
6562: if ($hidepriv) {
6563: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6564: (!$nothide{$uname.':'.$udom})) {
6565: next;
6566: }
6567: }
6568: if ($end > 0 && $end < $now) {
6569: $status = 'previous';
6570: } elsif ($start > $now) {
6571: $status = 'future';
6572: } else {
6573: $status = 'active';
6574: }
6575: foreach my $type (keys(%{$types})) {
6576: if ($status eq $type) {
6577: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6578: push(@{$$users{$role}{$user}},$type);
6579: }
6580: $match = 1;
6581: }
6582: }
6583: if (($match) && (ref($userdata) eq 'HASH')) {
6584: if (!exists($$userdata{$uname.':'.$udom})) {
6585: &get_user_info($udom,$uname,\%idx,$userdata);
6586: }
6587: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6588: push(@{$seclists{$uname.':'.$udom}},$usec);
6589: }
6590: if (ref($statushash) eq 'HASH') {
6591: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6592: }
6593: }
6594: }
6595: }
6596: }
6597: if (grep(/^ow$/,@{$roles})) {
6598: if ((defined($cdom)) && (defined($cnum))) {
6599: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6600: if ( defined($csettings{'internal.courseowner'}) ) {
6601: my $owner = $csettings{'internal.courseowner'};
6602: next if ($owner eq '');
6603: my ($ownername,$ownerdom);
6604: if ($owner =~ /^([^:]+):([^:]+)$/) {
6605: $ownername = $1;
6606: $ownerdom = $2;
6607: } else {
6608: $ownername = $owner;
6609: $ownerdom = $cdom;
6610: $owner = $ownername.':'.$ownerdom;
6611: }
6612: @{$$users{'ow'}{$owner}} = 'any';
6613: if (defined($userdata) &&
6614: !exists($$userdata{$owner})) {
6615: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6616: if (!grep(/^none$/,@{$seclists{$owner}})) {
6617: push(@{$seclists{$owner}},'none');
6618: }
6619: if (ref($statushash) eq 'HASH') {
6620: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6621: }
6622: }
6623: }
6624: }
6625: }
6626: foreach my $user (keys(%seclists)) {
6627: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6628: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6629: }
6630: }
6631: return;
6632: }
6633:
6634: sub get_user_info {
6635: my ($udom,$uname,$idx,$userdata) = @_;
6636: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6637: &plainname($uname,$udom,'lastname');
6638: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6639: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6640: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6641: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6642: return;
6643: }
6644:
6645: ###############################################
6646:
6647: =pod
6648:
6649: =item * &get_user_quota()
6650:
6651: Retrieves quota assigned for storage of portfolio files for a user
6652:
6653: Incoming parameters:
6654: 1. user's username
6655: 2. user's domain
6656:
6657: Returns:
6658: 1. Disk quota (in Mb) assigned to student.
6659: 2. (Optional) Type of setting: custom or default
6660: (individually assigned or default for user's
6661: institutional status).
6662: 3. (Optional) - User's institutional status (e.g., faculty, staff
6663: or student - types as defined in localenroll::inst_usertypes
6664: for user's domain, which determines default quota for user.
6665: 4. (Optional) - Default quota which would apply to the user.
6666:
6667: If a value has been stored in the user's environment,
6668: it will return that, otherwise it returns the maximal default
6669: defined for the user's instituional status(es) in the domain.
6670:
6671: =cut
6672:
6673: ###############################################
6674:
6675:
6676: sub get_user_quota {
6677: my ($uname,$udom) = @_;
6678: my ($quota,$quotatype,$settingstatus,$defquota);
6679: if (!defined($udom)) {
6680: $udom = $env{'user.domain'};
6681: }
6682: if (!defined($uname)) {
6683: $uname = $env{'user.name'};
6684: }
6685: if (($udom eq '' || $uname eq '') ||
6686: ($udom eq 'public') && ($uname eq 'public')) {
6687: $quota = 0;
6688: $quotatype = 'default';
6689: $defquota = 0;
6690: } else {
6691: my $inststatus;
6692: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6693: $quota = $env{'environment.portfolioquota'};
6694: $inststatus = $env{'environment.inststatus'};
6695: } else {
6696: my %userenv =
6697: &Apache::lonnet::get('environment',['portfolioquota',
6698: 'inststatus'],$udom,$uname);
6699: my ($tmp) = keys(%userenv);
6700: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6701: $quota = $userenv{'portfolioquota'};
6702: $inststatus = $userenv{'inststatus'};
6703: } else {
6704: undef(%userenv);
6705: }
6706: }
6707: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6708: if ($quota eq '') {
6709: $quota = $defquota;
6710: $quotatype = 'default';
6711: } else {
6712: $quotatype = 'custom';
6713: }
6714: }
6715: if (wantarray) {
6716: return ($quota,$quotatype,$settingstatus,$defquota);
6717: } else {
6718: return $quota;
6719: }
6720: }
6721:
6722: ###############################################
6723:
6724: =pod
6725:
6726: =item * &default_quota()
6727:
6728: Retrieves default quota assigned for storage of user portfolio files,
6729: given an (optional) user's institutional status.
6730:
6731: Incoming parameters:
6732: 1. domain
6733: 2. (Optional) institutional status(es). This is a : separated list of
6734: status types (e.g., faculty, staff, student etc.)
6735: which apply to the user for whom the default is being retrieved.
6736: If the institutional status string in undefined, the domain
6737: default quota will be returned.
6738:
6739: Returns:
6740: 1. Default disk quota (in Mb) for user portfolios in the domain.
6741: 2. (Optional) institutional type which determined the value of the
6742: default quota.
6743:
6744: If a value has been stored in the domain's configuration db,
6745: it will return that, otherwise it returns 20 (for backwards
6746: compatibility with domains which have not set up a configuration
6747: db file; the original statically defined portfolio quota was 20 Mb).
6748:
6749: If the user's status includes multiple types (e.g., staff and student),
6750: the largest default quota which applies to the user determines the
6751: default quota returned.
6752:
6753: =cut
6754:
6755: ###############################################
6756:
6757:
6758: sub default_quota {
6759: my ($udom,$inststatus) = @_;
6760: my ($defquota,$settingstatus);
6761: my %quotahash = &Apache::lonnet::get_dom('configuration',
6762: ['quotas'],$udom);
6763: if (ref($quotahash{'quotas'}) eq 'HASH') {
6764: if ($inststatus ne '') {
6765: my @statuses = split(/:/,$inststatus);
6766: foreach my $item (@statuses) {
6767: if ($quotahash{'quotas'}{$item} ne '') {
6768: if ($defquota eq '') {
6769: $defquota = $quotahash{'quotas'}{$item};
6770: $settingstatus = $item;
6771: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6772: $defquota = $quotahash{'quotas'}{$item};
6773: $settingstatus = $item;
6774: }
6775: }
6776: }
6777: }
6778: if ($defquota eq '') {
6779: $defquota = $quotahash{'quotas'}{'default'};
6780: $settingstatus = 'default';
6781: }
6782: } else {
6783: $settingstatus = 'default';
6784: $defquota = 20;
6785: }
6786: if (wantarray) {
6787: return ($defquota,$settingstatus);
6788: } else {
6789: return $defquota;
6790: }
6791: }
6792:
6793: sub get_secgrprole_info {
6794: my ($cdom,$cnum,$needroles,$type) = @_;
6795: my %sections_count = &get_sections($cdom,$cnum);
6796: my @sections = (sort {$a <=> $b} keys(%sections_count));
6797: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6798: my @groups = sort(keys(%curr_groups));
6799: my $allroles = [];
6800: my $rolehash;
6801: my $accesshash = {
6802: active => 'Currently has access',
6803: future => 'Will have future access',
6804: previous => 'Previously had access',
6805: };
6806: if ($needroles) {
6807: $rolehash = {'all' => 'all'};
6808: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6809: if (&Apache::lonnet::error(%user_roles)) {
6810: undef(%user_roles);
6811: }
6812: foreach my $item (keys(%user_roles)) {
6813: my ($role)=split(/\:/,$item,2);
6814: if ($role eq 'cr') { next; }
6815: if ($role =~ /^cr/) {
6816: $$rolehash{$role} = (split('/',$role))[3];
6817: } else {
6818: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
6819: }
6820: }
6821: foreach my $key (sort(keys(%{$rolehash}))) {
6822: push(@{$allroles},$key);
6823: }
6824: push (@{$allroles},'st');
6825: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
6826: }
6827: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
6828: }
6829:
6830: sub user_picker {
6831: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
6832: my $currdom = $dom;
6833: my %curr_selected = (
6834: srchin => 'dom',
6835: srchby => 'lastname',
6836: );
6837: my $srchterm;
6838: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
6839: if ($srch->{'srchby'} ne '') {
6840: $curr_selected{'srchby'} = $srch->{'srchby'};
6841: }
6842: if ($srch->{'srchin'} ne '') {
6843: $curr_selected{'srchin'} = $srch->{'srchin'};
6844: }
6845: if ($srch->{'srchtype'} ne '') {
6846: $curr_selected{'srchtype'} = $srch->{'srchtype'};
6847: }
6848: if ($srch->{'srchdomain'} ne '') {
6849: $currdom = $srch->{'srchdomain'};
6850: }
6851: $srchterm = $srch->{'srchterm'};
6852: }
6853: my %lt=&Apache::lonlocal::texthash(
6854: 'usr' => 'Search criteria',
6855: 'doma' => 'Domain/institution to search',
6856: 'uname' => 'username',
6857: 'lastname' => 'last name',
6858: 'lastfirst' => 'last name, first name',
6859: 'crs' => 'in this course',
6860: 'dom' => 'in selected LON-CAPA domain',
6861: 'alc' => 'all LON-CAPA',
6862: 'instd' => 'in institutional directory for selected domain',
6863: 'exact' => 'is',
6864: 'contains' => 'contains',
6865: 'begins' => 'begins with',
6866: 'youm' => "You must include some text to search for.",
6867: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
6868: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
6869: 'yomc' => "You must choose a domain when using an institutional directory search.",
6870: 'ymcd' => "You must choose a domain when using a domain search.",
6871: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
6872: 'whse' => "When searching by last,first you must include at least one character in the first name.",
6873: 'thfo' => "The following need to be corrected before the search can be run:",
6874: );
6875: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
6876: my $srchinsel = ' <select name="srchin">';
6877:
6878: my @srchins = ('crs','dom','alc','instd');
6879:
6880: foreach my $option (@srchins) {
6881: # FIXME 'alc' option unavailable until
6882: # loncreateuser::print_user_query_page()
6883: # has been completed.
6884: next if ($option eq 'alc');
6885: next if ($option eq 'crs' && !$env{'request.course.id'});
6886: if ($curr_selected{'srchin'} eq $option) {
6887: $srchinsel .= '
6888: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6889: } else {
6890: $srchinsel .= '
6891: <option value="'.$option.'">'.$lt{$option}.'</option>';
6892: }
6893: }
6894: $srchinsel .= "\n </select>\n";
6895:
6896: my $srchbysel = ' <select name="srchby">';
6897: foreach my $option ('lastname','lastfirst','uname') {
6898: if ($curr_selected{'srchby'} eq $option) {
6899: $srchbysel .= '
6900: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6901: } else {
6902: $srchbysel .= '
6903: <option value="'.$option.'">'.$lt{$option}.'</option>';
6904: }
6905: }
6906: $srchbysel .= "\n </select>\n";
6907:
6908: my $srchtypesel = ' <select name="srchtype">';
6909: foreach my $option ('begins','contains','exact') {
6910: if ($curr_selected{'srchtype'} eq $option) {
6911: $srchtypesel .= '
6912: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6913: } else {
6914: $srchtypesel .= '
6915: <option value="'.$option.'">'.$lt{$option}.'</option>';
6916: }
6917: }
6918: $srchtypesel .= "\n </select>\n";
6919:
6920: my ($newuserscript,$new_user_create);
6921:
6922: if ($forcenewuser) {
6923: if (ref($srch) eq 'HASH') {
6924: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
6925: if ($cancreate) {
6926: $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
6927: } else {
6928: my $helplink = ' href="javascript:helpMenu('."'display'".')"';
6929: my %usertypetext = (
6930: official => 'institutional',
6931: unofficial => 'non-institutional',
6932: );
6933: $new_user_create = '<br /><span class="LC_warning">'.&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.&mt('Contact the <a[_1]>helpdesk</a> for assistance.',$helplink).'</span><br /><br />';
6934: }
6935: }
6936: }
6937:
6938: $newuserscript = <<"ENDSCRIPT";
6939:
6940: function setSearch(createnew,callingForm) {
6941: if (createnew == 1) {
6942: for (var i=0; i<callingForm.srchby.length; i++) {
6943: if (callingForm.srchby.options[i].value == 'uname') {
6944: callingForm.srchby.selectedIndex = i;
6945: }
6946: }
6947: for (var i=0; i<callingForm.srchin.length; i++) {
6948: if ( callingForm.srchin.options[i].value == 'dom') {
6949: callingForm.srchin.selectedIndex = i;
6950: }
6951: }
6952: for (var i=0; i<callingForm.srchtype.length; i++) {
6953: if (callingForm.srchtype.options[i].value == 'exact') {
6954: callingForm.srchtype.selectedIndex = i;
6955: }
6956: }
6957: for (var i=0; i<callingForm.srchdomain.length; i++) {
6958: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
6959: callingForm.srchdomain.selectedIndex = i;
6960: }
6961: }
6962: }
6963: }
6964: ENDSCRIPT
6965:
6966: }
6967:
6968: my $output = <<"END_BLOCK";
6969: <script type="text/javascript">
6970: function validateEntry(callingForm) {
6971:
6972: var checkok = 1;
6973: var srchin;
6974: for (var i=0; i<callingForm.srchin.length; i++) {
6975: if ( callingForm.srchin[i].checked ) {
6976: srchin = callingForm.srchin[i].value;
6977: }
6978: }
6979:
6980: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
6981: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
6982: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
6983: var srchterm = callingForm.srchterm.value;
6984: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
6985: var msg = "";
6986:
6987: if (srchterm == "") {
6988: checkok = 0;
6989: msg += "$lt{'youm'}\\n";
6990: }
6991:
6992: if (srchtype== 'begins') {
6993: if (srchterm.length < 2) {
6994: checkok = 0;
6995: msg += "$lt{'thte'}\\n";
6996: }
6997: }
6998:
6999: if (srchtype== 'contains') {
7000: if (srchterm.length < 3) {
7001: checkok = 0;
7002: msg += "$lt{'thet'}\\n";
7003: }
7004: }
7005: if (srchin == 'instd') {
7006: if (srchdomain == '') {
7007: checkok = 0;
7008: msg += "$lt{'yomc'}\\n";
7009: }
7010: }
7011: if (srchin == 'dom') {
7012: if (srchdomain == '') {
7013: checkok = 0;
7014: msg += "$lt{'ymcd'}\\n";
7015: }
7016: }
7017: if (srchby == 'lastfirst') {
7018: if (srchterm.indexOf(",") == -1) {
7019: checkok = 0;
7020: msg += "$lt{'whus'}\\n";
7021: }
7022: if (srchterm.indexOf(",") == srchterm.length -1) {
7023: checkok = 0;
7024: msg += "$lt{'whse'}\\n";
7025: }
7026: }
7027: if (checkok == 0) {
7028: alert("$lt{'thfo'}\\n"+msg);
7029: return;
7030: }
7031: if (checkok == 1) {
7032: callingForm.submit();
7033: }
7034: }
7035:
7036: $newuserscript
7037:
7038: </script>
7039:
7040: $new_user_create
7041:
7042: <table>
7043: <tr>
7044: <td>$lt{'doma'}:</td>
7045: <td>$domform</td>
7046: </td>
7047: </tr>
7048: <tr>
7049: <td>$lt{'usr'}:</td>
7050: <td>$srchbysel
7051: $srchtypesel
7052: <input type="text" size="15" name="srchterm" value="$srchterm" />
7053: $srchinsel
7054: </td>
7055: </tr>
7056: </table>
7057: <br />
7058: END_BLOCK
7059:
7060: return $output;
7061: }
7062:
7063: sub user_rule_check {
7064: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7065: my $response;
7066: if (ref($usershash) eq 'HASH') {
7067: foreach my $user (keys(%{$usershash})) {
7068: my ($uname,$udom) = split(/:/,$user);
7069: next if ($udom eq '' || $uname eq '');
7070: my ($id,$newuser);
7071: if (ref($usershash->{$user}) eq 'HASH') {
7072: $newuser = $usershash->{$user}->{'newuser'};
7073: $id = $usershash->{$user}->{'id'};
7074: }
7075: my $inst_response;
7076: if (ref($checks) eq 'HASH') {
7077: if (defined($checks->{'username'})) {
7078: ($inst_response,%{$inst_results->{$user}}) =
7079: &Apache::lonnet::get_instuser($udom,$uname);
7080: } elsif (defined($checks->{'id'})) {
7081: ($inst_response,%{$inst_results->{$user}}) =
7082: &Apache::lonnet::get_instuser($udom,undef,$id);
7083: }
7084: } else {
7085: ($inst_response,%{$inst_results->{$user}}) =
7086: &Apache::lonnet::get_instuser($udom,$uname);
7087: return;
7088: }
7089: if (!$got_rules->{$udom}) {
7090: my %domconfig = &Apache::lonnet::get_dom('configuration',
7091: ['usercreation'],$udom);
7092: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7093: foreach my $item ('username','id') {
7094: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7095: $$curr_rules{$udom}{$item} =
7096: $domconfig{'usercreation'}{$item.'_rule'};
7097: }
7098: }
7099: }
7100: $got_rules->{$udom} = 1;
7101: }
7102: foreach my $item (keys(%{$checks})) {
7103: if (ref($$curr_rules{$udom}) eq 'HASH') {
7104: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7105: if (@{$$curr_rules{$udom}{$item}} > 0) {
7106: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7107: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7108: if ($rule_check{$rule}) {
7109: $$rulematch{$user}{$item} = $rule;
7110: if ($inst_response eq 'ok') {
7111: if (ref($inst_results) eq 'HASH') {
7112: if (ref($inst_results->{$user}) eq 'HASH') {
7113: if (keys(%{$inst_results->{$user}}) == 0) {
7114: $$alerts{$item}{$udom}{$uname} = 1;
7115: }
7116: }
7117: }
7118: }
7119: last;
7120: }
7121: }
7122: }
7123: }
7124: }
7125: }
7126: }
7127: }
7128: return;
7129: }
7130:
7131: sub user_rule_formats {
7132: my ($domain,$domdesc,$curr_rules,$check) = @_;
7133: my %text = (
7134: 'username' => 'Usernames',
7135: 'id' => 'IDs',
7136: );
7137: my $output;
7138: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7139: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7140: if (@{$ruleorder} > 0) {
7141: $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
7142: foreach my $rule (@{$ruleorder}) {
7143: if (ref($curr_rules) eq 'ARRAY') {
7144: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7145: if (ref($rules->{$rule}) eq 'HASH') {
7146: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7147: $rules->{$rule}{'desc'}.'</li>';
7148: }
7149: }
7150: }
7151: }
7152: $output .= '</ul>';
7153: }
7154: }
7155: return $output;
7156: }
7157:
7158: sub instrule_disallow_msg {
7159: my ($checkitem,$domdesc,$count,$mode) = @_;
7160: my $response;
7161: my %text = (
7162: item => 'username',
7163: items => 'usernames',
7164: match => 'matches',
7165: do => 'does',
7166: action => 'a username',
7167: one => 'one',
7168: );
7169: if ($count > 1) {
7170: $text{'item'} = 'usernames';
7171: $text{'match'} ='match';
7172: $text{'do'} = 'do';
7173: $text{'action'} = 'usernames',
7174: $text{'one'} = 'ones';
7175: }
7176: if ($checkitem eq 'id') {
7177: $text{'items'} = 'IDs';
7178: $text{'item'} = 'ID';
7179: $text{'action'} = 'an ID';
7180: if ($count > 1) {
7181: $text{'item'} = 'IDs';
7182: $text{'action'} = 'IDs';
7183: }
7184: }
7185: $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
7186: if ($mode eq 'upload') {
7187: if ($checkitem eq 'username') {
7188: $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7189: } elsif ($checkitem eq 'id') {
7190: $response .= &mt("Either upload a file which includes $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
7191: }
7192: } elsif ($mode eq 'selfcreate') {
7193: if ($checkitem eq 'id') {
7194: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
7195: }
7196: } else {
7197: if ($checkitem eq 'username') {
7198: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7199: } elsif ($checkitem eq 'id') {
7200: $response .= &mt("You must either choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
7201: }
7202: }
7203: return $response;
7204: }
7205:
7206: sub personal_data_fieldtitles {
7207: my %fieldtitles = &Apache::lonlocal::texthash (
7208: id => 'Student/Employee ID',
7209: permanentemail => 'E-mail address',
7210: lastname => 'Last Name',
7211: firstname => 'First Name',
7212: middlename => 'Middle Name',
7213: generation => 'Generation',
7214: gen => 'Generation',
7215: );
7216: return %fieldtitles;
7217: }
7218:
7219: sub sorted_inst_types {
7220: my ($dom) = @_;
7221: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7222: my $othertitle = &mt('All users');
7223: if ($env{'request.course.id'}) {
7224: $othertitle = &mt('Any users');
7225: }
7226: my @types;
7227: if (ref($order) eq 'ARRAY') {
7228: @types = @{$order};
7229: }
7230: if (@types == 0) {
7231: if (ref($usertypes) eq 'HASH') {
7232: @types = sort(keys(%{$usertypes}));
7233: }
7234: }
7235: if (keys(%{$usertypes}) > 0) {
7236: $othertitle = &mt('Other users');
7237: }
7238: return ($othertitle,$usertypes,\@types);
7239: }
7240:
7241: sub get_institutional_codes {
7242: my ($settings,$allcourses,$LC_code) = @_;
7243: # Get complete list of course sections to update
7244: my @currsections = ();
7245: my @currxlists = ();
7246: my $coursecode = $$settings{'internal.coursecode'};
7247:
7248: if ($$settings{'internal.sectionnums'} ne '') {
7249: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7250: }
7251:
7252: if ($$settings{'internal.crosslistings'} ne '') {
7253: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7254: }
7255:
7256: if (@currxlists > 0) {
7257: foreach (@currxlists) {
7258: if (m/^([^:]+):(\w*)$/) {
7259: unless (grep/^$1$/,@{$allcourses}) {
7260: push @{$allcourses},$1;
7261: $$LC_code{$1} = $2;
7262: }
7263: }
7264: }
7265: }
7266:
7267: if (@currsections > 0) {
7268: foreach (@currsections) {
7269: if (m/^(\w+):(\w*)$/) {
7270: my $sec = $coursecode.$1;
7271: my $lc_sec = $2;
7272: unless (grep/^$sec$/,@{$allcourses}) {
7273: push @{$allcourses},$sec;
7274: $$LC_code{$sec} = $lc_sec;
7275: }
7276: }
7277: }
7278: }
7279: return;
7280: }
7281:
7282: =pod
7283:
7284: =back
7285:
7286: =head1 HTTP Helpers
7287:
7288: =over 4
7289:
7290: =item * &get_unprocessed_cgi($query,$possible_names)
7291:
7292: Modify the %env hash to contain unprocessed CGI form parameters held in
7293: $query. The parameters listed in $possible_names (an array reference),
7294: will be set in $env{'form.name'} if they do not already exist.
7295:
7296: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7297: $possible_names is an ref to an array of form element names. As an example:
7298: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7299: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7300:
7301: =cut
7302:
7303: sub get_unprocessed_cgi {
7304: my ($query,$possible_names)= @_;
7305: # $Apache::lonxml::debug=1;
7306: foreach my $pair (split(/&/,$query)) {
7307: my ($name, $value) = split(/=/,$pair);
7308: $name = &unescape($name);
7309: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7310: $value =~ tr/+/ /;
7311: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7312: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7313: }
7314: }
7315: }
7316:
7317: =pod
7318:
7319: =item * &cacheheader()
7320:
7321: returns cache-controlling header code
7322:
7323: =cut
7324:
7325: sub cacheheader {
7326: unless ($env{'request.method'} eq 'GET') { return ''; }
7327: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7328: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7329: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7330: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7331: return $output;
7332: }
7333:
7334: =pod
7335:
7336: =item * &no_cache($r)
7337:
7338: specifies header code to not have cache
7339:
7340: =cut
7341:
7342: sub no_cache {
7343: my ($r) = @_;
7344: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7345: $env{'request.method'} ne 'GET') { return ''; }
7346: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7347: $r->no_cache(1);
7348: $r->header_out("Expires" => $date);
7349: $r->header_out("Pragma" => "no-cache");
7350: }
7351:
7352: sub content_type {
7353: my ($r,$type,$charset) = @_;
7354: if ($r) {
7355: # Note that printout.pl calls this with undef for $r.
7356: &no_cache($r);
7357: }
7358: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7359: unless ($charset) {
7360: $charset=&Apache::lonlocal::current_encoding;
7361: }
7362: if ($charset) { $type.='; charset='.$charset; }
7363: if ($r) {
7364: $r->content_type($type);
7365: } else {
7366: print("Content-type: $type\n\n");
7367: }
7368: }
7369:
7370: =pod
7371:
7372: =item * &add_to_env($name,$value)
7373:
7374: adds $name to the %env hash with value
7375: $value, if $name already exists, the entry is converted to an array
7376: reference and $value is added to the array.
7377:
7378: =cut
7379:
7380: sub add_to_env {
7381: my ($name,$value)=@_;
7382: if (defined($env{$name})) {
7383: if (ref($env{$name})) {
7384: #already have multiple values
7385: push(@{ $env{$name} },$value);
7386: } else {
7387: #first time seeing multiple values, convert hash entry to an arrayref
7388: my $first=$env{$name};
7389: undef($env{$name});
7390: push(@{ $env{$name} },$first,$value);
7391: }
7392: } else {
7393: $env{$name}=$value;
7394: }
7395: }
7396:
7397: =pod
7398:
7399: =item * &get_env_multiple($name)
7400:
7401: gets $name from the %env hash, it seemlessly handles the cases where multiple
7402: values may be defined and end up as an array ref.
7403:
7404: returns an array of values
7405:
7406: =cut
7407:
7408: sub get_env_multiple {
7409: my ($name) = @_;
7410: my @values;
7411: if (defined($env{$name})) {
7412: # exists is it an array
7413: if (ref($env{$name})) {
7414: @values=@{ $env{$name} };
7415: } else {
7416: $values[0]=$env{$name};
7417: }
7418: }
7419: return(@values);
7420: }
7421:
7422: sub ask_for_embedded_content {
7423: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
7424: my $upload_output = '
7425: <form name="upload_embedded" action="'.$actionurl.'"
7426: method="post" enctype="multipart/form-data">';
7427: $upload_output .= $state;
7428: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
7429:
7430: my $num = 0;
7431: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
7432: $upload_output .= &start_data_table_row().
7433: '<td>'.$embed_file.'</td><td>';
7434: if ($args->{'ignore_remote_references'}
7435: && $embed_file =~ m{^\w+://}) {
7436: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
7437: } elsif ($args->{'error_on_invalid_names'}
7438: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
7439:
7440: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
7441:
7442: } else {
7443: $upload_output .='
7444: <input name="embedded_item_'.$num.'" type="file" value="" />
7445: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
7446: my $attrib = join(':',@{$$allfiles{$embed_file}});
7447: $upload_output .=
7448: "\n\t\t".
7449: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
7450: $attrib.'" />';
7451: if (exists($$codebase{$embed_file})) {
7452: $upload_output .=
7453: "\n\t\t".
7454: '<input name="codebase_'.$num.'" type="hidden" value="'.
7455: &escape($$codebase{$embed_file}).'" />';
7456: }
7457: }
7458: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
7459: $num++;
7460: }
7461: $upload_output .= &Apache::loncommon::end_data_table().'<br />
7462: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
7463: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
7464: '.&mt('(only files for which a location has been provided will be uploaded)').'
7465: </form>';
7466: return $upload_output;
7467: }
7468:
7469: sub upload_embedded {
7470: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
7471: $current_disk_usage) = @_;
7472: my $output;
7473: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
7474: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
7475: my $orig_uploaded_filename =
7476: $env{'form.embedded_item_'.$i.'.filename'};
7477:
7478: $env{'form.embedded_orig_'.$i} =
7479: &unescape($env{'form.embedded_orig_'.$i});
7480: my ($path,$fname) =
7481: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
7482: # no path, whole string is fname
7483: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
7484:
7485: $path = $env{'form.currentpath'}.$path;
7486: $fname = &Apache::lonnet::clean_filename($fname);
7487: # See if there is anything left
7488: next if ($fname eq '');
7489:
7490: # Check if file already exists as a file or directory.
7491: my ($state,$msg);
7492: if ($context eq 'portfolio') {
7493: my $port_path = $dirpath;
7494: if ($group ne '') {
7495: $port_path = "groups/$group/$port_path";
7496: }
7497: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
7498: $dir_root,$port_path,$disk_quota,
7499: $current_disk_usage,$uname,$udom);
7500: if ($state eq 'will_exceed_quota'
7501: || $state eq 'file_locked'
7502: || $state eq 'file_exists' ) {
7503: $output .= $msg;
7504: next;
7505: }
7506: } elsif (($context eq 'author') || ($context eq 'testbank')) {
7507: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
7508: if ($state eq 'exists') {
7509: $output .= $msg;
7510: next;
7511: }
7512: }
7513: # Check if extension is valid
7514: if (($fname =~ /\.(\w+)$/) &&
7515: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
7516: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
7517: next;
7518: } elsif (($fname =~ /\.(\w+)$/) &&
7519: (!defined(&Apache::loncommon::fileembstyle($1)))) {
7520: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
7521: next;
7522: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
7523: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
7524: next;
7525: }
7526:
7527: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
7528: if ($context eq 'portfolio') {
7529: my $result=
7530: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
7531: $dirpath.$path);
7532: if ($result !~ m|^/uploaded/|) {
7533: $output .= '<span class="LC_error">'
7534: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
7535: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
7536: .'</span><br />';
7537: next;
7538: } else {
7539: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
7540: $path.$fname.'</span>').'</p>';
7541: }
7542: } else {
7543: # Save the file
7544: my $target = $env{'form.embedded_item_'.$i};
7545: my $fullpath = $dir_root.$dirpath.'/'.$path;
7546: my $dest = $fullpath.$fname;
7547: my $url = $url_root.$dirpath.'/'.$path.$fname;
7548: my @parts=split(/\//,$fullpath);
7549: my $count;
7550: my $filepath = $dir_root;
7551: for ($count=4;$count<=$#parts;$count++) {
7552: $filepath .= "/$parts[$count]";
7553: if ((-e $filepath)!=1) {
7554: mkdir($filepath,0770);
7555: }
7556: }
7557: my $fh;
7558: if (!open($fh,'>'.$dest)) {
7559: &Apache::lonnet::logthis('Failed to create '.$dest);
7560: $output .= '<span class="LC_error">'.
7561: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7562: '</span><br />';
7563: } else {
7564: if (!print $fh $env{'form.embedded_item_'.$i}) {
7565: &Apache::lonnet::logthis('Failed to write to '.$dest);
7566: $output .= '<span class="LC_error">'.
7567: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7568: '</span><br />';
7569: } else {
7570: if ($context eq 'testbank') {
7571: $output .= &mt('Embedded file uploaded successfully:').
7572: ' <a href="'.$url.'">'.
7573: $orig_uploaded_filename.'</a><br />';
7574: } else {
7575: $output .= '<span class=\"LC_fontsize_large\">'.
7576: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
7577: $orig_uploaded_filename.'</a>').'</span><br />';
7578: }
7579: }
7580: close($fh);
7581: }
7582: }
7583: }
7584: return $output;
7585: }
7586:
7587: sub check_for_existing {
7588: my ($path,$fname,$element) = @_;
7589: my ($state,$msg);
7590: if (-d $path.'/'.$fname) {
7591: $state = 'exists';
7592: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7593: } elsif (-e $path.'/'.$fname) {
7594: $state = 'exists';
7595: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7596: }
7597: if ($state eq 'exists') {
7598: $msg = '<span class="LC_error">'.$msg.'</span><br />';
7599: }
7600: return ($state,$msg);
7601: }
7602:
7603: sub check_for_upload {
7604: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
7605: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
7606: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
7607: my $getpropath = 1;
7608: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
7609: $getpropath);
7610: my $found_file = 0;
7611: my $locked_file = 0;
7612: foreach my $line (@dir_list) {
7613: my ($file_name)=split(/\&/,$line,2);
7614: if ($file_name eq $fname){
7615: $file_name = $path.$file_name;
7616: if ($group ne '') {
7617: $file_name = $group.$file_name;
7618: }
7619: $found_file = 1;
7620: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
7621: $locked_file = 1;
7622: }
7623: }
7624: }
7625: if (($current_disk_usage + $filesize) > $disk_quota){
7626: my $msg = '<span class="LC_error">'.
7627: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
7628: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
7629: return ('will_exceed_quota',$msg);
7630: } elsif ($found_file) {
7631: if ($locked_file) {
7632: my $msg = '<span class="LC_error">';
7633: $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
7634: $msg .= '</span><br />';
7635: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
7636: return ('file_locked',$msg);
7637: } else {
7638: my $msg = '<span class="LC_error">';
7639: $msg .= &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
7640: $msg .= '</span>';
7641: $msg .= '<br />';
7642: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
7643: return ('file_exists',$msg);
7644: }
7645: }
7646: }
7647:
7648:
7649: =pod
7650:
7651: =back
7652:
7653: =head1 CSV Upload/Handling functions
7654:
7655: =over 4
7656:
7657: =item * &upfile_store($r)
7658:
7659: Store uploaded file, $r should be the HTTP Request object,
7660: needs $env{'form.upfile'}
7661: returns $datatoken to be put into hidden field
7662:
7663: =cut
7664:
7665: sub upfile_store {
7666: my $r=shift;
7667: $env{'form.upfile'}=~s/\r/\n/gs;
7668: $env{'form.upfile'}=~s/\f/\n/gs;
7669: $env{'form.upfile'}=~s/\n+/\n/gs;
7670: $env{'form.upfile'}=~s/\n+$//gs;
7671:
7672: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7673: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7674: {
7675: my $datafile = $r->dir_config('lonDaemons').
7676: '/tmp/'.$datatoken.'.tmp';
7677: if ( open(my $fh,">$datafile") ) {
7678: print $fh $env{'form.upfile'};
7679: close($fh);
7680: }
7681: }
7682: return $datatoken;
7683: }
7684:
7685: =pod
7686:
7687: =item * &load_tmp_file($r)
7688:
7689: Load uploaded file from tmp, $r should be the HTTP Request object,
7690: needs $env{'form.datatoken'},
7691: sets $env{'form.upfile'} to the contents of the file
7692:
7693: =cut
7694:
7695: sub load_tmp_file {
7696: my $r=shift;
7697: my @studentdata=();
7698: {
7699: my $studentfile = $r->dir_config('lonDaemons').
7700: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7701: if ( open(my $fh,"<$studentfile") ) {
7702: @studentdata=<$fh>;
7703: close($fh);
7704: }
7705: }
7706: $env{'form.upfile'}=join('',@studentdata);
7707: }
7708:
7709: =pod
7710:
7711: =item * &upfile_record_sep()
7712:
7713: Separate uploaded file into records
7714: returns array of records,
7715: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7716:
7717: =cut
7718:
7719: sub upfile_record_sep {
7720: if ($env{'form.upfiletype'} eq 'xml') {
7721: } else {
7722: my @records;
7723: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7724: if ($line=~/^\s*$/) { next; }
7725: push(@records,$line);
7726: }
7727: return @records;
7728: }
7729: }
7730:
7731: =pod
7732:
7733: =item * &record_sep($record)
7734:
7735: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7736:
7737: =cut
7738:
7739: sub takeleft {
7740: my $index=shift;
7741: return substr('0000'.$index,-4,4);
7742: }
7743:
7744: sub record_sep {
7745: my $record=shift;
7746: my %components=();
7747: if ($env{'form.upfiletype'} eq 'xml') {
7748: } elsif ($env{'form.upfiletype'} eq 'space') {
7749: my $i=0;
7750: foreach my $field (split(/\s+/,$record)) {
7751: $field=~s/^(\"|\')//;
7752: $field=~s/(\"|\')$//;
7753: $components{&takeleft($i)}=$field;
7754: $i++;
7755: }
7756: } elsif ($env{'form.upfiletype'} eq 'tab') {
7757: my $i=0;
7758: foreach my $field (split(/\t/,$record)) {
7759: $field=~s/^(\"|\')//;
7760: $field=~s/(\"|\')$//;
7761: $components{&takeleft($i)}=$field;
7762: $i++;
7763: }
7764: } else {
7765: my $separator=',';
7766: if ($env{'form.upfiletype'} eq 'semisv') {
7767: $separator=';';
7768: }
7769: my $i=0;
7770: # the character we are looking for to indicate the end of a quote or a record
7771: my $looking_for=$separator;
7772: # do not add the characters to the fields
7773: my $ignore=0;
7774: # we just encountered a separator (or the beginning of the record)
7775: my $just_found_separator=1;
7776: # store the field we are working on here
7777: my $field='';
7778: # work our way through all characters in record
7779: foreach my $character ($record=~/(.)/g) {
7780: if ($character eq $looking_for) {
7781: if ($character ne $separator) {
7782: # Found the end of a quote, again looking for separator
7783: $looking_for=$separator;
7784: $ignore=1;
7785: } else {
7786: # Found a separator, store away what we got
7787: $components{&takeleft($i)}=$field;
7788: $i++;
7789: $just_found_separator=1;
7790: $ignore=0;
7791: $field='';
7792: }
7793: next;
7794: }
7795: # single or double quotation marks after a separator indicate beginning of a quote
7796: # we are now looking for the end of the quote and need to ignore separators
7797: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
7798: $looking_for=$character;
7799: next;
7800: }
7801: # ignore would be true after we reached the end of a quote
7802: if ($ignore) { next; }
7803: if (($just_found_separator) && ($character=~/\s/)) { next; }
7804: $field.=$character;
7805: $just_found_separator=0;
7806: }
7807: # catch the very last entry, since we never encountered the separator
7808: $components{&takeleft($i)}=$field;
7809: }
7810: return %components;
7811: }
7812:
7813: ######################################################
7814: ######################################################
7815:
7816: =pod
7817:
7818: =item * &upfile_select_html()
7819:
7820: Return HTML code to select a file from the users machine and specify
7821: the file type.
7822:
7823: =cut
7824:
7825: ######################################################
7826: ######################################################
7827: sub upfile_select_html {
7828: my %Types = (
7829: csv => &mt('CSV (comma separated values, spreadsheet)'),
7830: semisv => &mt('Semicolon separated values'),
7831: space => &mt('Space separated'),
7832: tab => &mt('Tabulator separated'),
7833: # xml => &mt('HTML/XML'),
7834: );
7835: my $Str = '<input type="file" name="upfile" size="50" />'.
7836: '<br />Type: <select name="upfiletype">';
7837: foreach my $type (sort(keys(%Types))) {
7838: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
7839: }
7840: $Str .= "</select>\n";
7841: return $Str;
7842: }
7843:
7844: sub get_samples {
7845: my ($records,$toget) = @_;
7846: my @samples=({});
7847: my $got=0;
7848: foreach my $rec (@$records) {
7849: my %temp = &record_sep($rec);
7850: if (! grep(/\S/, values(%temp))) { next; }
7851: if (%temp) {
7852: $samples[$got]=\%temp;
7853: $got++;
7854: if ($got == $toget) { last; }
7855: }
7856: }
7857: return \@samples;
7858: }
7859:
7860: ######################################################
7861: ######################################################
7862:
7863: =pod
7864:
7865: =item * &csv_print_samples($r,$records)
7866:
7867: Prints a table of sample values from each column uploaded $r is an
7868: Apache Request ref, $records is an arrayref from
7869: &Apache::loncommon::upfile_record_sep
7870:
7871: =cut
7872:
7873: ######################################################
7874: ######################################################
7875: sub csv_print_samples {
7876: my ($r,$records) = @_;
7877: my $samples = &get_samples($records,5);
7878:
7879: $r->print(&mt('Samples').'<br />'.&start_data_table().
7880: &start_data_table_header_row());
7881: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7882: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
7883: $r->print(&end_data_table_header_row());
7884: foreach my $hash (@$samples) {
7885: $r->print(&start_data_table_row());
7886: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7887: $r->print('<td>');
7888: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
7889: $r->print('</td>');
7890: }
7891: $r->print(&end_data_table_row());
7892: }
7893: $r->print(&end_data_table().'<br />'."\n");
7894: }
7895:
7896: ######################################################
7897: ######################################################
7898:
7899: =pod
7900:
7901: =item * &csv_print_select_table($r,$records,$d)
7902:
7903: Prints a table to create associations between values and table columns.
7904:
7905: $r is an Apache Request ref,
7906: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7907: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
7908:
7909: =cut
7910:
7911: ######################################################
7912: ######################################################
7913: sub csv_print_select_table {
7914: my ($r,$records,$d) = @_;
7915: my $i=0;
7916: my $samples = &get_samples($records,1);
7917: $r->print(&mt('Associate columns with student attributes.')."\n".
7918: &start_data_table().&start_data_table_header_row().
7919: '<th>'.&mt('Attribute').'</th>'.
7920: '<th>'.&mt('Column').'</th>'.
7921: &end_data_table_header_row()."\n");
7922: foreach my $array_ref (@$d) {
7923: my ($value,$display,$defaultcol)=@{ $array_ref };
7924: $r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
7925:
7926: $r->print('<td><select name=f'.$i.
7927: ' onchange="javascript:flip(this.form,'.$i.');">');
7928: $r->print('<option value="none"></option>');
7929: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7930: $r->print('<option value="'.$sample.'"'.
7931: ($sample eq $defaultcol ? ' selected="selected" ' : '').
7932: '>'.&mt('Column [_1]',($sample+1)).'</option>');
7933: }
7934: $r->print('</select></td>'.&end_data_table_row()."\n");
7935: $i++;
7936: }
7937: $r->print(&end_data_table());
7938: $i--;
7939: return $i;
7940: }
7941:
7942: ######################################################
7943: ######################################################
7944:
7945: =pod
7946:
7947: =item * &csv_samples_select_table($r,$records,$d)
7948:
7949: Prints a table of sample values from the upload and can make associate samples to internal names.
7950:
7951: $r is an Apache Request ref,
7952: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7953: $d is an array of 2 element arrays (internal name, displayed name)
7954:
7955: =cut
7956:
7957: ######################################################
7958: ######################################################
7959: sub csv_samples_select_table {
7960: my ($r,$records,$d) = @_;
7961: my $i=0;
7962: #
7963: my $max_samples = 5;
7964: my $samples = &get_samples($records,$max_samples);
7965: $r->print(&start_data_table().
7966: &start_data_table_header_row().'<th>'.
7967: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
7968: &end_data_table_header_row());
7969:
7970: foreach my $key (sort(keys(%{ $samples->[0] }))) {
7971: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
7972: ' onchange="javascript:flip(this.form,'.$i.');">');
7973: foreach my $option (@$d) {
7974: my ($value,$display,$defaultcol)=@{ $option };
7975: $r->print('<option value="'.$value.'"'.
7976: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
7977: $display.'</option>');
7978: }
7979: $r->print('</select></td><td>');
7980: foreach my $line (0..($max_samples-1)) {
7981: if (defined($samples->[$line]{$key})) {
7982: $r->print($samples->[$line]{$key}."<br />\n");
7983: }
7984: }
7985: $r->print('</td>'.&end_data_table_row());
7986: $i++;
7987: }
7988: $r->print(&end_data_table());
7989: $i--;
7990: return($i);
7991: }
7992:
7993: ######################################################
7994: ######################################################
7995:
7996: =pod
7997:
7998: =item * &clean_excel_name($name)
7999:
8000: Returns a replacement for $name which does not contain any illegal characters.
8001:
8002: =cut
8003:
8004: ######################################################
8005: ######################################################
8006: sub clean_excel_name {
8007: my ($name) = @_;
8008: $name =~ s/[:\*\?\/\\]//g;
8009: if (length($name) > 31) {
8010: $name = substr($name,0,31);
8011: }
8012: return $name;
8013: }
8014:
8015: =pod
8016:
8017: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8018:
8019: Returns either 1 or undef
8020:
8021: 1 if the part is to be hidden, undef if it is to be shown
8022:
8023: Arguments are:
8024:
8025: $id the id of the part to be checked
8026: $symb, optional the symb of the resource to check
8027: $udom, optional the domain of the user to check for
8028: $uname, optional the username of the user to check for
8029:
8030: =cut
8031:
8032: sub check_if_partid_hidden {
8033: my ($id,$symb,$udom,$uname) = @_;
8034: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8035: $symb,$udom,$uname);
8036: my $truth=1;
8037: #if the string starts with !, then the list is the list to show not hide
8038: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8039: my @hiddenlist=split(/,/,$hiddenparts);
8040: foreach my $checkid (@hiddenlist) {
8041: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8042: }
8043: return !$truth;
8044: }
8045:
8046:
8047: ############################################################
8048: ############################################################
8049:
8050: =pod
8051:
8052: =back
8053:
8054: =head1 cgi-bin script and graphing routines
8055:
8056: =over 4
8057:
8058: =item * &get_cgi_id()
8059:
8060: Inputs: none
8061:
8062: Returns an id which can be used to pass environment variables
8063: to various cgi-bin scripts. These environment variables will
8064: be removed from the users environment after a given time by
8065: the routine &Apache::lonnet::transfer_profile_to_env.
8066:
8067: =cut
8068:
8069: ############################################################
8070: ############################################################
8071: my $uniq=0;
8072: sub get_cgi_id {
8073: $uniq=($uniq+1)%100000;
8074: return (time.'_'.$$.'_'.$uniq);
8075: }
8076:
8077: ############################################################
8078: ############################################################
8079:
8080: =pod
8081:
8082: =item * &DrawBarGraph()
8083:
8084: Facilitates the plotting of data in a (stacked) bar graph.
8085: Puts plot definition data into the users environment in order for
8086: graph.png to plot it. Returns an <img> tag for the plot.
8087: The bars on the plot are labeled '1','2',...,'n'.
8088:
8089: Inputs:
8090:
8091: =over 4
8092:
8093: =item $Title: string, the title of the plot
8094:
8095: =item $xlabel: string, text describing the X-axis of the plot
8096:
8097: =item $ylabel: string, text describing the Y-axis of the plot
8098:
8099: =item $Max: scalar, the maximum Y value to use in the plot
8100: If $Max is < any data point, the graph will not be rendered.
8101:
8102: =item $colors: array ref holding the colors to be used for the data sets when
8103: they are plotted. If undefined, default values will be used.
8104:
8105: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8106:
8107: =item @Values: An array of array references. Each array reference holds data
8108: to be plotted in a stacked bar chart.
8109:
8110: =item If the final element of @Values is a hash reference the key/value
8111: pairs will be added to the graph definition.
8112:
8113: =back
8114:
8115: Returns:
8116:
8117: An <img> tag which references graph.png and the appropriate identifying
8118: information for the plot.
8119:
8120: =cut
8121:
8122: ############################################################
8123: ############################################################
8124: sub DrawBarGraph {
8125: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8126: #
8127: if (! defined($colors)) {
8128: $colors = ['#33ff00',
8129: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8130: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8131: ];
8132: }
8133: my $extra_settings = {};
8134: if (ref($Values[-1]) eq 'HASH') {
8135: $extra_settings = pop(@Values);
8136: }
8137: #
8138: my $identifier = &get_cgi_id();
8139: my $id = 'cgi.'.$identifier;
8140: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8141: return '';
8142: }
8143: #
8144: my @Labels;
8145: if (defined($labels)) {
8146: @Labels = @$labels;
8147: } else {
8148: for (my $i=0;$i<@{$Values[0]};$i++) {
8149: push (@Labels,$i+1);
8150: }
8151: }
8152: #
8153: my $NumBars = scalar(@{$Values[0]});
8154: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8155: my %ValuesHash;
8156: my $NumSets=1;
8157: foreach my $array (@Values) {
8158: next if (! ref($array));
8159: $ValuesHash{$id.'.data.'.$NumSets++} =
8160: join(',',@$array);
8161: }
8162: #
8163: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8164: if ($NumBars < 3) {
8165: $width = 120+$NumBars*32;
8166: $xskip = 1;
8167: $bar_width = 30;
8168: } elsif ($NumBars < 5) {
8169: $width = 120+$NumBars*20;
8170: $xskip = 1;
8171: $bar_width = 20;
8172: } elsif ($NumBars < 10) {
8173: $width = 120+$NumBars*15;
8174: $xskip = 1;
8175: $bar_width = 15;
8176: } elsif ($NumBars <= 25) {
8177: $width = 120+$NumBars*11;
8178: $xskip = 5;
8179: $bar_width = 8;
8180: } elsif ($NumBars <= 50) {
8181: $width = 120+$NumBars*8;
8182: $xskip = 5;
8183: $bar_width = 4;
8184: } else {
8185: $width = 120+$NumBars*8;
8186: $xskip = 5;
8187: $bar_width = 4;
8188: }
8189: #
8190: $Max = 1 if ($Max < 1);
8191: if ( int($Max) < $Max ) {
8192: $Max++;
8193: $Max = int($Max);
8194: }
8195: $Title = '' if (! defined($Title));
8196: $xlabel = '' if (! defined($xlabel));
8197: $ylabel = '' if (! defined($ylabel));
8198: $ValuesHash{$id.'.title'} = &escape($Title);
8199: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8200: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8201: $ValuesHash{$id.'.y_max_value'} = $Max;
8202: $ValuesHash{$id.'.NumBars'} = $NumBars;
8203: $ValuesHash{$id.'.NumSets'} = $NumSets;
8204: $ValuesHash{$id.'.PlotType'} = 'bar';
8205: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8206: $ValuesHash{$id.'.height'} = $height;
8207: $ValuesHash{$id.'.width'} = $width;
8208: $ValuesHash{$id.'.xskip'} = $xskip;
8209: $ValuesHash{$id.'.bar_width'} = $bar_width;
8210: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8211: #
8212: # Deal with other parameters
8213: while (my ($key,$value) = each(%$extra_settings)) {
8214: $ValuesHash{$id.'.'.$key} = $value;
8215: }
8216: #
8217: &Apache::lonnet::appenv(\%ValuesHash);
8218: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8219: }
8220:
8221: ############################################################
8222: ############################################################
8223:
8224: =pod
8225:
8226: =item * &DrawXYGraph()
8227:
8228: Facilitates the plotting of data in an XY graph.
8229: Puts plot definition data into the users environment in order for
8230: graph.png to plot it. Returns an <img> tag for the plot.
8231:
8232: Inputs:
8233:
8234: =over 4
8235:
8236: =item $Title: string, the title of the plot
8237:
8238: =item $xlabel: string, text describing the X-axis of the plot
8239:
8240: =item $ylabel: string, text describing the Y-axis of the plot
8241:
8242: =item $Max: scalar, the maximum Y value to use in the plot
8243: If $Max is < any data point, the graph will not be rendered.
8244:
8245: =item $colors: Array ref containing the hex color codes for the data to be
8246: plotted in. If undefined, default values will be used.
8247:
8248: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8249:
8250: =item $Ydata: Array ref containing Array refs.
8251: Each of the contained arrays will be plotted as a separate curve.
8252:
8253: =item %Values: hash indicating or overriding any default values which are
8254: passed to graph.png.
8255: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8256:
8257: =back
8258:
8259: Returns:
8260:
8261: An <img> tag which references graph.png and the appropriate identifying
8262: information for the plot.
8263:
8264: =cut
8265:
8266: ############################################################
8267: ############################################################
8268: sub DrawXYGraph {
8269: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8270: #
8271: # Create the identifier for the graph
8272: my $identifier = &get_cgi_id();
8273: my $id = 'cgi.'.$identifier;
8274: #
8275: $Title = '' if (! defined($Title));
8276: $xlabel = '' if (! defined($xlabel));
8277: $ylabel = '' if (! defined($ylabel));
8278: my %ValuesHash =
8279: (
8280: $id.'.title' => &escape($Title),
8281: $id.'.xlabel' => &escape($xlabel),
8282: $id.'.ylabel' => &escape($ylabel),
8283: $id.'.y_max_value'=> $Max,
8284: $id.'.labels' => join(',',@$Xlabels),
8285: $id.'.PlotType' => 'XY',
8286: );
8287: #
8288: if (defined($colors) && ref($colors) eq 'ARRAY') {
8289: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8290: }
8291: #
8292: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8293: return '';
8294: }
8295: my $NumSets=1;
8296: foreach my $array (@{$Ydata}){
8297: next if (! ref($array));
8298: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8299: }
8300: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8301: #
8302: # Deal with other parameters
8303: while (my ($key,$value) = each(%Values)) {
8304: $ValuesHash{$id.'.'.$key} = $value;
8305: }
8306: #
8307: &Apache::lonnet::appenv(\%ValuesHash);
8308: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8309: }
8310:
8311: ############################################################
8312: ############################################################
8313:
8314: =pod
8315:
8316: =item * &DrawXYYGraph()
8317:
8318: Facilitates the plotting of data in an XY graph with two Y axes.
8319: Puts plot definition data into the users environment in order for
8320: graph.png to plot it. Returns an <img> tag for the plot.
8321:
8322: Inputs:
8323:
8324: =over 4
8325:
8326: =item $Title: string, the title of the plot
8327:
8328: =item $xlabel: string, text describing the X-axis of the plot
8329:
8330: =item $ylabel: string, text describing the Y-axis of the plot
8331:
8332: =item $colors: Array ref containing the hex color codes for the data to be
8333: plotted in. If undefined, default values will be used.
8334:
8335: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8336:
8337: =item $Ydata1: The first data set
8338:
8339: =item $Min1: The minimum value of the left Y-axis
8340:
8341: =item $Max1: The maximum value of the left Y-axis
8342:
8343: =item $Ydata2: The second data set
8344:
8345: =item $Min2: The minimum value of the right Y-axis
8346:
8347: =item $Max2: The maximum value of the left Y-axis
8348:
8349: =item %Values: hash indicating or overriding any default values which are
8350: passed to graph.png.
8351: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8352:
8353: =back
8354:
8355: Returns:
8356:
8357: An <img> tag which references graph.png and the appropriate identifying
8358: information for the plot.
8359:
8360: =cut
8361:
8362: ############################################################
8363: ############################################################
8364: sub DrawXYYGraph {
8365: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8366: $Ydata2,$Min2,$Max2,%Values)=@_;
8367: #
8368: # Create the identifier for the graph
8369: my $identifier = &get_cgi_id();
8370: my $id = 'cgi.'.$identifier;
8371: #
8372: $Title = '' if (! defined($Title));
8373: $xlabel = '' if (! defined($xlabel));
8374: $ylabel = '' if (! defined($ylabel));
8375: my %ValuesHash =
8376: (
8377: $id.'.title' => &escape($Title),
8378: $id.'.xlabel' => &escape($xlabel),
8379: $id.'.ylabel' => &escape($ylabel),
8380: $id.'.labels' => join(',',@$Xlabels),
8381: $id.'.PlotType' => 'XY',
8382: $id.'.NumSets' => 2,
8383: $id.'.two_axes' => 1,
8384: $id.'.y1_max_value' => $Max1,
8385: $id.'.y1_min_value' => $Min1,
8386: $id.'.y2_max_value' => $Max2,
8387: $id.'.y2_min_value' => $Min2,
8388: );
8389: #
8390: if (defined($colors) && ref($colors) eq 'ARRAY') {
8391: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8392: }
8393: #
8394: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
8395: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
8396: return '';
8397: }
8398: my $NumSets=1;
8399: foreach my $array ($Ydata1,$Ydata2){
8400: next if (! ref($array));
8401: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8402: }
8403: #
8404: # Deal with other parameters
8405: while (my ($key,$value) = each(%Values)) {
8406: $ValuesHash{$id.'.'.$key} = $value;
8407: }
8408: #
8409: &Apache::lonnet::appenv(\%ValuesHash);
8410: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8411: }
8412:
8413: ############################################################
8414: ############################################################
8415:
8416: =pod
8417:
8418: =back
8419:
8420: =head1 Statistics helper routines?
8421:
8422: Bad place for them but what the hell.
8423:
8424: =over 4
8425:
8426: =item * &chartlink()
8427:
8428: Returns a link to the chart for a specific student.
8429:
8430: Inputs:
8431:
8432: =over 4
8433:
8434: =item $linktext: The text of the link
8435:
8436: =item $sname: The students username
8437:
8438: =item $sdomain: The students domain
8439:
8440: =back
8441:
8442: =back
8443:
8444: =cut
8445:
8446: ############################################################
8447: ############################################################
8448: sub chartlink {
8449: my ($linktext, $sname, $sdomain) = @_;
8450: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
8451: '&SelectedStudent='.&escape($sname.':'.$sdomain).
8452: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
8453: '">'.$linktext.'</a>';
8454: }
8455:
8456: #######################################################
8457: #######################################################
8458:
8459: =pod
8460:
8461: =head1 Course Environment Routines
8462:
8463: =over 4
8464:
8465: =item * &restore_course_settings()
8466:
8467: =item * &store_course_settings()
8468:
8469: Restores/Store indicated form parameters from the course environment.
8470: Will not overwrite existing values of the form parameters.
8471:
8472: Inputs:
8473: a scalar describing the data (e.g. 'chart', 'problem_analysis')
8474:
8475: a hash ref describing the data to be stored. For example:
8476:
8477: %Save_Parameters = ('Status' => 'scalar',
8478: 'chartoutputmode' => 'scalar',
8479: 'chartoutputdata' => 'scalar',
8480: 'Section' => 'array',
8481: 'Group' => 'array',
8482: 'StudentData' => 'array',
8483: 'Maps' => 'array');
8484:
8485: Returns: both routines return nothing
8486:
8487: =back
8488:
8489: =cut
8490:
8491: #######################################################
8492: #######################################################
8493: sub store_course_settings {
8494: return &store_settings($env{'request.course.id'},@_);
8495: }
8496:
8497: sub store_settings {
8498: # save to the environment
8499: # appenv the same items, just to be safe
8500: my $udom = $env{'user.domain'};
8501: my $uname = $env{'user.name'};
8502: my ($context,$prefix,$Settings) = @_;
8503: my %SaveHash;
8504: my %AppHash;
8505: while (my ($setting,$type) = each(%$Settings)) {
8506: my $basename = join('.','internal',$context,$prefix,$setting);
8507: my $envname = 'environment.'.$basename;
8508: if (exists($env{'form.'.$setting})) {
8509: # Save this value away
8510: if ($type eq 'scalar' &&
8511: (! exists($env{$envname}) ||
8512: $env{$envname} ne $env{'form.'.$setting})) {
8513: $SaveHash{$basename} = $env{'form.'.$setting};
8514: $AppHash{$envname} = $env{'form.'.$setting};
8515: } elsif ($type eq 'array') {
8516: my $stored_form;
8517: if (ref($env{'form.'.$setting})) {
8518: $stored_form = join(',',
8519: map {
8520: &escape($_);
8521: } sort(@{$env{'form.'.$setting}}));
8522: } else {
8523: $stored_form =
8524: &escape($env{'form.'.$setting});
8525: }
8526: # Determine if the array contents are the same.
8527: if ($stored_form ne $env{$envname}) {
8528: $SaveHash{$basename} = $stored_form;
8529: $AppHash{$envname} = $stored_form;
8530: }
8531: }
8532: }
8533: }
8534: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
8535: $udom,$uname);
8536: if ($put_result !~ /^(ok|delayed)/) {
8537: &Apache::lonnet::logthis('unable to save form parameters, '.
8538: 'got error:'.$put_result);
8539: }
8540: # Make sure these settings stick around in this session, too
8541: &Apache::lonnet::appenv(\%AppHash);
8542: return;
8543: }
8544:
8545: sub restore_course_settings {
8546: return &restore_settings($env{'request.course.id'},@_);
8547: }
8548:
8549: sub restore_settings {
8550: my ($context,$prefix,$Settings) = @_;
8551: while (my ($setting,$type) = each(%$Settings)) {
8552: next if (exists($env{'form.'.$setting}));
8553: my $envname = 'environment.internal.'.$context.'.'.$prefix.
8554: '.'.$setting;
8555: if (exists($env{$envname})) {
8556: if ($type eq 'scalar') {
8557: $env{'form.'.$setting} = $env{$envname};
8558: } elsif ($type eq 'array') {
8559: $env{'form.'.$setting} = [
8560: map {
8561: &unescape($_);
8562: } split(',',$env{$envname})
8563: ];
8564: }
8565: }
8566: }
8567: }
8568:
8569: #######################################################
8570: #######################################################
8571:
8572: =pod
8573:
8574: =head1 Domain E-mail Routines
8575:
8576: =over 4
8577:
8578: =item * &build_recipient_list()
8579:
8580: Build recipient lists for three types of e-mail:
8581: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
8582: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
8583:
8584: Inputs:
8585: defmail (scalar - email address of default recipient),
8586: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
8587: defdom (domain for which to retrieve configuration settings),
8588: origmail (scalar - email address of recipient from loncapa.conf,
8589: i.e., predates configuration by DC via domainprefs.pm
8590:
8591: Returns: comma separated list of addresses to which to send e-mail.
8592:
8593: =back
8594:
8595: =cut
8596:
8597: ############################################################
8598: ############################################################
8599: sub build_recipient_list {
8600: my ($defmail,$mailing,$defdom,$origmail) = @_;
8601: my @recipients;
8602: my $otheremails;
8603: my %domconfig =
8604: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
8605: if (ref($domconfig{'contacts'}) eq 'HASH') {
8606: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
8607: my @contacts = ('adminemail','supportemail');
8608: foreach my $item (@contacts) {
8609: if ($domconfig{'contacts'}{$mailing}{$item}) {
8610: my $addr = $domconfig{'contacts'}{$item};
8611: if (!grep(/^\Q$addr\E$/,@recipients)) {
8612: push(@recipients,$addr);
8613: }
8614: }
8615: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
8616: }
8617: }
8618: } elsif ($origmail ne '') {
8619: push(@recipients,$origmail);
8620: }
8621: if (defined($defmail)) {
8622: if ($defmail ne '') {
8623: push(@recipients,$defmail);
8624: }
8625: }
8626: if ($otheremails) {
8627: my @others;
8628: if ($otheremails =~ /,/) {
8629: @others = split(/,/,$otheremails);
8630: } else {
8631: push(@others,$otheremails);
8632: }
8633: foreach my $addr (@others) {
8634: if (!grep(/^\Q$addr\E$/,@recipients)) {
8635: push(@recipients,$addr);
8636: }
8637: }
8638: }
8639: my $recipientlist = join(',',@recipients);
8640: return $recipientlist;
8641: }
8642:
8643: ############################################################
8644: ############################################################
8645:
8646: =pod
8647:
8648: =head1 Course Catalog Routines
8649:
8650: =over 4
8651:
8652: =item * &gather_categories()
8653:
8654: Converts category definitions - keys of categories hash stored in
8655: coursecategories in configuration.db on the primary library server in a
8656: domain - to an array. Also generates javascript and idx hash used to
8657: generate Domain Coordinator interface for editing Course Categories.
8658:
8659: Inputs:
8660:
8661: categories (reference to hash of category definitions).
8662:
8663: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8664: categories and subcategories).
8665:
8666: idx (reference to hash of counters used in Domain Coordinator interface for
8667: editing Course Categories).
8668:
8669: jsarray (reference to array of categories used to create Javascript arrays for
8670: Domain Coordinator interface for editing Course Categories).
8671:
8672: Returns: nothing
8673:
8674: Side effects: populates cats, idx and jsarray.
8675:
8676: =cut
8677:
8678: sub gather_categories {
8679: my ($categories,$cats,$idx,$jsarray) = @_;
8680: my %counters;
8681: my $num = 0;
8682: foreach my $item (keys(%{$categories})) {
8683: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
8684: if ($container eq '' && $depth == 0) {
8685: $cats->[$depth][$categories->{$item}] = $cat;
8686: } else {
8687: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
8688: }
8689: my ($escitem,$tail) = split(/:/,$item,2);
8690: if ($counters{$tail} eq '') {
8691: $counters{$tail} = $num;
8692: $num ++;
8693: }
8694: if (ref($idx) eq 'HASH') {
8695: $idx->{$item} = $counters{$tail};
8696: }
8697: if (ref($jsarray) eq 'ARRAY') {
8698: push(@{$jsarray->[$counters{$tail}]},$item);
8699: }
8700: }
8701: return;
8702: }
8703:
8704: =pod
8705:
8706: =item * &extract_categories()
8707:
8708: Used to generate breadcrumb trails for course categories.
8709:
8710: Inputs:
8711:
8712: categories (reference to hash of category definitions).
8713:
8714: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8715: categories and subcategories).
8716:
8717: trails (reference to array of breacrumb trails for each category).
8718:
8719: allitems (reference to hash - key is category key
8720: (format: escaped(name):escaped(parent category):depth in hierarchy).
8721:
8722: idx (reference to hash of counters used in Domain Coordinator interface for
8723: editing Course Categories).
8724:
8725: jsarray (reference to array of categories used to create Javascript arrays for
8726: Domain Coordinator interface for editing Course Categories).
8727:
8728: subcats (reference to hash of arrays containing all subcategories within each
8729: category, -recursive)
8730:
8731: Returns: nothing
8732:
8733: Side effects: populates trails and allitems hash references.
8734:
8735: =cut
8736:
8737: sub extract_categories {
8738: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
8739: if (ref($categories) eq 'HASH') {
8740: &gather_categories($categories,$cats,$idx,$jsarray);
8741: if (ref($cats->[0]) eq 'ARRAY') {
8742: for (my $i=0; $i<@{$cats->[0]}; $i++) {
8743: my $name = $cats->[0][$i];
8744: my $item = &escape($name).'::0';
8745: my $trailstr;
8746: if ($name eq 'instcode') {
8747: $trailstr = &mt('Official courses (with institutional codes)');
8748: } else {
8749: $trailstr = $name;
8750: }
8751: if ($allitems->{$item} eq '') {
8752: push(@{$trails},$trailstr);
8753: $allitems->{$item} = scalar(@{$trails})-1;
8754: }
8755: my @parents = ($name);
8756: if (ref($cats->[1]{$name}) eq 'ARRAY') {
8757: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
8758: my $category = $cats->[1]{$name}[$j];
8759: if (ref($subcats) eq 'HASH') {
8760: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
8761: }
8762: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
8763: }
8764: } else {
8765: if (ref($subcats) eq 'HASH') {
8766: $subcats->{$item} = [];
8767: }
8768: }
8769: }
8770: }
8771: }
8772: return;
8773: }
8774:
8775: =pod
8776:
8777: =item *&recurse_categories()
8778:
8779: Recursively used to generate breadcrumb trails for course categories.
8780:
8781: Inputs:
8782:
8783: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8784: categories and subcategories).
8785:
8786: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
8787:
8788: category (current course category, for which breadcrumb trail is being generated).
8789:
8790: trails (reference to array of breadcrumb trails for each category).
8791:
8792: allitems (reference to hash - key is category key
8793: (format: escaped(name):escaped(parent category):depth in hierarchy).
8794:
8795: parents (array containing containers directories for current category,
8796: back to top level).
8797:
8798: Returns: nothing
8799:
8800: Side effects: populates trails and allitems hash references
8801:
8802: =cut
8803:
8804: sub recurse_categories {
8805: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
8806: my $shallower = $depth - 1;
8807: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
8808: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
8809: my $name = $cats->[$depth]{$category}[$k];
8810: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8811: my $trailstr = join(' -> ',(@{$parents},$category));
8812: if ($allitems->{$item} eq '') {
8813: push(@{$trails},$trailstr);
8814: $allitems->{$item} = scalar(@{$trails})-1;
8815: }
8816: my $deeper = $depth+1;
8817: push(@{$parents},$category);
8818: if (ref($subcats) eq 'HASH') {
8819: my $subcat = &escape($name).':'.$category.':'.$depth;
8820: for (my $j=@{$parents}; $j>=0; $j--) {
8821: my $higher;
8822: if ($j > 0) {
8823: $higher = &escape($parents->[$j]).':'.
8824: &escape($parents->[$j-1]).':'.$j;
8825: } else {
8826: $higher = &escape($parents->[$j]).'::'.$j;
8827: }
8828: push(@{$subcats->{$higher}},$subcat);
8829: }
8830: }
8831: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
8832: $subcats);
8833: pop(@{$parents});
8834: }
8835: } else {
8836: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8837: my $trailstr = join(' -> ',(@{$parents},$category));
8838: if ($allitems->{$item} eq '') {
8839: push(@{$trails},$trailstr);
8840: $allitems->{$item} = scalar(@{$trails})-1;
8841: }
8842: }
8843: return;
8844: }
8845:
8846: =pod
8847:
8848: =item *&assign_categories_table()
8849:
8850: Create a datatable for display of hierarchical categories in a domain,
8851: with checkboxes to allow a course to be categorized.
8852:
8853: Inputs:
8854:
8855: cathash - reference to hash of categories defined for the domain (from
8856: configuration.db)
8857:
8858: currcat - scalar with an & separated list of categories assigned to a course.
8859:
8860: Returns: $output (markup to be displayed)
8861:
8862: =cut
8863:
8864: sub assign_categories_table {
8865: my ($cathash,$currcat) = @_;
8866: my $output;
8867: if (ref($cathash) eq 'HASH') {
8868: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
8869: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
8870: $maxdepth = scalar(@cats);
8871: if (@cats > 0) {
8872: my $itemcount = 0;
8873: if (ref($cats[0]) eq 'ARRAY') {
8874: $output = &Apache::loncommon::start_data_table();
8875: my @currcategories;
8876: if ($currcat ne '') {
8877: @currcategories = split('&',$currcat);
8878: }
8879: for (my $i=0; $i<@{$cats[0]}; $i++) {
8880: my $parent = $cats[0][$i];
8881: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
8882: next if ($parent eq 'instcode');
8883: my $item = &escape($parent).'::0';
8884: my $checked = '';
8885: if (@currcategories > 0) {
8886: if (grep(/^\Q$item\E$/,@currcategories)) {
8887: $checked = ' checked="checked" ';
8888: }
8889: }
8890: $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
8891: '<input type="checkbox" name="usecategory" value="'.
8892: $item.'"'.$checked.' />'.$parent.'</span>'.
8893: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
8894: my $depth = 1;
8895: push(@path,$parent);
8896: $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
8897: pop(@path);
8898: $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
8899: $itemcount ++;
8900: }
8901: $output .= &Apache::loncommon::end_data_table();
8902: }
8903: }
8904: }
8905: return $output;
8906: }
8907:
8908: =pod
8909:
8910: =item *&assign_category_rows()
8911:
8912: Create a datatable row for display of nested categories in a domain,
8913: with checkboxes to allow a course to be categorized,called recursively.
8914:
8915: Inputs:
8916:
8917: itemcount - track row number for alternating colors
8918:
8919: cats - reference to array of arrays/hashes which encapsulates hierarchy of
8920: categories and subcategories.
8921:
8922: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
8923:
8924: parent - parent of current category item
8925:
8926: path - Array containing all categories back up through the hierarchy from the
8927: current category to the top level.
8928:
8929: currcategories - reference to array of current categories assigned to the course
8930:
8931: Returns: $output (markup to be displayed).
8932:
8933: =cut
8934:
8935: sub assign_category_rows {
8936: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
8937: my ($text,$name,$item,$chgstr);
8938: if (ref($cats) eq 'ARRAY') {
8939: my $maxdepth = scalar(@{$cats});
8940: if (ref($cats->[$depth]) eq 'HASH') {
8941: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
8942: my $numchildren = @{$cats->[$depth]{$parent}};
8943: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
8944: $text .= '<td><table class="LC_datatable">';
8945: for (my $j=0; $j<$numchildren; $j++) {
8946: $name = $cats->[$depth]{$parent}[$j];
8947: $item = &escape($name).':'.&escape($parent).':'.$depth;
8948: my $deeper = $depth+1;
8949: my $checked = '';
8950: if (ref($currcategories) eq 'ARRAY') {
8951: if (@{$currcategories} > 0) {
8952: if (grep(/^\Q$item\E$/,@{$currcategories})) {
8953: $checked = ' checked="checked" ';
8954: }
8955: }
8956: }
8957: $text .= '<tr><td><span class="LC_nobreak"><label>'.
8958: '<input type="checkbox" name="usecategory" value="'.
8959: $item.'"'.$checked.' />'.$name.'</label></span>'.
8960: '<input type="hidden" name="catname" value="'.$name.'" />'.
8961: '</td><td>';
8962: if (ref($path) eq 'ARRAY') {
8963: push(@{$path},$name);
8964: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
8965: pop(@{$path});
8966: }
8967: $text .= '</td></tr>';
8968: }
8969: $text .= '</table></td>';
8970: }
8971: }
8972: }
8973: return $text;
8974: }
8975:
8976: ############################################################
8977: ############################################################
8978:
8979:
8980: sub commit_customrole {
8981: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
8982: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
8983: ($start?', '.&mt('starting').' '.localtime($start):'').
8984: ($end?', ending '.localtime($end):'').': <b>'.
8985: &Apache::lonnet::assigncustomrole(
8986: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
8987: '</b><br />';
8988: return $output;
8989: }
8990:
8991: sub commit_standardrole {
8992: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
8993: my ($output,$logmsg,$linefeed);
8994: if ($context eq 'auto') {
8995: $linefeed = "\n";
8996: } else {
8997: $linefeed = "<br />\n";
8998: }
8999: if ($three eq 'st') {
9000: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9001: $one,$two,$sec,$context);
9002: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9003: ($result eq 'unknown_course') || ($result eq 'refused')) {
9004: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9005: } else {
9006: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9007: ($start?', '.&mt('starting').' '.localtime($start):'').
9008: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9009: if ($context eq 'auto') {
9010: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9011: } else {
9012: $output .= '<b>'.$result.'</b>'.$linefeed.
9013: &mt('Add to classlist').': <b>ok</b>';
9014: }
9015: $output .= $linefeed;
9016: }
9017: } else {
9018: $output = &mt('Assigning').' '.$three.' in '.$url.
9019: ($start?', '.&mt('starting').' '.localtime($start):'').
9020: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9021: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9022: if ($context eq 'auto') {
9023: $output .= $result.$linefeed;
9024: } else {
9025: $output .= '<b>'.$result.'</b>'.$linefeed;
9026: }
9027: }
9028: return $output;
9029: }
9030:
9031: sub commit_studentrole {
9032: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9033: my ($result,$linefeed,$oldsecurl,$newsecurl);
9034: if ($context eq 'auto') {
9035: $linefeed = "\n";
9036: } else {
9037: $linefeed = '<br />'."\n";
9038: }
9039: if (defined($one) && defined($two)) {
9040: my $cid=$one.'_'.$two;
9041: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9042: my $secchange = 0;
9043: my $expire_role_result;
9044: my $modify_section_result;
9045: if ($oldsec ne '-1') {
9046: if ($oldsec ne $sec) {
9047: $secchange = 1;
9048: my $now = time;
9049: my $uurl='/'.$cid;
9050: $uurl=~s/\_/\//g;
9051: if ($oldsec) {
9052: $uurl.='/'.$oldsec;
9053: }
9054: $oldsecurl = $uurl;
9055: $expire_role_result =
9056: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9057: if ($env{'request.course.sec'} ne '') {
9058: if ($expire_role_result eq 'refused') {
9059: my @roles = ('st');
9060: my @statuses = ('previous');
9061: my @roledoms = ($one);
9062: my $withsec = 1;
9063: my %roleshash =
9064: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9065: \@statuses,\@roles,\@roledoms,$withsec);
9066: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9067: my ($oldstart,$oldend) =
9068: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9069: if ($oldend > 0 && $oldend <= $now) {
9070: $expire_role_result = 'ok';
9071: }
9072: }
9073: }
9074: }
9075: $result = $expire_role_result;
9076: }
9077: }
9078: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9079: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9080: if ($modify_section_result =~ /^ok/) {
9081: if ($secchange == 1) {
9082: if ($sec eq '') {
9083: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9084: } else {
9085: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9086: }
9087: } elsif ($oldsec eq '-1') {
9088: if ($sec eq '') {
9089: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9090: } else {
9091: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9092: }
9093: } else {
9094: if ($sec eq '') {
9095: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9096: } else {
9097: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9098: }
9099: }
9100: } else {
9101: if ($secchange) {
9102: $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
9103: } else {
9104: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9105: }
9106: }
9107: $result = $modify_section_result;
9108: } elsif ($secchange == 1) {
9109: if ($oldsec eq '') {
9110: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9111: } else {
9112: $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
9113: }
9114: if ($expire_role_result eq 'refused') {
9115: my $newsecurl = '/'.$cid;
9116: $newsecurl =~ s/\_/\//g;
9117: if ($sec ne '') {
9118: $newsecurl.='/'.$sec;
9119: }
9120: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9121: if ($sec eq '') {
9122: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
9123: } else {
9124: $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
9125: }
9126: }
9127: }
9128: }
9129: } else {
9130: $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
9131: $result = "error: incomplete course id\n";
9132: }
9133: return $result;
9134: }
9135:
9136: ############################################################
9137: ############################################################
9138:
9139: sub check_clone {
9140: my ($args,$linefeed) = @_;
9141: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9142: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9143: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9144: my $clonemsg;
9145: my $can_clone = 0;
9146:
9147: if ($clonehome eq 'no_host') {
9148: $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
9149: } else {
9150: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9151: if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
9152: $can_clone = 1;
9153: } else {
9154: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9155: $args->{'clonedomain'},$args->{'clonecourse'});
9156: my @cloners = split(/,/,$clonehash{'cloners'});
9157: if (grep(/^\*$/,@cloners)) {
9158: $can_clone = 1;
9159: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9160: $can_clone = 1;
9161: } else {
9162: my %roleshash =
9163: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9164: $args->{'ccdomain'},
9165: 'userroles',['active'],['cc'],
9166: [$args->{'clonedomain'}]);
9167: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9168: $can_clone = 1;
9169: } else {
9170: $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
9171: }
9172: }
9173: }
9174: }
9175: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9176: }
9177:
9178: sub construct_course {
9179: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
9180: my $outcome;
9181: my $linefeed = '<br />'."\n";
9182: if ($context eq 'auto') {
9183: $linefeed = "\n";
9184: }
9185:
9186: #
9187: # Are we cloning?
9188: #
9189: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9190: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9191: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9192: if ($context ne 'auto') {
9193: if ($clonemsg ne '') {
9194: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9195: }
9196: }
9197: $outcome .= $clonemsg.$linefeed;
9198:
9199: if (!$can_clone) {
9200: return (0,$outcome);
9201: }
9202: }
9203:
9204: #
9205: # Open course
9206: #
9207: my $crstype = lc($args->{'crstype'});
9208: my %cenv=();
9209: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9210: $args->{'cdescr'},
9211: $args->{'curl'},
9212: $args->{'course_home'},
9213: $args->{'nonstandard'},
9214: $args->{'crscode'},
9215: $args->{'ccuname'}.':'.
9216: $args->{'ccdomain'},
9217: $args->{'crstype'});
9218:
9219: # Note: The testing routines depend on this being output; see
9220: # Utils::Course. This needs to at least be output as a comment
9221: # if anyone ever decides to not show this, and Utils::Course::new
9222: # will need to be suitably modified.
9223: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9224: #
9225: # Check if created correctly
9226: #
9227: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9228: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9229: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9230:
9231: #
9232: # Do the cloning
9233: #
9234: if ($can_clone && $cloneid) {
9235: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9236: if ($context ne 'auto') {
9237: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9238: }
9239: $outcome .= $clonemsg.$linefeed;
9240: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9241: # Copy all files
9242: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9243: # Restore URL
9244: $cenv{'url'}=$oldcenv{'url'};
9245: # Restore title
9246: $cenv{'description'}=$oldcenv{'description'};
9247: # Mark as cloned
9248: $cenv{'clonedfrom'}=$cloneid;
9249: # Need to clone grading mode
9250: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9251: $cenv{'grading'}=$newenv{'grading'};
9252: # Do not clone these environment entries
9253: &Apache::lonnet::del('environment',
9254: ['default_enrollment_start_date',
9255: 'default_enrollment_end_date',
9256: 'question.email',
9257: 'policy.email',
9258: 'comment.email',
9259: 'pch.users.denied',
9260: 'plc.users.denied'],
9261: $$crsudom,$$crsunum);
9262: }
9263:
9264: #
9265: # Set environment (will override cloned, if existing)
9266: #
9267: my @sections = ();
9268: my @xlists = ();
9269: if ($args->{'crstype'}) {
9270: $cenv{'type'}=$args->{'crstype'};
9271: }
9272: if ($args->{'crsid'}) {
9273: $cenv{'courseid'}=$args->{'crsid'};
9274: }
9275: if ($args->{'crscode'}) {
9276: $cenv{'internal.coursecode'}=$args->{'crscode'};
9277: }
9278: if ($args->{'crsquota'} ne '') {
9279: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9280: } else {
9281: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9282: }
9283: if ($args->{'ccuname'}) {
9284: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9285: ':'.$args->{'ccdomain'};
9286: } else {
9287: $cenv{'internal.courseowner'} = $args->{'curruser'};
9288: }
9289: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9290: if ($args->{'crssections'}) {
9291: $cenv{'internal.sectionnums'} = '';
9292: if ($args->{'crssections'} =~ m/,/) {
9293: @sections = split/,/,$args->{'crssections'};
9294: } else {
9295: $sections[0] = $args->{'crssections'};
9296: }
9297: if (@sections > 0) {
9298: foreach my $item (@sections) {
9299: my ($sec,$gp) = split/:/,$item;
9300: my $class = $args->{'crscode'}.$sec;
9301: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9302: $cenv{'internal.sectionnums'} .= $item.',';
9303: unless ($addcheck eq 'ok') {
9304: push @badclasses, $class;
9305: }
9306: }
9307: $cenv{'internal.sectionnums'} =~ s/,$//;
9308: }
9309: }
9310: # do not hide course coordinator from staff listing,
9311: # even if privileged
9312: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9313: # add crosslistings
9314: if ($args->{'crsxlist'}) {
9315: $cenv{'internal.crosslistings'}='';
9316: if ($args->{'crsxlist'} =~ m/,/) {
9317: @xlists = split/,/,$args->{'crsxlist'};
9318: } else {
9319: $xlists[0] = $args->{'crsxlist'};
9320: }
9321: if (@xlists > 0) {
9322: foreach my $item (@xlists) {
9323: my ($xl,$gp) = split/:/,$item;
9324: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9325: $cenv{'internal.crosslistings'} .= $item.',';
9326: unless ($addcheck eq 'ok') {
9327: push @badclasses, $xl;
9328: }
9329: }
9330: $cenv{'internal.crosslistings'} =~ s/,$//;
9331: }
9332: }
9333: if ($args->{'autoadds'}) {
9334: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9335: }
9336: if ($args->{'autodrops'}) {
9337: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9338: }
9339: # check for notification of enrollment changes
9340: my @notified = ();
9341: if ($args->{'notify_owner'}) {
9342: if ($args->{'ccuname'} ne '') {
9343: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9344: }
9345: }
9346: if ($args->{'notify_dc'}) {
9347: if ($uname ne '') {
9348: push(@notified,$uname.':'.$udom);
9349: }
9350: }
9351: if (@notified > 0) {
9352: my $notifylist;
9353: if (@notified > 1) {
9354: $notifylist = join(',',@notified);
9355: } else {
9356: $notifylist = $notified[0];
9357: }
9358: $cenv{'internal.notifylist'} = $notifylist;
9359: }
9360: if (@badclasses > 0) {
9361: my %lt=&Apache::lonlocal::texthash(
9362: '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',
9363: 'dnhr' => 'does not have rights to access enrollment in these classes',
9364: 'adby' => 'as determined by the policies of your institution on access to official classlists'
9365: );
9366: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
9367: ' ('.$lt{'adby'}.')';
9368: if ($context eq 'auto') {
9369: $outcome .= $badclass_msg.$linefeed;
9370: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
9371: foreach my $item (@badclasses) {
9372: if ($context eq 'auto') {
9373: $outcome .= " - $item\n";
9374: } else {
9375: $outcome .= "<li>$item</li>\n";
9376: }
9377: }
9378: if ($context eq 'auto') {
9379: $outcome .= $linefeed;
9380: } else {
9381: $outcome .= "</ul><br /><br /></div>\n";
9382: }
9383: }
9384: }
9385: if ($args->{'no_end_date'}) {
9386: $args->{'endaccess'} = 0;
9387: }
9388: $cenv{'internal.autostart'}=$args->{'enrollstart'};
9389: $cenv{'internal.autoend'}=$args->{'enrollend'};
9390: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
9391: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
9392: if ($args->{'showphotos'}) {
9393: $cenv{'internal.showphotos'}=$args->{'showphotos'};
9394: }
9395: $cenv{'internal.authtype'} = $args->{'authtype'};
9396: $cenv{'internal.autharg'} = $args->{'autharg'};
9397: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
9398: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
9399: my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student');
9400: if ($context eq 'auto') {
9401: $outcome .= $krb_msg;
9402: } else {
9403: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
9404: }
9405: $outcome .= $linefeed;
9406: }
9407: }
9408: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
9409: if ($args->{'setpolicy'}) {
9410: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9411: }
9412: if ($args->{'setcontent'}) {
9413: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9414: }
9415: }
9416: if ($args->{'reshome'}) {
9417: $cenv{'reshome'}=$args->{'reshome'}.'/';
9418: $cenv{'reshome'}=~s/\/+$/\//;
9419: }
9420: #
9421: # course has keyed access
9422: #
9423: if ($args->{'setkeys'}) {
9424: $cenv{'keyaccess'}='yes';
9425: }
9426: # if specified, key authority is not course, but user
9427: # only active if keyaccess is yes
9428: if ($args->{'keyauth'}) {
9429: my ($user,$domain) = split(':',$args->{'keyauth'});
9430: $user = &LONCAPA::clean_username($user);
9431: $domain = &LONCAPA::clean_username($domain);
9432: if ($user ne '' && $domain ne '') {
9433: $cenv{'keyauth'}=$user.':'.$domain;
9434: }
9435: }
9436:
9437: if ($args->{'disresdis'}) {
9438: $cenv{'pch.roles.denied'}='st';
9439: }
9440: if ($args->{'disablechat'}) {
9441: $cenv{'plc.roles.denied'}='st';
9442: }
9443:
9444: # Record we've not yet viewed the Course Initialization Helper for this
9445: # course
9446: $cenv{'course.helper.not.run'} = 1;
9447: #
9448: # Use new Randomseed
9449: #
9450: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
9451: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
9452: #
9453: # The encryption code and receipt prefix for this course
9454: #
9455: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
9456: $cenv{'internal.encpref'}=100+int(9*rand(99));
9457: #
9458: # By default, use standard grading
9459: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
9460:
9461: $outcome .= $linefeed.&mt('Setting environment').': '.
9462: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
9463: #
9464: # Open all assignments
9465: #
9466: if ($args->{'openall'}) {
9467: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
9468: my %storecontent = ($storeunder => time,
9469: $storeunder.'.type' => 'date_start');
9470:
9471: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
9472: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
9473: }
9474: #
9475: # Set first page
9476: #
9477: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
9478: || ($cloneid)) {
9479: use LONCAPA::map;
9480: $outcome .= &mt('Setting first resource').': ';
9481:
9482: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
9483: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
9484:
9485: $outcome .= ($fatal?$errtext:'read ok').' - ';
9486: my $title; my $url;
9487: if ($args->{'firstres'} eq 'syl') {
9488: $title=&mt('Syllabus');
9489: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
9490: } else {
9491: $title=&mt('Navigate Contents');
9492: $url='/adm/navmaps';
9493: }
9494:
9495: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
9496: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
9497:
9498: if ($errtext) { $fatal=2; }
9499: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
9500: }
9501:
9502: return (1,$outcome);
9503: }
9504:
9505: ############################################################
9506: ############################################################
9507:
9508: sub course_type {
9509: my ($cid) = @_;
9510: if (!defined($cid)) {
9511: $cid = $env{'request.course.id'};
9512: }
9513: if (defined($env{'course.'.$cid.'.type'})) {
9514: return $env{'course.'.$cid.'.type'};
9515: } else {
9516: return 'Course';
9517: }
9518: }
9519:
9520: sub group_term {
9521: my $crstype = &course_type();
9522: my %names = (
9523: 'Course' => 'group',
9524: 'Group' => 'team',
9525: );
9526: return $names{$crstype};
9527: }
9528:
9529: sub icon {
9530: my ($file)=@_;
9531: my $curfext = lc((split(/\./,$file))[-1]);
9532: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
9533: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
9534: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
9535: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
9536: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9537: $curfext.".gif") {
9538: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9539: $curfext.".gif";
9540: }
9541: }
9542: return &lonhttpdurl($iconname);
9543: }
9544:
9545: sub lonhttpdurl {
9546: #
9547: # Had been used for "small fry" static images on separate port 8080.
9548: # Modify here if lightweight http functionality desired again.
9549: # Currently eliminated due to increasing firewall issues.
9550: #
9551: my ($url)=@_;
9552: return $url;
9553: }
9554:
9555: sub connection_aborted {
9556: my ($r)=@_;
9557: $r->print(" ");$r->rflush();
9558: my $c = $r->connection;
9559: return $c->aborted();
9560: }
9561:
9562: # Escapes strings that may have embedded 's that will be put into
9563: # strings as 'strings'.
9564: sub escape_single {
9565: my ($input) = @_;
9566: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
9567: $input =~ s/\'/\\\'/g; # Esacpe the 's....
9568: return $input;
9569: }
9570:
9571: # Same as escape_single, but escape's "'s This
9572: # can be used for "strings"
9573: sub escape_double {
9574: my ($input) = @_;
9575: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
9576: $input =~ s/\"/\\\"/g; # Esacpe the "s....
9577: return $input;
9578: }
9579:
9580: # Escapes the last element of a full URL.
9581: sub escape_url {
9582: my ($url) = @_;
9583: my @urlslices = split(/\//, $url,-1);
9584: my $lastitem = &escape(pop(@urlslices));
9585: return join('/',@urlslices).'/'.$lastitem;
9586: }
9587:
9588: # -------------------------------------------------------- Initliaze user login
9589: sub init_user_environment {
9590: my ($r, $username, $domain, $authhost, $form, $args) = @_;
9591: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
9592:
9593: my $public=($username eq 'public' && $domain eq 'public');
9594:
9595: # See if old ID present, if so, remove
9596:
9597: my ($filename,$cookie,$userroles);
9598: my $now=time;
9599:
9600: if ($public) {
9601: my $max_public=100;
9602: my $oldest;
9603: my $oldest_time=0;
9604: for(my $next=1;$next<=$max_public;$next++) {
9605: if (-e $lonids."/publicuser_$next.id") {
9606: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
9607: if ($mtime<$oldest_time || !$oldest_time) {
9608: $oldest_time=$mtime;
9609: $oldest=$next;
9610: }
9611: } else {
9612: $cookie="publicuser_$next";
9613: last;
9614: }
9615: }
9616: if (!$cookie) { $cookie="publicuser_$oldest"; }
9617: } else {
9618: # if this isn't a robot, kill any existing non-robot sessions
9619: if (!$args->{'robot'}) {
9620: opendir(DIR,$lonids);
9621: while ($filename=readdir(DIR)) {
9622: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
9623: unlink($lonids.'/'.$filename);
9624: }
9625: }
9626: closedir(DIR);
9627: }
9628: # Give them a new cookie
9629: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
9630: : $now.$$.int(rand(10000)));
9631: $cookie="$username\_$id\_$domain\_$authhost";
9632:
9633: # Initialize roles
9634:
9635: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
9636: }
9637: # ------------------------------------ Check browser type and MathML capability
9638:
9639: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
9640: $clientunicode,$clientos) = &decode_user_agent($r);
9641:
9642: # -------------------------------------- Any accessibility options to remember?
9643: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
9644: foreach my $option ('imagesuppress','appletsuppress',
9645: 'embedsuppress','fontenhance','blackwhite') {
9646: if ($form->{$option} eq 'true') {
9647: &Apache::lonnet::put('environment',{$option => 'on'},
9648: $domain,$username);
9649: } else {
9650: &Apache::lonnet::del('environment',[$option],
9651: $domain,$username);
9652: }
9653: }
9654: }
9655: # ------------------------------------------------------------- Get environment
9656:
9657: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
9658: my ($tmp) = keys(%userenv);
9659: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9660: # default remote control to off
9661: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
9662: } else {
9663: undef(%userenv);
9664: }
9665: if (($userenv{'interface'}) && (!$form->{'interface'})) {
9666: $form->{'interface'}=$userenv{'interface'};
9667: }
9668: $env{'environment.remote'}=$userenv{'remote'};
9669: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
9670:
9671: # --------------- Do not trust query string to be put directly into environment
9672: foreach my $option ('imagesuppress','appletsuppress',
9673: 'embedsuppress','fontenhance','blackwhite',
9674: 'interface','localpath','localres') {
9675: $form->{$option}=~s/[\n\r\=]//gs;
9676: }
9677: # --------------------------------------------------------- Write first profile
9678:
9679: {
9680: my %initial_env =
9681: ("user.name" => $username,
9682: "user.domain" => $domain,
9683: "user.home" => $authhost,
9684: "browser.type" => $clientbrowser,
9685: "browser.version" => $clientversion,
9686: "browser.mathml" => $clientmathml,
9687: "browser.unicode" => $clientunicode,
9688: "browser.os" => $clientos,
9689: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
9690: "request.course.fn" => '',
9691: "request.course.uri" => '',
9692: "request.course.sec" => '',
9693: "request.role" => 'cm',
9694: "request.role.adv" => $env{'user.adv'},
9695: "request.host" => $ENV{'REMOTE_ADDR'},);
9696:
9697: if ($form->{'localpath'}) {
9698: $initial_env{"browser.localpath"} = $form->{'localpath'};
9699: $initial_env{"browser.localres"} = $form->{'localres'};
9700: }
9701:
9702: if ($public) {
9703: $initial_env{"environment.remote"} = "off";
9704: }
9705: if ($form->{'interface'}) {
9706: $form->{'interface'}=~s/\W//gs;
9707: $initial_env{"browser.interface"} = $form->{'interface'};
9708: $env{'browser.interface'}=$form->{'interface'};
9709: foreach my $option ('imagesuppress','appletsuppress',
9710: 'embedsuppress','fontenhance','blackwhite') {
9711: if (($form->{$option} eq 'true') ||
9712: ($userenv{$option} eq 'on')) {
9713: $initial_env{"browser.$option"} = "on";
9714: }
9715: }
9716: }
9717:
9718: $env{'user.environment'} = "$lonids/$cookie.id";
9719:
9720: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
9721: &GDBM_WRCREAT(),0640)) {
9722: &_add_to_env(\%disk_env,\%initial_env);
9723: &_add_to_env(\%disk_env,\%userenv,'environment.');
9724: &_add_to_env(\%disk_env,$userroles);
9725: if (ref($args->{'extra_env'})) {
9726: &_add_to_env(\%disk_env,$args->{'extra_env'});
9727: }
9728: untie(%disk_env);
9729: } else {
9730: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
9731: 'Could not create environment storage in lonauth: '.$!.'</span>');
9732: return 'error: '.$!;
9733: }
9734: }
9735: $env{'request.role'}='cm';
9736: $env{'request.role.adv'}=$env{'user.adv'};
9737: $env{'browser.type'}=$clientbrowser;
9738:
9739: return $cookie;
9740:
9741: }
9742:
9743: sub _add_to_env {
9744: my ($idf,$env_data,$prefix) = @_;
9745: if (ref($env_data) eq 'HASH') {
9746: while (my ($key,$value) = each(%$env_data)) {
9747: $idf->{$prefix.$key} = $value;
9748: $env{$prefix.$key} = $value;
9749: }
9750: }
9751: }
9752:
9753: # --- Get the symbolic name of a problem and the url
9754: sub get_symb {
9755: my ($request,$silent) = @_;
9756: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9757: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
9758: if ($symb eq '') {
9759: if (!$silent) {
9760: $request->print("Unable to handle ambiguous references:$url:.");
9761: return ();
9762: }
9763: }
9764: &Apache::lonenc::check_decrypt(\$symb);
9765: return ($symb);
9766: }
9767:
9768: # --------------------------------------------------------------Get annotation
9769:
9770: sub get_annotation {
9771: my ($symb,$enc) = @_;
9772:
9773: my $key = $symb;
9774: if (!$enc) {
9775: $key =
9776: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
9777: }
9778: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
9779: return $annotation{$key};
9780: }
9781:
9782: sub clean_symb {
9783: my ($symb) = @_;
9784:
9785: &Apache::lonenc::check_decrypt(\$symb);
9786: my $enc = $env{'request.enc'};
9787: delete($env{'request.enc'});
9788:
9789: return ($symb,$enc);
9790: }
9791:
9792: =pod
9793:
9794: =back
9795:
9796: =cut
9797:
9798: 1;
9799: __END__;
9800:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>