File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.697:
download - view:
text,
annotated -
select for diffs
Fri Nov 28 18:18:39 2008 UTC (15 years, 10 months ago) by
bisitz
Branches:
MAIN
CVS tags:
HEAD
Optimized layout for actions "Upload File" and "Create Subdirectory":
- Replaced hardcoded table by fieldsets
- Removed now unused styles from loncommon.pm
(LC_portfolio_actions, LC_portfolio_upload, LC_label, LC_value)
- Added missing/Updated translations
- Use common "%lt" instead of "%text" for localized texthash
- Wrapped "Delete Directory" and "Delete Selected" button in paragraph
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.697 2008/11/28 18:18:39 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: "<font color=yellow>INFO: Read file types</font>");
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'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></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.='</span></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\"><font color='#FFFFFF' size='2'>$text</font></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\"><font color='#FFFFFF' size='2'>$text</font></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,$fontcolor)=@_;
2772: if ($fontcolor) {
2773: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
2774: }
2775: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
2776: }
2777:
2778: sub track_student_link {
2779: my ($linktext,$sname,$sdom,$target,$start) = @_;
2780: my $link ="/adm/trackstudent?";
2781: my $title = 'View recent activity';
2782: if (defined($sname) && $sname !~ /^\s*$/ &&
2783: defined($sdom) && $sdom !~ /^\s*$/) {
2784: $link .= "selected_student=$sname:$sdom";
2785: $title .= ' of this student';
2786: }
2787: if (defined($target) && $target !~ /^\s*$/) {
2788: $target = qq{target="$target"};
2789: } else {
2790: $target = '';
2791: }
2792: if ($start) { $link.='&start='.$start; }
2793: $title = &mt($title);
2794: $linktext = &mt($linktext);
2795: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
2796: &help_open_topic('View_recent_activity');
2797: }
2798:
2799: # ===================================================== Display a student photo
2800:
2801:
2802: sub student_image_tag {
2803: my ($domain,$user)=@_;
2804: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
2805: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
2806: return '<img src="'.$imgsrc.'" align="right" />';
2807: } else {
2808: return '';
2809: }
2810: }
2811:
2812: =pod
2813:
2814: =back
2815:
2816: =head1 Access .tab File Data
2817:
2818: =over 4
2819:
2820: =item * &languageids()
2821:
2822: returns list of all language ids
2823:
2824: =cut
2825:
2826: sub languageids {
2827: return sort(keys(%language));
2828: }
2829:
2830: =pod
2831:
2832: =item * &languagedescription()
2833:
2834: returns description of a specified language id
2835:
2836: =cut
2837:
2838: sub languagedescription {
2839: my $code=shift;
2840: return ($supported_language{$code}?'* ':'').
2841: $language{$code}.
2842: ($supported_language{$code}?' ('.&mt('interface available').')':'');
2843: }
2844:
2845: sub plainlanguagedescription {
2846: my $code=shift;
2847: return $language{$code};
2848: }
2849:
2850: sub supportedlanguagecode {
2851: my $code=shift;
2852: return $supported_language{$code};
2853: }
2854:
2855: =pod
2856:
2857: =item * ©rightids()
2858:
2859: returns list of all copyrights
2860:
2861: =cut
2862:
2863: sub copyrightids {
2864: return sort(keys(%cprtag));
2865: }
2866:
2867: =pod
2868:
2869: =item * ©rightdescription()
2870:
2871: returns description of a specified copyright id
2872:
2873: =cut
2874:
2875: sub copyrightdescription {
2876: return &mt($cprtag{shift(@_)});
2877: }
2878:
2879: =pod
2880:
2881: =item * &source_copyrightids()
2882:
2883: returns list of all source copyrights
2884:
2885: =cut
2886:
2887: sub source_copyrightids {
2888: return sort(keys(%scprtag));
2889: }
2890:
2891: =pod
2892:
2893: =item * &source_copyrightdescription()
2894:
2895: returns description of a specified source copyright id
2896:
2897: =cut
2898:
2899: sub source_copyrightdescription {
2900: return &mt($scprtag{shift(@_)});
2901: }
2902:
2903: =pod
2904:
2905: =item * &filecategories()
2906:
2907: returns list of all file categories
2908:
2909: =cut
2910:
2911: sub filecategories {
2912: return sort(keys(%category_extensions));
2913: }
2914:
2915: =pod
2916:
2917: =item * &filecategorytypes()
2918:
2919: returns list of file types belonging to a given file
2920: category
2921:
2922: =cut
2923:
2924: sub filecategorytypes {
2925: my ($cat) = @_;
2926: return @{$category_extensions{lc($cat)}};
2927: }
2928:
2929: =pod
2930:
2931: =item * &fileembstyle()
2932:
2933: returns embedding style for a specified file type
2934:
2935: =cut
2936:
2937: sub fileembstyle {
2938: return $fe{lc(shift(@_))};
2939: }
2940:
2941: sub filemimetype {
2942: return $fm{lc(shift(@_))};
2943: }
2944:
2945:
2946: sub filecategoryselect {
2947: my ($name,$value)=@_;
2948: return &select_form($value,$name,
2949: '' => &mt('Any category'),
2950: map { $_,$_ } sort(keys(%category_extensions)));
2951: }
2952:
2953: =pod
2954:
2955: =item * &filedescription()
2956:
2957: returns description for a specified file type
2958:
2959: =cut
2960:
2961: sub filedescription {
2962: my $file_description = $fd{lc(shift())};
2963: $file_description =~ s:([\[\]]):~$1:g;
2964: return &mt($file_description);
2965: }
2966:
2967: =pod
2968:
2969: =item * &filedescriptionex()
2970:
2971: returns description for a specified file type with
2972: extra formatting
2973:
2974: =cut
2975:
2976: sub filedescriptionex {
2977: my $ex=shift;
2978: my $file_description = $fd{lc($ex)};
2979: $file_description =~ s:([\[\]]):~$1:g;
2980: return '.'.$ex.' '.&mt($file_description);
2981: }
2982:
2983: # End of .tab access
2984: =pod
2985:
2986: =back
2987:
2988: =cut
2989:
2990: # ------------------------------------------------------------------ File Types
2991: sub fileextensions {
2992: return sort(keys(%fe));
2993: }
2994:
2995: # ----------------------------------------------------------- Display Languages
2996: # returns a hash with all desired display languages
2997: #
2998:
2999: sub display_languages {
3000: my %languages=();
3001: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3002: $languages{$lang}=1;
3003: }
3004: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3005: if ($env{'form.displaylanguage'}) {
3006: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3007: $languages{$lang}=1;
3008: }
3009: }
3010: return %languages;
3011: }
3012:
3013: sub languages {
3014: my ($possible_langs) = @_;
3015: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3016: if (!ref($possible_langs)) {
3017: if( wantarray ) {
3018: return @preferred_langs;
3019: } else {
3020: return $preferred_langs[0];
3021: }
3022: }
3023: my %possibilities = map { $_ => 1 } (@$possible_langs);
3024: my @preferred_possibilities;
3025: foreach my $preferred_lang (@preferred_langs) {
3026: if (exists($possibilities{$preferred_lang})) {
3027: push(@preferred_possibilities, $preferred_lang);
3028: }
3029: }
3030: if( wantarray ) {
3031: return @preferred_possibilities;
3032: }
3033: return $preferred_possibilities[0];
3034: }
3035:
3036: ###############################################################
3037: ## Student Answer Attempts ##
3038: ###############################################################
3039:
3040: =pod
3041:
3042: =head1 Alternate Problem Views
3043:
3044: =over 4
3045:
3046: =item * &get_previous_attempt($symb, $username, $domain, $course,
3047: $getattempt, $regexp, $gradesub)
3048:
3049: Return string with previous attempt on problem. Arguments:
3050:
3051: =over 4
3052:
3053: =item * $symb: Problem, including path
3054:
3055: =item * $username: username of the desired student
3056:
3057: =item * $domain: domain of the desired student
3058:
3059: =item * $course: Course ID
3060:
3061: =item * $getattempt: Leave blank for all attempts, otherwise put
3062: something
3063:
3064: =item * $regexp: if string matches this regexp, the string will be
3065: sent to $gradesub
3066:
3067: =item * $gradesub: routine that processes the string if it matches $regexp
3068:
3069: =back
3070:
3071: The output string is a table containing all desired attempts, if any.
3072:
3073: =cut
3074:
3075: sub get_previous_attempt {
3076: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3077: my $prevattempts='';
3078: no strict 'refs';
3079: if ($symb) {
3080: my (%returnhash)=
3081: &Apache::lonnet::restore($symb,$course,$domain,$username);
3082: if ($returnhash{'version'}) {
3083: my %lasthash=();
3084: my $version;
3085: for ($version=1;$version<=$returnhash{'version'};$version++) {
3086: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3087: $lasthash{$key}=$returnhash{$version.':'.$key};
3088: }
3089: }
3090: $prevattempts=&start_data_table().&start_data_table_header_row();
3091: $prevattempts.='<th>'.&mt('History').'</th>';
3092: foreach my $key (sort(keys(%lasthash))) {
3093: my ($ign,@parts) = split(/\./,$key);
3094: if ($#parts > 0) {
3095: my $data=$parts[-1];
3096: pop(@parts);
3097: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3098: } else {
3099: if ($#parts == 0) {
3100: $prevattempts.='<th>'.$parts[0].'</th>';
3101: } else {
3102: $prevattempts.='<th>'.$ign.'</th>';
3103: }
3104: }
3105: }
3106: $prevattempts.=&end_data_table_header_row();
3107: if ($getattempt eq '') {
3108: for ($version=1;$version<=$returnhash{'version'};$version++) {
3109: $prevattempts.=&start_data_table_row().
3110: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3111: foreach my $key (sort(keys(%lasthash))) {
3112: my $value = &format_previous_attempt_value($key,
3113: $returnhash{$version.':'.$key});
3114: $prevattempts.='<td>'.$value.' </td>';
3115: }
3116: $prevattempts.=&end_data_table_row();
3117: }
3118: }
3119: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3120: foreach my $key (sort(keys(%lasthash))) {
3121: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3122: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3123: $prevattempts.='<td>'.$value.' </td>';
3124: }
3125: $prevattempts.= &end_data_table_row().&end_data_table();
3126: } else {
3127: $prevattempts=
3128: &start_data_table().&start_data_table_row().
3129: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3130: &end_data_table_row().&end_data_table();
3131: }
3132: } else {
3133: $prevattempts=
3134: &start_data_table().&start_data_table_row().
3135: '<td>'.&mt('No data.').'</td>'.
3136: &end_data_table_row().&end_data_table();
3137: }
3138: }
3139:
3140: sub format_previous_attempt_value {
3141: my ($key,$value) = @_;
3142: if ($key =~ /timestamp/) {
3143: $value = &Apache::lonlocal::locallocaltime($value);
3144: } elsif (ref($value) eq 'ARRAY') {
3145: $value = '('.join(', ', @{ $value }).')';
3146: } else {
3147: $value = &unescape($value);
3148: }
3149: return $value;
3150: }
3151:
3152:
3153: sub relative_to_absolute {
3154: my ($url,$output)=@_;
3155: my $parser=HTML::TokeParser->new(\$output);
3156: my $token;
3157: my $thisdir=$url;
3158: my @rlinks=();
3159: while ($token=$parser->get_token) {
3160: if ($token->[0] eq 'S') {
3161: if ($token->[1] eq 'a') {
3162: if ($token->[2]->{'href'}) {
3163: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3164: }
3165: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3166: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3167: } elsif ($token->[1] eq 'base') {
3168: $thisdir=$token->[2]->{'href'};
3169: }
3170: }
3171: }
3172: $thisdir=~s-/[^/]*$--;
3173: foreach my $link (@rlinks) {
3174: unless (($link=~/^http:\/\//i) ||
3175: ($link=~/^\//) ||
3176: ($link=~/^javascript:/i) ||
3177: ($link=~/^mailto:/i) ||
3178: ($link=~/^\#/)) {
3179: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3180: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3181: }
3182: }
3183: # -------------------------------------------------- Deal with Applet codebases
3184: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3185: return $output;
3186: }
3187:
3188: =pod
3189:
3190: =item * &get_student_view()
3191:
3192: show a snapshot of what student was looking at
3193:
3194: =cut
3195:
3196: sub get_student_view {
3197: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3198: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3199: my (%form);
3200: my @elements=('symb','courseid','domain','username');
3201: foreach my $element (@elements) {
3202: $form{'grade_'.$element}=eval '$'.$element #'
3203: }
3204: if (defined($moreenv)) {
3205: %form=(%form,%{$moreenv});
3206: }
3207: if (defined($target)) { $form{'grade_target'} = $target; }
3208: $feedurl=&Apache::lonnet::clutter($feedurl);
3209: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3210: $userview=~s/\<body[^\>]*\>//gi;
3211: $userview=~s/\<\/body\>//gi;
3212: $userview=~s/\<html\>//gi;
3213: $userview=~s/\<\/html\>//gi;
3214: $userview=~s/\<head\>//gi;
3215: $userview=~s/\<\/head\>//gi;
3216: $userview=~s/action\s*\=/would_be_action\=/gi;
3217: $userview=&relative_to_absolute($feedurl,$userview);
3218: if (wantarray) {
3219: return ($userview,$response);
3220: } else {
3221: return $userview;
3222: }
3223: }
3224:
3225: sub get_student_view_with_retries {
3226: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3227:
3228: my $ok = 0; # True if we got a good response.
3229: my $content;
3230: my $response;
3231:
3232: # Try to get the student_view done. within the retries count:
3233:
3234: do {
3235: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3236: $ok = $response->is_success;
3237: if (!$ok) {
3238: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3239: }
3240: $retries--;
3241: } while (!$ok && ($retries > 0));
3242:
3243: if (!$ok) {
3244: $content = ''; # On error return an empty content.
3245: }
3246: if (wantarray) {
3247: return ($content, $response);
3248: } else {
3249: return $content;
3250: }
3251: }
3252:
3253: =pod
3254:
3255: =item * &get_student_answers()
3256:
3257: show a snapshot of how student was answering problem
3258:
3259: =cut
3260:
3261: sub get_student_answers {
3262: my ($symb,$username,$domain,$courseid,%form) = @_;
3263: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3264: my (%moreenv);
3265: my @elements=('symb','courseid','domain','username');
3266: foreach my $element (@elements) {
3267: $moreenv{'grade_'.$element}=eval '$'.$element #'
3268: }
3269: $moreenv{'grade_target'}='answer';
3270: %moreenv=(%form,%moreenv);
3271: $feedurl = &Apache::lonnet::clutter($feedurl);
3272: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3273: return $userview;
3274: }
3275:
3276: =pod
3277:
3278: =item * &submlink()
3279:
3280: Inputs: $text $uname $udom $symb $target
3281:
3282: Returns: A link to grades.pm such as to see the SUBM view of a student
3283:
3284: =cut
3285:
3286: ###############################################
3287: sub submlink {
3288: my ($text,$uname,$udom,$symb,$target)=@_;
3289: if (!($uname && $udom)) {
3290: (my $cursymb, my $courseid,$udom,$uname)=
3291: &Apache::lonnet::whichuser($symb);
3292: if (!$symb) { $symb=$cursymb; }
3293: }
3294: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3295: $symb=&escape($symb);
3296: if ($target) { $target="target=\"$target\""; }
3297: return '<a href="/adm/grades?&command=submission&'.
3298: 'symb='.$symb.'&student='.$uname.
3299: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3300: }
3301: ##############################################
3302:
3303: =pod
3304:
3305: =item * &pgrdlink()
3306:
3307: Inputs: $text $uname $udom $symb $target
3308:
3309: Returns: A link to grades.pm such as to see the PGRD view of a student
3310:
3311: =cut
3312:
3313: ###############################################
3314: sub pgrdlink {
3315: my $link=&submlink(@_);
3316: $link=~s/(&command=submission)/$1&showgrading=yes/;
3317: return $link;
3318: }
3319: ##############################################
3320:
3321: =pod
3322:
3323: =item * &pprmlink()
3324:
3325: Inputs: $text $uname $udom $symb $target
3326:
3327: Returns: A link to parmset.pm such as to see the PPRM view of a
3328: student and a specific resource
3329:
3330: =cut
3331:
3332: ###############################################
3333: sub pprmlink {
3334: my ($text,$uname,$udom,$symb,$target)=@_;
3335: if (!($uname && $udom)) {
3336: (my $cursymb, my $courseid,$udom,$uname)=
3337: &Apache::lonnet::whichuser($symb);
3338: if (!$symb) { $symb=$cursymb; }
3339: }
3340: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3341: $symb=&escape($symb);
3342: if ($target) { $target="target=\"$target\""; }
3343: return '<a href="/adm/parmset?command=set&'.
3344: 'symb='.$symb.'&uname='.$uname.
3345: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3346: }
3347: ##############################################
3348:
3349: =pod
3350:
3351: =back
3352:
3353: =cut
3354:
3355: ###############################################
3356:
3357:
3358: sub timehash {
3359: my ($thistime) = @_;
3360: my $timezone = &Apache::lonlocal::gettimezone();
3361: my $dt = DateTime->from_epoch(epoch => $thistime)
3362: ->set_time_zone($timezone);
3363: my $wday = $dt->day_of_week();
3364: if ($wday == 7) { $wday = 0; }
3365: return ( 'second' => $dt->second(),
3366: 'minute' => $dt->minute(),
3367: 'hour' => $dt->hour(),
3368: 'day' => $dt->day_of_month(),
3369: 'month' => $dt->month(),
3370: 'year' => $dt->year(),
3371: 'weekday' => $wday,
3372: 'dayyear' => $dt->day_of_year(),
3373: 'dlsav' => $dt->is_dst() );
3374: }
3375:
3376: sub utc_string {
3377: my ($date)=@_;
3378: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3379: }
3380:
3381: sub maketime {
3382: my %th=@_;
3383: my ($epoch_time,$timezone,$dt);
3384: $timezone = &Apache::lonlocal::gettimezone();
3385: eval {
3386: $dt = DateTime->new( year => $th{'year'},
3387: month => $th{'month'},
3388: day => $th{'day'},
3389: hour => $th{'hour'},
3390: minute => $th{'minute'},
3391: second => $th{'second'},
3392: time_zone => $timezone,
3393: );
3394: };
3395: if (!$@) {
3396: $epoch_time = $dt->epoch;
3397: if ($epoch_time) {
3398: return $epoch_time;
3399: }
3400: }
3401: return POSIX::mktime(
3402: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3403: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3404: }
3405:
3406: #########################################
3407:
3408: sub findallcourses {
3409: my ($roles,$uname,$udom) = @_;
3410: my %roles;
3411: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3412: my %courses;
3413: my $now=time;
3414: if (!defined($uname)) {
3415: $uname = $env{'user.name'};
3416: }
3417: if (!defined($udom)) {
3418: $udom = $env{'user.domain'};
3419: }
3420: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3421: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3422: if (!%roles) {
3423: %roles = (
3424: cc => 1,
3425: in => 1,
3426: ep => 1,
3427: ta => 1,
3428: cr => 1,
3429: st => 1,
3430: );
3431: }
3432: foreach my $entry (keys(%roleshash)) {
3433: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3434: if ($trole =~ /^cr/) {
3435: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3436: } else {
3437: next if (!exists($roles{$trole}));
3438: }
3439: if ($tend) {
3440: next if ($tend < $now);
3441: }
3442: if ($tstart) {
3443: next if ($tstart > $now);
3444: }
3445: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3446: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3447: if ($secpart eq '') {
3448: ($cnum,$role) = split(/_/,$cnumpart);
3449: $sec = 'none';
3450: $realsec = '';
3451: } else {
3452: $cnum = $cnumpart;
3453: ($sec,$role) = split(/_/,$secpart);
3454: $realsec = $sec;
3455: }
3456: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3457: }
3458: } else {
3459: foreach my $key (keys(%env)) {
3460: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3461: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3462: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3463: next if ($role eq 'ca' || $role eq 'aa');
3464: next if (%roles && !exists($roles{$role}));
3465: my ($starttime,$endtime)=split(/\./,$env{$key});
3466: my $active=1;
3467: if ($starttime) {
3468: if ($now<$starttime) { $active=0; }
3469: }
3470: if ($endtime) {
3471: if ($now>$endtime) { $active=0; }
3472: }
3473: if ($active) {
3474: if ($sec eq '') {
3475: $sec = 'none';
3476: }
3477: $courses{$cdom.'_'.$cnum}{$sec} =
3478: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3479: }
3480: }
3481: }
3482: }
3483: return %courses;
3484: }
3485:
3486: ###############################################
3487:
3488: sub blockcheck {
3489: my ($setters,$activity,$uname,$udom) = @_;
3490:
3491: if (!defined($udom)) {
3492: $udom = $env{'user.domain'};
3493: }
3494: if (!defined($uname)) {
3495: $uname = $env{'user.name'};
3496: }
3497:
3498: # If uname and udom are for a course, check for blocks in the course.
3499:
3500: if (&Apache::lonnet::is_course($udom,$uname)) {
3501: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3502: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3503: return ($startblock,$endblock);
3504: }
3505:
3506: my $startblock = 0;
3507: my $endblock = 0;
3508: my %live_courses = &findallcourses(undef,$uname,$udom);
3509:
3510: # If uname is for a user, and activity is course-specific, i.e.,
3511: # boards, chat or groups, check for blocking in current course only.
3512:
3513: if (($activity eq 'boards' || $activity eq 'chat' ||
3514: $activity eq 'groups') && ($env{'request.course.id'})) {
3515: foreach my $key (keys(%live_courses)) {
3516: if ($key ne $env{'request.course.id'}) {
3517: delete($live_courses{$key});
3518: }
3519: }
3520: }
3521:
3522: my $otheruser = 0;
3523: my %own_courses;
3524: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3525: # Resource belongs to user other than current user.
3526: $otheruser = 1;
3527: # Gather courses for current user
3528: %own_courses =
3529: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3530: }
3531:
3532: # Gather active course roles - course coordinator, instructor,
3533: # exam proctor, ta, student, or custom role.
3534:
3535: foreach my $course (keys(%live_courses)) {
3536: my ($cdom,$cnum);
3537: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3538: $cdom = $env{'course.'.$course.'.domain'};
3539: $cnum = $env{'course.'.$course.'.num'};
3540: } else {
3541: ($cdom,$cnum) = split(/_/,$course);
3542: }
3543: my $no_ownblock = 0;
3544: my $no_userblock = 0;
3545: if ($otheruser && $activity ne 'com') {
3546: # Check if current user has 'evb' priv for this
3547: if (defined($own_courses{$course})) {
3548: foreach my $sec (keys(%{$own_courses{$course}})) {
3549: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3550: if ($sec ne 'none') {
3551: $checkrole .= '/'.$sec;
3552: }
3553: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3554: $no_ownblock = 1;
3555: last;
3556: }
3557: }
3558: }
3559: # if they have 'evb' priv and are currently not playing student
3560: next if (($no_ownblock) &&
3561: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3562: }
3563: foreach my $sec (keys(%{$live_courses{$course}})) {
3564: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3565: if ($sec ne 'none') {
3566: $checkrole .= '/'.$sec;
3567: }
3568: if ($otheruser) {
3569: # Resource belongs to user other than current user.
3570: # Assemble privs for that user, and check for 'evb' priv.
3571: my ($trole,$tdom,$tnum,$tsec);
3572: my $entry = $live_courses{$course}{$sec};
3573: if ($entry =~ /^cr/) {
3574: ($trole,$tdom,$tnum,$tsec) =
3575: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3576: } else {
3577: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3578: }
3579: my ($spec,$area,$trest,%allroles,%userroles);
3580: $area = '/'.$tdom.'/'.$tnum;
3581: $trest = $tnum;
3582: if ($tsec ne '') {
3583: $area .= '/'.$tsec;
3584: $trest .= '/'.$tsec;
3585: }
3586: $spec = $trole.'.'.$area;
3587: if ($trole =~ /^cr/) {
3588: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3589: $tdom,$spec,$trest,$area);
3590: } else {
3591: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3592: $tdom,$spec,$trest,$area);
3593: }
3594: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3595: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3596: if ($1) {
3597: $no_userblock = 1;
3598: last;
3599: }
3600: }
3601: } else {
3602: # Resource belongs to current user
3603: # Check for 'evb' priv via lonnet::allowed().
3604: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3605: $no_ownblock = 1;
3606: last;
3607: }
3608: }
3609: }
3610: # if they have the evb priv and are currently not playing student
3611: next if (($no_ownblock) &&
3612: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3613: next if ($no_userblock);
3614:
3615: # Retrieve blocking times and identity of blocker for course
3616: # of specified user, unless user has 'evb' privilege.
3617:
3618: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3619: if (($start != 0) &&
3620: (($startblock == 0) || ($startblock > $start))) {
3621: $startblock = $start;
3622: }
3623: if (($end != 0) &&
3624: (($endblock == 0) || ($endblock < $end))) {
3625: $endblock = $end;
3626: }
3627: }
3628: return ($startblock,$endblock);
3629: }
3630:
3631: sub get_blocks {
3632: my ($setters,$activity,$cdom,$cnum) = @_;
3633: my $startblock = 0;
3634: my $endblock = 0;
3635: my $course = $cdom.'_'.$cnum;
3636: $setters->{$course} = {};
3637: $setters->{$course}{'staff'} = [];
3638: $setters->{$course}{'times'} = [];
3639: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3640: foreach my $record (keys(%records)) {
3641: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3642: if ($start <= time && $end >= time) {
3643: my ($staff_name,$staff_dom,$title,$blocks) =
3644: &parse_block_record($records{$record});
3645: if ($blocks->{$activity} eq 'on') {
3646: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3647: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3648: if ( ($startblock == 0) || ($startblock > $start) ) {
3649: $startblock = $start;
3650: }
3651: if ( ($endblock == 0) || ($endblock < $end) ) {
3652: $endblock = $end;
3653: }
3654: }
3655: }
3656: }
3657: return ($startblock,$endblock);
3658: }
3659:
3660: sub parse_block_record {
3661: my ($record) = @_;
3662: my ($setuname,$setudom,$title,$blocks);
3663: if (ref($record) eq 'HASH') {
3664: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3665: $title = &unescape($record->{'event'});
3666: $blocks = $record->{'blocks'};
3667: } else {
3668: my @data = split(/:/,$record,3);
3669: if (scalar(@data) eq 2) {
3670: $title = $data[1];
3671: ($setuname,$setudom) = split(/@/,$data[0]);
3672: } else {
3673: ($setuname,$setudom,$title) = @data;
3674: }
3675: $blocks = { 'com' => 'on' };
3676: }
3677: return ($setuname,$setudom,$title,$blocks);
3678: }
3679:
3680: sub build_block_table {
3681: my ($startblock,$endblock,$setters) = @_;
3682: my %lt = &Apache::lonlocal::texthash(
3683: 'cacb' => 'Currently active communication blocks',
3684: 'cour' => 'Course',
3685: 'dura' => 'Duration',
3686: 'blse' => 'Block set by'
3687: );
3688: my $output;
3689: $output = '<br />'.$lt{'cacb'}.':<br />';
3690: $output .= &start_data_table();
3691: $output .= '
3692: <tr>
3693: <th>'.$lt{'cour'}.'</th>
3694: <th>'.$lt{'dura'}.'</th>
3695: <th>'.$lt{'blse'}.'</th>
3696: </tr>
3697: ';
3698: foreach my $course (keys(%{$setters})) {
3699: my %courseinfo=&Apache::lonnet::coursedescription($course);
3700: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
3701: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
3702: my $fullname = &plainname($uname,$udom);
3703: if (defined($env{'user.name'}) && defined($env{'user.domain'})
3704: && $env{'user.name'} ne 'public'
3705: && $env{'user.domain'} ne 'public') {
3706: $fullname = &aboutmewrapper($fullname,$uname,$udom);
3707: }
3708: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
3709: $openblock = &Apache::lonlocal::locallocaltime($openblock);
3710: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
3711: $output .= &Apache::loncommon::start_data_table_row().
3712: '<td>'.$courseinfo{'description'}.'</td>'.
3713: '<td>'.$openblock.' to '.$closeblock.'</td>'.
3714: '<td>'.$fullname.'</td>'.
3715: &Apache::loncommon::end_data_table_row();
3716: }
3717: }
3718: $output .= &end_data_table();
3719: }
3720:
3721: sub blocking_status {
3722: my ($activity,$uname,$udom) = @_;
3723: my %setters;
3724: my ($blocked,$output,$ownitem,$is_course);
3725: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
3726: if ($startblock && $endblock) {
3727: $blocked = 1;
3728: if (wantarray) {
3729: my $category;
3730: if ($activity eq 'boards') {
3731: $category = 'Discussion posts in this course';
3732: } elsif ($activity eq 'blogs') {
3733: $category = 'Blogs';
3734: } elsif ($activity eq 'port') {
3735: if (defined($uname) && defined($udom)) {
3736: if ($uname eq $env{'user.name'} &&
3737: $udom eq $env{'user.domain'}) {
3738: $ownitem = 1;
3739: }
3740: }
3741: $is_course = &Apache::lonnet::is_course($udom,$uname);
3742: if ($ownitem) {
3743: $category = 'Your portfolio files';
3744: } elsif ($is_course) {
3745: my $coursedesc;
3746: foreach my $course (keys(%setters)) {
3747: my %courseinfo =
3748: &Apache::lonnet::coursedescription($course);
3749: $coursedesc = $courseinfo{'description'};
3750: }
3751: $category = "Group files in the course '$coursedesc'";
3752: } else {
3753: $category = 'Portfolio files belonging to ';
3754: if ($env{'user.name'} eq 'public' &&
3755: $env{'user.domain'} eq 'public') {
3756: $category .= &plainname($uname,$udom);
3757: } else {
3758: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
3759: }
3760: }
3761: } elsif ($activity eq 'groups') {
3762: $category = 'Groups in this course';
3763: }
3764: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
3765: my $showend = &Apache::lonlocal::locallocaltime($endblock);
3766: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
3767: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
3768: $output .= &build_block_table($startblock,$endblock,\%setters);
3769: }
3770: }
3771: }
3772: if (wantarray) {
3773: return ($blocked,$output);
3774: } else {
3775: return $blocked;
3776: }
3777: }
3778:
3779: ###############################################
3780:
3781: sub check_ip_acc {
3782: my ($acc)=@_;
3783: &Apache::lonxml::debug("acc is $acc");
3784: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
3785: return 1;
3786: }
3787: my $allowed=0;
3788: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
3789:
3790: my $name;
3791: foreach my $pattern (split(',',$acc)) {
3792: $pattern =~ s/^\s*//;
3793: $pattern =~ s/\s*$//;
3794: if ($pattern =~ /\*$/) {
3795: #35.8.*
3796: $pattern=~s/\*//;
3797: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3798: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
3799: #35.8.3.[34-56]
3800: my $low=$2;
3801: my $high=$3;
3802: $pattern=$1;
3803: if ($ip =~ /^\Q$pattern\E/) {
3804: my $last=(split(/\./,$ip))[3];
3805: if ($last <=$high && $last >=$low) { $allowed=1; }
3806: }
3807: } elsif ($pattern =~ /^\*/) {
3808: #*.msu.edu
3809: $pattern=~s/\*//;
3810: if (!defined($name)) {
3811: use Socket;
3812: my $netaddr=inet_aton($ip);
3813: ($name)=gethostbyaddr($netaddr,AF_INET);
3814: }
3815: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3816: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
3817: #127.0.0.1
3818: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
3819: } else {
3820: #some.name.com
3821: if (!defined($name)) {
3822: use Socket;
3823: my $netaddr=inet_aton($ip);
3824: ($name)=gethostbyaddr($netaddr,AF_INET);
3825: }
3826: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
3827: }
3828: if ($allowed) { last; }
3829: }
3830: return $allowed;
3831: }
3832:
3833: ###############################################
3834:
3835: =pod
3836:
3837: =head1 Domain Template Functions
3838:
3839: =over 4
3840:
3841: =item * &determinedomain()
3842:
3843: Inputs: $domain (usually will be undef)
3844:
3845: Returns: Determines which domain should be used for designs
3846:
3847: =cut
3848:
3849: ###############################################
3850: sub determinedomain {
3851: my $domain=shift;
3852: if (! $domain) {
3853: # Determine domain if we have not been given one
3854: $domain = $Apache::lonnet::perlvar{'lonDefDomain'};
3855: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
3856: if ($env{'request.role.domain'}) {
3857: $domain=$env{'request.role.domain'};
3858: }
3859: }
3860: return $domain;
3861: }
3862: ###############################################
3863:
3864: sub devalidate_domconfig_cache {
3865: my ($udom)=@_;
3866: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
3867: }
3868:
3869: # ---------------------- Get domain configuration for a domain
3870: sub get_domainconf {
3871: my ($udom) = @_;
3872: my $cachetime=1800;
3873: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
3874: if (defined($cached)) { return %{$result}; }
3875:
3876: my %domconfig = &Apache::lonnet::get_dom('configuration',
3877: ['login','rolecolors'],$udom);
3878: my (%designhash,%legacy);
3879: if (keys(%domconfig) > 0) {
3880: if (ref($domconfig{'login'}) eq 'HASH') {
3881: if (keys(%{$domconfig{'login'}})) {
3882: foreach my $key (keys(%{$domconfig{'login'}})) {
3883: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
3884: }
3885: } else {
3886: $legacy{'login'} = 1;
3887: }
3888: } else {
3889: $legacy{'login'} = 1;
3890: }
3891: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
3892: if (keys(%{$domconfig{'rolecolors'}})) {
3893: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
3894: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
3895: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
3896: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
3897: }
3898: }
3899: }
3900: } else {
3901: $legacy{'rolecolors'} = 1;
3902: }
3903: } else {
3904: $legacy{'rolecolors'} = 1;
3905: }
3906: if (keys(%legacy) > 0) {
3907: my %legacyhash = &get_legacy_domconf($udom);
3908: foreach my $item (keys(%legacyhash)) {
3909: if ($item =~ /^\Q$udom\E\.login/) {
3910: if ($legacy{'login'}) {
3911: $designhash{$item} = $legacyhash{$item};
3912: }
3913: } else {
3914: if ($legacy{'rolecolors'}) {
3915: $designhash{$item} = $legacyhash{$item};
3916: }
3917: }
3918: }
3919: }
3920: } else {
3921: %designhash = &get_legacy_domconf($udom);
3922: }
3923: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
3924: $cachetime);
3925: return %designhash;
3926: }
3927:
3928: sub get_legacy_domconf {
3929: my ($udom) = @_;
3930: my %legacyhash;
3931: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
3932: my $designfile = $designdir.'/'.$udom.'.tab';
3933: if (-e $designfile) {
3934: if ( open (my $fh,"<$designfile") ) {
3935: while (my $line = <$fh>) {
3936: next if ($line =~ /^\#/);
3937: chomp($line);
3938: my ($key,$val)=(split(/\=/,$line));
3939: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
3940: }
3941: close($fh);
3942: }
3943: }
3944: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
3945: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
3946: }
3947: return %legacyhash;
3948: }
3949:
3950: =pod
3951:
3952: =item * &domainlogo()
3953:
3954: Inputs: $domain (usually will be undef)
3955:
3956: Returns: A link to a domain logo, if the domain logo exists.
3957: If the domain logo does not exist, a description of the domain.
3958:
3959: =cut
3960:
3961: ###############################################
3962: sub domainlogo {
3963: my $domain = &determinedomain(shift);
3964: my %designhash = &get_domainconf($domain);
3965: # See if there is a logo
3966: if ($designhash{$domain.'.login.domlogo'} ne '') {
3967: my $imgsrc = $designhash{$domain.'.login.domlogo'};
3968: if ($imgsrc =~ m{^/(adm|res)/}) {
3969: if ($imgsrc =~ m{^/res/}) {
3970: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
3971: &Apache::lonnet::repcopy($local_name);
3972: }
3973: $imgsrc = &lonhttpdurl($imgsrc);
3974: }
3975: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
3976: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
3977: return &Apache::lonnet::domain($domain,'description');
3978: } else {
3979: return '';
3980: }
3981: }
3982: ##############################################
3983:
3984: =pod
3985:
3986: =item * &designparm()
3987:
3988: Inputs: $which parameter; $domain (usually will be undef)
3989:
3990: Returns: value of designparamter $which
3991:
3992: =cut
3993:
3994:
3995: ##############################################
3996: sub designparm {
3997: my ($which,$domain)=@_;
3998: if ($env{'browser.blackwhite'} eq 'on') {
3999: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
4000: return '#000000';
4001: }
4002: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
4003: return '#FFFFFF';
4004: }
4005: if ($which=~/\.tabbg$/) {
4006: return '#CCCCCC';
4007: }
4008: }
4009: if (exists($env{'environment.color.'.$which})) {
4010: return $env{'environment.color.'.$which};
4011: }
4012: $domain=&determinedomain($domain);
4013: my %domdesign = &get_domainconf($domain);
4014: my $output;
4015: if ($domdesign{$domain.'.'.$which} ne '') {
4016: $output = $domdesign{$domain.'.'.$which};
4017: } else {
4018: $output = $defaultdesign{$which};
4019: }
4020: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4021: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4022: if ($output =~ m{^/(adm|res)/}) {
4023: if ($output =~ m{^/res/}) {
4024: my $local_name = &Apache::lonnet::filelocation('',$output);
4025: &Apache::lonnet::repcopy($local_name);
4026: }
4027: $output = &lonhttpdurl($output);
4028: }
4029: }
4030: return $output;
4031: }
4032:
4033: ###############################################
4034: ###############################################
4035:
4036: =pod
4037:
4038: =back
4039:
4040: =head1 HTML Helpers
4041:
4042: =over 4
4043:
4044: =item * &bodytag()
4045:
4046: Returns a uniform header for LON-CAPA web pages.
4047:
4048: Inputs:
4049:
4050: =over 4
4051:
4052: =item * $title, A title to be displayed on the page.
4053:
4054: =item * $function, the current role (can be undef).
4055:
4056: =item * $addentries, extra parameters for the <body> tag.
4057:
4058: =item * $bodyonly, if defined, only return the <body> tag.
4059:
4060: =item * $domain, if defined, force a given domain.
4061:
4062: =item * $forcereg, if page should register as content page (relevant for
4063: text interface only)
4064:
4065: =item * $customtitle, alternate text to use instead of $title
4066: in the title box that appears, this text
4067: is not auto translated like the $title is
4068:
4069: =item * $notopbar, if true, keep the 'what is this' info but remove the
4070: navigational links
4071:
4072: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4073:
4074: =item * $notitle, if true keep the nav controls, but remove the title bar
4075:
4076: =item * $no_inline_link, if true and in remote mode, don't show the
4077: 'Switch To Inline Menu' link
4078:
4079: =item * $args, optional argument valid values are
4080: no_auto_mt_title -> prevents &mt()ing the title arg
4081: inherit_jsmath -> when creating popup window in a page,
4082: should it have jsmath forced on by the
4083: current page
4084:
4085: =back
4086:
4087: Returns: A uniform header for LON-CAPA web pages.
4088: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4089: If $bodyonly is undef or zero, an html string containing a <body> tag and
4090: other decorations will be returned.
4091:
4092: =cut
4093:
4094: sub bodytag {
4095: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
4096: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
4097:
4098: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4099:
4100: $function = &get_users_function() if (!$function);
4101: my $img = &designparm($function.'.img',$domain);
4102: my $font = &designparm($function.'.font',$domain);
4103: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4104:
4105: my %design = ( 'style' => 'margin-top: 0px',
4106: 'bgcolor' => $pgbg,
4107: 'text' => $font,
4108: 'alink' => &designparm($function.'.alink',$domain),
4109: 'vlink' => &designparm($function.'.vlink',$domain),
4110: 'link' => &designparm($function.'.link',$domain),);
4111: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4112:
4113: # role and realm
4114: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4115: if ($role eq 'ca') {
4116: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4117: $realm = &plainname($rname,$rdom);
4118: }
4119: # realm
4120: if ($env{'request.course.id'}) {
4121: if ($env{'request.role'} !~ /^cr/) {
4122: $role = &Apache::lonnet::plaintext($role,&course_type());
4123: }
4124: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4125: } else {
4126: $role = &Apache::lonnet::plaintext($role);
4127: }
4128:
4129: if (!$realm) { $realm=' '; }
4130: # Set messages
4131: my $messages=&domainlogo($domain);
4132:
4133: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4134:
4135: # construct main body tag
4136: my $bodytag = "<body $extra_body_attr>".
4137: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4138:
4139: if ($bodyonly) {
4140: return $bodytag;
4141: } elsif ($env{'browser.interface'} eq 'textual') {
4142: # Accessibility
4143:
4144: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4145: if (!$notitle) {
4146: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4147: }
4148: return $bodytag;
4149: }
4150:
4151: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4152: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4153: undef($role);
4154: } else {
4155: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4156: }
4157:
4158: my $roleinfo=(<<ENDROLE);
4159: <td class="LC_title_bar_who">
4160: <div class="LC_title_bar_name">
4161: $name
4162:
4163: </div>
4164: <div class="LC_title_bar_role">
4165: $role
4166: </div>
4167: <div class="LC_title_bar_realm">
4168: $realm
4169: </div>
4170: </td>
4171: ENDROLE
4172:
4173: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4174: if ($customtitle) {
4175: $titleinfo = $customtitle;
4176: }
4177: #
4178: # Extra info if you are the DC
4179: my $dc_info = '';
4180: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4181: $env{'course.'.$env{'request.course.id'}.
4182: '.domain'}.'/'})) {
4183: my $cid = $env{'request.course.id'};
4184: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4185: $dc_info =~ s/\s+$//;
4186: $dc_info = '('.$dc_info.')';
4187: }
4188:
4189: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4190: # No Remote
4191: if ($env{'request.state'} eq 'construct') {
4192: $forcereg=1;
4193: }
4194:
4195: if (!$customtitle && $env{'request.state'} eq 'construct') {
4196: # this is for resources; directories have customtitle, and crumbs
4197: # and select recent are created in lonpubdir.pm
4198: my ($uname,$thisdisfn)=
4199: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4200: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4201: $formaction=~s/\/+/\//g;
4202:
4203: my $parentpath = '';
4204: my $lastitem = '';
4205: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4206: $parentpath = $1;
4207: $lastitem = $2;
4208: } else {
4209: $lastitem = $thisdisfn;
4210: }
4211: $titleinfo =
4212: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4213: .'<b>'.&mt('Construction Space').'</b>: '
4214: .'<form name="dirs" method="post" action="'.$formaction
4215: .'" target="_top"><tt><b>'
4216: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
4217: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4218: .'</form>'
4219: .&Apache::lonmenu::constspaceform();
4220: }
4221:
4222: my $titletable;
4223: if (!$notitle) {
4224: $titletable =
4225: '<table id="LC_title_bar">'.
4226: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4227: '</tr></table>';
4228: }
4229: if ($notopbar) {
4230: $bodytag .= $titletable;
4231: } else {
4232: if ($env{'request.state'} eq 'construct') {
4233: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4234: $titletable);
4235: } else {
4236: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4237: $titletable;
4238: }
4239: }
4240: return $bodytag;
4241: }
4242:
4243: #
4244: # Top frame rendering, Remote is up
4245: #
4246:
4247: my $imgsrc = $img;
4248: if ($img =~ /^\/adm/) {
4249: $imgsrc = &lonhttpdurl($img);
4250: }
4251: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4252:
4253: # Explicit link to get inline menu
4254: my $menu= ($no_inline_link?''
4255: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4256: #
4257: if ($notitle) {
4258: return $bodytag;
4259: }
4260: return(<<ENDBODY);
4261: $bodytag
4262: <table id="LC_title_bar" class="LC_with_remote">
4263: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4264: <td class="LC_title_bar_domain_logo">$messages </td>
4265: </tr>
4266: <tr><td>$titleinfo $dc_info $menu</td>
4267: $roleinfo
4268: </tr>
4269: </table>
4270: ENDBODY
4271: }
4272:
4273: sub make_attr_string {
4274: my ($register,$attr_ref) = @_;
4275:
4276: if ($attr_ref && !ref($attr_ref)) {
4277: die("addentries Must be a hash ref ".
4278: join(':',caller(1))." ".
4279: join(':',caller(0))." ");
4280: }
4281:
4282: if ($register) {
4283: my ($on_load,$on_unload);
4284: foreach my $key (keys(%{$attr_ref})) {
4285: if (lc($key) eq 'onload') {
4286: $on_load.=$attr_ref->{$key}.';';
4287: delete($attr_ref->{$key});
4288:
4289: } elsif (lc($key) eq 'onunload') {
4290: $on_unload.=$attr_ref->{$key}.';';
4291: delete($attr_ref->{$key});
4292: }
4293: }
4294: $attr_ref->{'onload'} =
4295: &Apache::lonmenu::loadevents(). $on_load;
4296: $attr_ref->{'onunload'}=
4297: &Apache::lonmenu::unloadevents().$on_unload;
4298: }
4299:
4300: # Accessibility font enhance
4301: if ($env{'browser.fontenhance'} eq 'on') {
4302: my $style;
4303: foreach my $key (keys(%{$attr_ref})) {
4304: if (lc($key) eq 'style') {
4305: $style.=$attr_ref->{$key}.';';
4306: delete($attr_ref->{$key});
4307: }
4308: }
4309: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4310: }
4311:
4312: if ($env{'browser.blackwhite'} eq 'on') {
4313: delete($attr_ref->{'font'});
4314: delete($attr_ref->{'link'});
4315: delete($attr_ref->{'alink'});
4316: delete($attr_ref->{'vlink'});
4317: delete($attr_ref->{'bgcolor'});
4318: delete($attr_ref->{'background'});
4319: }
4320:
4321: my $attr_string;
4322: foreach my $attr (keys(%$attr_ref)) {
4323: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4324: }
4325: return $attr_string;
4326: }
4327:
4328:
4329: ###############################################
4330: ###############################################
4331:
4332: =pod
4333:
4334: =item * &endbodytag()
4335:
4336: Returns a uniform footer for LON-CAPA web pages.
4337:
4338: Inputs: 1 - optional reference to an args hash
4339: If in the hash, key for noredirectlink has a value which evaluates to true,
4340: a 'Continue' link is not displayed if the page contains an
4341: internal redirect in the <head></head> section,
4342: i.e., $env{'internal.head.redirect'} exists
4343:
4344: =cut
4345:
4346: sub endbodytag {
4347: my ($args) = @_;
4348: my $endbodytag='</body>';
4349: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4350: if ( exists( $env{'internal.head.redirect'} ) ) {
4351: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4352: $endbodytag=
4353: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4354: &mt('Continue').'</a>'.
4355: $endbodytag;
4356: }
4357: }
4358: return $endbodytag;
4359: }
4360:
4361: =pod
4362:
4363: =item * &standard_css()
4364:
4365: Returns a style sheet
4366:
4367: Inputs: (all optional)
4368: domain -> force to color decorate a page for a specific
4369: domain
4370: function -> force usage of a specific rolish color scheme
4371: bgcolor -> override the default page bgcolor
4372:
4373: =cut
4374:
4375: sub standard_css {
4376: my ($function,$domain,$bgcolor) = @_;
4377: $function = &get_users_function() if (!$function);
4378: my $img = &designparm($function.'.img', $domain);
4379: my $tabbg = &designparm($function.'.tabbg', $domain);
4380: my $font = &designparm($function.'.font', $domain);
4381: my $sidebg = &designparm($function.'.sidebg',$domain);
4382: my $pgbg_or_bgcolor =
4383: $bgcolor ||
4384: &designparm($function.'.pgbg', $domain);
4385: my $pgbg = &designparm($function.'.pgbg', $domain);
4386: my $alink = &designparm($function.'.alink', $domain);
4387: my $vlink = &designparm($function.'.vlink', $domain);
4388: my $link = &designparm($function.'.link', $domain);
4389:
4390: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4391: my $mono = 'monospace';
4392: my $data_table_head = $tabbg;
4393: my $data_table_light = '#EEEEEE';
4394: my $data_table_dark = '#DDDDDD';
4395: my $data_table_darker = '#CCCCCC';
4396: my $data_table_highlight = '#FFFF00';
4397: my $mail_new = '#FFBB77';
4398: my $mail_new_hover = '#DD9955';
4399: my $mail_read = '#BBBB77';
4400: my $mail_read_hover = '#999944';
4401: my $mail_replied = '#AAAA88';
4402: my $mail_replied_hover = '#888855';
4403: my $mail_other = '#99BBBB';
4404: my $mail_other_hover = '#669999';
4405: my $table_header = '#DDDDDD';
4406: my $feedback_link_bg = '#BBBBBB';
4407:
4408: my $border = ($env{'browser.type'} eq 'explorer' ||
4409: $env{'browser.type'} eq 'safari' ) ? '0px 2px 0px 2px'
4410: : '0px 3px 0px 4px';
4411:
4412:
4413: return <<END;
4414: h1, h2, h3, th { font-family: $sans }
4415: a:focus { color: red; background: yellow }
4416: table.thinborder,
4417:
4418: table.thinborder tr th {
4419: border-style: solid;
4420: border-width: 1px;
4421: background: $tabbg;
4422: }
4423: table.thinborder tr td {
4424: border-style: solid;
4425: border-width: 1px
4426: }
4427:
4428: form, .inline { display: inline; }
4429: .center { text-align: center; }
4430: .LC_filename {font-family: $mono; white-space:pre;}
4431: .LC_error {
4432: color: red;
4433: font-size: larger;
4434: }
4435: .LC_warning,
4436: .LC_diff_removed {
4437: color: red;
4438: }
4439:
4440: .LC_info,
4441: .LC_success,
4442: .LC_diff_added {
4443: color: green;
4444: }
4445: .LC_unknown {
4446: color: yellow;
4447: }
4448:
4449: .LC_icon {
4450: border: 0px;
4451: }
4452: .LC_indexer_icon {
4453: border: 0px;
4454: height: 22px;
4455: }
4456: .LC_docs_spacer {
4457: width: 25px;
4458: height: 1px;
4459: border: 0px;
4460: }
4461:
4462: .LC_internal_info {
4463: color: #999;
4464: }
4465:
4466: table.LC_pastsubmission {
4467: border: 1px solid black;
4468: margin: 2px;
4469: }
4470:
4471: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4472: width: 100%;
4473: background: $pgbg;
4474: border: 2px;
4475: border-collapse: separate;
4476: padding: 0px;
4477: }
4478:
4479: table#LC_title_bar, table.LC_breadcrumbs,
4480: table#LC_title_bar.LC_with_remote {
4481: width: 100%;
4482: border-color: $pgbg;
4483: border-style: solid;
4484: border-width: $border;
4485:
4486: background: $pgbg;
4487: font-family: $sans;
4488: border-collapse: collapse;
4489: padding: 0px;
4490: }
4491:
4492: table.LC_docs_path {
4493: width: 100%;
4494: border: 0;
4495: background: $pgbg;
4496: font-family: $sans;
4497: border-collapse: collapse;
4498: padding: 0px;
4499: }
4500:
4501: table#LC_title_bar td {
4502: background: $tabbg;
4503: }
4504: table#LC_title_bar td.LC_title_bar_who {
4505: background: $tabbg;
4506: color: $font;
4507: font: small $sans;
4508: text-align: right;
4509: }
4510: span.LC_metadata {
4511: font-family: $sans;
4512: }
4513: span.LC_title_bar_title {
4514: font: bold x-large $sans;
4515: }
4516: table#LC_title_bar td.LC_title_bar_domain_logo {
4517: background: $sidebg;
4518: text-align: right;
4519: padding: 0px;
4520: }
4521: table#LC_title_bar td.LC_title_bar_role_logo {
4522: background: $sidebg;
4523: padding: 0px;
4524: }
4525:
4526: table#LC_menubuttons_mainmenu {
4527: width: 100%;
4528: border: 0px;
4529: border-spacing: 1px;
4530: padding: 0px 1px;
4531: margin: 0px;
4532: border-collapse: separate;
4533: }
4534: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
4535: border: 0px;
4536: }
4537: table#LC_top_nav td {
4538: background: $tabbg;
4539: border: 0px;
4540: font-size: small;
4541: }
4542: table#LC_top_nav td a, div#LC_top_nav a {
4543: color: $font;
4544: font-family: $sans;
4545: }
4546: table#LC_top_nav td.LC_top_nav_logo {
4547: background: $tabbg;
4548: text-align: left;
4549: white-space: nowrap;
4550: width: 31px;
4551: }
4552: table#LC_top_nav td.LC_top_nav_logo img {
4553: border: 0px;
4554: vertical-align: bottom;
4555: }
4556: table#LC_top_nav td.LC_top_nav_exit,
4557: table#LC_top_nav td.LC_top_nav_help {
4558: width: 2.0em;
4559: }
4560: table#LC_top_nav td.LC_top_nav_login {
4561: width: 4.0em;
4562: text-align: center;
4563: }
4564: table.LC_breadcrumbs td, table.LC_docs_path td {
4565: background: $tabbg;
4566: color: $font;
4567: font-family: $sans;
4568: font-size: smaller;
4569: }
4570: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4571: table.LC_docs_path td.LC_docs_path_component {
4572: background: $tabbg;
4573: color: $font;
4574: font-family: $sans;
4575: font-size: larger;
4576: text-align: right;
4577: }
4578: td.LC_table_cell_checkbox {
4579: text-align: center;
4580: }
4581: table#LC_mainmenu td.LC_mainmenu_column {
4582: vertical-align: top;
4583: }
4584:
4585: .LC_menubuttons_inline_text {
4586: color: $font;
4587: font-family: $sans;
4588: font-size: smaller;
4589: }
4590:
4591: .LC_menubuttons_link {
4592: text-decoration: none;
4593: }
4594: #2008--9-5: new menu style sheet.Changed category
4595: .LC_menubuttons_category {
4596: color: $font;
4597: background: $pgbg;
4598: font-family: $sans;
4599: font-size: larger;
4600: font-weight: bold;
4601: }
4602:
4603: td.LC_menubuttons_text {
4604: width: 90%;
4605: color: $font;
4606: font-family: $sans;
4607: }
4608:
4609: td.LC_menubuttons_img {
4610: }
4611:
4612: .LC_current_location {
4613: font-family: $sans;
4614: background: $tabbg;
4615: }
4616: .LC_new_mail {
4617: font-family: $sans;
4618: background: $tabbg;
4619: font-weight: bold;
4620: }
4621:
4622: .LC_rolesmenu_is {
4623: font-family: $sans;
4624: }
4625:
4626: .LC_rolesmenu_selected {
4627: font-family: $sans;
4628: }
4629:
4630: .LC_rolesmenu_future {
4631: font-family: $sans;
4632: }
4633:
4634:
4635: .LC_rolesmenu_will {
4636: font-family: $sans;
4637: }
4638:
4639: .LC_rolesmenu_will_not {
4640: font-family: $sans;
4641: }
4642:
4643: .LC_rolesmenu_expired {
4644: font-family: $sans;
4645: }
4646:
4647: .LC_rolesinfo {
4648: font-family: $sans;
4649: }
4650:
4651: .LC_dropadd_labeltext {
4652: font-family: $sans;
4653: text-align: right;
4654: }
4655:
4656: .LC_preferences_labeltext {
4657: font-family: $sans;
4658: text-align: right;
4659: }
4660:
4661: .LC_roleslog_note {
4662: font-size: smaller;
4663: }
4664:
4665: table.LC_aboutme_port {
4666: border: 0px;
4667: border-collapse: collapse;
4668: border-spacing: 0px;
4669: }
4670: table.LC_data_table, table.LC_mail_list {
4671: border: 1px solid #000000;
4672: border-collapse: separate;
4673: border-spacing: 1px;
4674: background: $pgbg;
4675: }
4676: .LC_data_table_dense {
4677: font-size: small;
4678: }
4679: table.LC_nested_outer {
4680: border: 1px solid #000000;
4681: border-collapse: collapse;
4682: border-spacing: 0px;
4683: width: 100%;
4684: }
4685: table.LC_nested {
4686: border: 0px;
4687: border-collapse: collapse;
4688: border-spacing: 0px;
4689: width: 100%;
4690: }
4691: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
4692: table.LC_prior_tries tr th {
4693: font-weight: bold;
4694: background-color: $data_table_head;
4695: font-size: smaller;
4696: }
4697: table.LC_data_table tr.LC_odd_row > td,
4698: table.LC_aboutme_port tr td {
4699: background-color: $data_table_light;
4700: padding: 2px;
4701: }
4702: table.LC_data_table tr.LC_even_row > td,
4703: table.LC_aboutme_port tr.LC_even_row td {
4704: background-color: $data_table_dark;
4705: }
4706: table.LC_data_table tr.LC_data_table_highlight td {
4707: background-color: $data_table_darker;
4708: }
4709: table.LC_data_table tr td.LC_leftcol_header {
4710: background-color: $data_table_head;
4711: font-weight: bold;
4712: }
4713: table.LC_data_table tr.LC_empty_row td,
4714: table.LC_nested tr.LC_empty_row td {
4715: background-color: #FFFFFF;
4716: font-weight: bold;
4717: font-style: italic;
4718: text-align: center;
4719: padding: 8px;
4720: }
4721: table.LC_nested tr.LC_empty_row td {
4722: padding: 4ex
4723: }
4724: table.LC_nested_outer tr th {
4725: font-weight: bold;
4726: background-color: $data_table_head;
4727: font-size: smaller;
4728: border-bottom: 1px solid #000000;
4729: }
4730: table.LC_nested_outer tr td.LC_subheader {
4731: background-color: $data_table_head;
4732: font-weight: bold;
4733: font-size: small;
4734: border-bottom: 1px solid #000000;
4735: text-align: right;
4736: }
4737: table.LC_nested tr.LC_info_row td {
4738: background-color: #CCC;
4739: font-weight: bold;
4740: font-size: small;
4741: text-align: center;
4742: }
4743: table.LC_nested tr.LC_info_row td.LC_left_item,
4744: table.LC_nested_outer tr th.LC_left_item {
4745: text-align: left;
4746: }
4747: table.LC_nested td {
4748: background-color: #FFF;
4749: font-size: small;
4750: }
4751: table.LC_nested_outer tr th.LC_right_item,
4752: table.LC_nested tr.LC_info_row td.LC_right_item,
4753: table.LC_nested tr.LC_odd_row td.LC_right_item,
4754: table.LC_nested tr td.LC_right_item {
4755: text-align: right;
4756: }
4757:
4758: table.LC_nested tr.LC_odd_row td {
4759: background-color: #EEE;
4760: }
4761:
4762: table.LC_createuser {
4763: }
4764:
4765: table.LC_createuser tr.LC_section_row td {
4766: font-size: smaller;
4767: }
4768:
4769: table.LC_createuser tr.LC_info_row td {
4770: background-color: #CCC;
4771: font-weight: bold;
4772: text-align: center;
4773: }
4774:
4775: table.LC_calendar {
4776: border: 1px solid #000000;
4777: border-collapse: collapse;
4778: }
4779: table.LC_calendar_pickdate {
4780: font-size: xx-small;
4781: }
4782: table.LC_calendar tr td {
4783: border: 1px solid #000000;
4784: vertical-align: top;
4785: }
4786: table.LC_calendar tr td.LC_calendar_day_empty {
4787: background-color: $data_table_dark;
4788: }
4789: table.LC_calendar tr td.LC_calendar_day_current {
4790: background-color: $data_table_highlight;
4791: }
4792:
4793: table.LC_mail_list tr.LC_mail_new {
4794: background-color: $mail_new;
4795: }
4796: table.LC_mail_list tr.LC_mail_new:hover {
4797: background-color: $mail_new_hover;
4798: }
4799: table.LC_mail_list tr.LC_mail_read {
4800: background-color: $mail_read;
4801: }
4802: table.LC_mail_list tr.LC_mail_read:hover {
4803: background-color: $mail_read_hover;
4804: }
4805: table.LC_mail_list tr.LC_mail_replied {
4806: background-color: $mail_replied;
4807: }
4808: table.LC_mail_list tr.LC_mail_replied:hover {
4809: background-color: $mail_replied_hover;
4810: }
4811: table.LC_mail_list tr.LC_mail_other {
4812: background-color: $mail_other;
4813: }
4814: table.LC_mail_list tr.LC_mail_other:hover {
4815: background-color: $mail_other_hover;
4816: }
4817: table.LC_mail_list tr.LC_mail_even {
4818: }
4819: table.LC_mail_list tr.LC_mail_odd {
4820: }
4821:
4822: table#LC_cstr_controls {
4823: width: 100%;
4824: border-collapse: collapse;
4825: }
4826: table#LC_cstr_controls tr td {
4827: border: 4px solid $pgbg;
4828: padding: 4px;
4829: text-align: center;
4830: background: $tabbg;
4831: }
4832: table#LC_cstr_controls tr th {
4833: border: 4px solid $pgbg;
4834: background: $table_header;
4835: text-align: center;
4836: font-family: $sans;
4837: font-size: smaller;
4838: }
4839:
4840: table.LC_data_table tr > td.LC_browser_file,
4841: table.LC_data_table tr > td.LC_browser_file_published {
4842: background: #CCFF88;
4843: }
4844: table.LC_data_table tr > td.LC_browser_file_locked,
4845: table.LC_data_table tr > td.LC_browser_file_unpublished {
4846: background: #FFAA99;
4847: }
4848: table.LC_data_table tr > td.LC_browser_file_obsolete {
4849: background: #AAAAAA;
4850: }
4851: table.LC_data_table tr > td.LC_browser_file_modified,
4852: table.LC_data_table tr > td.LC_browser_file_metamodified {
4853: background: #FFFF77;
4854: }
4855: table.LC_data_table tr.LC_browser_folder > td {
4856: background: #CCCCFF;
4857: }
4858:
4859: span.LC_current_location {
4860: font-size: x-large;
4861: background: $pgbg;
4862: }
4863:
4864: span.LC_parm_menu_item {
4865: font-size: larger;
4866: font-family: $sans;
4867: }
4868: span.LC_parm_scope_all {
4869: color: red;
4870: }
4871: span.LC_parm_scope_folder {
4872: color: green;
4873: }
4874: span.LC_parm_scope_resource {
4875: color: orange;
4876: }
4877: span.LC_parm_part {
4878: color: blue;
4879: }
4880: span.LC_parm_folder, span.LC_parm_symb {
4881: font-size: x-small;
4882: font-family: $mono;
4883: color: #AAAAAA;
4884: }
4885:
4886: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
4887: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
4888: border: 1px solid black;
4889: border-collapse: collapse;
4890: }
4891: table.LC_parm_overview_restrictions td {
4892: border-width: 1px 4px 1px 4px;
4893: border-style: solid;
4894: border-color: $pgbg;
4895: text-align: center;
4896: }
4897: table.LC_parm_overview_restrictions th {
4898: background: $tabbg;
4899: border-width: 1px 4px 1px 4px;
4900: border-style: solid;
4901: border-color: $pgbg;
4902: }
4903: table#LC_helpmenu {
4904: border: 0px;
4905: height: 55px;
4906: border-spacing: 0px;
4907: }
4908:
4909: table#LC_helpmenu fieldset legend {
4910: font-size: larger;
4911: font-weight: bold;
4912: }
4913: table#LC_helpmenu_links {
4914: width: 100%;
4915: border: 1px solid black;
4916: background: $pgbg;
4917: padding: 0px;
4918: border-spacing: 1px;
4919: }
4920: table#LC_helpmenu_links tr td {
4921: padding: 1px;
4922: background: $tabbg;
4923: text-align: center;
4924: font-weight: bold;
4925: }
4926:
4927: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
4928: table#LC_helpmenu_links a:active {
4929: text-decoration: none;
4930: color: $font;
4931: }
4932: table#LC_helpmenu_links a:hover {
4933: text-decoration: underline;
4934: color: $vlink;
4935: }
4936:
4937: .LC_chrt_popup_exists {
4938: border: 1px solid #339933;
4939: margin: -1px;
4940: }
4941: .LC_chrt_popup_up {
4942: border: 1px solid yellow;
4943: margin: -1px;
4944: }
4945: .LC_chrt_popup {
4946: border: 1px solid #8888FF;
4947: background: #CCCCFF;
4948: }
4949: table.LC_pick_box {
4950: border-collapse: separate;
4951: background: white;
4952: border: 1px solid black;
4953: border-spacing: 1px;
4954: }
4955: table.LC_pick_box td.LC_pick_box_title {
4956: background: $tabbg;
4957: font-weight: bold;
4958: text-align: right;
4959: width: 184px;
4960: padding: 8px;
4961: }
4962: table.LC_pick_box td.LC_selfenroll_pick_box_title {
4963: background: $tabbg;
4964: font-weight: bold;
4965: text-align: right;
4966: width: 350px;
4967: padding: 8px;
4968: }
4969:
4970: table.LC_pick_box td.LC_pick_box_value {
4971: text-align: left;
4972: padding: 8px;
4973: }
4974: table.LC_pick_box td.LC_pick_box_select {
4975: text-align: left;
4976: padding: 8px;
4977: }
4978: table.LC_pick_box td.LC_pick_box_separator {
4979: padding: 0px;
4980: height: 1px;
4981: background: black;
4982: }
4983: table.LC_pick_box td.LC_pick_box_submit {
4984: text-align: right;
4985: }
4986: table.LC_pick_box td.LC_evenrow_value {
4987: text-align: left;
4988: padding: 8px;
4989: background-color: $data_table_light;
4990: }
4991: table.LC_pick_box td.LC_oddrow_value {
4992: text-align: left;
4993: padding: 8px;
4994: background-color: $data_table_light;
4995: }
4996: table.LC_helpform_receipt {
4997: width: 620px;
4998: border-collapse: separate;
4999: background: white;
5000: border: 1px solid black;
5001: border-spacing: 1px;
5002: }
5003: table.LC_helpform_receipt td.LC_pick_box_title {
5004: background: $tabbg;
5005: font-weight: bold;
5006: text-align: right;
5007: width: 184px;
5008: padding: 8px;
5009: }
5010: table.LC_helpform_receipt td.LC_evenrow_value {
5011: text-align: left;
5012: padding: 8px;
5013: background-color: $data_table_light;
5014: }
5015: table.LC_helpform_receipt td.LC_oddrow_value {
5016: text-align: left;
5017: padding: 8px;
5018: background-color: $data_table_light;
5019: }
5020: table.LC_helpform_receipt td.LC_pick_box_separator {
5021: padding: 0px;
5022: height: 1px;
5023: background: black;
5024: }
5025: span.LC_helpform_receipt_cat {
5026: font-weight: bold;
5027: }
5028: table.LC_group_priv_box {
5029: background: white;
5030: border: 1px solid black;
5031: border-spacing: 1px;
5032: }
5033: table.LC_group_priv_box td.LC_pick_box_title {
5034: background: $tabbg;
5035: font-weight: bold;
5036: text-align: right;
5037: width: 184px;
5038: }
5039: table.LC_group_priv_box td.LC_groups_fixed {
5040: background: $data_table_light;
5041: text-align: center;
5042: }
5043: table.LC_group_priv_box td.LC_groups_optional {
5044: background: $data_table_dark;
5045: text-align: center;
5046: }
5047: table.LC_group_priv_box td.LC_groups_functionality {
5048: background: $data_table_darker;
5049: text-align: center;
5050: font-weight: bold;
5051: }
5052: table.LC_group_priv td {
5053: text-align: left;
5054: padding: 0px;
5055: }
5056:
5057: table.LC_notify_front_page {
5058: background: white;
5059: border: 1px solid black;
5060: padding: 8px;
5061: }
5062: table.LC_notify_front_page td {
5063: padding: 8px;
5064: }
5065: .LC_navbuttons {
5066: margin: 2ex 0ex 2ex 0ex;
5067: }
5068: .LC_topic_bar {
5069: font-family: $sans;
5070: font-weight: bold;
5071: width: 100%;
5072: background: $tabbg;
5073: vertical-align: middle;
5074: margin: 2ex 0ex 2ex 0ex;
5075: }
5076: .LC_topic_bar span {
5077: vertical-align: middle;
5078: }
5079: .LC_topic_bar img {
5080: vertical-align: bottom;
5081: }
5082: table.LC_course_group_status {
5083: margin: 20px;
5084: }
5085: table.LC_status_selector td {
5086: vertical-align: top;
5087: text-align: center;
5088: padding: 4px;
5089: }
5090: table.LC_descriptive_input td.LC_description {
5091: vertical-align: top;
5092: text-align: right;
5093: font-weight: bold;
5094: }
5095: div.LC_feedback_link {
5096: clear: both;
5097: background: white;
5098: width: 100%;
5099: }
5100: span.LC_feedback_link {
5101: background: $feedback_link_bg;
5102: font-size: larger;
5103: }
5104: span.LC_message_link {
5105: background: $feedback_link_bg;
5106: font-size: larger;
5107: position: absolute;
5108: right: 1em;
5109: }
5110:
5111: table.LC_prior_tries {
5112: border: 1px solid #000000;
5113: border-collapse: separate;
5114: border-spacing: 1px;
5115: }
5116:
5117: table.LC_prior_tries td {
5118: padding: 2px;
5119: }
5120:
5121: .LC_answer_correct {
5122: background: #AAFFAA;
5123: color: black;
5124: }
5125: .LC_answer_charged_try {
5126: background: #FFAAAA ! important;
5127: color: black;
5128: }
5129: .LC_answer_not_charged_try,
5130: .LC_answer_no_grade,
5131: .LC_answer_late {
5132: background: #FFFFAA;
5133: color: black;
5134: }
5135: .LC_answer_previous {
5136: background: #AAAAFF;
5137: color: black;
5138: }
5139: .LC_answer_no_message {
5140: background: #FFFFFF;
5141: color: black;
5142: }
5143: .LC_answer_unknown {
5144: background: orange;
5145: color: black;
5146: }
5147:
5148:
5149: span.LC_prior_numerical,
5150: span.LC_prior_string,
5151: span.LC_prior_custom,
5152: span.LC_prior_reaction,
5153: span.LC_prior_math {
5154: font-family: monospace;
5155: white-space: pre;
5156: }
5157:
5158: span.LC_prior_string {
5159: font-family: monospace;
5160: white-space: pre;
5161: }
5162:
5163: table.LC_prior_option {
5164: width: 100%;
5165: border-collapse: collapse;
5166: }
5167: table.LC_prior_rank, table.LC_prior_match {
5168: border-collapse: collapse;
5169: }
5170: table.LC_prior_option tr td,
5171: table.LC_prior_rank tr td,
5172: table.LC_prior_match tr td {
5173: border: 1px solid #000000;
5174: }
5175:
5176: span.LC_nobreak {
5177: white-space: nowrap;
5178: }
5179:
5180: span.LC_cusr_emph {
5181: font-style: italic;
5182: }
5183:
5184: span.LC_cusr_subheading {
5185: font-weight: normal;
5186: font-size: 85%;
5187: }
5188:
5189: table.LC_docs_documents {
5190: background: #BBBBBB;
5191: border-width: 0px;
5192: border-collapse: collapse;
5193: }
5194:
5195: table.LC_docs_documents td.LC_docs_document {
5196: border: 2px solid black;
5197: padding: 4px;
5198: }
5199:
5200: .LC_docs_course_commands div {
5201: float: left;
5202: border: 4px solid #AAAAAA;
5203: padding: 4px;
5204: background: #DDDDCC;
5205: }
5206:
5207: .LC_docs_entry_move {
5208: border: 0px;
5209: border-collapse: collapse;
5210: }
5211:
5212: .LC_docs_entry_move td {
5213: border: 2px solid #BBBBBB;
5214: background: #DDDDDD;
5215: }
5216:
5217: .LC_docs_editor td.LC_docs_entry_commands {
5218: background: #DDDDDD;
5219: font-size: x-small;
5220: }
5221: .LC_docs_copy {
5222: color: #000099;
5223: }
5224: .LC_docs_cut {
5225: color: #550044;
5226: }
5227: .LC_docs_rename {
5228: color: #009900;
5229: }
5230: .LC_docs_remove {
5231: color: #990000;
5232: }
5233:
5234: .LC_docs_reinit_warn,
5235: .LC_docs_ext_edit {
5236: font-size: x-small;
5237: }
5238:
5239: .LC_docs_editor td.LC_docs_entry_title,
5240: .LC_docs_editor td.LC_docs_entry_icon {
5241: background: #FFFFBB;
5242: }
5243: .LC_docs_editor td.LC_docs_entry_parameter {
5244: background: #BBBBFF;
5245: font-size: x-small;
5246: white-space: nowrap;
5247: }
5248:
5249: table.LC_docs_adddocs td,
5250: table.LC_docs_adddocs th {
5251: border: 1px solid #BBBBBB;
5252: padding: 4px;
5253: background: #DDDDDD;
5254: }
5255:
5256: table.LC_sty_begin {
5257: background: #BBFFBB;
5258: }
5259: table.LC_sty_end {
5260: background: #FFBBBB;
5261: }
5262:
5263: table.LC_double_column {
5264: border-width: 0px;
5265: border-collapse: collapse;
5266: width: 100%;
5267: padding: 2px;
5268: }
5269:
5270: table.LC_double_column tr td.LC_left_col {
5271: top: 2px;
5272: left: 2px;
5273: width: 47%;
5274: vertical-align: top;
5275: }
5276:
5277: table.LC_double_column tr td.LC_right_col {
5278: top: 2px;
5279: right: 2px;
5280: width: 47%;
5281: vertical-align: top;
5282: }
5283:
5284: span.LC_role_level {
5285: font-weight: bold;
5286: }
5287:
5288: div.LC_left_float {
5289: float: left;
5290: padding-right: 5%;
5291: padding-bottom: 4px;
5292: }
5293:
5294: div.LC_clear_float_header {
5295: padding-bottom: 2px;
5296: }
5297:
5298: div.LC_clear_float_footer {
5299: padding-top: 10px;
5300: clear: both;
5301: }
5302:
5303:
5304: div.LC_grade_select_mode {
5305: font-family: $sans;
5306: }
5307: div.LC_grade_select_mode div div {
5308: margin: 5px;
5309: }
5310: div.LC_grade_select_mode_selector {
5311: margin: 5px;
5312: float: left;
5313: }
5314: div.LC_grade_select_mode_selector_header {
5315: font: bold medium $sans;
5316: }
5317: div.LC_grade_select_mode_type {
5318: clear: left;
5319: }
5320:
5321: div.LC_grade_show_user {
5322: margin-top: 20px;
5323: border: 1px solid black;
5324: }
5325: div.LC_grade_user_name {
5326: background: #DDDDEE;
5327: border-bottom: 1px solid black;
5328: font: bold large $sans;
5329: }
5330: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5331: background: #DDEEDD;
5332: }
5333:
5334: div.LC_grade_show_problem,
5335: div.LC_grade_submissions,
5336: div.LC_grade_message_center,
5337: div.LC_grade_info_links,
5338: div.LC_grade_assign {
5339: margin: 5px;
5340: width: 99%;
5341: background: #FFFFFF;
5342: }
5343: div.LC_grade_show_problem_header,
5344: div.LC_grade_submissions_header,
5345: div.LC_grade_message_center_header,
5346: div.LC_grade_assign_header {
5347: font: bold large $sans;
5348: }
5349: div.LC_grade_show_problem_problem,
5350: div.LC_grade_submissions_body,
5351: div.LC_grade_message_center_body,
5352: div.LC_grade_assign_body {
5353: border: 1px solid black;
5354: width: 99%;
5355: background: #FFFFFF;
5356: }
5357: span.LC_grade_check_note {
5358: font: normal medium $sans;
5359: display: inline;
5360: position: absolute;
5361: right: 1em;
5362: }
5363:
5364: table.LC_scantron_action {
5365: width: 100%;
5366: }
5367: table.LC_scantron_action tr th {
5368: font: normal bold $sans;
5369: }
5370:
5371: div.LC_edit_problem_header,
5372: div.LC_edit_problem_footer {
5373: font: normal medium $sans;
5374: margin: 2px;
5375: }
5376: div.LC_edit_problem_header,
5377: div.LC_edit_problem_header div,
5378: div.LC_edit_problem_footer,
5379: div.LC_edit_problem_footer div,
5380: div.LC_edit_problem_editxml_header,
5381: div.LC_edit_problem_editxml_header div {
5382: margin-top: 5px;
5383: }
5384: div.LC_edit_problem_header_edit_row {
5385: background: $tabbg;
5386: padding: 3px;
5387: margin-bottom: 5px;
5388: }
5389: div.LC_edit_problem_header_title {
5390: font: larger bold $sans;
5391: background: $tabbg;
5392: padding: 3px;
5393: }
5394: table.LC_edit_problem_header_title {
5395: font: larger bold $sans;
5396: width: 100%;
5397: border-color: $pgbg;
5398: border-style: solid;
5399: border-width: $border;
5400:
5401: background: $tabbg;
5402: border-collapse: collapse;
5403: padding: 0px
5404: }
5405:
5406: div.LC_edit_problem_discards {
5407: float: left;
5408: padding-bottom: 5px;
5409: }
5410: div.LC_edit_problem_saves {
5411: float: right;
5412: padding-bottom: 5px;
5413: }
5414: hr.LC_edit_problem_divide {
5415: clear: both;
5416: color: $tabbg;
5417: background-color: $tabbg;
5418: height: 3px;
5419: border: 0px;
5420: }
5421: img.stift{
5422: border-width:0;
5423: vertical-align:middle;
5424: }
5425:
5426: table#LC_mainmenu{
5427: margin-top:10px;
5428: width:80%;
5429:
5430: }
5431:
5432: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5433: vertical-align: top;
5434: width: 45%;
5435: }
5436: .LC_mainmenu_fieldset_category {
5437: color: $font;
5438: background: $pgbg;
5439: font-family: $sans;
5440: font-size: small;
5441: font-weight: bold;
5442: }
5443: fieldset#LC_mainmenu_fieldset {
5444: margin:0px 10px 10px 0px;
5445:
5446: }
5447: /* ---- Remove when done ----
5448: # The following styles is part of the redesign of LON-CAPA and are
5449: # subject to change during this project.
5450: # Don't rely on their current functionality as they might be
5451: # changed or removed.
5452: # --------------------------*/
5453:
5454:
5455: body {
5456: font-family: Tahoma, Arial,Helvetica,sans-serif;
5457: font-size: 0.85em;
5458: line-height: 130%;
5459: color: RGB(45, 45, 45);
5460: }
5461:
5462: a:link,a:visited {
5463: /*color: RGB(0, 118, 127);*/
5464: /*text-decoration: underline;*/
5465: }
5466:
5467: a:hover{
5468: text-decoration:none;
5469: }
5470: /*a:hover,
5471: UL.smallMenu A:hover,
5472: UL.MenuBreadcrumbs A:hover,
5473: UL#TabMainMenuContent A:hover{
5474: color: rgb(200, 10, 50);
5475: }*/
5476:
5477: h1 {
5478: padding:5px 10px 5px 20px;
5479: line-height:130%;
5480: }
5481: h2,h4,h6 {
5482: /*color: RGB(0, 118, 127);*/
5483: }
5484: h2,h3,h4,h5,h6
5485: {
5486: margin:5px 0px 5px 0px;
5487: line-height:130%;
5488: }
5489:
5490: .right {
5491: text-align: right;
5492: }
5493:
5494: .center {
5495: text-align: center;
5496: }
5497:
5498: .left {
5499: text-align: left;
5500: }
5501:
5502:
5503: .HeadRight {
5504: text-align: right;
5505: float: right;
5506: margin: 0px;
5507: padding: 0px;
5508: right:0;
5509: position:absolute;
5510: }
5511:
5512: img {
5513: /* border: 0px; */
5514: }
5515:
5516: .personalBgColor {
5517: background: RGB(237, 239, 0) url(images/headHighlight.png) repeat-y left top;
5518: }
5519:
5520: p {
5521: padding: 10px;
5522: }
5523: DL,UL,Div,Fieldset {
5524: /*margin: 10px;*/
5525: overflow:hidden;
5526: }
5527: OL.smallMenu {
5528: margin: 0px 0px 0px 0px;
5529: }
5530:
5531: OL.smallMenu li {
5532: display: inline;
5533: padding: 5px 5px 0px 10px;
5534: vertical-align: top;
5535: }
5536:
5537: OL.smallMenu li img {
5538: vertical-align: bottom;
5539: }
5540:
5541: OL.smallMenu A {
5542: font-size: 90%;
5543: color: RGB(80, 80, 80);
5544: text-decoration: none;
5545: }
5546:
5547: OL#TabMainMenuContent {
5548:
5549: margin: 0px 0px 10px 0px;
5550: padding: 0px;
5551: }
5552:
5553: OL#TabMainMenuContent LI {
5554: display: inline;
5555: vertical-align: bottom;
5556: border-bottom: solid 1px RGB(175, 175, 175);
5557: border-right: solid 1px RGB(175, 175, 175);
5558: padding: 5px 15px 5px 15px;
5559: margin-right:4px;
5560: line-height: 140%;
5561: font-weight: bold;
5562: overflow:hidden;
5563: background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left top;
5564: }
5565:
5566: OL#TabMainMenuContent LI A {
5567: color: RGB(47, 47, 47);
5568: text-decoration: none;
5569: }
5570:
5571: OL#TabMainMenuContent DIV.columnSection {
5572: margin-bottom: 0px;
5573: }
5574:
5575: OL#MenuBreadcrumbs {
5576: border-top: solid 1px RGB(255, 255, 255);
5577: height: 20px;
5578: line-height: 20px;
5579: vertical-align: bottom;
5580: margin: 0px 0px 30px 0px;
5581: padding-left: 10px;
5582: list-style-position: inside;
5583: background: RGB(211, 206, 205) URL(images/TabMenuBG.png) repeat-x left
5584: top;
5585: }
5586:
5587: OL#MenuBreadcrumbs li {
5588: background: url(images/pfeil_white.png) no-repeat left center;
5589: display: inline;
5590: padding: 0px 0px 0px 10px;
5591: vertical-align: bottom;
5592: overflow:hidden;
5593: }
5594:
5595: OL#MenuBreadcrumbs LI A {
5596: text-decoration: none;
5597: font-size:90%;
5598: }
5599:
5600: h4.hcell {
5601: padding: 3px 10px 3px 10px;
5602: margin: 0px;
5603: background: RGB(0, 118, 127);
5604: color: white;
5605: border: outset 1px;
5606: }
5607:
5608: DIV.DivContentBoxSpecial
5609: {
5610: border: solid 1px RGB(100, 100, 100);
5611: }
5612:
5613: FIELDSET
5614: {
5615: /*width:78%;*/
5616: }
5617: DIV.DivContentBox,
5618: DIV.DivContentBoxSpecial {
5619: width: 80%;
5620: margin:10px;
5621: }
5622:
5623: FIELDSET legend,DL DT {
5624: font-weight: bold;
5625: font-size: 110%;
5626: /*padding-left: 0px;*/
5627: /* margin-left: 0px;*/
5628: }
5629:
5630: DIV.DivImportant {
5631: background: url(images/important.png) no-repeat center top;
5632: padding: 100px 10px 10px 10px;
5633: width: 200px;
5634: border: double 4px RGB(200, 200, 200);
5635: }
5636:
5637:
5638:
5639: DL.ListStyleClean DT {
5640: padding-right: 5px;
5641: display: table-header-group;
5642: }
5643:
5644: DL.ListStyleClean DD {
5645: display: table-row;
5646: }
5647:
5648: .ListStyleClean,
5649: .ListStyleSimple,
5650: .ListStyleNormal,
5651: .ListStyleNormal_Border,
5652: .ListStyleSpecial
5653: {
5654: /*display:block; */
5655: width: 400px;
5656: list-style-position: inside;
5657: list-style-type: none;
5658: overflow: hidden;
5659: padding: 0px;
5660: }
5661:
5662: .ListStyleClean li,
5663: .ListStyleSimple li,
5664: .ListStyleSimple DD,
5665: .ListStyleNormal li,
5666: .ListStyleNormal DD,
5667: .ListStyleSpecial li,
5668: .ListStyleSpecial DD
5669: {
5670: margin: 0px;
5671: padding: 5px 5px 5px 10px;
5672: clear: both;
5673: /*display:block;*/
5674: }
5675:
5676: .ListStyleClean LI,
5677: .ListStyleClean DD {
5678: padding-top: 0px;
5679: padding-bottom: 0px;
5680: }
5681:
5682: .ListStyleSimple DD,
5683: .ListStyleSimple LI{
5684: border-bottom: solid 1px RGB(150, 150, 150);
5685: }
5686:
5687: .ListStyleSpecial LI,
5688: .ListStyleSpecial DD {
5689: list-style-type: none;
5690: background-color: RGB(220, 220, 220);
5691: margin-bottom: 4px;
5692: }
5693:
5694: table.SimpleTable *{
5695: padding:10px;
5696: }
5697:
5698: table.SimpleTable td {
5699: vertical-align:top;
5700: border:solid 1px RGB(210,210,210);
5701: }
5702: table.SimpleTable thead{
5703: background:rgb(210,210,210);
5704: }
5705:
5706: DIV.columnSection {
5707: display: block;
5708: clear: both;
5709: overflow: hidden;
5710: margin:0px;
5711: }
5712:
5713: DIV.columnSection>* {
5714: float: left;
5715: margin: 10px 20px 10px 0px;
5716: overflow:hidden;
5717: }
5718:
5719: DIV.columnSection>FIELDSET,
5720: DIV.columnSection>DIV.DivContentBox,
5721: DIV.columnSection>DIV.DivContentBoxSpecial
5722: {
5723: width: 480px;
5724:
5725: }
5726:
5727: .LC_loginpage_container {
5728: text-align:left;
5729: margin : 0 auto;
5730: width:65%;
5731: padding: 10px;
5732: height: auto;
5733: background-color:#FFFFFF;
5734: border:1px solid #CCCCCC;
5735: }
5736:
5737:
5738: .LC_loginpage_loginContainer {
5739: float:left;
5740: width:60%;
5741: }
5742:
5743: .LC_loginpage_loginInfo {
5744: margin-top:20px;
5745: margin-left:20px;
5746: float:left;
5747: width:30%;
5748: border:1px solid #CCCCCC;
5749: padding:10px;
5750: }
5751:
5752: .LC_loginpage_space {
5753: clear:both;
5754: margin-bottom:20px;
5755: border-bottom: 1px solid #CCCCCC;
5756: }
5757:
5758: .LC_loginpage_fieldset{
5759: border: 1px solid #CCCCCC;
5760: margin: 0 auto;
5761: }
5762:
5763: .LC_loginpage_legend{
5764: padding: 2px;
5765: margin: 0px;
5766: font-size:14px;
5767: font-weight:bold;
5768: }
5769:
5770:
5771:
5772: END
5773: }
5774:
5775: =pod
5776:
5777: =item * &headtag()
5778:
5779: Returns a uniform footer for LON-CAPA web pages.
5780:
5781: Inputs: $title - optional title for the head
5782: $head_extra - optional extra HTML to put inside the <head>
5783: $args - optional arguments
5784: force_register - if is true call registerurl so the remote is
5785: informed
5786: redirect -> array ref of
5787: 1- seconds before redirect occurs
5788: 2- url to redirect to
5789: 3- whether the side effect should occur
5790: (side effect of setting
5791: $env{'internal.head.redirect'} to the url
5792: redirected too)
5793: domain -> force to color decorate a page for a specific
5794: domain
5795: function -> force usage of a specific rolish color scheme
5796: bgcolor -> override the default page bgcolor
5797: no_auto_mt_title
5798: -> prevent &mt()ing the title arg
5799:
5800: =cut
5801:
5802: sub headtag {
5803: my ($title,$head_extra,$args) = @_;
5804:
5805: my $function = $args->{'function'} || &get_users_function();
5806: my $domain = $args->{'domain'} || &determinedomain();
5807: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5808: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5809: $Apache::lonnet::perlvar{'lonVersion'},
5810: #time(),
5811: $env{'environment.color.timestamp'},
5812: $function,$domain,$bgcolor);
5813:
5814: $url = '/adm/css/'.&escape($url).'.css';
5815:
5816: my $result =
5817: '<head>'.
5818: &font_settings();
5819:
5820: if (!$args->{'frameset'}) {
5821: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5822: }
5823: if ($args->{'force_register'}) {
5824: $result .= &Apache::lonmenu::registerurl(1);
5825: }
5826: if (!$args->{'no_nav_bar'}
5827: && !$args->{'only_body'}
5828: && !$args->{'frameset'}) {
5829: $result .= &help_menu_js();
5830: }
5831:
5832: if (ref($args->{'redirect'})) {
5833: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5834: $url = &Apache::lonenc::check_encrypt($url);
5835: if (!$inhibit_continue) {
5836: $env{'internal.head.redirect'} = $url;
5837: }
5838: $result.=<<ADDMETA
5839: <meta http-equiv="pragma" content="no-cache" />
5840: <meta http-equiv="Refresh" content="$time; url=$url" />
5841: ADDMETA
5842: }
5843: if (!defined($title)) {
5844: $title = 'The LearningOnline Network with CAPA';
5845: }
5846: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5847: $result .= '<title> LON-CAPA '.$title.'</title>'
5848: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5849: .$head_extra;
5850: return $result;
5851: }
5852:
5853: =pod
5854:
5855: =item * &font_settings()
5856:
5857: Returns neccessary <meta> to set the proper encoding
5858:
5859: Inputs: none
5860:
5861: =cut
5862:
5863: sub font_settings {
5864: my $headerstring='';
5865: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5866: $headerstring.=
5867: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5868: }
5869: return $headerstring;
5870: }
5871:
5872: =pod
5873:
5874: =item * &xml_begin()
5875:
5876: Returns the needed doctype and <html>
5877:
5878: Inputs: none
5879:
5880: =cut
5881:
5882: sub xml_begin {
5883: my $output='';
5884:
5885: if ($env{'internal.start_page'}==1) {
5886: &Apache::lonhtmlcommon::init_htmlareafields();
5887: }
5888:
5889: if ($env{'browser.mathml'}) {
5890: $output='<?xml version="1.0"?>'
5891: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5892: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5893:
5894: # .'<!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">] >'
5895: .'<!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">'
5896: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5897: .'xmlns="http://www.w3.org/1999/xhtml">';
5898: } else {
5899: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>';
5900: }
5901: return $output;
5902: }
5903:
5904: =pod
5905:
5906: =item * &endheadtag()
5907:
5908: Returns a uniform </head> for LON-CAPA web pages.
5909:
5910: Inputs: none
5911:
5912: =cut
5913:
5914: sub endheadtag {
5915: return '</head>';
5916: }
5917:
5918: =pod
5919:
5920: =item * &head()
5921:
5922: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
5923:
5924: Inputs:
5925:
5926: =over 4
5927:
5928: $title - optional title for the page
5929:
5930: $head_extra - optional extra HTML to put inside the <head>
5931:
5932: =back
5933:
5934: =cut
5935:
5936: sub head {
5937: my ($title,$head_extra,$args) = @_;
5938: return &headtag($title,$head_extra,$args).&endheadtag();
5939: }
5940:
5941: =pod
5942:
5943: =item * &start_page()
5944:
5945: Returns a complete <html> .. <body> section for LON-CAPA web pages.
5946:
5947: Inputs:
5948:
5949: =over 4
5950:
5951: $title - optional title for the page
5952:
5953: $head_extra - optional extra HTML to incude inside the <head>
5954:
5955: $args - additional optional args supported are:
5956:
5957: =over 8
5958:
5959: only_body -> is true will set &bodytag() onlybodytag
5960: arg on
5961: no_nav_bar -> is true will set &bodytag() notopbar arg on
5962: add_entries -> additional attributes to add to the <body>
5963: domain -> force to color decorate a page for a
5964: specific domain
5965: function -> force usage of a specific rolish color
5966: scheme
5967: redirect -> see &headtag()
5968: bgcolor -> override the default page bg color
5969: js_ready -> return a string ready for being used in
5970: a javascript writeln
5971: html_encode -> return a string ready for being used in
5972: a html attribute
5973: force_register -> if is true will turn on the &bodytag()
5974: $forcereg arg
5975: body_title -> alternate text to use instead of $title
5976: in the title box that appears, this text
5977: is not auto translated like the $title is
5978: frameset -> if true will start with a <frameset>
5979: rather than <body>
5980: no_title -> if true the title bar won't be shown
5981: skip_phases -> hash ref of
5982: head -> skip the <html><head> generation
5983: body -> skip all <body> generation
5984: no_inline_link -> if true and in remote mode, don't show the
5985: 'Switch To Inline Menu' link
5986: no_auto_mt_title -> prevent &mt()ing the title arg
5987: inherit_jsmath -> when creating popup window in a page,
5988: should it have jsmath forced on by the
5989: current page
5990:
5991: =back
5992:
5993: =back
5994:
5995: =cut
5996:
5997: sub start_page {
5998: my ($title,$head_extra,$args) = @_;
5999: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6000: my %head_args;
6001: foreach my $arg ('redirect','force_register','domain','function',
6002: 'bgcolor','frameset','no_nav_bar','only_body',
6003: 'no_auto_mt_title') {
6004: if (defined($args->{$arg})) {
6005: $head_args{$arg} = $args->{$arg};
6006: }
6007: }
6008:
6009: $env{'internal.start_page'}++;
6010: my $result;
6011: if (! exists($args->{'skip_phases'}{'head'}) ) {
6012: $result.=
6013: &xml_begin().
6014: &headtag($title,$head_extra,\%head_args).&endheadtag();
6015: }
6016:
6017: if (! exists($args->{'skip_phases'}{'body'}) ) {
6018: if ($args->{'frameset'}) {
6019: my $attr_string = &make_attr_string($args->{'force_register'},
6020: $args->{'add_entries'});
6021: $result .= "\n<frameset $attr_string>\n";
6022: } else {
6023: $result .=
6024: &bodytag($title,
6025: $args->{'function'}, $args->{'add_entries'},
6026: $args->{'only_body'}, $args->{'domain'},
6027: $args->{'force_register'}, $args->{'body_title'},
6028: $args->{'no_nav_bar'}, $args->{'bgcolor'},
6029: $args->{'no_title'}, $args->{'no_inline_link'},
6030: $args);
6031: }
6032: }
6033:
6034: if ($args->{'js_ready'}) {
6035: $result = &js_ready($result);
6036: }
6037: if ($args->{'html_encode'}) {
6038: $result = &html_encode($result);
6039: }
6040: return $result;
6041: }
6042:
6043:
6044: =pod
6045:
6046: =item * &head()
6047:
6048: Returns a complete </body></html> section for LON-CAPA web pages.
6049:
6050: Inputs: $args - additional optional args supported are:
6051: js_ready -> return a string ready for being used in
6052: a javascript writeln
6053: html_encode -> return a string ready for being used in
6054: a html attribute
6055: frameset -> if true will start with a <frameset>
6056: rather than <body>
6057: dicsussion -> if true will get discussion from
6058: lonxml::xmlend
6059: (you can pass the target and parser arguments
6060: through optional 'target' and 'parser' args
6061: to this routine)
6062:
6063: =cut
6064:
6065: sub end_page {
6066: my ($args) = @_;
6067: $env{'internal.end_page'}++;
6068: my $result;
6069: if ($args->{'discussion'}) {
6070: my ($target,$parser);
6071: if (ref($args->{'discussion'})) {
6072: ($target,$parser) =($args->{'discussion'}{'target'},
6073: $args->{'discussion'}{'parser'});
6074: }
6075: $result .= &Apache::lonxml::xmlend($target,$parser);
6076: }
6077:
6078: if ($args->{'frameset'}) {
6079: $result .= '</frameset>';
6080: } else {
6081: $result .= &endbodytag($args);
6082: }
6083: $result .= "\n</html>";
6084:
6085: if ($args->{'js_ready'}) {
6086: $result = &js_ready($result);
6087: }
6088:
6089: if ($args->{'html_encode'}) {
6090: $result = &html_encode($result);
6091: }
6092:
6093: return $result;
6094: }
6095:
6096: sub html_encode {
6097: my ($result) = @_;
6098:
6099: $result = &HTML::Entities::encode($result,'<>&"');
6100:
6101: return $result;
6102: }
6103: sub js_ready {
6104: my ($result) = @_;
6105:
6106: $result =~ s/[\n\r]/ /xmsg;
6107: $result =~ s/\\/\\\\/xmsg;
6108: $result =~ s/'/\\'/xmsg;
6109: $result =~ s{</}{<\\/}xmsg;
6110:
6111: return $result;
6112: }
6113:
6114: sub validate_page {
6115: if ( exists($env{'internal.start_page'})
6116: && $env{'internal.start_page'} > 1) {
6117: &Apache::lonnet::logthis('start_page called multiple times '.
6118: $env{'internal.start_page'}.' '.
6119: $ENV{'request.filename'});
6120: }
6121: if ( exists($env{'internal.end_page'})
6122: && $env{'internal.end_page'} > 1) {
6123: &Apache::lonnet::logthis('end_page called multiple times '.
6124: $env{'internal.end_page'}.' '.
6125: $env{'request.filename'});
6126: }
6127: if ( exists($env{'internal.start_page'})
6128: && ! exists($env{'internal.end_page'})) {
6129: &Apache::lonnet::logthis('start_page called without end_page '.
6130: $env{'request.filename'});
6131: }
6132: if ( ! exists($env{'internal.start_page'})
6133: && exists($env{'internal.end_page'})) {
6134: &Apache::lonnet::logthis('end_page called without start_page'.
6135: $env{'request.filename'});
6136: }
6137: }
6138:
6139: sub simple_error_page {
6140: my ($r,$title,$msg) = @_;
6141: my $page =
6142: &Apache::loncommon::start_page($title).
6143: &mt($msg).
6144: &Apache::loncommon::end_page();
6145: if (ref($r)) {
6146: $r->print($page);
6147: return;
6148: }
6149: return $page;
6150: }
6151:
6152: {
6153: my @row_count;
6154: sub start_data_table {
6155: my ($add_class) = @_;
6156: my $css_class = (join(' ','LC_data_table',$add_class));
6157: unshift(@row_count,0);
6158: return '<table class="'.$css_class.'">'."\n";
6159: }
6160:
6161: sub end_data_table {
6162: shift(@row_count);
6163: return '</table>'."\n";;
6164: }
6165:
6166: sub start_data_table_row {
6167: my ($add_class) = @_;
6168: $row_count[0]++;
6169: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6170: $css_class = (join(' ',$css_class,$add_class));
6171: return '<tr class="'.$css_class.'">'."\n";;
6172: }
6173:
6174: sub continue_data_table_row {
6175: my ($add_class) = @_;
6176: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6177: $css_class = (join(' ',$css_class,$add_class));
6178: return '<tr class="'.$css_class.'">'."\n";;
6179: }
6180:
6181: sub end_data_table_row {
6182: return '</tr>'."\n";;
6183: }
6184:
6185: sub start_data_table_empty_row {
6186: $row_count[0]++;
6187: return '<tr class="LC_empty_row" >'."\n";;
6188: }
6189:
6190: sub end_data_table_empty_row {
6191: return '</tr>'."\n";;
6192: }
6193:
6194: sub start_data_table_header_row {
6195: return '<tr class="LC_header_row">'."\n";;
6196: }
6197:
6198: sub end_data_table_header_row {
6199: return '</tr>'."\n";;
6200: }
6201: }
6202:
6203: =pod
6204:
6205: =item * &inhibit_menu_check($arg)
6206:
6207: Checks for a inhibitmenu state and generates output to preserve it
6208:
6209: Inputs: $arg - can be any of
6210: - undef - in which case the return value is a string
6211: to add into arguments list of a uri
6212: - 'input' - in which case the return value is a HTML
6213: <form> <input> field of type hidden to
6214: preserve the value
6215: - a url - in which case the return value is the url with
6216: the neccesary cgi args added to preserve the
6217: inhibitmenu state
6218: - a ref to a url - no return value, but the string is
6219: updated to include the neccessary cgi
6220: args to preserve the inhibitmenu state
6221:
6222: =cut
6223:
6224: sub inhibit_menu_check {
6225: my ($arg) = @_;
6226: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6227: if ($arg eq 'input') {
6228: if ($env{'form.inhibitmenu'}) {
6229: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6230: } else {
6231: return
6232: }
6233: }
6234: if ($env{'form.inhibitmenu'}) {
6235: if (ref($arg)) {
6236: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6237: } elsif ($arg eq '') {
6238: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6239: } else {
6240: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6241: }
6242: }
6243: if (!ref($arg)) {
6244: return $arg;
6245: }
6246: }
6247:
6248: ###############################################
6249:
6250: =pod
6251:
6252: =back
6253:
6254: =head1 User Information Routines
6255:
6256: =over 4
6257:
6258: =item * &get_users_function()
6259:
6260: Used by &bodytag to determine the current users primary role.
6261: Returns either 'student','coordinator','admin', or 'author'.
6262:
6263: =cut
6264:
6265: ###############################################
6266: sub get_users_function {
6267: my $function = 'student';
6268: if ($env{'request.role'}=~/^(cc|in|ta|ep)/) {
6269: $function='coordinator';
6270: }
6271: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6272: $function='admin';
6273: }
6274: if (($env{'request.role'}=~/^(au|ca)/) ||
6275: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6276: $function='author';
6277: }
6278: return $function;
6279: }
6280:
6281: ###############################################
6282:
6283: =pod
6284:
6285: =item * &check_user_status()
6286:
6287: Determines current status of supplied role for a
6288: specific user. Roles can be active, previous or future.
6289:
6290: Inputs:
6291: user's domain, user's username, course's domain,
6292: course's number, optional section ID.
6293:
6294: Outputs:
6295: role status: active, previous or future.
6296:
6297: =cut
6298:
6299: sub check_user_status {
6300: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6301: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6302: my @uroles = keys %userinfo;
6303: my $srchstr;
6304: my $active_chk = 'none';
6305: my $now = time;
6306: if (@uroles > 0) {
6307: if (($role eq 'cc') || ($sec eq '') || (!defined($sec))) {
6308: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6309: } else {
6310: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6311: }
6312: if (grep/^\Q$srchstr\E$/,@uroles) {
6313: my $role_end = 0;
6314: my $role_start = 0;
6315: $active_chk = 'active';
6316: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6317: $role_end = $1;
6318: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6319: $role_start = $1;
6320: }
6321: }
6322: if ($role_start > 0) {
6323: if ($now < $role_start) {
6324: $active_chk = 'future';
6325: }
6326: }
6327: if ($role_end > 0) {
6328: if ($now > $role_end) {
6329: $active_chk = 'previous';
6330: }
6331: }
6332: }
6333: }
6334: return $active_chk;
6335: }
6336:
6337: ###############################################
6338:
6339: =pod
6340:
6341: =item * &get_sections()
6342:
6343: Determines all the sections for a course including
6344: sections with students and sections containing other roles.
6345: Incoming parameters:
6346:
6347: 1. domain
6348: 2. course number
6349: 3. reference to array containing roles for which sections should
6350: be gathered (optional).
6351: 4. reference to array containing status types for which sections
6352: should be gathered (optional).
6353:
6354: If the third argument is undefined, sections are gathered for any role.
6355: If the fourth argument is undefined, sections are gathered for any status.
6356: Permissible values are 'active' or 'future' or 'previous'.
6357:
6358: Returns section hash (keys are section IDs, values are
6359: number of users in each section), subject to the
6360: optional roles filter, optional status filter
6361:
6362: =cut
6363:
6364: ###############################################
6365: sub get_sections {
6366: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6367: if (!defined($cdom) || !defined($cnum)) {
6368: my $cid = $env{'request.course.id'};
6369:
6370: return if (!defined($cid));
6371:
6372: $cdom = $env{'course.'.$cid.'.domain'};
6373: $cnum = $env{'course.'.$cid.'.num'};
6374: }
6375:
6376: my %sectioncount;
6377: my $now = time;
6378:
6379: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6380: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6381: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6382: my $status_index = &Apache::loncoursedata::CL_STATUS();
6383: my $start_index = &Apache::loncoursedata::CL_START();
6384: my $end_index = &Apache::loncoursedata::CL_END();
6385: my $status;
6386: while (my ($student,$data) = each(%$classlist)) {
6387: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6388: $data->[$status_index],
6389: $data->[$start_index],
6390: $data->[$end_index]);
6391: if ($stu_status eq 'Active') {
6392: $status = 'active';
6393: } elsif ($end < $now) {
6394: $status = 'previous';
6395: } elsif ($start > $now) {
6396: $status = 'future';
6397: }
6398: if ($section ne '-1' && $section !~ /^\s*$/) {
6399: if ((!defined($possible_status)) || (($status ne '') &&
6400: (grep/^\Q$status\E$/,@{$possible_status}))) {
6401: $sectioncount{$section}++;
6402: }
6403: }
6404: }
6405: }
6406: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6407: foreach my $user (sort(keys(%courseroles))) {
6408: if ($user !~ /^(\w{2})/) { next; }
6409: my ($role) = ($user =~ /^(\w{2})/);
6410: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6411: my ($section,$status);
6412: if ($role eq 'cr' &&
6413: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6414: $section=$1;
6415: }
6416: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6417: if (!defined($section) || $section eq '-1') { next; }
6418: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6419: if ($end == -1 && $start == -1) {
6420: next; #deleted role
6421: }
6422: if (!defined($possible_status)) {
6423: $sectioncount{$section}++;
6424: } else {
6425: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6426: $status = 'active';
6427: } elsif ($end < $now) {
6428: $status = 'future';
6429: } elsif ($start > $now) {
6430: $status = 'previous';
6431: }
6432: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6433: $sectioncount{$section}++;
6434: }
6435: }
6436: }
6437: return %sectioncount;
6438: }
6439:
6440: ###############################################
6441:
6442: =pod
6443:
6444: =item * &get_course_users()
6445:
6446: Retrieves usernames:domains for users in the specified course
6447: with specific role(s), and access status.
6448:
6449: Incoming parameters:
6450: 1. course domain
6451: 2. course number
6452: 3. access status: users must have - either active,
6453: previous, future, or all.
6454: 4. reference to array of permissible roles
6455: 5. reference to array of section restrictions (optional)
6456: 6. reference to results object (hash of hashes).
6457: 7. reference to optional userdata hash
6458: 8. reference to optional statushash
6459: 9. flag if privileged users (except those set to unhide in
6460: course settings) should be excluded
6461: Keys of top level results hash are roles.
6462: Keys of inner hashes are username:domain, with
6463: values set to access type.
6464: Optional userdata hash returns an array with arguments in the
6465: same order as loncoursedata::get_classlist() for student data.
6466:
6467: Optional statushash returns
6468:
6469: Entries for end, start, section and status are blank because
6470: of the possibility of multiple values for non-student roles.
6471:
6472: =cut
6473:
6474: ###############################################
6475:
6476: sub get_course_users {
6477: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6478: my %idx = ();
6479: my %seclists;
6480:
6481: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6482: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6483: $idx{end} = &Apache::loncoursedata::CL_END();
6484: $idx{start} = &Apache::loncoursedata::CL_START();
6485: $idx{id} = &Apache::loncoursedata::CL_ID();
6486: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6487: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6488: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6489:
6490: if (grep(/^st$/,@{$roles})) {
6491: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6492: my $now = time;
6493: foreach my $student (keys(%{$classlist})) {
6494: my $match = 0;
6495: my $secmatch = 0;
6496: my $section = $$classlist{$student}[$idx{section}];
6497: my $status = $$classlist{$student}[$idx{status}];
6498: if ($section eq '') {
6499: $section = 'none';
6500: }
6501: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6502: if (grep(/^all$/,@{$sections})) {
6503: $secmatch = 1;
6504: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6505: if (grep(/^none$/,@{$sections})) {
6506: $secmatch = 1;
6507: }
6508: } else {
6509: if (grep(/^\Q$section\E$/,@{$sections})) {
6510: $secmatch = 1;
6511: }
6512: }
6513: if (!$secmatch) {
6514: next;
6515: }
6516: }
6517: if (defined($$types{'active'})) {
6518: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6519: push(@{$$users{st}{$student}},'active');
6520: $match = 1;
6521: }
6522: }
6523: if (defined($$types{'previous'})) {
6524: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6525: push(@{$$users{st}{$student}},'previous');
6526: $match = 1;
6527: }
6528: }
6529: if (defined($$types{'future'})) {
6530: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6531: push(@{$$users{st}{$student}},'future');
6532: $match = 1;
6533: }
6534: }
6535: if ($match) {
6536: push(@{$seclists{$student}},$section);
6537: if (ref($userdata) eq 'HASH') {
6538: $$userdata{$student} = $$classlist{$student};
6539: }
6540: if (ref($statushash) eq 'HASH') {
6541: $statushash->{$student}{'st'}{$section} = $status;
6542: }
6543: }
6544: }
6545: }
6546: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6547: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6548: my $now = time;
6549: my %displaystatus = ( previous => 'Expired',
6550: active => 'Active',
6551: future => 'Future',
6552: );
6553: my %nothide;
6554: if ($hidepriv) {
6555: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6556: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6557: if ($user !~ /:/) {
6558: $nothide{join(':',split(/[\@]/,$user))}=1;
6559: } else {
6560: $nothide{$user} = 1;
6561: }
6562: }
6563: }
6564: foreach my $person (sort(keys(%coursepersonnel))) {
6565: my $match = 0;
6566: my $secmatch = 0;
6567: my $status;
6568: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6569: $user =~ s/:$//;
6570: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6571: if ($end == -1 || $start == -1) {
6572: next;
6573: }
6574: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6575: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6576: my ($uname,$udom) = split(/:/,$user);
6577: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6578: if (grep(/^all$/,@{$sections})) {
6579: $secmatch = 1;
6580: } elsif ($usec eq '') {
6581: if (grep(/^none$/,@{$sections})) {
6582: $secmatch = 1;
6583: }
6584: } else {
6585: if (grep(/^\Q$usec\E$/,@{$sections})) {
6586: $secmatch = 1;
6587: }
6588: }
6589: if (!$secmatch) {
6590: next;
6591: }
6592: }
6593: if ($usec eq '') {
6594: $usec = 'none';
6595: }
6596: if ($uname ne '' && $udom ne '') {
6597: if ($hidepriv) {
6598: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6599: (!$nothide{$uname.':'.$udom})) {
6600: next;
6601: }
6602: }
6603: if ($end > 0 && $end < $now) {
6604: $status = 'previous';
6605: } elsif ($start > $now) {
6606: $status = 'future';
6607: } else {
6608: $status = 'active';
6609: }
6610: foreach my $type (keys(%{$types})) {
6611: if ($status eq $type) {
6612: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6613: push(@{$$users{$role}{$user}},$type);
6614: }
6615: $match = 1;
6616: }
6617: }
6618: if (($match) && (ref($userdata) eq 'HASH')) {
6619: if (!exists($$userdata{$uname.':'.$udom})) {
6620: &get_user_info($udom,$uname,\%idx,$userdata);
6621: }
6622: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6623: push(@{$seclists{$uname.':'.$udom}},$usec);
6624: }
6625: if (ref($statushash) eq 'HASH') {
6626: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6627: }
6628: }
6629: }
6630: }
6631: }
6632: if (grep(/^ow$/,@{$roles})) {
6633: if ((defined($cdom)) && (defined($cnum))) {
6634: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6635: if ( defined($csettings{'internal.courseowner'}) ) {
6636: my $owner = $csettings{'internal.courseowner'};
6637: next if ($owner eq '');
6638: my ($ownername,$ownerdom);
6639: if ($owner =~ /^([^:]+):([^:]+)$/) {
6640: $ownername = $1;
6641: $ownerdom = $2;
6642: } else {
6643: $ownername = $owner;
6644: $ownerdom = $cdom;
6645: $owner = $ownername.':'.$ownerdom;
6646: }
6647: @{$$users{'ow'}{$owner}} = 'any';
6648: if (defined($userdata) &&
6649: !exists($$userdata{$owner})) {
6650: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6651: if (!grep(/^none$/,@{$seclists{$owner}})) {
6652: push(@{$seclists{$owner}},'none');
6653: }
6654: if (ref($statushash) eq 'HASH') {
6655: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6656: }
6657: }
6658: }
6659: }
6660: }
6661: foreach my $user (keys(%seclists)) {
6662: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6663: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6664: }
6665: }
6666: return;
6667: }
6668:
6669: sub get_user_info {
6670: my ($udom,$uname,$idx,$userdata) = @_;
6671: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6672: &plainname($uname,$udom,'lastname');
6673: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6674: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6675: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6676: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6677: return;
6678: }
6679:
6680: ###############################################
6681:
6682: =pod
6683:
6684: =item * &get_user_quota()
6685:
6686: Retrieves quota assigned for storage of portfolio files for a user
6687:
6688: Incoming parameters:
6689: 1. user's username
6690: 2. user's domain
6691:
6692: Returns:
6693: 1. Disk quota (in Mb) assigned to student.
6694: 2. (Optional) Type of setting: custom or default
6695: (individually assigned or default for user's
6696: institutional status).
6697: 3. (Optional) - User's institutional status (e.g., faculty, staff
6698: or student - types as defined in localenroll::inst_usertypes
6699: for user's domain, which determines default quota for user.
6700: 4. (Optional) - Default quota which would apply to the user.
6701:
6702: If a value has been stored in the user's environment,
6703: it will return that, otherwise it returns the maximal default
6704: defined for the user's instituional status(es) in the domain.
6705:
6706: =cut
6707:
6708: ###############################################
6709:
6710:
6711: sub get_user_quota {
6712: my ($uname,$udom) = @_;
6713: my ($quota,$quotatype,$settingstatus,$defquota);
6714: if (!defined($udom)) {
6715: $udom = $env{'user.domain'};
6716: }
6717: if (!defined($uname)) {
6718: $uname = $env{'user.name'};
6719: }
6720: if (($udom eq '' || $uname eq '') ||
6721: ($udom eq 'public') && ($uname eq 'public')) {
6722: $quota = 0;
6723: $quotatype = 'default';
6724: $defquota = 0;
6725: } else {
6726: my $inststatus;
6727: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6728: $quota = $env{'environment.portfolioquota'};
6729: $inststatus = $env{'environment.inststatus'};
6730: } else {
6731: my %userenv =
6732: &Apache::lonnet::get('environment',['portfolioquota',
6733: 'inststatus'],$udom,$uname);
6734: my ($tmp) = keys(%userenv);
6735: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6736: $quota = $userenv{'portfolioquota'};
6737: $inststatus = $userenv{'inststatus'};
6738: } else {
6739: undef(%userenv);
6740: }
6741: }
6742: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6743: if ($quota eq '') {
6744: $quota = $defquota;
6745: $quotatype = 'default';
6746: } else {
6747: $quotatype = 'custom';
6748: }
6749: }
6750: if (wantarray) {
6751: return ($quota,$quotatype,$settingstatus,$defquota);
6752: } else {
6753: return $quota;
6754: }
6755: }
6756:
6757: ###############################################
6758:
6759: =pod
6760:
6761: =item * &default_quota()
6762:
6763: Retrieves default quota assigned for storage of user portfolio files,
6764: given an (optional) user's institutional status.
6765:
6766: Incoming parameters:
6767: 1. domain
6768: 2. (Optional) institutional status(es). This is a : separated list of
6769: status types (e.g., faculty, staff, student etc.)
6770: which apply to the user for whom the default is being retrieved.
6771: If the institutional status string in undefined, the domain
6772: default quota will be returned.
6773:
6774: Returns:
6775: 1. Default disk quota (in Mb) for user portfolios in the domain.
6776: 2. (Optional) institutional type which determined the value of the
6777: default quota.
6778:
6779: If a value has been stored in the domain's configuration db,
6780: it will return that, otherwise it returns 20 (for backwards
6781: compatibility with domains which have not set up a configuration
6782: db file; the original statically defined portfolio quota was 20 Mb).
6783:
6784: If the user's status includes multiple types (e.g., staff and student),
6785: the largest default quota which applies to the user determines the
6786: default quota returned.
6787:
6788: =cut
6789:
6790: ###############################################
6791:
6792:
6793: sub default_quota {
6794: my ($udom,$inststatus) = @_;
6795: my ($defquota,$settingstatus);
6796: my %quotahash = &Apache::lonnet::get_dom('configuration',
6797: ['quotas'],$udom);
6798: if (ref($quotahash{'quotas'}) eq 'HASH') {
6799: if ($inststatus ne '') {
6800: my @statuses = split(/:/,$inststatus);
6801: foreach my $item (@statuses) {
6802: if ($quotahash{'quotas'}{$item} ne '') {
6803: if ($defquota eq '') {
6804: $defquota = $quotahash{'quotas'}{$item};
6805: $settingstatus = $item;
6806: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6807: $defquota = $quotahash{'quotas'}{$item};
6808: $settingstatus = $item;
6809: }
6810: }
6811: }
6812: }
6813: if ($defquota eq '') {
6814: $defquota = $quotahash{'quotas'}{'default'};
6815: $settingstatus = 'default';
6816: }
6817: } else {
6818: $settingstatus = 'default';
6819: $defquota = 20;
6820: }
6821: if (wantarray) {
6822: return ($defquota,$settingstatus);
6823: } else {
6824: return $defquota;
6825: }
6826: }
6827:
6828: sub get_secgrprole_info {
6829: my ($cdom,$cnum,$needroles,$type) = @_;
6830: my %sections_count = &get_sections($cdom,$cnum);
6831: my @sections = (sort {$a <=> $b} keys(%sections_count));
6832: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6833: my @groups = sort(keys(%curr_groups));
6834: my $allroles = [];
6835: my $rolehash;
6836: my $accesshash = {
6837: active => 'Currently has access',
6838: future => 'Will have future access',
6839: previous => 'Previously had access',
6840: };
6841: if ($needroles) {
6842: $rolehash = {'all' => 'all'};
6843: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6844: if (&Apache::lonnet::error(%user_roles)) {
6845: undef(%user_roles);
6846: }
6847: foreach my $item (keys(%user_roles)) {
6848: my ($role)=split(/\:/,$item,2);
6849: if ($role eq 'cr') { next; }
6850: if ($role =~ /^cr/) {
6851: $$rolehash{$role} = (split('/',$role))[3];
6852: } else {
6853: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
6854: }
6855: }
6856: foreach my $key (sort(keys(%{$rolehash}))) {
6857: push(@{$allroles},$key);
6858: }
6859: push (@{$allroles},'st');
6860: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
6861: }
6862: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
6863: }
6864:
6865: sub user_picker {
6866: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
6867: my $currdom = $dom;
6868: my %curr_selected = (
6869: srchin => 'dom',
6870: srchby => 'lastname',
6871: );
6872: my $srchterm;
6873: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
6874: if ($srch->{'srchby'} ne '') {
6875: $curr_selected{'srchby'} = $srch->{'srchby'};
6876: }
6877: if ($srch->{'srchin'} ne '') {
6878: $curr_selected{'srchin'} = $srch->{'srchin'};
6879: }
6880: if ($srch->{'srchtype'} ne '') {
6881: $curr_selected{'srchtype'} = $srch->{'srchtype'};
6882: }
6883: if ($srch->{'srchdomain'} ne '') {
6884: $currdom = $srch->{'srchdomain'};
6885: }
6886: $srchterm = $srch->{'srchterm'};
6887: }
6888: my %lt=&Apache::lonlocal::texthash(
6889: 'usr' => 'Search criteria',
6890: 'doma' => 'Domain/institution to search',
6891: 'uname' => 'username',
6892: 'lastname' => 'last name',
6893: 'lastfirst' => 'last name, first name',
6894: 'crs' => 'in this course',
6895: 'dom' => 'in selected LON-CAPA domain',
6896: 'alc' => 'all LON-CAPA',
6897: 'instd' => 'in institutional directory for selected domain',
6898: 'exact' => 'is',
6899: 'contains' => 'contains',
6900: 'begins' => 'begins with',
6901: 'youm' => "You must include some text to search for.",
6902: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
6903: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
6904: 'yomc' => "You must choose a domain when using an institutional directory search.",
6905: 'ymcd' => "You must choose a domain when using a domain search.",
6906: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
6907: 'whse' => "When searching by last,first you must include at least one character in the first name.",
6908: 'thfo' => "The following need to be corrected before the search can be run:",
6909: );
6910: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
6911: my $srchinsel = ' <select name="srchin">';
6912:
6913: my @srchins = ('crs','dom','alc','instd');
6914:
6915: foreach my $option (@srchins) {
6916: # FIXME 'alc' option unavailable until
6917: # loncreateuser::print_user_query_page()
6918: # has been completed.
6919: next if ($option eq 'alc');
6920: next if ($option eq 'crs' && !$env{'request.course.id'});
6921: if ($curr_selected{'srchin'} eq $option) {
6922: $srchinsel .= '
6923: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6924: } else {
6925: $srchinsel .= '
6926: <option value="'.$option.'">'.$lt{$option}.'</option>';
6927: }
6928: }
6929: $srchinsel .= "\n </select>\n";
6930:
6931: my $srchbysel = ' <select name="srchby">';
6932: foreach my $option ('lastname','lastfirst','uname') {
6933: if ($curr_selected{'srchby'} eq $option) {
6934: $srchbysel .= '
6935: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6936: } else {
6937: $srchbysel .= '
6938: <option value="'.$option.'">'.$lt{$option}.'</option>';
6939: }
6940: }
6941: $srchbysel .= "\n </select>\n";
6942:
6943: my $srchtypesel = ' <select name="srchtype">';
6944: foreach my $option ('begins','contains','exact') {
6945: if ($curr_selected{'srchtype'} eq $option) {
6946: $srchtypesel .= '
6947: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
6948: } else {
6949: $srchtypesel .= '
6950: <option value="'.$option.'">'.$lt{$option}.'</option>';
6951: }
6952: }
6953: $srchtypesel .= "\n </select>\n";
6954:
6955: my ($newuserscript,$new_user_create);
6956:
6957: if ($forcenewuser) {
6958: if (ref($srch) eq 'HASH') {
6959: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
6960: if ($cancreate) {
6961: $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>';
6962: } else {
6963: my $helplink = ' href="javascript:helpMenu('."'display'".')"';
6964: my %usertypetext = (
6965: official => 'institutional',
6966: unofficial => 'non-institutional',
6967: );
6968: $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 />';
6969: }
6970: }
6971: }
6972:
6973: $newuserscript = <<"ENDSCRIPT";
6974:
6975: function setSearch(createnew,callingForm) {
6976: if (createnew == 1) {
6977: for (var i=0; i<callingForm.srchby.length; i++) {
6978: if (callingForm.srchby.options[i].value == 'uname') {
6979: callingForm.srchby.selectedIndex = i;
6980: }
6981: }
6982: for (var i=0; i<callingForm.srchin.length; i++) {
6983: if ( callingForm.srchin.options[i].value == 'dom') {
6984: callingForm.srchin.selectedIndex = i;
6985: }
6986: }
6987: for (var i=0; i<callingForm.srchtype.length; i++) {
6988: if (callingForm.srchtype.options[i].value == 'exact') {
6989: callingForm.srchtype.selectedIndex = i;
6990: }
6991: }
6992: for (var i=0; i<callingForm.srchdomain.length; i++) {
6993: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
6994: callingForm.srchdomain.selectedIndex = i;
6995: }
6996: }
6997: }
6998: }
6999: ENDSCRIPT
7000:
7001: }
7002:
7003: my $output = <<"END_BLOCK";
7004: <script type="text/javascript">
7005: function validateEntry(callingForm) {
7006:
7007: var checkok = 1;
7008: var srchin;
7009: for (var i=0; i<callingForm.srchin.length; i++) {
7010: if ( callingForm.srchin[i].checked ) {
7011: srchin = callingForm.srchin[i].value;
7012: }
7013: }
7014:
7015: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7016: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7017: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7018: var srchterm = callingForm.srchterm.value;
7019: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7020: var msg = "";
7021:
7022: if (srchterm == "") {
7023: checkok = 0;
7024: msg += "$lt{'youm'}\\n";
7025: }
7026:
7027: if (srchtype== 'begins') {
7028: if (srchterm.length < 2) {
7029: checkok = 0;
7030: msg += "$lt{'thte'}\\n";
7031: }
7032: }
7033:
7034: if (srchtype== 'contains') {
7035: if (srchterm.length < 3) {
7036: checkok = 0;
7037: msg += "$lt{'thet'}\\n";
7038: }
7039: }
7040: if (srchin == 'instd') {
7041: if (srchdomain == '') {
7042: checkok = 0;
7043: msg += "$lt{'yomc'}\\n";
7044: }
7045: }
7046: if (srchin == 'dom') {
7047: if (srchdomain == '') {
7048: checkok = 0;
7049: msg += "$lt{'ymcd'}\\n";
7050: }
7051: }
7052: if (srchby == 'lastfirst') {
7053: if (srchterm.indexOf(",") == -1) {
7054: checkok = 0;
7055: msg += "$lt{'whus'}\\n";
7056: }
7057: if (srchterm.indexOf(",") == srchterm.length -1) {
7058: checkok = 0;
7059: msg += "$lt{'whse'}\\n";
7060: }
7061: }
7062: if (checkok == 0) {
7063: alert("$lt{'thfo'}\\n"+msg);
7064: return;
7065: }
7066: if (checkok == 1) {
7067: callingForm.submit();
7068: }
7069: }
7070:
7071: $newuserscript
7072:
7073: </script>
7074:
7075: $new_user_create
7076:
7077: <table>
7078: <tr>
7079: <td>$lt{'doma'}:</td>
7080: <td>$domform</td>
7081: </td>
7082: </tr>
7083: <tr>
7084: <td>$lt{'usr'}:</td>
7085: <td>$srchbysel
7086: $srchtypesel
7087: <input type="text" size="15" name="srchterm" value="$srchterm" />
7088: $srchinsel
7089: </td>
7090: </tr>
7091: </table>
7092: <br />
7093: END_BLOCK
7094:
7095: return $output;
7096: }
7097:
7098: sub user_rule_check {
7099: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7100: my $response;
7101: if (ref($usershash) eq 'HASH') {
7102: foreach my $user (keys(%{$usershash})) {
7103: my ($uname,$udom) = split(/:/,$user);
7104: next if ($udom eq '' || $uname eq '');
7105: my ($id,$newuser);
7106: if (ref($usershash->{$user}) eq 'HASH') {
7107: $newuser = $usershash->{$user}->{'newuser'};
7108: $id = $usershash->{$user}->{'id'};
7109: }
7110: my $inst_response;
7111: if (ref($checks) eq 'HASH') {
7112: if (defined($checks->{'username'})) {
7113: ($inst_response,%{$inst_results->{$user}}) =
7114: &Apache::lonnet::get_instuser($udom,$uname);
7115: } elsif (defined($checks->{'id'})) {
7116: ($inst_response,%{$inst_results->{$user}}) =
7117: &Apache::lonnet::get_instuser($udom,undef,$id);
7118: }
7119: } else {
7120: ($inst_response,%{$inst_results->{$user}}) =
7121: &Apache::lonnet::get_instuser($udom,$uname);
7122: return;
7123: }
7124: if (!$got_rules->{$udom}) {
7125: my %domconfig = &Apache::lonnet::get_dom('configuration',
7126: ['usercreation'],$udom);
7127: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7128: foreach my $item ('username','id') {
7129: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7130: $$curr_rules{$udom}{$item} =
7131: $domconfig{'usercreation'}{$item.'_rule'};
7132: }
7133: }
7134: }
7135: $got_rules->{$udom} = 1;
7136: }
7137: foreach my $item (keys(%{$checks})) {
7138: if (ref($$curr_rules{$udom}) eq 'HASH') {
7139: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7140: if (@{$$curr_rules{$udom}{$item}} > 0) {
7141: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7142: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7143: if ($rule_check{$rule}) {
7144: $$rulematch{$user}{$item} = $rule;
7145: if ($inst_response eq 'ok') {
7146: if (ref($inst_results) eq 'HASH') {
7147: if (ref($inst_results->{$user}) eq 'HASH') {
7148: if (keys(%{$inst_results->{$user}}) == 0) {
7149: $$alerts{$item}{$udom}{$uname} = 1;
7150: }
7151: }
7152: }
7153: }
7154: last;
7155: }
7156: }
7157: }
7158: }
7159: }
7160: }
7161: }
7162: }
7163: return;
7164: }
7165:
7166: sub user_rule_formats {
7167: my ($domain,$domdesc,$curr_rules,$check) = @_;
7168: my %text = (
7169: 'username' => 'Usernames',
7170: 'id' => 'IDs',
7171: );
7172: my $output;
7173: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7174: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7175: if (@{$ruleorder} > 0) {
7176: $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>';
7177: foreach my $rule (@{$ruleorder}) {
7178: if (ref($curr_rules) eq 'ARRAY') {
7179: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7180: if (ref($rules->{$rule}) eq 'HASH') {
7181: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7182: $rules->{$rule}{'desc'}.'</li>';
7183: }
7184: }
7185: }
7186: }
7187: $output .= '</ul>';
7188: }
7189: }
7190: return $output;
7191: }
7192:
7193: sub instrule_disallow_msg {
7194: my ($checkitem,$domdesc,$count,$mode) = @_;
7195: my $response;
7196: my %text = (
7197: item => 'username',
7198: items => 'usernames',
7199: match => 'matches',
7200: do => 'does',
7201: action => 'a username',
7202: one => 'one',
7203: );
7204: if ($count > 1) {
7205: $text{'item'} = 'usernames';
7206: $text{'match'} ='match';
7207: $text{'do'} = 'do';
7208: $text{'action'} = 'usernames',
7209: $text{'one'} = 'ones';
7210: }
7211: if ($checkitem eq 'id') {
7212: $text{'items'} = 'IDs';
7213: $text{'item'} = 'ID';
7214: $text{'action'} = 'an ID';
7215: if ($count > 1) {
7216: $text{'item'} = 'IDs';
7217: $text{'action'} = 'IDs';
7218: }
7219: }
7220: $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 />';
7221: if ($mode eq 'upload') {
7222: if ($checkitem eq 'username') {
7223: $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'}.");
7224: } elsif ($checkitem eq 'id') {
7225: $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.");
7226: }
7227: } elsif ($mode eq 'selfcreate') {
7228: if ($checkitem eq 'id') {
7229: $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.");
7230: }
7231: } else {
7232: if ($checkitem eq 'username') {
7233: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7234: } elsif ($checkitem eq 'id') {
7235: $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.");
7236: }
7237: }
7238: return $response;
7239: }
7240:
7241: sub personal_data_fieldtitles {
7242: my %fieldtitles = &Apache::lonlocal::texthash (
7243: id => 'Student/Employee ID',
7244: permanentemail => 'E-mail address',
7245: lastname => 'Last Name',
7246: firstname => 'First Name',
7247: middlename => 'Middle Name',
7248: generation => 'Generation',
7249: gen => 'Generation',
7250: );
7251: return %fieldtitles;
7252: }
7253:
7254: sub sorted_inst_types {
7255: my ($dom) = @_;
7256: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7257: my $othertitle = &mt('All users');
7258: if ($env{'request.course.id'}) {
7259: $othertitle = &mt('Any users');
7260: }
7261: my @types;
7262: if (ref($order) eq 'ARRAY') {
7263: @types = @{$order};
7264: }
7265: if (@types == 0) {
7266: if (ref($usertypes) eq 'HASH') {
7267: @types = sort(keys(%{$usertypes}));
7268: }
7269: }
7270: if (keys(%{$usertypes}) > 0) {
7271: $othertitle = &mt('Other users');
7272: }
7273: return ($othertitle,$usertypes,\@types);
7274: }
7275:
7276: sub get_institutional_codes {
7277: my ($settings,$allcourses,$LC_code) = @_;
7278: # Get complete list of course sections to update
7279: my @currsections = ();
7280: my @currxlists = ();
7281: my $coursecode = $$settings{'internal.coursecode'};
7282:
7283: if ($$settings{'internal.sectionnums'} ne '') {
7284: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7285: }
7286:
7287: if ($$settings{'internal.crosslistings'} ne '') {
7288: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7289: }
7290:
7291: if (@currxlists > 0) {
7292: foreach (@currxlists) {
7293: if (m/^([^:]+):(\w*)$/) {
7294: unless (grep/^$1$/,@{$allcourses}) {
7295: push @{$allcourses},$1;
7296: $$LC_code{$1} = $2;
7297: }
7298: }
7299: }
7300: }
7301:
7302: if (@currsections > 0) {
7303: foreach (@currsections) {
7304: if (m/^(\w+):(\w*)$/) {
7305: my $sec = $coursecode.$1;
7306: my $lc_sec = $2;
7307: unless (grep/^$sec$/,@{$allcourses}) {
7308: push @{$allcourses},$sec;
7309: $$LC_code{$sec} = $lc_sec;
7310: }
7311: }
7312: }
7313: }
7314: return;
7315: }
7316:
7317: =pod
7318:
7319: =back
7320:
7321: =head1 HTTP Helpers
7322:
7323: =over 4
7324:
7325: =item * &get_unprocessed_cgi($query,$possible_names)
7326:
7327: Modify the %env hash to contain unprocessed CGI form parameters held in
7328: $query. The parameters listed in $possible_names (an array reference),
7329: will be set in $env{'form.name'} if they do not already exist.
7330:
7331: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7332: $possible_names is an ref to an array of form element names. As an example:
7333: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7334: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7335:
7336: =cut
7337:
7338: sub get_unprocessed_cgi {
7339: my ($query,$possible_names)= @_;
7340: # $Apache::lonxml::debug=1;
7341: foreach my $pair (split(/&/,$query)) {
7342: my ($name, $value) = split(/=/,$pair);
7343: $name = &unescape($name);
7344: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7345: $value =~ tr/+/ /;
7346: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7347: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7348: }
7349: }
7350: }
7351:
7352: =pod
7353:
7354: =item * &cacheheader()
7355:
7356: returns cache-controlling header code
7357:
7358: =cut
7359:
7360: sub cacheheader {
7361: unless ($env{'request.method'} eq 'GET') { return ''; }
7362: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7363: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7364: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7365: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7366: return $output;
7367: }
7368:
7369: =pod
7370:
7371: =item * &no_cache($r)
7372:
7373: specifies header code to not have cache
7374:
7375: =cut
7376:
7377: sub no_cache {
7378: my ($r) = @_;
7379: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7380: $env{'request.method'} ne 'GET') { return ''; }
7381: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7382: $r->no_cache(1);
7383: $r->header_out("Expires" => $date);
7384: $r->header_out("Pragma" => "no-cache");
7385: }
7386:
7387: sub content_type {
7388: my ($r,$type,$charset) = @_;
7389: if ($r) {
7390: # Note that printout.pl calls this with undef for $r.
7391: &no_cache($r);
7392: }
7393: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7394: unless ($charset) {
7395: $charset=&Apache::lonlocal::current_encoding;
7396: }
7397: if ($charset) { $type.='; charset='.$charset; }
7398: if ($r) {
7399: $r->content_type($type);
7400: } else {
7401: print("Content-type: $type\n\n");
7402: }
7403: }
7404:
7405: =pod
7406:
7407: =item * &add_to_env($name,$value)
7408:
7409: adds $name to the %env hash with value
7410: $value, if $name already exists, the entry is converted to an array
7411: reference and $value is added to the array.
7412:
7413: =cut
7414:
7415: sub add_to_env {
7416: my ($name,$value)=@_;
7417: if (defined($env{$name})) {
7418: if (ref($env{$name})) {
7419: #already have multiple values
7420: push(@{ $env{$name} },$value);
7421: } else {
7422: #first time seeing multiple values, convert hash entry to an arrayref
7423: my $first=$env{$name};
7424: undef($env{$name});
7425: push(@{ $env{$name} },$first,$value);
7426: }
7427: } else {
7428: $env{$name}=$value;
7429: }
7430: }
7431:
7432: =pod
7433:
7434: =item * &get_env_multiple($name)
7435:
7436: gets $name from the %env hash, it seemlessly handles the cases where multiple
7437: values may be defined and end up as an array ref.
7438:
7439: returns an array of values
7440:
7441: =cut
7442:
7443: sub get_env_multiple {
7444: my ($name) = @_;
7445: my @values;
7446: if (defined($env{$name})) {
7447: # exists is it an array
7448: if (ref($env{$name})) {
7449: @values=@{ $env{$name} };
7450: } else {
7451: $values[0]=$env{$name};
7452: }
7453: }
7454: return(@values);
7455: }
7456:
7457: sub ask_for_embedded_content {
7458: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
7459: my $upload_output = '
7460: <form name="upload_embedded" action="'.$actionurl.'"
7461: method="post" enctype="multipart/form-data">';
7462: $upload_output .= $state;
7463: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
7464:
7465: my $num = 0;
7466: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
7467: $upload_output .= &start_data_table_row().
7468: '<td>'.$embed_file.'</td><td>';
7469: if ($args->{'ignore_remote_references'}
7470: && $embed_file =~ m{^\w+://}) {
7471: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
7472: } elsif ($args->{'error_on_invalid_names'}
7473: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
7474:
7475: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
7476:
7477: } else {
7478: $upload_output .='
7479: <input name="embedded_item_'.$num.'" type="file" value="" />
7480: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
7481: my $attrib = join(':',@{$$allfiles{$embed_file}});
7482: $upload_output .=
7483: "\n\t\t".
7484: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
7485: $attrib.'" />';
7486: if (exists($$codebase{$embed_file})) {
7487: $upload_output .=
7488: "\n\t\t".
7489: '<input name="codebase_'.$num.'" type="hidden" value="'.
7490: &escape($$codebase{$embed_file}).'" />';
7491: }
7492: }
7493: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
7494: $num++;
7495: }
7496: $upload_output .= &Apache::loncommon::end_data_table().'<br />
7497: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
7498: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
7499: '.&mt('(only files for which a location has been provided will be uploaded)').'
7500: </form>';
7501: return $upload_output;
7502: }
7503:
7504: sub upload_embedded {
7505: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
7506: $current_disk_usage) = @_;
7507: my $output;
7508: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
7509: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
7510: my $orig_uploaded_filename =
7511: $env{'form.embedded_item_'.$i.'.filename'};
7512:
7513: $env{'form.embedded_orig_'.$i} =
7514: &unescape($env{'form.embedded_orig_'.$i});
7515: my ($path,$fname) =
7516: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
7517: # no path, whole string is fname
7518: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
7519:
7520: $path = $env{'form.currentpath'}.$path;
7521: $fname = &Apache::lonnet::clean_filename($fname);
7522: # See if there is anything left
7523: next if ($fname eq '');
7524:
7525: # Check if file already exists as a file or directory.
7526: my ($state,$msg);
7527: if ($context eq 'portfolio') {
7528: my $port_path = $dirpath;
7529: if ($group ne '') {
7530: $port_path = "groups/$group/$port_path";
7531: }
7532: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
7533: $dir_root,$port_path,$disk_quota,
7534: $current_disk_usage,$uname,$udom);
7535: if ($state eq 'will_exceed_quota'
7536: || $state eq 'file_locked'
7537: || $state eq 'file_exists' ) {
7538: $output .= $msg;
7539: next;
7540: }
7541: } elsif (($context eq 'author') || ($context eq 'testbank')) {
7542: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
7543: if ($state eq 'exists') {
7544: $output .= $msg;
7545: next;
7546: }
7547: }
7548: # Check if extension is valid
7549: if (($fname =~ /\.(\w+)$/) &&
7550: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
7551: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
7552: next;
7553: } elsif (($fname =~ /\.(\w+)$/) &&
7554: (!defined(&Apache::loncommon::fileembstyle($1)))) {
7555: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
7556: next;
7557: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
7558: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
7559: next;
7560: }
7561:
7562: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
7563: if ($context eq 'portfolio') {
7564: my $result=
7565: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
7566: $dirpath.$path);
7567: if ($result !~ m|^/uploaded/|) {
7568: $output .= '<span class="LC_error">'
7569: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
7570: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
7571: .'</span><br />';
7572: next;
7573: } else {
7574: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
7575: $path.$fname.'</span>').'</p>';
7576: }
7577: } else {
7578: # Save the file
7579: my $target = $env{'form.embedded_item_'.$i};
7580: my $fullpath = $dir_root.$dirpath.'/'.$path;
7581: my $dest = $fullpath.$fname;
7582: my $url = $url_root.$dirpath.'/'.$path.$fname;
7583: my @parts=split(/\//,$fullpath);
7584: my $count;
7585: my $filepath = $dir_root;
7586: for ($count=4;$count<=$#parts;$count++) {
7587: $filepath .= "/$parts[$count]";
7588: if ((-e $filepath)!=1) {
7589: mkdir($filepath,0770);
7590: }
7591: }
7592: my $fh;
7593: if (!open($fh,'>'.$dest)) {
7594: &Apache::lonnet::logthis('Failed to create '.$dest);
7595: $output .= '<span class="LC_error">'.
7596: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7597: '</span><br />';
7598: } else {
7599: if (!print $fh $env{'form.embedded_item_'.$i}) {
7600: &Apache::lonnet::logthis('Failed to write to '.$dest);
7601: $output .= '<span class="LC_error">'.
7602: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7603: '</span><br />';
7604: } else {
7605: if ($context eq 'testbank') {
7606: $output .= &mt('Embedded file uploaded successfully:').
7607: ' <a href="'.$url.'">'.
7608: $orig_uploaded_filename.'</a><br />';
7609: } else {
7610: $output .= '<font size="+2">'.
7611: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
7612: $orig_uploaded_filename.'</a>').'</font><br />';
7613: }
7614: }
7615: close($fh);
7616: }
7617: }
7618: }
7619: return $output;
7620: }
7621:
7622: sub check_for_existing {
7623: my ($path,$fname,$element) = @_;
7624: my ($state,$msg);
7625: if (-d $path.'/'.$fname) {
7626: $state = 'exists';
7627: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7628: } elsif (-e $path.'/'.$fname) {
7629: $state = 'exists';
7630: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7631: }
7632: if ($state eq 'exists') {
7633: $msg = '<span class="LC_error">'.$msg.'</span><br />';
7634: }
7635: return ($state,$msg);
7636: }
7637:
7638: sub check_for_upload {
7639: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
7640: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
7641: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
7642: my $getpropath = 1;
7643: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
7644: $getpropath);
7645: my $found_file = 0;
7646: my $locked_file = 0;
7647: foreach my $line (@dir_list) {
7648: my ($file_name)=split(/\&/,$line,2);
7649: if ($file_name eq $fname){
7650: $file_name = $path.$file_name;
7651: if ($group ne '') {
7652: $file_name = $group.$file_name;
7653: }
7654: $found_file = 1;
7655: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
7656: $locked_file = 1;
7657: }
7658: }
7659: }
7660: if (($current_disk_usage + $filesize) > $disk_quota){
7661: my $msg = '<span class="LC_error">'.
7662: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
7663: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
7664: return ('will_exceed_quota',$msg);
7665: } elsif ($found_file) {
7666: if ($locked_file) {
7667: my $msg = '<span class="LC_error">';
7668: $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>');
7669: $msg .= '</span><br />';
7670: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
7671: return ('file_locked',$msg);
7672: } else {
7673: my $msg = '<span class="LC_error">';
7674: $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'});
7675: $msg .= '</span>';
7676: $msg .= '<br />';
7677: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
7678: return ('file_exists',$msg);
7679: }
7680: }
7681: }
7682:
7683:
7684: =pod
7685:
7686: =back
7687:
7688: =head1 CSV Upload/Handling functions
7689:
7690: =over 4
7691:
7692: =item * &upfile_store($r)
7693:
7694: Store uploaded file, $r should be the HTTP Request object,
7695: needs $env{'form.upfile'}
7696: returns $datatoken to be put into hidden field
7697:
7698: =cut
7699:
7700: sub upfile_store {
7701: my $r=shift;
7702: $env{'form.upfile'}=~s/\r/\n/gs;
7703: $env{'form.upfile'}=~s/\f/\n/gs;
7704: $env{'form.upfile'}=~s/\n+/\n/gs;
7705: $env{'form.upfile'}=~s/\n+$//gs;
7706:
7707: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7708: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7709: {
7710: my $datafile = $r->dir_config('lonDaemons').
7711: '/tmp/'.$datatoken.'.tmp';
7712: if ( open(my $fh,">$datafile") ) {
7713: print $fh $env{'form.upfile'};
7714: close($fh);
7715: }
7716: }
7717: return $datatoken;
7718: }
7719:
7720: =pod
7721:
7722: =item * &load_tmp_file($r)
7723:
7724: Load uploaded file from tmp, $r should be the HTTP Request object,
7725: needs $env{'form.datatoken'},
7726: sets $env{'form.upfile'} to the contents of the file
7727:
7728: =cut
7729:
7730: sub load_tmp_file {
7731: my $r=shift;
7732: my @studentdata=();
7733: {
7734: my $studentfile = $r->dir_config('lonDaemons').
7735: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7736: if ( open(my $fh,"<$studentfile") ) {
7737: @studentdata=<$fh>;
7738: close($fh);
7739: }
7740: }
7741: $env{'form.upfile'}=join('',@studentdata);
7742: }
7743:
7744: =pod
7745:
7746: =item * &upfile_record_sep()
7747:
7748: Separate uploaded file into records
7749: returns array of records,
7750: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7751:
7752: =cut
7753:
7754: sub upfile_record_sep {
7755: if ($env{'form.upfiletype'} eq 'xml') {
7756: } else {
7757: my @records;
7758: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7759: if ($line=~/^\s*$/) { next; }
7760: push(@records,$line);
7761: }
7762: return @records;
7763: }
7764: }
7765:
7766: =pod
7767:
7768: =item * &record_sep($record)
7769:
7770: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7771:
7772: =cut
7773:
7774: sub takeleft {
7775: my $index=shift;
7776: return substr('0000'.$index,-4,4);
7777: }
7778:
7779: sub record_sep {
7780: my $record=shift;
7781: my %components=();
7782: if ($env{'form.upfiletype'} eq 'xml') {
7783: } elsif ($env{'form.upfiletype'} eq 'space') {
7784: my $i=0;
7785: foreach my $field (split(/\s+/,$record)) {
7786: $field=~s/^(\"|\')//;
7787: $field=~s/(\"|\')$//;
7788: $components{&takeleft($i)}=$field;
7789: $i++;
7790: }
7791: } elsif ($env{'form.upfiletype'} eq 'tab') {
7792: my $i=0;
7793: foreach my $field (split(/\t/,$record)) {
7794: $field=~s/^(\"|\')//;
7795: $field=~s/(\"|\')$//;
7796: $components{&takeleft($i)}=$field;
7797: $i++;
7798: }
7799: } else {
7800: my $separator=',';
7801: if ($env{'form.upfiletype'} eq 'semisv') {
7802: $separator=';';
7803: }
7804: my $i=0;
7805: # the character we are looking for to indicate the end of a quote or a record
7806: my $looking_for=$separator;
7807: # do not add the characters to the fields
7808: my $ignore=0;
7809: # we just encountered a separator (or the beginning of the record)
7810: my $just_found_separator=1;
7811: # store the field we are working on here
7812: my $field='';
7813: # work our way through all characters in record
7814: foreach my $character ($record=~/(.)/g) {
7815: if ($character eq $looking_for) {
7816: if ($character ne $separator) {
7817: # Found the end of a quote, again looking for separator
7818: $looking_for=$separator;
7819: $ignore=1;
7820: } else {
7821: # Found a separator, store away what we got
7822: $components{&takeleft($i)}=$field;
7823: $i++;
7824: $just_found_separator=1;
7825: $ignore=0;
7826: $field='';
7827: }
7828: next;
7829: }
7830: # single or double quotation marks after a separator indicate beginning of a quote
7831: # we are now looking for the end of the quote and need to ignore separators
7832: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
7833: $looking_for=$character;
7834: next;
7835: }
7836: # ignore would be true after we reached the end of a quote
7837: if ($ignore) { next; }
7838: if (($just_found_separator) && ($character=~/\s/)) { next; }
7839: $field.=$character;
7840: $just_found_separator=0;
7841: }
7842: # catch the very last entry, since we never encountered the separator
7843: $components{&takeleft($i)}=$field;
7844: }
7845: return %components;
7846: }
7847:
7848: ######################################################
7849: ######################################################
7850:
7851: =pod
7852:
7853: =item * &upfile_select_html()
7854:
7855: Return HTML code to select a file from the users machine and specify
7856: the file type.
7857:
7858: =cut
7859:
7860: ######################################################
7861: ######################################################
7862: sub upfile_select_html {
7863: my %Types = (
7864: csv => &mt('CSV (comma separated values, spreadsheet)'),
7865: semisv => &mt('Semicolon separated values'),
7866: space => &mt('Space separated'),
7867: tab => &mt('Tabulator separated'),
7868: # xml => &mt('HTML/XML'),
7869: );
7870: my $Str = '<input type="file" name="upfile" size="50" />'.
7871: '<br />Type: <select name="upfiletype">';
7872: foreach my $type (sort(keys(%Types))) {
7873: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
7874: }
7875: $Str .= "</select>\n";
7876: return $Str;
7877: }
7878:
7879: sub get_samples {
7880: my ($records,$toget) = @_;
7881: my @samples=({});
7882: my $got=0;
7883: foreach my $rec (@$records) {
7884: my %temp = &record_sep($rec);
7885: if (! grep(/\S/, values(%temp))) { next; }
7886: if (%temp) {
7887: $samples[$got]=\%temp;
7888: $got++;
7889: if ($got == $toget) { last; }
7890: }
7891: }
7892: return \@samples;
7893: }
7894:
7895: ######################################################
7896: ######################################################
7897:
7898: =pod
7899:
7900: =item * &csv_print_samples($r,$records)
7901:
7902: Prints a table of sample values from each column uploaded $r is an
7903: Apache Request ref, $records is an arrayref from
7904: &Apache::loncommon::upfile_record_sep
7905:
7906: =cut
7907:
7908: ######################################################
7909: ######################################################
7910: sub csv_print_samples {
7911: my ($r,$records) = @_;
7912: my $samples = &get_samples($records,5);
7913:
7914: $r->print(&mt('Samples').'<br />'.&start_data_table().
7915: &start_data_table_header_row());
7916: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7917: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
7918: $r->print(&end_data_table_header_row());
7919: foreach my $hash (@$samples) {
7920: $r->print(&start_data_table_row());
7921: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7922: $r->print('<td>');
7923: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
7924: $r->print('</td>');
7925: }
7926: $r->print(&end_data_table_row());
7927: }
7928: $r->print(&end_data_table().'<br />'."\n");
7929: }
7930:
7931: ######################################################
7932: ######################################################
7933:
7934: =pod
7935:
7936: =item * &csv_print_select_table($r,$records,$d)
7937:
7938: Prints a table to create associations between values and table columns.
7939:
7940: $r is an Apache Request ref,
7941: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7942: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
7943:
7944: =cut
7945:
7946: ######################################################
7947: ######################################################
7948: sub csv_print_select_table {
7949: my ($r,$records,$d) = @_;
7950: my $i=0;
7951: my $samples = &get_samples($records,1);
7952: $r->print(&mt('Associate columns with student attributes.')."\n".
7953: &start_data_table().&start_data_table_header_row().
7954: '<th>'.&mt('Attribute').'</th>'.
7955: '<th>'.&mt('Column').'</th>'.
7956: &end_data_table_header_row()."\n");
7957: foreach my $array_ref (@$d) {
7958: my ($value,$display,$defaultcol)=@{ $array_ref };
7959: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
7960:
7961: $r->print('<td><select name=f'.$i.
7962: ' onchange="javascript:flip(this.form,'.$i.');">');
7963: $r->print('<option value="none"></option>');
7964: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
7965: $r->print('<option value="'.$sample.'"'.
7966: ($sample eq $defaultcol ? ' selected="selected" ' : '').
7967: '>'.&mt('Column [_1]',($sample+1)).'</option>');
7968: }
7969: $r->print('</select></td>'.&end_data_table_row()."\n");
7970: $i++;
7971: }
7972: $r->print(&end_data_table());
7973: $i--;
7974: return $i;
7975: }
7976:
7977: ######################################################
7978: ######################################################
7979:
7980: =pod
7981:
7982: =item * &csv_samples_select_table($r,$records,$d)
7983:
7984: Prints a table of sample values from the upload and can make associate samples to internal names.
7985:
7986: $r is an Apache Request ref,
7987: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
7988: $d is an array of 2 element arrays (internal name, displayed name)
7989:
7990: =cut
7991:
7992: ######################################################
7993: ######################################################
7994: sub csv_samples_select_table {
7995: my ($r,$records,$d) = @_;
7996: my $i=0;
7997: #
7998: my $max_samples = 5;
7999: my $samples = &get_samples($records,$max_samples);
8000: $r->print(&start_data_table().
8001: &start_data_table_header_row().'<th>'.
8002: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8003: &end_data_table_header_row());
8004:
8005: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8006: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8007: ' onchange="javascript:flip(this.form,'.$i.');">');
8008: foreach my $option (@$d) {
8009: my ($value,$display,$defaultcol)=@{ $option };
8010: $r->print('<option value="'.$value.'"'.
8011: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8012: $display.'</option>');
8013: }
8014: $r->print('</select></td><td>');
8015: foreach my $line (0..($max_samples-1)) {
8016: if (defined($samples->[$line]{$key})) {
8017: $r->print($samples->[$line]{$key}."<br />\n");
8018: }
8019: }
8020: $r->print('</td>'.&end_data_table_row());
8021: $i++;
8022: }
8023: $r->print(&end_data_table());
8024: $i--;
8025: return($i);
8026: }
8027:
8028: ######################################################
8029: ######################################################
8030:
8031: =pod
8032:
8033: =item * &clean_excel_name($name)
8034:
8035: Returns a replacement for $name which does not contain any illegal characters.
8036:
8037: =cut
8038:
8039: ######################################################
8040: ######################################################
8041: sub clean_excel_name {
8042: my ($name) = @_;
8043: $name =~ s/[:\*\?\/\\]//g;
8044: if (length($name) > 31) {
8045: $name = substr($name,0,31);
8046: }
8047: return $name;
8048: }
8049:
8050: =pod
8051:
8052: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8053:
8054: Returns either 1 or undef
8055:
8056: 1 if the part is to be hidden, undef if it is to be shown
8057:
8058: Arguments are:
8059:
8060: $id the id of the part to be checked
8061: $symb, optional the symb of the resource to check
8062: $udom, optional the domain of the user to check for
8063: $uname, optional the username of the user to check for
8064:
8065: =cut
8066:
8067: sub check_if_partid_hidden {
8068: my ($id,$symb,$udom,$uname) = @_;
8069: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8070: $symb,$udom,$uname);
8071: my $truth=1;
8072: #if the string starts with !, then the list is the list to show not hide
8073: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8074: my @hiddenlist=split(/,/,$hiddenparts);
8075: foreach my $checkid (@hiddenlist) {
8076: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8077: }
8078: return !$truth;
8079: }
8080:
8081:
8082: ############################################################
8083: ############################################################
8084:
8085: =pod
8086:
8087: =back
8088:
8089: =head1 cgi-bin script and graphing routines
8090:
8091: =over 4
8092:
8093: =item * &get_cgi_id()
8094:
8095: Inputs: none
8096:
8097: Returns an id which can be used to pass environment variables
8098: to various cgi-bin scripts. These environment variables will
8099: be removed from the users environment after a given time by
8100: the routine &Apache::lonnet::transfer_profile_to_env.
8101:
8102: =cut
8103:
8104: ############################################################
8105: ############################################################
8106: my $uniq=0;
8107: sub get_cgi_id {
8108: $uniq=($uniq+1)%100000;
8109: return (time.'_'.$$.'_'.$uniq);
8110: }
8111:
8112: ############################################################
8113: ############################################################
8114:
8115: =pod
8116:
8117: =item * &DrawBarGraph()
8118:
8119: Facilitates the plotting of data in a (stacked) bar graph.
8120: Puts plot definition data into the users environment in order for
8121: graph.png to plot it. Returns an <img> tag for the plot.
8122: The bars on the plot are labeled '1','2',...,'n'.
8123:
8124: Inputs:
8125:
8126: =over 4
8127:
8128: =item $Title: string, the title of the plot
8129:
8130: =item $xlabel: string, text describing the X-axis of the plot
8131:
8132: =item $ylabel: string, text describing the Y-axis of the plot
8133:
8134: =item $Max: scalar, the maximum Y value to use in the plot
8135: If $Max is < any data point, the graph will not be rendered.
8136:
8137: =item $colors: array ref holding the colors to be used for the data sets when
8138: they are plotted. If undefined, default values will be used.
8139:
8140: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8141:
8142: =item @Values: An array of array references. Each array reference holds data
8143: to be plotted in a stacked bar chart.
8144:
8145: =item If the final element of @Values is a hash reference the key/value
8146: pairs will be added to the graph definition.
8147:
8148: =back
8149:
8150: Returns:
8151:
8152: An <img> tag which references graph.png and the appropriate identifying
8153: information for the plot.
8154:
8155: =cut
8156:
8157: ############################################################
8158: ############################################################
8159: sub DrawBarGraph {
8160: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8161: #
8162: if (! defined($colors)) {
8163: $colors = ['#33ff00',
8164: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8165: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8166: ];
8167: }
8168: my $extra_settings = {};
8169: if (ref($Values[-1]) eq 'HASH') {
8170: $extra_settings = pop(@Values);
8171: }
8172: #
8173: my $identifier = &get_cgi_id();
8174: my $id = 'cgi.'.$identifier;
8175: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8176: return '';
8177: }
8178: #
8179: my @Labels;
8180: if (defined($labels)) {
8181: @Labels = @$labels;
8182: } else {
8183: for (my $i=0;$i<@{$Values[0]};$i++) {
8184: push (@Labels,$i+1);
8185: }
8186: }
8187: #
8188: my $NumBars = scalar(@{$Values[0]});
8189: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8190: my %ValuesHash;
8191: my $NumSets=1;
8192: foreach my $array (@Values) {
8193: next if (! ref($array));
8194: $ValuesHash{$id.'.data.'.$NumSets++} =
8195: join(',',@$array);
8196: }
8197: #
8198: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8199: if ($NumBars < 3) {
8200: $width = 120+$NumBars*32;
8201: $xskip = 1;
8202: $bar_width = 30;
8203: } elsif ($NumBars < 5) {
8204: $width = 120+$NumBars*20;
8205: $xskip = 1;
8206: $bar_width = 20;
8207: } elsif ($NumBars < 10) {
8208: $width = 120+$NumBars*15;
8209: $xskip = 1;
8210: $bar_width = 15;
8211: } elsif ($NumBars <= 25) {
8212: $width = 120+$NumBars*11;
8213: $xskip = 5;
8214: $bar_width = 8;
8215: } elsif ($NumBars <= 50) {
8216: $width = 120+$NumBars*8;
8217: $xskip = 5;
8218: $bar_width = 4;
8219: } else {
8220: $width = 120+$NumBars*8;
8221: $xskip = 5;
8222: $bar_width = 4;
8223: }
8224: #
8225: $Max = 1 if ($Max < 1);
8226: if ( int($Max) < $Max ) {
8227: $Max++;
8228: $Max = int($Max);
8229: }
8230: $Title = '' if (! defined($Title));
8231: $xlabel = '' if (! defined($xlabel));
8232: $ylabel = '' if (! defined($ylabel));
8233: $ValuesHash{$id.'.title'} = &escape($Title);
8234: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8235: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8236: $ValuesHash{$id.'.y_max_value'} = $Max;
8237: $ValuesHash{$id.'.NumBars'} = $NumBars;
8238: $ValuesHash{$id.'.NumSets'} = $NumSets;
8239: $ValuesHash{$id.'.PlotType'} = 'bar';
8240: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8241: $ValuesHash{$id.'.height'} = $height;
8242: $ValuesHash{$id.'.width'} = $width;
8243: $ValuesHash{$id.'.xskip'} = $xskip;
8244: $ValuesHash{$id.'.bar_width'} = $bar_width;
8245: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8246: #
8247: # Deal with other parameters
8248: while (my ($key,$value) = each(%$extra_settings)) {
8249: $ValuesHash{$id.'.'.$key} = $value;
8250: }
8251: #
8252: &Apache::lonnet::appenv(\%ValuesHash);
8253: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8254: }
8255:
8256: ############################################################
8257: ############################################################
8258:
8259: =pod
8260:
8261: =item * &DrawXYGraph()
8262:
8263: Facilitates the plotting of data in an XY graph.
8264: Puts plot definition data into the users environment in order for
8265: graph.png to plot it. Returns an <img> tag for the plot.
8266:
8267: Inputs:
8268:
8269: =over 4
8270:
8271: =item $Title: string, the title of the plot
8272:
8273: =item $xlabel: string, text describing the X-axis of the plot
8274:
8275: =item $ylabel: string, text describing the Y-axis of the plot
8276:
8277: =item $Max: scalar, the maximum Y value to use in the plot
8278: If $Max is < any data point, the graph will not be rendered.
8279:
8280: =item $colors: Array ref containing the hex color codes for the data to be
8281: plotted in. If undefined, default values will be used.
8282:
8283: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8284:
8285: =item $Ydata: Array ref containing Array refs.
8286: Each of the contained arrays will be plotted as a separate curve.
8287:
8288: =item %Values: hash indicating or overriding any default values which are
8289: passed to graph.png.
8290: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8291:
8292: =back
8293:
8294: Returns:
8295:
8296: An <img> tag which references graph.png and the appropriate identifying
8297: information for the plot.
8298:
8299: =cut
8300:
8301: ############################################################
8302: ############################################################
8303: sub DrawXYGraph {
8304: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8305: #
8306: # Create the identifier for the graph
8307: my $identifier = &get_cgi_id();
8308: my $id = 'cgi.'.$identifier;
8309: #
8310: $Title = '' if (! defined($Title));
8311: $xlabel = '' if (! defined($xlabel));
8312: $ylabel = '' if (! defined($ylabel));
8313: my %ValuesHash =
8314: (
8315: $id.'.title' => &escape($Title),
8316: $id.'.xlabel' => &escape($xlabel),
8317: $id.'.ylabel' => &escape($ylabel),
8318: $id.'.y_max_value'=> $Max,
8319: $id.'.labels' => join(',',@$Xlabels),
8320: $id.'.PlotType' => 'XY',
8321: );
8322: #
8323: if (defined($colors) && ref($colors) eq 'ARRAY') {
8324: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8325: }
8326: #
8327: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8328: return '';
8329: }
8330: my $NumSets=1;
8331: foreach my $array (@{$Ydata}){
8332: next if (! ref($array));
8333: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8334: }
8335: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8336: #
8337: # Deal with other parameters
8338: while (my ($key,$value) = each(%Values)) {
8339: $ValuesHash{$id.'.'.$key} = $value;
8340: }
8341: #
8342: &Apache::lonnet::appenv(\%ValuesHash);
8343: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8344: }
8345:
8346: ############################################################
8347: ############################################################
8348:
8349: =pod
8350:
8351: =item * &DrawXYYGraph()
8352:
8353: Facilitates the plotting of data in an XY graph with two Y axes.
8354: Puts plot definition data into the users environment in order for
8355: graph.png to plot it. Returns an <img> tag for the plot.
8356:
8357: Inputs:
8358:
8359: =over 4
8360:
8361: =item $Title: string, the title of the plot
8362:
8363: =item $xlabel: string, text describing the X-axis of the plot
8364:
8365: =item $ylabel: string, text describing the Y-axis of the plot
8366:
8367: =item $colors: Array ref containing the hex color codes for the data to be
8368: plotted in. If undefined, default values will be used.
8369:
8370: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8371:
8372: =item $Ydata1: The first data set
8373:
8374: =item $Min1: The minimum value of the left Y-axis
8375:
8376: =item $Max1: The maximum value of the left Y-axis
8377:
8378: =item $Ydata2: The second data set
8379:
8380: =item $Min2: The minimum value of the right Y-axis
8381:
8382: =item $Max2: The maximum value of the left Y-axis
8383:
8384: =item %Values: hash indicating or overriding any default values which are
8385: passed to graph.png.
8386: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8387:
8388: =back
8389:
8390: Returns:
8391:
8392: An <img> tag which references graph.png and the appropriate identifying
8393: information for the plot.
8394:
8395: =cut
8396:
8397: ############################################################
8398: ############################################################
8399: sub DrawXYYGraph {
8400: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8401: $Ydata2,$Min2,$Max2,%Values)=@_;
8402: #
8403: # Create the identifier for the graph
8404: my $identifier = &get_cgi_id();
8405: my $id = 'cgi.'.$identifier;
8406: #
8407: $Title = '' if (! defined($Title));
8408: $xlabel = '' if (! defined($xlabel));
8409: $ylabel = '' if (! defined($ylabel));
8410: my %ValuesHash =
8411: (
8412: $id.'.title' => &escape($Title),
8413: $id.'.xlabel' => &escape($xlabel),
8414: $id.'.ylabel' => &escape($ylabel),
8415: $id.'.labels' => join(',',@$Xlabels),
8416: $id.'.PlotType' => 'XY',
8417: $id.'.NumSets' => 2,
8418: $id.'.two_axes' => 1,
8419: $id.'.y1_max_value' => $Max1,
8420: $id.'.y1_min_value' => $Min1,
8421: $id.'.y2_max_value' => $Max2,
8422: $id.'.y2_min_value' => $Min2,
8423: );
8424: #
8425: if (defined($colors) && ref($colors) eq 'ARRAY') {
8426: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8427: }
8428: #
8429: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
8430: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
8431: return '';
8432: }
8433: my $NumSets=1;
8434: foreach my $array ($Ydata1,$Ydata2){
8435: next if (! ref($array));
8436: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8437: }
8438: #
8439: # Deal with other parameters
8440: while (my ($key,$value) = each(%Values)) {
8441: $ValuesHash{$id.'.'.$key} = $value;
8442: }
8443: #
8444: &Apache::lonnet::appenv(\%ValuesHash);
8445: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8446: }
8447:
8448: ############################################################
8449: ############################################################
8450:
8451: =pod
8452:
8453: =back
8454:
8455: =head1 Statistics helper routines?
8456:
8457: Bad place for them but what the hell.
8458:
8459: =over 4
8460:
8461: =item * &chartlink()
8462:
8463: Returns a link to the chart for a specific student.
8464:
8465: Inputs:
8466:
8467: =over 4
8468:
8469: =item $linktext: The text of the link
8470:
8471: =item $sname: The students username
8472:
8473: =item $sdomain: The students domain
8474:
8475: =back
8476:
8477: =back
8478:
8479: =cut
8480:
8481: ############################################################
8482: ############################################################
8483: sub chartlink {
8484: my ($linktext, $sname, $sdomain) = @_;
8485: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
8486: '&SelectedStudent='.&escape($sname.':'.$sdomain).
8487: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
8488: '">'.$linktext.'</a>';
8489: }
8490:
8491: #######################################################
8492: #######################################################
8493:
8494: =pod
8495:
8496: =head1 Course Environment Routines
8497:
8498: =over 4
8499:
8500: =item * &restore_course_settings()
8501:
8502: =item * &store_course_settings()
8503:
8504: Restores/Store indicated form parameters from the course environment.
8505: Will not overwrite existing values of the form parameters.
8506:
8507: Inputs:
8508: a scalar describing the data (e.g. 'chart', 'problem_analysis')
8509:
8510: a hash ref describing the data to be stored. For example:
8511:
8512: %Save_Parameters = ('Status' => 'scalar',
8513: 'chartoutputmode' => 'scalar',
8514: 'chartoutputdata' => 'scalar',
8515: 'Section' => 'array',
8516: 'Group' => 'array',
8517: 'StudentData' => 'array',
8518: 'Maps' => 'array');
8519:
8520: Returns: both routines return nothing
8521:
8522: =back
8523:
8524: =cut
8525:
8526: #######################################################
8527: #######################################################
8528: sub store_course_settings {
8529: return &store_settings($env{'request.course.id'},@_);
8530: }
8531:
8532: sub store_settings {
8533: # save to the environment
8534: # appenv the same items, just to be safe
8535: my $udom = $env{'user.domain'};
8536: my $uname = $env{'user.name'};
8537: my ($context,$prefix,$Settings) = @_;
8538: my %SaveHash;
8539: my %AppHash;
8540: while (my ($setting,$type) = each(%$Settings)) {
8541: my $basename = join('.','internal',$context,$prefix,$setting);
8542: my $envname = 'environment.'.$basename;
8543: if (exists($env{'form.'.$setting})) {
8544: # Save this value away
8545: if ($type eq 'scalar' &&
8546: (! exists($env{$envname}) ||
8547: $env{$envname} ne $env{'form.'.$setting})) {
8548: $SaveHash{$basename} = $env{'form.'.$setting};
8549: $AppHash{$envname} = $env{'form.'.$setting};
8550: } elsif ($type eq 'array') {
8551: my $stored_form;
8552: if (ref($env{'form.'.$setting})) {
8553: $stored_form = join(',',
8554: map {
8555: &escape($_);
8556: } sort(@{$env{'form.'.$setting}}));
8557: } else {
8558: $stored_form =
8559: &escape($env{'form.'.$setting});
8560: }
8561: # Determine if the array contents are the same.
8562: if ($stored_form ne $env{$envname}) {
8563: $SaveHash{$basename} = $stored_form;
8564: $AppHash{$envname} = $stored_form;
8565: }
8566: }
8567: }
8568: }
8569: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
8570: $udom,$uname);
8571: if ($put_result !~ /^(ok|delayed)/) {
8572: &Apache::lonnet::logthis('unable to save form parameters, '.
8573: 'got error:'.$put_result);
8574: }
8575: # Make sure these settings stick around in this session, too
8576: &Apache::lonnet::appenv(\%AppHash);
8577: return;
8578: }
8579:
8580: sub restore_course_settings {
8581: return &restore_settings($env{'request.course.id'},@_);
8582: }
8583:
8584: sub restore_settings {
8585: my ($context,$prefix,$Settings) = @_;
8586: while (my ($setting,$type) = each(%$Settings)) {
8587: next if (exists($env{'form.'.$setting}));
8588: my $envname = 'environment.internal.'.$context.'.'.$prefix.
8589: '.'.$setting;
8590: if (exists($env{$envname})) {
8591: if ($type eq 'scalar') {
8592: $env{'form.'.$setting} = $env{$envname};
8593: } elsif ($type eq 'array') {
8594: $env{'form.'.$setting} = [
8595: map {
8596: &unescape($_);
8597: } split(',',$env{$envname})
8598: ];
8599: }
8600: }
8601: }
8602: }
8603:
8604: #######################################################
8605: #######################################################
8606:
8607: =pod
8608:
8609: =head1 Domain E-mail Routines
8610:
8611: =over 4
8612:
8613: =item * &build_recipient_list()
8614:
8615: Build recipient lists for three types of e-mail:
8616: (a) Error Reports, (b) Package Updates, (c) Help requests, generated by
8617: lonerrorhandler.pm, CHECKRPMS and lonsupportreq.pm respectively.
8618:
8619: Inputs:
8620: defmail (scalar - email address of default recipient),
8621: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
8622: defdom (domain for which to retrieve configuration settings),
8623: origmail (scalar - email address of recipient from loncapa.conf,
8624: i.e., predates configuration by DC via domainprefs.pm
8625:
8626: Returns: comma separated list of addresses to which to send e-mail.
8627:
8628: =back
8629:
8630: =cut
8631:
8632: ############################################################
8633: ############################################################
8634: sub build_recipient_list {
8635: my ($defmail,$mailing,$defdom,$origmail) = @_;
8636: my @recipients;
8637: my $otheremails;
8638: my %domconfig =
8639: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
8640: if (ref($domconfig{'contacts'}) eq 'HASH') {
8641: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
8642: my @contacts = ('adminemail','supportemail');
8643: foreach my $item (@contacts) {
8644: if ($domconfig{'contacts'}{$mailing}{$item}) {
8645: my $addr = $domconfig{'contacts'}{$item};
8646: if (!grep(/^\Q$addr\E$/,@recipients)) {
8647: push(@recipients,$addr);
8648: }
8649: }
8650: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
8651: }
8652: }
8653: } elsif ($origmail ne '') {
8654: push(@recipients,$origmail);
8655: }
8656: if (defined($defmail)) {
8657: if ($defmail ne '') {
8658: push(@recipients,$defmail);
8659: }
8660: }
8661: if ($otheremails) {
8662: my @others;
8663: if ($otheremails =~ /,/) {
8664: @others = split(/,/,$otheremails);
8665: } else {
8666: push(@others,$otheremails);
8667: }
8668: foreach my $addr (@others) {
8669: if (!grep(/^\Q$addr\E$/,@recipients)) {
8670: push(@recipients,$addr);
8671: }
8672: }
8673: }
8674: my $recipientlist = join(',',@recipients);
8675: return $recipientlist;
8676: }
8677:
8678: ############################################################
8679: ############################################################
8680:
8681: =pod
8682:
8683: =head1 Course Catalog Routines
8684:
8685: =over 4
8686:
8687: =item * &gather_categories()
8688:
8689: Converts category definitions - keys of categories hash stored in
8690: coursecategories in configuration.db on the primary library server in a
8691: domain - to an array. Also generates javascript and idx hash used to
8692: generate Domain Coordinator interface for editing Course Categories.
8693:
8694: Inputs:
8695:
8696: categories (reference to hash of category definitions).
8697:
8698: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8699: categories and subcategories).
8700:
8701: idx (reference to hash of counters used in Domain Coordinator interface for
8702: editing Course Categories).
8703:
8704: jsarray (reference to array of categories used to create Javascript arrays for
8705: Domain Coordinator interface for editing Course Categories).
8706:
8707: Returns: nothing
8708:
8709: Side effects: populates cats, idx and jsarray.
8710:
8711: =cut
8712:
8713: sub gather_categories {
8714: my ($categories,$cats,$idx,$jsarray) = @_;
8715: my %counters;
8716: my $num = 0;
8717: foreach my $item (keys(%{$categories})) {
8718: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
8719: if ($container eq '' && $depth == 0) {
8720: $cats->[$depth][$categories->{$item}] = $cat;
8721: } else {
8722: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
8723: }
8724: my ($escitem,$tail) = split(/:/,$item,2);
8725: if ($counters{$tail} eq '') {
8726: $counters{$tail} = $num;
8727: $num ++;
8728: }
8729: if (ref($idx) eq 'HASH') {
8730: $idx->{$item} = $counters{$tail};
8731: }
8732: if (ref($jsarray) eq 'ARRAY') {
8733: push(@{$jsarray->[$counters{$tail}]},$item);
8734: }
8735: }
8736: return;
8737: }
8738:
8739: =pod
8740:
8741: =item * &extract_categories()
8742:
8743: Used to generate breadcrumb trails for course categories.
8744:
8745: Inputs:
8746:
8747: categories (reference to hash of category definitions).
8748:
8749: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8750: categories and subcategories).
8751:
8752: trails (reference to array of breacrumb trails for each category).
8753:
8754: allitems (reference to hash - key is category key
8755: (format: escaped(name):escaped(parent category):depth in hierarchy).
8756:
8757: idx (reference to hash of counters used in Domain Coordinator interface for
8758: editing Course Categories).
8759:
8760: jsarray (reference to array of categories used to create Javascript arrays for
8761: Domain Coordinator interface for editing Course Categories).
8762:
8763: subcats (reference to hash of arrays containing all subcategories within each
8764: category, -recursive)
8765:
8766: Returns: nothing
8767:
8768: Side effects: populates trails and allitems hash references.
8769:
8770: =cut
8771:
8772: sub extract_categories {
8773: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
8774: if (ref($categories) eq 'HASH') {
8775: &gather_categories($categories,$cats,$idx,$jsarray);
8776: if (ref($cats->[0]) eq 'ARRAY') {
8777: for (my $i=0; $i<@{$cats->[0]}; $i++) {
8778: my $name = $cats->[0][$i];
8779: my $item = &escape($name).'::0';
8780: my $trailstr;
8781: if ($name eq 'instcode') {
8782: $trailstr = &mt('Official courses (with institutional codes)');
8783: } else {
8784: $trailstr = $name;
8785: }
8786: if ($allitems->{$item} eq '') {
8787: push(@{$trails},$trailstr);
8788: $allitems->{$item} = scalar(@{$trails})-1;
8789: }
8790: my @parents = ($name);
8791: if (ref($cats->[1]{$name}) eq 'ARRAY') {
8792: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
8793: my $category = $cats->[1]{$name}[$j];
8794: if (ref($subcats) eq 'HASH') {
8795: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
8796: }
8797: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
8798: }
8799: } else {
8800: if (ref($subcats) eq 'HASH') {
8801: $subcats->{$item} = [];
8802: }
8803: }
8804: }
8805: }
8806: }
8807: return;
8808: }
8809:
8810: =pod
8811:
8812: =item *&recurse_categories()
8813:
8814: Recursively used to generate breadcrumb trails for course categories.
8815:
8816: Inputs:
8817:
8818: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8819: categories and subcategories).
8820:
8821: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
8822:
8823: category (current course category, for which breadcrumb trail is being generated).
8824:
8825: trails (reference to array of breadcrumb trails for each category).
8826:
8827: allitems (reference to hash - key is category key
8828: (format: escaped(name):escaped(parent category):depth in hierarchy).
8829:
8830: parents (array containing containers directories for current category,
8831: back to top level).
8832:
8833: Returns: nothing
8834:
8835: Side effects: populates trails and allitems hash references
8836:
8837: =cut
8838:
8839: sub recurse_categories {
8840: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
8841: my $shallower = $depth - 1;
8842: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
8843: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
8844: my $name = $cats->[$depth]{$category}[$k];
8845: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8846: my $trailstr = join(' -> ',(@{$parents},$category));
8847: if ($allitems->{$item} eq '') {
8848: push(@{$trails},$trailstr);
8849: $allitems->{$item} = scalar(@{$trails})-1;
8850: }
8851: my $deeper = $depth+1;
8852: push(@{$parents},$category);
8853: if (ref($subcats) eq 'HASH') {
8854: my $subcat = &escape($name).':'.$category.':'.$depth;
8855: for (my $j=@{$parents}; $j>=0; $j--) {
8856: my $higher;
8857: if ($j > 0) {
8858: $higher = &escape($parents->[$j]).':'.
8859: &escape($parents->[$j-1]).':'.$j;
8860: } else {
8861: $higher = &escape($parents->[$j]).'::'.$j;
8862: }
8863: push(@{$subcats->{$higher}},$subcat);
8864: }
8865: }
8866: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
8867: $subcats);
8868: pop(@{$parents});
8869: }
8870: } else {
8871: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
8872: my $trailstr = join(' -> ',(@{$parents},$category));
8873: if ($allitems->{$item} eq '') {
8874: push(@{$trails},$trailstr);
8875: $allitems->{$item} = scalar(@{$trails})-1;
8876: }
8877: }
8878: return;
8879: }
8880:
8881: =pod
8882:
8883: =item *&assign_categories_table()
8884:
8885: Create a datatable for display of hierarchical categories in a domain,
8886: with checkboxes to allow a course to be categorized.
8887:
8888: Inputs:
8889:
8890: cathash - reference to hash of categories defined for the domain (from
8891: configuration.db)
8892:
8893: currcat - scalar with an & separated list of categories assigned to a course.
8894:
8895: Returns: $output (markup to be displayed)
8896:
8897: =cut
8898:
8899: sub assign_categories_table {
8900: my ($cathash,$currcat) = @_;
8901: my $output;
8902: if (ref($cathash) eq 'HASH') {
8903: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
8904: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
8905: $maxdepth = scalar(@cats);
8906: if (@cats > 0) {
8907: my $itemcount = 0;
8908: if (ref($cats[0]) eq 'ARRAY') {
8909: $output = &Apache::loncommon::start_data_table();
8910: my @currcategories;
8911: if ($currcat ne '') {
8912: @currcategories = split('&',$currcat);
8913: }
8914: for (my $i=0; $i<@{$cats[0]}; $i++) {
8915: my $parent = $cats[0][$i];
8916: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
8917: next if ($parent eq 'instcode');
8918: my $item = &escape($parent).'::0';
8919: my $checked = '';
8920: if (@currcategories > 0) {
8921: if (grep(/^\Q$item\E$/,@currcategories)) {
8922: $checked = ' checked="checked" ';
8923: }
8924: }
8925: $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
8926: '<input type="checkbox" name="usecategory" value="'.
8927: $item.'"'.$checked.' />'.$parent.'</span>'.
8928: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
8929: my $depth = 1;
8930: push(@path,$parent);
8931: $output .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
8932: pop(@path);
8933: $output .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
8934: $itemcount ++;
8935: }
8936: $output .= &Apache::loncommon::end_data_table();
8937: }
8938: }
8939: }
8940: return $output;
8941: }
8942:
8943: =pod
8944:
8945: =item *&assign_category_rows()
8946:
8947: Create a datatable row for display of nested categories in a domain,
8948: with checkboxes to allow a course to be categorized,called recursively.
8949:
8950: Inputs:
8951:
8952: itemcount - track row number for alternating colors
8953:
8954: cats - reference to array of arrays/hashes which encapsulates hierarchy of
8955: categories and subcategories.
8956:
8957: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
8958:
8959: parent - parent of current category item
8960:
8961: path - Array containing all categories back up through the hierarchy from the
8962: current category to the top level.
8963:
8964: currcategories - reference to array of current categories assigned to the course
8965:
8966: Returns: $output (markup to be displayed).
8967:
8968: =cut
8969:
8970: sub assign_category_rows {
8971: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
8972: my ($text,$name,$item,$chgstr);
8973: if (ref($cats) eq 'ARRAY') {
8974: my $maxdepth = scalar(@{$cats});
8975: if (ref($cats->[$depth]) eq 'HASH') {
8976: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
8977: my $numchildren = @{$cats->[$depth]{$parent}};
8978: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
8979: $text .= '<td><table class="LC_datatable">';
8980: for (my $j=0; $j<$numchildren; $j++) {
8981: $name = $cats->[$depth]{$parent}[$j];
8982: $item = &escape($name).':'.&escape($parent).':'.$depth;
8983: my $deeper = $depth+1;
8984: my $checked = '';
8985: if (ref($currcategories) eq 'ARRAY') {
8986: if (@{$currcategories} > 0) {
8987: if (grep(/^\Q$item\E$/,@{$currcategories})) {
8988: $checked = ' checked="checked" ';
8989: }
8990: }
8991: }
8992: $text .= '<tr><td><span class="LC_nobreak"><label>'.
8993: '<input type="checkbox" name="usecategory" value="'.
8994: $item.'"'.$checked.' />'.$name.'</label></span>'.
8995: '<input type="hidden" name="catname" value="'.$name.'" />'.
8996: '</td><td>';
8997: if (ref($path) eq 'ARRAY') {
8998: push(@{$path},$name);
8999: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
9000: pop(@{$path});
9001: }
9002: $text .= '</td></tr>';
9003: }
9004: $text .= '</table></td>';
9005: }
9006: }
9007: }
9008: return $text;
9009: }
9010:
9011: ############################################################
9012: ############################################################
9013:
9014:
9015: sub commit_customrole {
9016: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
9017: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
9018: ($start?', '.&mt('starting').' '.localtime($start):'').
9019: ($end?', ending '.localtime($end):'').': <b>'.
9020: &Apache::lonnet::assigncustomrole(
9021: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
9022: '</b><br />';
9023: return $output;
9024: }
9025:
9026: sub commit_standardrole {
9027: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9028: my ($output,$logmsg,$linefeed);
9029: if ($context eq 'auto') {
9030: $linefeed = "\n";
9031: } else {
9032: $linefeed = "<br />\n";
9033: }
9034: if ($three eq 'st') {
9035: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9036: $one,$two,$sec,$context);
9037: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9038: ($result eq 'unknown_course') || ($result eq 'refused')) {
9039: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9040: } else {
9041: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9042: ($start?', '.&mt('starting').' '.localtime($start):'').
9043: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9044: if ($context eq 'auto') {
9045: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9046: } else {
9047: $output .= '<b>'.$result.'</b>'.$linefeed.
9048: &mt('Add to classlist').': <b>ok</b>';
9049: }
9050: $output .= $linefeed;
9051: }
9052: } else {
9053: $output = &mt('Assigning').' '.$three.' in '.$url.
9054: ($start?', '.&mt('starting').' '.localtime($start):'').
9055: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9056: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9057: if ($context eq 'auto') {
9058: $output .= $result.$linefeed;
9059: } else {
9060: $output .= '<b>'.$result.'</b>'.$linefeed;
9061: }
9062: }
9063: return $output;
9064: }
9065:
9066: sub commit_studentrole {
9067: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9068: my ($result,$linefeed,$oldsecurl,$newsecurl);
9069: if ($context eq 'auto') {
9070: $linefeed = "\n";
9071: } else {
9072: $linefeed = '<br />'."\n";
9073: }
9074: if (defined($one) && defined($two)) {
9075: my $cid=$one.'_'.$two;
9076: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9077: my $secchange = 0;
9078: my $expire_role_result;
9079: my $modify_section_result;
9080: if ($oldsec ne '-1') {
9081: if ($oldsec ne $sec) {
9082: $secchange = 1;
9083: my $now = time;
9084: my $uurl='/'.$cid;
9085: $uurl=~s/\_/\//g;
9086: if ($oldsec) {
9087: $uurl.='/'.$oldsec;
9088: }
9089: $oldsecurl = $uurl;
9090: $expire_role_result =
9091: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9092: if ($env{'request.course.sec'} ne '') {
9093: if ($expire_role_result eq 'refused') {
9094: my @roles = ('st');
9095: my @statuses = ('previous');
9096: my @roledoms = ($one);
9097: my $withsec = 1;
9098: my %roleshash =
9099: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9100: \@statuses,\@roles,\@roledoms,$withsec);
9101: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9102: my ($oldstart,$oldend) =
9103: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9104: if ($oldend > 0 && $oldend <= $now) {
9105: $expire_role_result = 'ok';
9106: }
9107: }
9108: }
9109: }
9110: $result = $expire_role_result;
9111: }
9112: }
9113: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9114: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9115: if ($modify_section_result =~ /^ok/) {
9116: if ($secchange == 1) {
9117: if ($sec eq '') {
9118: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9119: } else {
9120: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9121: }
9122: } elsif ($oldsec eq '-1') {
9123: if ($sec eq '') {
9124: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9125: } else {
9126: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9127: }
9128: } else {
9129: if ($sec eq '') {
9130: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9131: } else {
9132: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9133: }
9134: }
9135: } else {
9136: if ($secchange) {
9137: $$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;
9138: } else {
9139: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9140: }
9141: }
9142: $result = $modify_section_result;
9143: } elsif ($secchange == 1) {
9144: if ($oldsec eq '') {
9145: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9146: } else {
9147: $$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;
9148: }
9149: if ($expire_role_result eq 'refused') {
9150: my $newsecurl = '/'.$cid;
9151: $newsecurl =~ s/\_/\//g;
9152: if ($sec ne '') {
9153: $newsecurl.='/'.$sec;
9154: }
9155: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9156: if ($sec eq '') {
9157: $$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;
9158: } else {
9159: $$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;
9160: }
9161: }
9162: }
9163: }
9164: } else {
9165: $$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;
9166: $result = "error: incomplete course id\n";
9167: }
9168: return $result;
9169: }
9170:
9171: ############################################################
9172: ############################################################
9173:
9174: sub check_clone {
9175: my ($args,$linefeed) = @_;
9176: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9177: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9178: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9179: my $clonemsg;
9180: my $can_clone = 0;
9181:
9182: if ($clonehome eq 'no_host') {
9183: $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'});
9184: } else {
9185: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9186: if ($env{'request.role.domain'} eq $args->{'clonedomain'}) {
9187: $can_clone = 1;
9188: } else {
9189: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9190: $args->{'clonedomain'},$args->{'clonecourse'});
9191: my @cloners = split(/,/,$clonehash{'cloners'});
9192: if (grep(/^\*$/,@cloners)) {
9193: $can_clone = 1;
9194: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9195: $can_clone = 1;
9196: } else {
9197: my %roleshash =
9198: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9199: $args->{'ccdomain'},
9200: 'userroles',['active'],['cc'],
9201: [$args->{'clonedomain'}]);
9202: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':cc'}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9203: $can_clone = 1;
9204: } else {
9205: $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'});
9206: }
9207: }
9208: }
9209: }
9210: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9211: }
9212:
9213: sub construct_course {
9214: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context) = @_;
9215: my $outcome;
9216: my $linefeed = '<br />'."\n";
9217: if ($context eq 'auto') {
9218: $linefeed = "\n";
9219: }
9220:
9221: #
9222: # Are we cloning?
9223: #
9224: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9225: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9226: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9227: if ($context ne 'auto') {
9228: if ($clonemsg ne '') {
9229: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9230: }
9231: }
9232: $outcome .= $clonemsg.$linefeed;
9233:
9234: if (!$can_clone) {
9235: return (0,$outcome);
9236: }
9237: }
9238:
9239: #
9240: # Open course
9241: #
9242: my $crstype = lc($args->{'crstype'});
9243: my %cenv=();
9244: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9245: $args->{'cdescr'},
9246: $args->{'curl'},
9247: $args->{'course_home'},
9248: $args->{'nonstandard'},
9249: $args->{'crscode'},
9250: $args->{'ccuname'}.':'.
9251: $args->{'ccdomain'},
9252: $args->{'crstype'});
9253:
9254: # Note: The testing routines depend on this being output; see
9255: # Utils::Course. This needs to at least be output as a comment
9256: # if anyone ever decides to not show this, and Utils::Course::new
9257: # will need to be suitably modified.
9258: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9259: #
9260: # Check if created correctly
9261: #
9262: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9263: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9264: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9265:
9266: #
9267: # Do the cloning
9268: #
9269: if ($can_clone && $cloneid) {
9270: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9271: if ($context ne 'auto') {
9272: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9273: }
9274: $outcome .= $clonemsg.$linefeed;
9275: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9276: # Copy all files
9277: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9278: # Restore URL
9279: $cenv{'url'}=$oldcenv{'url'};
9280: # Restore title
9281: $cenv{'description'}=$oldcenv{'description'};
9282: # Mark as cloned
9283: $cenv{'clonedfrom'}=$cloneid;
9284: # Need to clone grading mode
9285: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9286: $cenv{'grading'}=$newenv{'grading'};
9287: # Do not clone these environment entries
9288: &Apache::lonnet::del('environment',
9289: ['default_enrollment_start_date',
9290: 'default_enrollment_end_date',
9291: 'question.email',
9292: 'policy.email',
9293: 'comment.email',
9294: 'pch.users.denied',
9295: 'plc.users.denied'],
9296: $$crsudom,$$crsunum);
9297: }
9298:
9299: #
9300: # Set environment (will override cloned, if existing)
9301: #
9302: my @sections = ();
9303: my @xlists = ();
9304: if ($args->{'crstype'}) {
9305: $cenv{'type'}=$args->{'crstype'};
9306: }
9307: if ($args->{'crsid'}) {
9308: $cenv{'courseid'}=$args->{'crsid'};
9309: }
9310: if ($args->{'crscode'}) {
9311: $cenv{'internal.coursecode'}=$args->{'crscode'};
9312: }
9313: if ($args->{'crsquota'} ne '') {
9314: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9315: } else {
9316: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9317: }
9318: if ($args->{'ccuname'}) {
9319: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9320: ':'.$args->{'ccdomain'};
9321: } else {
9322: $cenv{'internal.courseowner'} = $args->{'curruser'};
9323: }
9324: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9325: if ($args->{'crssections'}) {
9326: $cenv{'internal.sectionnums'} = '';
9327: if ($args->{'crssections'} =~ m/,/) {
9328: @sections = split/,/,$args->{'crssections'};
9329: } else {
9330: $sections[0] = $args->{'crssections'};
9331: }
9332: if (@sections > 0) {
9333: foreach my $item (@sections) {
9334: my ($sec,$gp) = split/:/,$item;
9335: my $class = $args->{'crscode'}.$sec;
9336: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9337: $cenv{'internal.sectionnums'} .= $item.',';
9338: unless ($addcheck eq 'ok') {
9339: push @badclasses, $class;
9340: }
9341: }
9342: $cenv{'internal.sectionnums'} =~ s/,$//;
9343: }
9344: }
9345: # do not hide course coordinator from staff listing,
9346: # even if privileged
9347: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9348: # add crosslistings
9349: if ($args->{'crsxlist'}) {
9350: $cenv{'internal.crosslistings'}='';
9351: if ($args->{'crsxlist'} =~ m/,/) {
9352: @xlists = split/,/,$args->{'crsxlist'};
9353: } else {
9354: $xlists[0] = $args->{'crsxlist'};
9355: }
9356: if (@xlists > 0) {
9357: foreach my $item (@xlists) {
9358: my ($xl,$gp) = split/:/,$item;
9359: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9360: $cenv{'internal.crosslistings'} .= $item.',';
9361: unless ($addcheck eq 'ok') {
9362: push @badclasses, $xl;
9363: }
9364: }
9365: $cenv{'internal.crosslistings'} =~ s/,$//;
9366: }
9367: }
9368: if ($args->{'autoadds'}) {
9369: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9370: }
9371: if ($args->{'autodrops'}) {
9372: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9373: }
9374: # check for notification of enrollment changes
9375: my @notified = ();
9376: if ($args->{'notify_owner'}) {
9377: if ($args->{'ccuname'} ne '') {
9378: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9379: }
9380: }
9381: if ($args->{'notify_dc'}) {
9382: if ($uname ne '') {
9383: push(@notified,$uname.':'.$udom);
9384: }
9385: }
9386: if (@notified > 0) {
9387: my $notifylist;
9388: if (@notified > 1) {
9389: $notifylist = join(',',@notified);
9390: } else {
9391: $notifylist = $notified[0];
9392: }
9393: $cenv{'internal.notifylist'} = $notifylist;
9394: }
9395: if (@badclasses > 0) {
9396: my %lt=&Apache::lonlocal::texthash(
9397: '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',
9398: 'dnhr' => 'does not have rights to access enrollment in these classes',
9399: 'adby' => 'as determined by the policies of your institution on access to official classlists'
9400: );
9401: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
9402: ' ('.$lt{'adby'}.')';
9403: if ($context eq 'auto') {
9404: $outcome .= $badclass_msg.$linefeed;
9405: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
9406: foreach my $item (@badclasses) {
9407: if ($context eq 'auto') {
9408: $outcome .= " - $item\n";
9409: } else {
9410: $outcome .= "<li>$item</li>\n";
9411: }
9412: }
9413: if ($context eq 'auto') {
9414: $outcome .= $linefeed;
9415: } else {
9416: $outcome .= "</ul><br /><br /></div>\n";
9417: }
9418: }
9419: }
9420: if ($args->{'no_end_date'}) {
9421: $args->{'endaccess'} = 0;
9422: }
9423: $cenv{'internal.autostart'}=$args->{'enrollstart'};
9424: $cenv{'internal.autoend'}=$args->{'enrollend'};
9425: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
9426: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
9427: if ($args->{'showphotos'}) {
9428: $cenv{'internal.showphotos'}=$args->{'showphotos'};
9429: }
9430: $cenv{'internal.authtype'} = $args->{'authtype'};
9431: $cenv{'internal.autharg'} = $args->{'autharg'};
9432: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
9433: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
9434: 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');
9435: if ($context eq 'auto') {
9436: $outcome .= $krb_msg;
9437: } else {
9438: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
9439: }
9440: $outcome .= $linefeed;
9441: }
9442: }
9443: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
9444: if ($args->{'setpolicy'}) {
9445: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9446: }
9447: if ($args->{'setcontent'}) {
9448: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9449: }
9450: }
9451: if ($args->{'reshome'}) {
9452: $cenv{'reshome'}=$args->{'reshome'}.'/';
9453: $cenv{'reshome'}=~s/\/+$/\//;
9454: }
9455: #
9456: # course has keyed access
9457: #
9458: if ($args->{'setkeys'}) {
9459: $cenv{'keyaccess'}='yes';
9460: }
9461: # if specified, key authority is not course, but user
9462: # only active if keyaccess is yes
9463: if ($args->{'keyauth'}) {
9464: my ($user,$domain) = split(':',$args->{'keyauth'});
9465: $user = &LONCAPA::clean_username($user);
9466: $domain = &LONCAPA::clean_username($domain);
9467: if ($user ne '' && $domain ne '') {
9468: $cenv{'keyauth'}=$user.':'.$domain;
9469: }
9470: }
9471:
9472: if ($args->{'disresdis'}) {
9473: $cenv{'pch.roles.denied'}='st';
9474: }
9475: if ($args->{'disablechat'}) {
9476: $cenv{'plc.roles.denied'}='st';
9477: }
9478:
9479: # Record we've not yet viewed the Course Initialization Helper for this
9480: # course
9481: $cenv{'course.helper.not.run'} = 1;
9482: #
9483: # Use new Randomseed
9484: #
9485: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
9486: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
9487: #
9488: # The encryption code and receipt prefix for this course
9489: #
9490: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
9491: $cenv{'internal.encpref'}=100+int(9*rand(99));
9492: #
9493: # By default, use standard grading
9494: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
9495:
9496: $outcome .= $linefeed.&mt('Setting environment').': '.
9497: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
9498: #
9499: # Open all assignments
9500: #
9501: if ($args->{'openall'}) {
9502: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
9503: my %storecontent = ($storeunder => time,
9504: $storeunder.'.type' => 'date_start');
9505:
9506: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
9507: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
9508: }
9509: #
9510: # Set first page
9511: #
9512: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
9513: || ($cloneid)) {
9514: use LONCAPA::map;
9515: $outcome .= &mt('Setting first resource').': ';
9516:
9517: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
9518: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
9519:
9520: $outcome .= ($fatal?$errtext:'read ok').' - ';
9521: my $title; my $url;
9522: if ($args->{'firstres'} eq 'syl') {
9523: $title=&mt('Syllabus');
9524: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
9525: } else {
9526: $title=&mt('Navigate Contents');
9527: $url='/adm/navmaps';
9528: }
9529:
9530: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
9531: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
9532:
9533: if ($errtext) { $fatal=2; }
9534: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
9535: }
9536:
9537: return (1,$outcome);
9538: }
9539:
9540: ############################################################
9541: ############################################################
9542:
9543: sub course_type {
9544: my ($cid) = @_;
9545: if (!defined($cid)) {
9546: $cid = $env{'request.course.id'};
9547: }
9548: if (defined($env{'course.'.$cid.'.type'})) {
9549: return $env{'course.'.$cid.'.type'};
9550: } else {
9551: return 'Course';
9552: }
9553: }
9554:
9555: sub group_term {
9556: my $crstype = &course_type();
9557: my %names = (
9558: 'Course' => 'group',
9559: 'Group' => 'team',
9560: );
9561: return $names{$crstype};
9562: }
9563:
9564: sub icon {
9565: my ($file)=@_;
9566: my $curfext = lc((split(/\./,$file))[-1]);
9567: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
9568: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
9569: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
9570: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
9571: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9572: $curfext.".gif") {
9573: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9574: $curfext.".gif";
9575: }
9576: }
9577: return &lonhttpdurl($iconname);
9578: }
9579:
9580: sub lonhttpdurl {
9581: #
9582: # Had been used for "small fry" static images on separate port 8080.
9583: # Modify here if lightweight http functionality desired again.
9584: # Currently eliminated due to increasing firewall issues.
9585: #
9586: my ($url)=@_;
9587: return $url;
9588: }
9589:
9590: sub connection_aborted {
9591: my ($r)=@_;
9592: $r->print(" ");$r->rflush();
9593: my $c = $r->connection;
9594: return $c->aborted();
9595: }
9596:
9597: # Escapes strings that may have embedded 's that will be put into
9598: # strings as 'strings'.
9599: sub escape_single {
9600: my ($input) = @_;
9601: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
9602: $input =~ s/\'/\\\'/g; # Esacpe the 's....
9603: return $input;
9604: }
9605:
9606: # Same as escape_single, but escape's "'s This
9607: # can be used for "strings"
9608: sub escape_double {
9609: my ($input) = @_;
9610: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
9611: $input =~ s/\"/\\\"/g; # Esacpe the "s....
9612: return $input;
9613: }
9614:
9615: # Escapes the last element of a full URL.
9616: sub escape_url {
9617: my ($url) = @_;
9618: my @urlslices = split(/\//, $url,-1);
9619: my $lastitem = &escape(pop(@urlslices));
9620: return join('/',@urlslices).'/'.$lastitem;
9621: }
9622:
9623: # -------------------------------------------------------- Initliaze user login
9624: sub init_user_environment {
9625: my ($r, $username, $domain, $authhost, $form, $args) = @_;
9626: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
9627:
9628: my $public=($username eq 'public' && $domain eq 'public');
9629:
9630: # See if old ID present, if so, remove
9631:
9632: my ($filename,$cookie,$userroles);
9633: my $now=time;
9634:
9635: if ($public) {
9636: my $max_public=100;
9637: my $oldest;
9638: my $oldest_time=0;
9639: for(my $next=1;$next<=$max_public;$next++) {
9640: if (-e $lonids."/publicuser_$next.id") {
9641: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
9642: if ($mtime<$oldest_time || !$oldest_time) {
9643: $oldest_time=$mtime;
9644: $oldest=$next;
9645: }
9646: } else {
9647: $cookie="publicuser_$next";
9648: last;
9649: }
9650: }
9651: if (!$cookie) { $cookie="publicuser_$oldest"; }
9652: } else {
9653: # if this isn't a robot, kill any existing non-robot sessions
9654: if (!$args->{'robot'}) {
9655: opendir(DIR,$lonids);
9656: while ($filename=readdir(DIR)) {
9657: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
9658: unlink($lonids.'/'.$filename);
9659: }
9660: }
9661: closedir(DIR);
9662: }
9663: # Give them a new cookie
9664: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
9665: : $now.$$.int(rand(10000)));
9666: $cookie="$username\_$id\_$domain\_$authhost";
9667:
9668: # Initialize roles
9669:
9670: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
9671: }
9672: # ------------------------------------ Check browser type and MathML capability
9673:
9674: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
9675: $clientunicode,$clientos) = &decode_user_agent($r);
9676:
9677: # -------------------------------------- Any accessibility options to remember?
9678: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
9679: foreach my $option ('imagesuppress','appletsuppress',
9680: 'embedsuppress','fontenhance','blackwhite') {
9681: if ($form->{$option} eq 'true') {
9682: &Apache::lonnet::put('environment',{$option => 'on'},
9683: $domain,$username);
9684: } else {
9685: &Apache::lonnet::del('environment',[$option],
9686: $domain,$username);
9687: }
9688: }
9689: }
9690: # ------------------------------------------------------------- Get environment
9691:
9692: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
9693: my ($tmp) = keys(%userenv);
9694: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9695: # default remote control to off
9696: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
9697: } else {
9698: undef(%userenv);
9699: }
9700: if (($userenv{'interface'}) && (!$form->{'interface'})) {
9701: $form->{'interface'}=$userenv{'interface'};
9702: }
9703: $env{'environment.remote'}=$userenv{'remote'};
9704: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
9705:
9706: # --------------- Do not trust query string to be put directly into environment
9707: foreach my $option ('imagesuppress','appletsuppress',
9708: 'embedsuppress','fontenhance','blackwhite',
9709: 'interface','localpath','localres') {
9710: $form->{$option}=~s/[\n\r\=]//gs;
9711: }
9712: # --------------------------------------------------------- Write first profile
9713:
9714: {
9715: my %initial_env =
9716: ("user.name" => $username,
9717: "user.domain" => $domain,
9718: "user.home" => $authhost,
9719: "browser.type" => $clientbrowser,
9720: "browser.version" => $clientversion,
9721: "browser.mathml" => $clientmathml,
9722: "browser.unicode" => $clientunicode,
9723: "browser.os" => $clientos,
9724: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
9725: "request.course.fn" => '',
9726: "request.course.uri" => '',
9727: "request.course.sec" => '',
9728: "request.role" => 'cm',
9729: "request.role.adv" => $env{'user.adv'},
9730: "request.host" => $ENV{'REMOTE_ADDR'},);
9731:
9732: if ($form->{'localpath'}) {
9733: $initial_env{"browser.localpath"} = $form->{'localpath'};
9734: $initial_env{"browser.localres"} = $form->{'localres'};
9735: }
9736:
9737: if ($public) {
9738: $initial_env{"environment.remote"} = "off";
9739: }
9740: if ($form->{'interface'}) {
9741: $form->{'interface'}=~s/\W//gs;
9742: $initial_env{"browser.interface"} = $form->{'interface'};
9743: $env{'browser.interface'}=$form->{'interface'};
9744: foreach my $option ('imagesuppress','appletsuppress',
9745: 'embedsuppress','fontenhance','blackwhite') {
9746: if (($form->{$option} eq 'true') ||
9747: ($userenv{$option} eq 'on')) {
9748: $initial_env{"browser.$option"} = "on";
9749: }
9750: }
9751: }
9752:
9753: $env{'user.environment'} = "$lonids/$cookie.id";
9754:
9755: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
9756: &GDBM_WRCREAT(),0640)) {
9757: &_add_to_env(\%disk_env,\%initial_env);
9758: &_add_to_env(\%disk_env,\%userenv,'environment.');
9759: &_add_to_env(\%disk_env,$userroles);
9760: if (ref($args->{'extra_env'})) {
9761: &_add_to_env(\%disk_env,$args->{'extra_env'});
9762: }
9763: untie(%disk_env);
9764: } else {
9765: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
9766: 'Could not create environment storage in lonauth: '.$!.'</font>');
9767: return 'error: '.$!;
9768: }
9769: }
9770: $env{'request.role'}='cm';
9771: $env{'request.role.adv'}=$env{'user.adv'};
9772: $env{'browser.type'}=$clientbrowser;
9773:
9774: return $cookie;
9775:
9776: }
9777:
9778: sub _add_to_env {
9779: my ($idf,$env_data,$prefix) = @_;
9780: if (ref($env_data) eq 'HASH') {
9781: while (my ($key,$value) = each(%$env_data)) {
9782: $idf->{$prefix.$key} = $value;
9783: $env{$prefix.$key} = $value;
9784: }
9785: }
9786: }
9787:
9788: # --- Get the symbolic name of a problem and the url
9789: sub get_symb {
9790: my ($request,$silent) = @_;
9791: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9792: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
9793: if ($symb eq '') {
9794: if (!$silent) {
9795: $request->print("Unable to handle ambiguous references:$url:.");
9796: return ();
9797: }
9798: }
9799: &Apache::lonenc::check_decrypt(\$symb);
9800: return ($symb);
9801: }
9802:
9803: # --------------------------------------------------------------Get annotation
9804:
9805: sub get_annotation {
9806: my ($symb,$enc) = @_;
9807:
9808: my $key = $symb;
9809: if (!$enc) {
9810: $key =
9811: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
9812: }
9813: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
9814: return $annotation{$key};
9815: }
9816:
9817: sub clean_symb {
9818: my ($symb) = @_;
9819:
9820: &Apache::lonenc::check_decrypt(\$symb);
9821: my $enc = $env{'request.enc'};
9822: delete($env{'request.enc'});
9823:
9824: return ($symb,$enc);
9825: }
9826:
9827: =pod
9828:
9829: =back
9830:
9831: =cut
9832:
9833: 1;
9834: __END__;
9835:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>