1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.692.4.25 2010/01/19 16:34:57 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use 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: // <![CDATA[
411: var stdeditbrowser;
412: function openstdbrowser(formname,uname,udom,roleflag,ignorefilter,courseadvonly) {
413: var url = '/adm/pickstudent?';
414: var filter;
415: if (!ignorefilter) {
416: eval('filter=document.'+formname+'.'+uname+'.value;');
417: }
418: if (filter != null) {
419: if (filter != '') {
420: url += 'filter='+filter+'&';
421: }
422: }
423: url += 'form=' + formname + '&unameelement='+uname+
424: '&udomelement='+udom;
425: if (roleflag) { url+="&roles=1"; }
426: if (courseadvonly) { url+="&courseadvonly=1"; }
427: var title = 'Student_Browser';
428: var options = 'scrollbars=1,resizable=1,menubar=0';
429: options += ',width=700,height=600';
430: stdeditbrowser = open(url,title,options,'1');
431: stdeditbrowser.focus();
432: }
433: // ]]>
434: </script>
435: ENDSTDBRW
436: }
437:
438: sub selectstudent_link {
439: my ($form,$unameele,$udomele,$courseadvonly)=@_;
440: my $callargs = "'".$form."','".$unameele."','".$udomele."'";
441: if ($env{'request.course.id'}) {
442: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
443: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
444: '/'.$env{'request.course.sec'})) {
445: return '';
446: }
447: if ($courseadvonly) {
448: $callargs .= ",'',1,1";
449: }
450: return '<span class="LC_nobreak">'.
451: '<a href="javascript:openstdbrowser('.$callargs.');">'.
452: &mt('Select User').'</a></span>';
453: }
454: if ($env{'request.role'}=~/^(au|dc|su)/) {
455: $callargs .= ",1";
456: return '<span class="LC_nobreak">'.
457: '<a href="javascript:openstdbrowser('.$callargs.');">'.
458: &mt('Select User').'</a></span>';
459: }
460: return '';
461: }
462:
463: sub authorbrowser_javascript {
464: return <<"ENDAUTHORBRW";
465: <script type="text/javascript">
466: // <![CDATA[
467: var stdeditbrowser;
468:
469: function openauthorbrowser(formname,udom) {
470: var url = '/adm/pickauthor?';
471: url += 'form='+formname+'&roledom='+udom;
472: var title = 'Author_Browser';
473: var options = 'scrollbars=1,resizable=1,menubar=0';
474: options += ',width=700,height=600';
475: stdeditbrowser = open(url,title,options,'1');
476: stdeditbrowser.focus();
477: }
478: // ]]>
479: </script>
480: ENDAUTHORBRW
481: }
482:
483: sub coursebrowser_javascript {
484: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
485: my $wintitle = 'Course_Browser';
486: if ($crstype eq 'Community') {
487: $wintitle = 'Community_Browser';
488: }
489: my $id_functions = &javascript_index_functions();
490: my $output = '
491: <script type="text/javascript" language="JavaScript">
492: // <![CDATA[
493: var stdeditbrowser;'."\n";
494:
495: $output .= <<"ENDSTDBRW";
496: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
497: var url = '/adm/pickcourse?';
498: var formid = getFormIdByName(formname);
499: var domainfilter = getDomainFromSelectbox(formname,udom);
500: if (domainfilter != null) {
501: if (domainfilter != '') {
502: url += 'domainfilter='+domainfilter+'&';
503: }
504: }
505: url += 'form=' + formname + '&cnumelement='+uname+
506: '&cdomelement='+udom+
507: '&cnameelement='+desc;
508: if (extra_element !=null && extra_element != '') {
509: if (formname == 'rolechoice' || formname == 'studentform') {
510: url += '&roleelement='+extra_element;
511: if (domainfilter == null || domainfilter == '') {
512: url += '&domainfilter='+extra_element;
513: }
514: }
515: else {
516: if (formname == 'portform') {
517: url += '&setroles='+extra_element;
518: } else {
519: if (formname == 'rules') {
520: url += '&fixeddom='+extra_element;
521: }
522: }
523: }
524: }
525: if (type != null && type != '') {
526: url += '&type='+type;
527: }
528: if (type_elem != null && type_elem != '') {
529: url += '&typeelement='+type_elem;
530: }
531: if (formname == 'ccrs') {
532: var ownername = document.forms[formid].ccuname.value;
533: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
534: url += '&cloner='+ownername+':'+ownerdom;
535: }
536: if (multflag !=null && multflag != '') {
537: url += '&multiple='+multflag;
538: }
539: var title = '$wintitle';
540: var options = 'scrollbars=1,resizable=1,menubar=0';
541: options += ',width=700,height=600';
542: stdeditbrowser = open(url,title,options,'1');
543: stdeditbrowser.focus();
544: }
545: $id_functions
546: ENDSTDBRW
547: if (($sec_element ne '') || ($role_element ne '')) {
548: $output .= &setsec_javascript($sec_element,$formname,$role_element);
549: }
550: $output .= '
551: // ]]>
552: </script>';
553: return $output;
554: }
555:
556: sub javascript_index_functions {
557: return <<"ENDJS";
558:
559: function getFormIdByName(formname) {
560: for (var i=0;i<document.forms.length;i++) {
561: if (document.forms[i].name == formname) {
562: return i;
563: }
564: }
565: return -1;
566: }
567:
568: function getIndexByName(formid,item) {
569: for (var i=0;i<document.forms[formid].elements.length;i++) {
570: if (document.forms[formid].elements[i].name == item) {
571: return i;
572: }
573: }
574: return -1;
575: }
576:
577: function getDomainFromSelectbox(formname,udom) {
578: var userdom;
579: var formid = getFormIdByName(formname);
580: if (formid > -1) {
581: var domid = getIndexByName(formid,udom);
582: if (domid > -1) {
583: if (document.forms[formid].elements[domid].type == 'select-one') {
584: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
585: }
586: if (document.forms[formid].elements[domid].type == 'hidden') {
587: userdom=document.forms[formid].elements[domid].value;
588: }
589: }
590: }
591: return userdom;
592: }
593:
594: ENDJS
595:
596: }
597:
598: sub userbrowser_javascript {
599: my $id_functions = &javascript_index_functions();
600: return <<"ENDUSERBRW";
601:
602: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
603: var url = '/adm/pickuser?';
604: var userdom = getDomainFromSelectbox(formname,udom);
605: if (userdom != null) {
606: if (userdom != '') {
607: url += 'srchdom='+userdom+'&';
608: }
609: }
610: url += 'form=' + formname + '&unameelement='+uname+
611: '&udomelement='+udom+
612: '&ulastelement='+ulast+
613: '&ufirstelement='+ufirst+
614: '&uemailelement='+uemail+
615: '&hideudomelement='+hideudom+
616: '&coursedom='+crsdom;
617: if ((caller != null) && (caller != undefined)) {
618: url += '&caller='+caller;
619: }
620: var title = 'User_Browser';
621: var options = 'scrollbars=1,resizable=1,menubar=0';
622: options += ',width=700,height=600';
623: var stdeditbrowser = open(url,title,options,'1');
624: stdeditbrowser.focus();
625: }
626:
627: function fix_domain (formname,udom,origdom,uname) {
628: var formid = getFormIdByName(formname);
629: if (formid > -1) {
630: var unameid = getIndexByName(formid,uname);
631: var domid = getIndexByName(formid,udom);
632: var hidedomid = getIndexByName(formid,origdom);
633: if (hidedomid > -1) {
634: var fixeddom = document.forms[formid].elements[hidedomid].value;
635: var unameval = document.forms[formid].elements[unameid].value;
636: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
637: if (domid > -1) {
638: var slct = document.forms[formid].elements[domid];
639: if (slct.type == 'select-one') {
640: var i;
641: for (i=0;i<slct.length;i++) {
642: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
643: }
644: }
645: if (slct.type == 'hidden') {
646: slct.value = fixeddom;
647: }
648: }
649: }
650: }
651: }
652: return;
653: }
654:
655: $id_functions
656: ENDUSERBRW
657: }
658:
659:
660: sub setsec_javascript {
661: my ($sec_element,$formname,$role_element) = @_;
662: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
663: $communityrolestr);
664: if ($role_element ne '') {
665: my @allroles = ('st','ta','ep','in','ad');
666: foreach my $crstype ('Course','Community') {
667: if ($crstype eq 'Community') {
668: foreach my $role (@allroles) {
669: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
670: }
671: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
672: } else {
673: foreach my $role (@allroles) {
674: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
675: }
676: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
677: }
678: }
679: $rolestr = '"'.join('","',@allroles).'"';
680: $courserolestr = '"'.join('","',@courserolenames).'"';
681: $communityrolestr = '"'.join('","',@communityrolenames).'"';
682: }
683: my $setsections = qq|
684: function setSect(sectionlist) {
685: var sectionsArray = new Array();
686: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
687: sectionsArray = sectionlist.split(",");
688: }
689: var numSections = sectionsArray.length;
690: document.$formname.$sec_element.length = 0;
691: if (numSections == 0) {
692: document.$formname.$sec_element.multiple=false;
693: document.$formname.$sec_element.size=1;
694: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
695: } else {
696: if (numSections == 1) {
697: document.$formname.$sec_element.multiple=false;
698: document.$formname.$sec_element.size=1;
699: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
700: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
701: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
702: } else {
703: for (var i=0; i<numSections; i++) {
704: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
705: }
706: document.$formname.$sec_element.multiple=true
707: if (numSections < 3) {
708: document.$formname.$sec_element.size=numSections;
709: } else {
710: document.$formname.$sec_element.size=3;
711: }
712: document.$formname.$sec_element.options[0].selected = false
713: }
714: }
715: }
716:
717: function setRole(crstype) {
718: |;
719: if ($role_element eq '') {
720: $setsections .= ' return;
721: }
722: ';
723: } else {
724: $setsections .= qq|
725: var elementLength = document.$formname.$role_element.length;
726: var allroles = Array($rolestr);
727: var courserolenames = Array($courserolestr);
728: var communityrolenames = Array($communityrolestr);
729: if (elementLength != undefined) {
730: if (document.$formname.$role_element.options[5].value == 'cc') {
731: if (crstype == 'Course') {
732: return;
733: } else {
734: allroles[5] = 'co';
735: for (var i=0; i<6; i++) {
736: document.$formname.$role_element.options[i].value = allroles[i];
737: document.$formname.$role_element.options[i].text = communityrolenames[i];
738: }
739: }
740: } else {
741: if (crstype == 'Community') {
742: return;
743: } else {
744: allroles[5] = 'cc';
745: for (var i=0; i<6; i++) {
746: document.$formname.$role_element.options[i].value = allroles[i];
747: document.$formname.$role_element.options[i].text = courserolenames[i];
748: }
749: }
750: }
751: }
752: return;
753: }
754: |;
755: }
756: return $setsections;
757: }
758:
759: sub selectcourse_link {
760: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
761: $typeelement) = @_;
762: my $type = $selecttype;
763: my $linktext = &mt('Select Course');
764: if ($selecttype eq 'Community') {
765: $linktext = &mt('Select Community');
766: } elsif ($selecttype eq 'Course/Community') {
767: $linktext = &mt('Select Course/Community');
768: $type = '';
769: }
770: return '<span class="LC_nobreak">'
771: ."<a href='"
772: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
773: .'","'.$udomele.'","'.$desc.'","'.$extra_element
774: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
775: ."'>".$linktext.'</a>'
776: .'</span>';
777: }
778:
779: sub selectauthor_link {
780: my ($form,$udom)=@_;
781: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
782: &mt('Select Author').'</a>';
783: }
784:
785: sub selectuser_link {
786: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
787: $coursedom,$linktext,$caller) = @_;
788: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
789: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
790: ');">'.$linktext.'</a>';
791: }
792:
793: sub check_uncheck_jscript {
794: my $jscript = <<"ENDSCRT";
795: function checkAll(field) {
796: if (field.length > 0) {
797: for (i = 0; i < field.length; i++) {
798: field[i].checked = true ;
799: }
800: } else {
801: field.checked = true
802: }
803: }
804:
805: function uncheckAll(field) {
806: if (field.length > 0) {
807: for (i = 0; i < field.length; i++) {
808: field[i].checked = false ;
809: }
810: } else {
811: field.checked = false ;
812: }
813: }
814: ENDSCRT
815: return $jscript;
816: }
817:
818: sub select_timezone {
819: my ($name,$selected,$onchange,$includeempty)=@_;
820: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
821: if ($includeempty) {
822: $output .= '<option value=""';
823: if (($selected eq '') || ($selected eq 'local')) {
824: $output .= ' selected="selected" ';
825: }
826: $output .= '> </option>';
827: }
828: my @timezones = DateTime::TimeZone->all_names;
829: foreach my $tzone (@timezones) {
830: $output.= '<option value="'.$tzone.'"';
831: if ($tzone eq $selected) {
832: $output.=' selected="selected"';
833: }
834: $output.=">$tzone</option>\n";
835: }
836: $output.="</select>";
837: return $output;
838: }
839:
840: sub select_datelocale {
841: my ($name,$selected,$onchange,$includeempty)=@_;
842: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
843: if ($includeempty) {
844: $output .= '<option value=""';
845: if ($selected eq '') {
846: $output .= ' selected="selected" ';
847: }
848: $output .= '> </option>';
849: }
850: my (@possibles,%locale_names);
851: my @locales = DateTime::Locale::Catalog::Locales;
852: foreach my $locale (@locales) {
853: if (ref($locale) eq 'HASH') {
854: my $id = $locale->{'id'};
855: if ($id ne '') {
856: my $en_terr = $locale->{'en_territory'};
857: my $native_terr = $locale->{'native_territory'};
858: my @languages = &Apache::lonlocal::preferred_languages();
859: if (grep(/^en$/,@languages) || !@languages) {
860: if ($en_terr ne '') {
861: $locale_names{$id} = '('.$en_terr.')';
862: } elsif ($native_terr ne '') {
863: $locale_names{$id} = $native_terr;
864: }
865: } else {
866: if ($native_terr ne '') {
867: $locale_names{$id} = $native_terr.' ';
868: } elsif ($en_terr ne '') {
869: $locale_names{$id} = '('.$en_terr.')';
870: }
871: }
872: push (@possibles,$id);
873: }
874: }
875: }
876: foreach my $item (sort(@possibles)) {
877: $output.= '<option value="'.$item.'"';
878: if ($item eq $selected) {
879: $output.=' selected="selected"';
880: }
881: $output.=">$item";
882: if ($locale_names{$item} ne '') {
883: $output.=" $locale_names{$item}</option>\n";
884: }
885: $output.="</option>\n";
886: }
887: $output.="</select>";
888: return $output;
889: }
890:
891: sub select_language {
892: my ($name,$selected,$includeempty) = @_;
893: my %langchoices;
894: if ($includeempty) {
895: %langchoices = ('' => 'No language preference');
896: }
897: foreach my $id (&languageids()) {
898: my $code = &supportedlanguagecode($id);
899: if ($code) {
900: $langchoices{$code} = &plainlanguagedescription($id);
901: }
902: }
903: return &select_form($selected,$name,%langchoices);
904: }
905:
906: =pod
907:
908: =item * &linked_select_forms(...)
909:
910: linked_select_forms returns a string containing a <script></script> block
911: and html for two <select> menus. The select menus will be linked in that
912: changing the value of the first menu will result in new values being placed
913: in the second menu. The values in the select menu will appear in alphabetical
914: order unless a defined order is provided.
915:
916: linked_select_forms takes the following ordered inputs:
917:
918: =over 4
919:
920: =item * $formname, the name of the <form> tag
921:
922: =item * $middletext, the text which appears between the <select> tags
923:
924: =item * $firstdefault, the default value for the first menu
925:
926: =item * $firstselectname, the name of the first <select> tag
927:
928: =item * $secondselectname, the name of the second <select> tag
929:
930: =item * $hashref, a reference to a hash containing the data for the menus.
931:
932: =item * $menuorder, the order of values in the first menu
933:
934: =back
935:
936: Below is an example of such a hash. Only the 'text', 'default', and
937: 'select2' keys must appear as stated. keys(%menu) are the possible
938: values for the first select menu. The text that coincides with the
939: first menu value is given in $menu{$choice1}->{'text'}. The values
940: and text for the second menu are given in the hash pointed to by
941: $menu{$choice1}->{'select2'}.
942:
943: my %menu = ( A1 => { text =>"Choice A1" ,
944: default => "B3",
945: select2 => {
946: B1 => "Choice B1",
947: B2 => "Choice B2",
948: B3 => "Choice B3",
949: B4 => "Choice B4"
950: },
951: order => ['B4','B3','B1','B2'],
952: },
953: A2 => { text =>"Choice A2" ,
954: default => "C2",
955: select2 => {
956: C1 => "Choice C1",
957: C2 => "Choice C2",
958: C3 => "Choice C3"
959: },
960: order => ['C2','C1','C3'],
961: },
962: A3 => { text =>"Choice A3" ,
963: default => "D6",
964: select2 => {
965: D1 => "Choice D1",
966: D2 => "Choice D2",
967: D3 => "Choice D3",
968: D4 => "Choice D4",
969: D5 => "Choice D5",
970: D6 => "Choice D6",
971: D7 => "Choice D7"
972: },
973: order => ['D4','D3','D2','D1','D7','D6','D5'],
974: }
975: );
976:
977: =cut
978:
979: sub linked_select_forms {
980: my ($formname,
981: $middletext,
982: $firstdefault,
983: $firstselectname,
984: $secondselectname,
985: $hashref,
986: $menuorder,
987: ) = @_;
988: my $second = "document.$formname.$secondselectname";
989: my $first = "document.$formname.$firstselectname";
990: # output the javascript to do the changing
991: my $result = '';
992: $result.='<script type="text/javascript" language="JavaScript">'."\n";
993: $result.="// <![CDATA[\n";
994: $result.="var select2data = new Object();\n";
995: $" = '","';
996: my $debug = '';
997: foreach my $s1 (sort(keys(%$hashref))) {
998: $result.="select2data.d_$s1 = new Object();\n";
999: $result.="select2data.d_$s1.def = new String('".
1000: $hashref->{$s1}->{'default'}."');\n";
1001: $result.="select2data.d_$s1.values = new Array(";
1002: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1003: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1004: @s2values = @{$hashref->{$s1}->{'order'}};
1005: }
1006: $result.="\"@s2values\");\n";
1007: $result.="select2data.d_$s1.texts = new Array(";
1008: my @s2texts;
1009: foreach my $value (@s2values) {
1010: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1011: }
1012: $result.="\"@s2texts\");\n";
1013: }
1014: $"=' ';
1015: $result.= <<"END";
1016:
1017: function select1_changed() {
1018: // Determine new choice
1019: var newvalue = "d_" + $first.value;
1020: // update select2
1021: var values = select2data[newvalue].values;
1022: var texts = select2data[newvalue].texts;
1023: var select2def = select2data[newvalue].def;
1024: var i;
1025: // out with the old
1026: for (i = 0; i < $second.options.length; i++) {
1027: $second.options[i] = null;
1028: }
1029: // in with the nuclear
1030: for (i=0;i<values.length; i++) {
1031: $second.options[i] = new Option(values[i]);
1032: $second.options[i].value = values[i];
1033: $second.options[i].text = texts[i];
1034: if (values[i] == select2def) {
1035: $second.options[i].selected = true;
1036: }
1037: }
1038: }
1039: // ]]>
1040: </script>
1041: END
1042: # output the initial values for the selection lists
1043: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1044: my @order = sort(keys(%{$hashref}));
1045: if (ref($menuorder) eq 'ARRAY') {
1046: @order = @{$menuorder};
1047: }
1048: foreach my $value (@order) {
1049: $result.=" <option value=\"$value\" ";
1050: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1051: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1052: }
1053: $result .= "</select>\n";
1054: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1055: $result .= $middletext;
1056: $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
1057: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1058:
1059: my @secondorder = sort(keys(%select2));
1060: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1061: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1062: }
1063: foreach my $value (@secondorder) {
1064: $result.=" <option value=\"$value\" ";
1065: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1066: $result.=">".&mt($select2{$value})."</option>\n";
1067: }
1068: $result .= "</select>\n";
1069: # return $debug;
1070: return $result;
1071: } # end of sub linked_select_forms {
1072:
1073: =pod
1074:
1075: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height)
1076:
1077: Returns a string corresponding to an HTML link to the given help
1078: $topic, where $topic corresponds to the name of a .tex file in
1079: /home/httpd/html/adm/help/tex, with underscores replaced by
1080: spaces.
1081:
1082: $text will optionally be linked to the same topic, allowing you to
1083: link text in addition to the graphic. If you do not want to link
1084: text, but wish to specify one of the later parameters, pass an
1085: empty string.
1086:
1087: $stayOnPage is a value that will be interpreted as a boolean. If true,
1088: the link will not open a new window. If false, the link will open
1089: a new window using Javascript. (Default is false.)
1090:
1091: $width and $height are optional numerical parameters that will
1092: override the width and height of the popped up window, which may
1093: be useful for certain help topics with big pictures included.
1094:
1095: =cut
1096:
1097: sub help_open_topic {
1098: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1099: $text = "" if (not defined $text);
1100: $stayOnPage = 0 if (not defined $stayOnPage);
1101: if ($env{'browser.interface'} eq 'textual') {
1102: $stayOnPage=1;
1103: }
1104: $width = 350 if (not defined $width);
1105: $height = 400 if (not defined $height);
1106: my $filename = $topic;
1107: $filename =~ s/ /_/g;
1108:
1109: my $template = "";
1110: my $link;
1111:
1112: $topic=~s/\W/\_/g;
1113:
1114: if (!$stayOnPage) {
1115: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1116: } else {
1117: $link = "/adm/help/${filename}.hlp";
1118: }
1119:
1120: # Add the text
1121: if ($text ne "") {
1122: $template .=
1123: "<table bgcolor='#3333AA' cellspacing='1' cellpadding='1' border='0'><tr>".
1124: "<td bgcolor='#5555FF'><span class=\"LC_nobreak\"><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1125: }
1126:
1127: # Add the graphic
1128: my $title = &mt('Online Help');
1129: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1130: $template .= '<a target="_top" href="'.$link.'" title="'.$title.'">'.
1131: '<img src="'.$helpicon.'" border="0" alt="'.&mt('Help: [_1]',$topic).
1132: '" title="'.$title.'" /></a>';
1133: if ($text ne '') {
1134: $template.='</span></td></tr></table>';
1135: }
1136: return $template;
1137:
1138: }
1139:
1140: # This is a quicky function for Latex cheatsheet editing, since it
1141: # appears in at least four places
1142: sub helpLatexCheatsheet {
1143: my ($topic,$text,$not_author) = @_;
1144: my $out;
1145: my $addOther = '';
1146: if ($topic) {
1147: $addOther = &Apache::loncommon::help_open_topic($topic,$text,
1148: undef, undef, 600) .
1149: '</td><td>';
1150: }
1151: $out = '<table><tr><td>'.
1152: $addOther .
1153: &Apache::loncommon::help_open_topic("Greek_Symbols",&mt('Greek Symbols'),
1154: undef,undef,600).
1155: '</td><td>'.
1156: &Apache::loncommon::help_open_topic("Other_Symbols",&mt('Other Symbols'),
1157: undef,undef,600).
1158: '</td>';
1159: unless ($not_author) {
1160: $out .= '<td>'.
1161: &Apache::loncommon::help_open_topic("Authoring_Output_Tags",&mt('Output Tags'),
1162: undef,undef,600).
1163: '</td>';
1164: }
1165: $out .= '</tr></table>';
1166: return $out;
1167: }
1168:
1169: sub general_help {
1170: my $helptopic='Student_Intro';
1171: if ($env{'request.role'}=~/^(ca|au)/) {
1172: $helptopic='Authoring_Intro';
1173: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1174: $helptopic='Course_Coordination_Intro';
1175: } elsif ($env{'request.role'}=~/^dc/) {
1176: $helptopic='Domain_Coordination_Intro';
1177: }
1178: return $helptopic;
1179: }
1180:
1181: sub update_help_link {
1182: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1183: my $origurl = $ENV{'REQUEST_URI'};
1184: $origurl=~s|^/~|/priv/|;
1185: my $timestamp = time;
1186: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1187: $$datum = &escape($$datum);
1188: }
1189:
1190: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1191: my $output .= <<"ENDOUTPUT";
1192: <script type="text/javascript">
1193: // <![CDATA[
1194: banner_link = '$banner_link';
1195: // ]]>
1196: </script>
1197: ENDOUTPUT
1198: return $output;
1199: }
1200:
1201: # now just updates the help link and generates a blue icon
1202: sub help_open_menu {
1203: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1204: = @_;
1205: $stayOnPage = 0 if (not defined $stayOnPage);
1206: # only use pop-up help (stayOnPage == 0)
1207: # if environment.remote is on (using remote control UI)
1208: if ($env{'browser.interface'} eq 'textual' ||
1209: $env{'environment.remote'} eq 'off' ) {
1210: $stayOnPage=1;
1211: }
1212: my $output;
1213: if ($component_help) {
1214: if (!$text) {
1215: $output=&help_open_topic($component_help,undef,$stayOnPage,
1216: $width,$height);
1217: } else {
1218: my $help_text;
1219: $help_text=&unescape($topic);
1220: $output='<table><tr><td>'.
1221: &help_open_topic($component_help,$help_text,$stayOnPage,
1222: $width,$height).'</td></tr></table>';
1223: }
1224: }
1225: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1226: return $output.$banner_link;
1227: }
1228:
1229: sub top_nav_help {
1230: my ($text) = @_;
1231: $text = &mt($text);
1232: my $stay_on_page =
1233: ($env{'browser.interface'} eq 'textual' ||
1234: $env{'environment.remote'} eq 'off' );
1235: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1236: : "javascript:helpMenu('open')";
1237: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1238:
1239: my $title = &mt('Get help');
1240:
1241: return <<"END";
1242: $banner_link
1243: <a href="$link" title="$title">$text</a>
1244: END
1245: }
1246:
1247: sub help_menu_js {
1248: my ($text) = @_;
1249:
1250: my $stayOnPage =
1251: ($env{'browser.interface'} eq 'textual' ||
1252: $env{'environment.remote'} eq 'off' );
1253:
1254: my $width = 620;
1255: my $height = 600;
1256: my $helptopic=&general_help();
1257: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1258: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1259: my $start_page =
1260: &Apache::loncommon::start_page('Help Menu', undef,
1261: {'frameset' => 1,
1262: 'js_ready' => 1,
1263: 'add_entries' => {
1264: 'border' => '0',
1265: 'rows' => "110,*",},});
1266: my $end_page =
1267: &Apache::loncommon::end_page({'frameset' => 1,
1268: 'js_ready' => 1,});
1269:
1270: my $template .= <<"ENDTEMPLATE";
1271: <script type="text/javascript">
1272: // <![CDATA[
1273: // <!-- BEGIN LON-CAPA Internal
1274: var banner_link = '';
1275: function helpMenu(target) {
1276: var caller = this;
1277: if (target == 'open') {
1278: var newWindow = null;
1279: try {
1280: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1281: }
1282: catch(error) {
1283: writeHelp(caller);
1284: return;
1285: }
1286: if (newWindow) {
1287: caller = newWindow;
1288: }
1289: }
1290: writeHelp(caller);
1291: return;
1292: }
1293: function writeHelp(caller) {
1294: caller.document.writeln('$start_page<frame name="bannerframe" src="'+banner_link+'" /><frame name="bodyframe" src="$details_link" /> $end_page')
1295: caller.document.close()
1296: caller.focus()
1297: }
1298: // END LON-CAPA Internal -->
1299: // ]]>
1300: </script>
1301: ENDTEMPLATE
1302: return $template;
1303: }
1304:
1305: sub help_open_bug {
1306: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1307: unless ($env{'user.adv'}) { return ''; }
1308: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1309: $text = "" if (not defined $text);
1310: $stayOnPage = 0 if (not defined $stayOnPage);
1311: if ($env{'browser.interface'} eq 'textual' ||
1312: $env{'environment.remote'} eq 'off' ) {
1313: $stayOnPage=1;
1314: }
1315: $width = 600 if (not defined $width);
1316: $height = 600 if (not defined $height);
1317:
1318: $topic=~s/\W+/\+/g;
1319: my $link='';
1320: my $template='';
1321: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1322: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1323: if (!$stayOnPage)
1324: {
1325: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1326: }
1327: else
1328: {
1329: $link = $url;
1330: }
1331: # Add the text
1332: if ($text ne "")
1333: {
1334: $template .=
1335: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1336: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1337: }
1338:
1339: # Add the graphic
1340: my $title = &mt('Report a Bug');
1341: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1342: $template .= <<"ENDTEMPLATE";
1343: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1344: ENDTEMPLATE
1345: if ($text ne '') { $template.='</td></tr></table>' };
1346: return $template;
1347:
1348: }
1349:
1350: sub help_open_faq {
1351: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1352: unless ($env{'user.adv'}) { return ''; }
1353: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1354: $text = "" if (not defined $text);
1355: $stayOnPage = 0 if (not defined $stayOnPage);
1356: if ($env{'browser.interface'} eq 'textual' ||
1357: $env{'environment.remote'} eq 'off' ) {
1358: $stayOnPage=1;
1359: }
1360: $width = 350 if (not defined $width);
1361: $height = 400 if (not defined $height);
1362:
1363: $topic=~s/\W+/\+/g;
1364: my $link='';
1365: my $template='';
1366: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1367: if (!$stayOnPage)
1368: {
1369: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1370: }
1371: else
1372: {
1373: $link = $url;
1374: }
1375:
1376: # Add the text
1377: if ($text ne "")
1378: {
1379: $template .=
1380: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1381: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><font color='#FFFFFF' size='2'>$text</font></a>";
1382: }
1383:
1384: # Add the graphic
1385: my $title = &mt('View the FAQ');
1386: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1387: $template .= <<"ENDTEMPLATE";
1388: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1389: ENDTEMPLATE
1390: if ($text ne '') { $template.='</td></tr></table>' };
1391: return $template;
1392:
1393: }
1394:
1395: ###############################################################
1396: ###############################################################
1397:
1398: =pod
1399:
1400: =item * &change_content_javascript():
1401:
1402: This and the next function allow you to create small sections of an
1403: otherwise static HTML page that you can update on the fly with
1404: Javascript, even in Netscape 4.
1405:
1406: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1407: must be written to the HTML page once. It will prove the Javascript
1408: function "change(name, content)". Calling the change function with the
1409: name of the section
1410: you want to update, matching the name passed to C<changable_area>, and
1411: the new content you want to put in there, will put the content into
1412: that area.
1413:
1414: B<Note>: Netscape 4 only reserves enough space for the changable area
1415: to contain room for the original contents. You need to "make space"
1416: for whatever changes you wish to make, and be B<sure> to check your
1417: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1418: it's adequate for updating a one-line status display, but little more.
1419: This script will set the space to 100% width, so you only need to
1420: worry about height in Netscape 4.
1421:
1422: Modern browsers are much less limiting, and if you can commit to the
1423: user not using Netscape 4, this feature may be used freely with
1424: pretty much any HTML.
1425:
1426: =cut
1427:
1428: sub change_content_javascript {
1429: # If we're on Netscape 4, we need to use Layer-based code
1430: if ($env{'browser.type'} eq 'netscape' &&
1431: $env{'browser.version'} =~ /^4\./) {
1432: return (<<NETSCAPE4);
1433: function change(name, content) {
1434: doc = document.layers[name+"___escape"].layers[0].document;
1435: doc.open();
1436: doc.write(content);
1437: doc.close();
1438: }
1439: NETSCAPE4
1440: } else {
1441: # Otherwise, we need to use semi-standards-compliant code
1442: # (technically, "innerHTML" isn't standard but the equivalent
1443: # is really scary, and every useful browser supports it
1444: return (<<DOMBASED);
1445: function change(name, content) {
1446: element = document.getElementById(name);
1447: element.innerHTML = content;
1448: }
1449: DOMBASED
1450: }
1451: }
1452:
1453: =pod
1454:
1455: =item * &changable_area($name,$origContent):
1456:
1457: This provides a "changable area" that can be modified on the fly via
1458: the Javascript code provided in C<change_content_javascript>. $name is
1459: the name you will use to reference the area later; do not repeat the
1460: same name on a given HTML page more then once. $origContent is what
1461: the area will originally contain, which can be left blank.
1462:
1463: =cut
1464:
1465: sub changable_area {
1466: my ($name, $origContent) = @_;
1467:
1468: if ($env{'browser.type'} eq 'netscape' &&
1469: $env{'browser.version'} =~ /^4\./) {
1470: # If this is netscape 4, we need to use the Layer tag
1471: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1472: } else {
1473: return "<span id='$name'>$origContent</span>";
1474: }
1475: }
1476:
1477: =pod
1478:
1479: =item * &viewport_geometry_js
1480:
1481: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1482:
1483: =cut
1484:
1485:
1486: sub viewport_geometry_js {
1487: return <<"GEOMETRY";
1488: var Geometry = {};
1489: function init_geometry() {
1490: if (Geometry.init) { return };
1491: Geometry.init=1;
1492: if (window.innerHeight) {
1493: Geometry.getViewportHeight = function() { return window.innerHeight; };
1494: Geometry.getViewportWidth = function() { return window.innerWidth; };
1495: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1496: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1497: }
1498: else if (document.documentElement && document.documentElement.clientHeight) {
1499: Geometry.getViewportHeight =
1500: function() { return document.documentElement.clientHeight; };
1501: Geometry.getViewportWidth =
1502: function() { return document.documentElement.clientWidth; };
1503:
1504: Geometry.getHorizontalScroll =
1505: function() { return document.documentElement.scrollLeft; };
1506: Geometry.getVerticalScroll =
1507: function() { return document.documentElement.scrollTop; };
1508: }
1509: else if (document.body.clientHeight) {
1510: Geometry.getViewportHeight =
1511: function() { return document.body.clientHeight; };
1512: Geometry.getViewportWidth =
1513: function() { return document.body.clientWidth; };
1514: Geometry.getHorizontalScroll =
1515: function() { return document.body.scrollLeft; };
1516: Geometry.getVerticalScroll =
1517: function() { return document.body.scrollTop; };
1518: }
1519: }
1520:
1521: GEOMETRY
1522: }
1523:
1524: =pod
1525:
1526: =item * &viewport_size_js()
1527:
1528: 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.
1529:
1530: =cut
1531:
1532: sub viewport_size_js {
1533: my $geometry = &viewport_geometry_js();
1534: return <<"DIMS";
1535:
1536: $geometry
1537:
1538: function getViewportDims(width,height) {
1539: init_geometry();
1540: width.value = Geometry.getViewportWidth();
1541: height.value = Geometry.getViewportHeight();
1542: return;
1543: }
1544:
1545: DIMS
1546: }
1547:
1548: =pod
1549:
1550: =item * &resize_textarea_js()
1551:
1552: emits the needed javascript to resize a textarea to be as big as possible
1553:
1554: creates a function resize_textrea that takes two IDs first should be
1555: the id of the element to resize, second should be the id of a div that
1556: surrounds everything that comes after the textarea, this routine needs
1557: to be attached to the <body> for the onload and onresize events.
1558:
1559: =back
1560:
1561: =cut
1562:
1563: sub resize_textarea_js {
1564: my $geometry = &viewport_geometry_js();
1565: return <<"RESIZE";
1566: <script type="text/javascript">
1567: // <![CDATA[
1568: $geometry
1569:
1570: function getX(element) {
1571: var x = 0;
1572: while (element) {
1573: x += element.offsetLeft;
1574: element = element.offsetParent;
1575: }
1576: return x;
1577: }
1578: function getY(element) {
1579: var y = 0;
1580: while (element) {
1581: y += element.offsetTop;
1582: element = element.offsetParent;
1583: }
1584: return y;
1585: }
1586:
1587:
1588: function resize_textarea(textarea_id,bottom_id) {
1589: init_geometry();
1590: var textarea = document.getElementById(textarea_id);
1591: //alert(textarea);
1592:
1593: var textarea_top = getY(textarea);
1594: var textarea_height = textarea.offsetHeight;
1595: var bottom = document.getElementById(bottom_id);
1596: var bottom_top = getY(bottom);
1597: var bottom_height = bottom.offsetHeight;
1598: var window_height = Geometry.getViewportHeight();
1599: var fudge = 23;
1600: var new_height = window_height-fudge-textarea_top-bottom_height;
1601: if (new_height < 300) {
1602: new_height = 300;
1603: }
1604: textarea.style.height=new_height+'px';
1605: }
1606: // ]]>
1607: </script>
1608: RESIZE
1609:
1610: }
1611:
1612: =pod
1613:
1614: =head1 Excel and CSV file utility routines
1615:
1616: =over 4
1617:
1618: =cut
1619:
1620: ###############################################################
1621: ###############################################################
1622:
1623: =pod
1624:
1625: =item * &csv_translate($text)
1626:
1627: Translate $text to allow it to be output as a 'comma separated values'
1628: format.
1629:
1630: =cut
1631:
1632: ###############################################################
1633: ###############################################################
1634: sub csv_translate {
1635: my $text = shift;
1636: $text =~ s/\"/\"\"/g;
1637: $text =~ s/\n/ /g;
1638: return $text;
1639: }
1640:
1641: ###############################################################
1642: ###############################################################
1643:
1644: =pod
1645:
1646: =item * &define_excel_formats()
1647:
1648: Define some commonly used Excel cell formats.
1649:
1650: Currently supported formats:
1651:
1652: =over 4
1653:
1654: =item header
1655:
1656: =item bold
1657:
1658: =item h1
1659:
1660: =item h2
1661:
1662: =item h3
1663:
1664: =item h4
1665:
1666: =item i
1667:
1668: =item date
1669:
1670: =back
1671:
1672: Inputs: $workbook
1673:
1674: Returns: $format, a hash reference.
1675:
1676: =cut
1677:
1678: ###############################################################
1679: ###############################################################
1680: sub define_excel_formats {
1681: my ($workbook) = @_;
1682: my $format;
1683: $format->{'header'} = $workbook->add_format(bold => 1,
1684: bottom => 1,
1685: align => 'center');
1686: $format->{'bold'} = $workbook->add_format(bold=>1);
1687: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1688: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1689: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1690: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1691: $format->{'i'} = $workbook->add_format(italic=>1);
1692: $format->{'date'} = $workbook->add_format(num_format=>
1693: 'mm/dd/yyyy hh:mm:ss');
1694: return $format;
1695: }
1696:
1697: ###############################################################
1698: ###############################################################
1699:
1700: =pod
1701:
1702: =item * &create_workbook()
1703:
1704: Create an Excel worksheet. If it fails, output message on the
1705: request object and return undefs.
1706:
1707: Inputs: Apache request object
1708:
1709: Returns (undef) on failure,
1710: Excel worksheet object, scalar with filename, and formats
1711: from &Apache::loncommon::define_excel_formats on success
1712:
1713: =cut
1714:
1715: ###############################################################
1716: ###############################################################
1717: sub create_workbook {
1718: my ($r) = @_;
1719: #
1720: # Create the excel spreadsheet
1721: my $filename = '/prtspool/'.
1722: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1723: time.'_'.rand(1000000000).'.xls';
1724: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1725: if (! defined($workbook)) {
1726: $r->log_error("Error creating excel spreadsheet $filename: $!");
1727: $r->print('<p>'.&mt("Unable to create new Excel file. ".
1728: "This error has been logged. ".
1729: "Please alert your LON-CAPA administrator").
1730: '</p>');
1731: return (undef);
1732: }
1733: #
1734: $workbook->set_tempdir('/home/httpd/perl/tmp');
1735: #
1736: my $format = &Apache::loncommon::define_excel_formats($workbook);
1737: return ($workbook,$filename,$format);
1738: }
1739:
1740: ###############################################################
1741: ###############################################################
1742:
1743: =pod
1744:
1745: =item * &create_text_file()
1746:
1747: Create a file to write to and eventually make available to the user.
1748: If file creation fails, outputs an error message on the request object and
1749: return undefs.
1750:
1751: Inputs: Apache request object, and file suffix
1752:
1753: Returns (undef) on failure,
1754: Filehandle and filename on success.
1755:
1756: =cut
1757:
1758: ###############################################################
1759: ###############################################################
1760: sub create_text_file {
1761: my ($r,$suffix) = @_;
1762: if (! defined($suffix)) { $suffix = 'txt'; };
1763: my $fh;
1764: my $filename = '/prtspool/'.
1765: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1766: time.'_'.rand(1000000000).'.'.$suffix;
1767: $fh = Apache::File->new('>/home/httpd'.$filename);
1768: if (! defined($fh)) {
1769: $r->log_error("Couldn't open $filename for output $!");
1770: $r->print(&mt('Problems occurred in creating the output file. '
1771: .'This error has been logged. '
1772: .'Please alert your LON-CAPA administrator.'));
1773: }
1774: return ($fh,$filename)
1775: }
1776:
1777:
1778: =pod
1779:
1780: =back
1781:
1782: =cut
1783:
1784: ###############################################################
1785: ## Home server <option> list generating code ##
1786: ###############################################################
1787:
1788: # ------------------------------------------
1789:
1790: sub domain_select {
1791: my ($name,$value,$multiple)=@_;
1792: my %domains=map {
1793: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1794: } &Apache::lonnet::all_domains();
1795: if ($multiple) {
1796: $domains{''}=&mt('Any domain');
1797: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1798: return &multiple_select_form($name,$value,4,\%domains);
1799: } else {
1800: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1801: return &select_form($name,$value,%domains);
1802: }
1803: }
1804:
1805: #-------------------------------------------
1806:
1807: =pod
1808:
1809: =head1 Routines for form select boxes
1810:
1811: =over 4
1812:
1813: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1814:
1815: Returns a string containing a <select> element int multiple mode
1816:
1817:
1818: Args:
1819: $name - name of the <select> element
1820: $value - scalar or array ref of values that should already be selected
1821: $size - number of rows long the select element is
1822: $hash - the elements should be 'option' => 'shown text'
1823: (shown text should already have been &mt())
1824: $order - (optional) array ref of the order to show the elements in
1825:
1826: =cut
1827:
1828: #-------------------------------------------
1829: sub multiple_select_form {
1830: my ($name,$value,$size,$hash,$order)=@_;
1831: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1832: my $output='';
1833: if (! defined($size)) {
1834: $size = 4;
1835: if (scalar(keys(%$hash))<4) {
1836: $size = scalar(keys(%$hash));
1837: }
1838: }
1839: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1840: my @order;
1841: if (ref($order) eq 'ARRAY') {
1842: @order = @{$order};
1843: } else {
1844: @order = sort(keys(%$hash));
1845: }
1846: if (exists($$hash{'select_form_order'})) {
1847: @order = @{$$hash{'select_form_order'}};
1848: }
1849:
1850: foreach my $key (@order) {
1851: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1852: $output.='selected="selected" ' if ($selected{$key});
1853: $output.='>'.$hash->{$key}."</option>\n";
1854: }
1855: $output.="</select>\n";
1856: return $output;
1857: }
1858:
1859: #-------------------------------------------
1860:
1861: =pod
1862:
1863: =item * &select_form($defdom,$name,%hash)
1864:
1865: Returns a string containing a <select name='$name' size='1'> form to
1866: allow a user to select options from a hash option_name => displayed text.
1867: See lonrights.pm for an example invocation and use.
1868:
1869: =cut
1870:
1871: #-------------------------------------------
1872: sub select_form {
1873: my ($def,$name,%hash) = @_;
1874: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1875: my @keys;
1876: if (exists($hash{'select_form_order'})) {
1877: @keys=@{$hash{'select_form_order'}};
1878: } else {
1879: @keys=sort(keys(%hash));
1880: }
1881: foreach my $key (@keys) {
1882: $selectform.=
1883: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
1884: ($key eq $def ? 'selected="selected" ' : '').
1885: ">".&mt($hash{$key})."</option>\n";
1886: }
1887: $selectform.="</select>";
1888: return $selectform;
1889: }
1890:
1891: # For display filters
1892:
1893: sub display_filter {
1894: if (!$env{'form.show'}) { $env{'form.show'}=10; }
1895: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1896: return '<span class="LC_nobreak"><label>'.&mt('Records [_1]',
1897: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
1898: (&mt('all'),10,20,50,100,1000,10000))).
1899: '</label></span> <span class="LC_nobreak">'.
1900: &mt('Filter [_1]',
1901: &select_form($env{'form.displayfilter'},
1902: 'displayfilter',
1903: ('currentfolder' => 'Current folder/page',
1904: 'containing' => 'Containing phrase',
1905: 'none' => 'None'))).
1906: '<input type="text" name="containingphrase" size="30" value="'.&HTML::Entities::encode($env{'form.containingphrase'}).'" /></span>';
1907: }
1908:
1909: sub gradeleveldescription {
1910: my $gradelevel=shift;
1911: my %gradelevels=(0 => 'Not specified',
1912: 1 => 'Grade 1',
1913: 2 => 'Grade 2',
1914: 3 => 'Grade 3',
1915: 4 => 'Grade 4',
1916: 5 => 'Grade 5',
1917: 6 => 'Grade 6',
1918: 7 => 'Grade 7',
1919: 8 => 'Grade 8',
1920: 9 => 'Grade 9',
1921: 10 => 'Grade 10',
1922: 11 => 'Grade 11',
1923: 12 => 'Grade 12',
1924: 13 => 'Grade 13',
1925: 14 => '100 Level',
1926: 15 => '200 Level',
1927: 16 => '300 Level',
1928: 17 => '400 Level',
1929: 18 => 'Graduate Level');
1930: return &mt($gradelevels{$gradelevel});
1931: }
1932:
1933: sub select_level_form {
1934: my ($deflevel,$name)=@_;
1935: unless ($deflevel) { $deflevel=0; }
1936: my $selectform = "<select name=\"$name\" size=\"1\">\n";
1937: for (my $i=0; $i<=18; $i++) {
1938: $selectform.="<option value=\"$i\" ".
1939: ($i==$deflevel ? 'selected="selected" ' : '').
1940: ">".&gradeleveldescription($i)."</option>\n";
1941: }
1942: $selectform.="</select>";
1943: return $selectform;
1944: }
1945:
1946: #-------------------------------------------
1947:
1948: =pod
1949:
1950: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
1951:
1952: Returns a string containing a <select name='$name' size='1'> form to
1953: allow a user to select the domain to preform an operation in.
1954: See loncreateuser.pm for an example invocation and use.
1955:
1956: If the $includeempty flag is set, it also includes an empty choice ("no domain
1957: selected");
1958:
1959: If the $showdomdesc flag is set, the domain name is followed by the domain description.
1960:
1961: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
1962:
1963: The optional $incdoms is a reference to an array of domains which will be the only available options.
1964:
1965: =cut
1966:
1967: #-------------------------------------------
1968: sub select_dom_form {
1969: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
1970: if ($onchange) {
1971: $onchange = ' onchange="'.$onchange.'"';
1972: }
1973: my @domains;
1974: if (ref($incdoms) eq 'ARRAY') {
1975: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
1976: } else {
1977: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
1978: }
1979: if ($includeempty) { @domains=('',@domains); }
1980: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1981: foreach my $dom (@domains) {
1982: $selectdomain.="<option value=\"$dom\" ".
1983: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
1984: if ($showdomdesc) {
1985: if ($dom ne '') {
1986: my $domdesc = &Apache::lonnet::domain($dom,'description');
1987: if ($domdesc ne '') {
1988: $selectdomain .= ' ('.$domdesc.')';
1989: }
1990: }
1991: }
1992: $selectdomain .= "</option>\n";
1993: }
1994: $selectdomain.="</select>";
1995: return $selectdomain;
1996: }
1997:
1998: #-------------------------------------------
1999:
2000: =pod
2001:
2002: =item * &home_server_form_item($domain,$name,$defaultflag)
2003:
2004: input: 4 arguments (two required, two optional) -
2005: $domain - domain of new user
2006: $name - name of form element
2007: $default - Value of 'default' causes a default item to be first
2008: option, and selected by default.
2009: $hide - Value of 'hide' causes hiding of the name of the server,
2010: if 1 server found, or default, if 0 found.
2011: output: returns 2 items:
2012: (a) form element which contains either:
2013: (i) <select name="$name">
2014: <option value="$hostid1">$hostid $servers{$hostid}</option>
2015: <option value="$hostid2">$hostid $servers{$hostid}</option>
2016: </select>
2017: form item if there are multiple library servers in $domain, or
2018: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2019: if there is only one library server in $domain.
2020:
2021: (b) number of library servers found.
2022:
2023: See loncreateuser.pm for example of use.
2024:
2025: =cut
2026:
2027: #-------------------------------------------
2028: sub home_server_form_item {
2029: my ($domain,$name,$default,$hide) = @_;
2030: my %servers = &Apache::lonnet::get_servers($domain,'library');
2031: my $result;
2032: my $numlib = keys(%servers);
2033: if ($numlib > 1) {
2034: $result .= '<select name="'.$name.'" />'."\n";
2035: if ($default) {
2036: $result .= '<option value="default" selected="selected">'.&mt('default').
2037: '</option>'."\n";
2038: }
2039: foreach my $hostid (sort(keys(%servers))) {
2040: $result.= '<option value="'.$hostid.'">'.
2041: $hostid.' '.$servers{$hostid}."</option>\n";
2042: }
2043: $result .= '</select>'."\n";
2044: } elsif ($numlib == 1) {
2045: my $hostid;
2046: foreach my $item (keys(%servers)) {
2047: $hostid = $item;
2048: }
2049: $result .= '<input type="hidden" name="'.$name.'" value="'.
2050: $hostid.'" />';
2051: if (!$hide) {
2052: $result .= $hostid.' '.$servers{$hostid};
2053: }
2054: $result .= "\n";
2055: } elsif ($default) {
2056: $result .= '<input type="hidden" name="'.$name.
2057: '" value="default" />';
2058: if (!$hide) {
2059: $result .= &mt('default');
2060: }
2061: $result .= "\n";
2062: }
2063: return ($result,$numlib);
2064: }
2065:
2066: =pod
2067:
2068: =back
2069:
2070: =cut
2071:
2072: ###############################################################
2073: ## Decoding User Agent ##
2074: ###############################################################
2075:
2076: =pod
2077:
2078: =head1 Decoding the User Agent
2079:
2080: =over 4
2081:
2082: =item * &decode_user_agent()
2083:
2084: Inputs: $r
2085:
2086: Outputs:
2087:
2088: =over 4
2089:
2090: =item * $httpbrowser
2091:
2092: =item * $clientbrowser
2093:
2094: =item * $clientversion
2095:
2096: =item * $clientmathml
2097:
2098: =item * $clientunicode
2099:
2100: =item * $clientos
2101:
2102: =back
2103:
2104: =back
2105:
2106: =cut
2107:
2108: ###############################################################
2109: ###############################################################
2110: sub decode_user_agent {
2111: my ($r)=@_;
2112: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2113: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2114: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2115: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2116: my $clientbrowser='unknown';
2117: my $clientversion='0';
2118: my $clientmathml='';
2119: my $clientunicode='0';
2120: for (my $i=0;$i<=$#browsertype;$i++) {
2121: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2122: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2123: $clientbrowser=$bname;
2124: $httpbrowser=~/$vreg/i;
2125: $clientversion=$1;
2126: $clientmathml=($clientversion>=$minv);
2127: $clientunicode=($clientversion>=$univ);
2128: }
2129: }
2130: my $clientos='unknown';
2131: if (($httpbrowser=~/linux/i) ||
2132: ($httpbrowser=~/unix/i) ||
2133: ($httpbrowser=~/ux/i) ||
2134: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2135: if (($httpbrowser=~/vax/i) ||
2136: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2137: if ($httpbrowser=~/next/i) { $clientos='next'; }
2138: if (($httpbrowser=~/mac/i) ||
2139: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2140: if ($httpbrowser=~/win/i) { $clientos='win'; }
2141: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2142: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2143: $clientunicode,$clientos,);
2144: }
2145:
2146: ###############################################################
2147: ## Authentication changing form generation subroutines ##
2148: ###############################################################
2149: ##
2150: ## All of the authform_xxxxxxx subroutines take their inputs in a
2151: ## hash, and have reasonable default values.
2152: ##
2153: ## formname = the name given in the <form> tag.
2154: #-------------------------------------------
2155:
2156: =pod
2157:
2158: =head1 Authentication Routines
2159:
2160: =over 4
2161:
2162: =item * &authform_xxxxxx()
2163:
2164: The authform_xxxxxx subroutines provide javascript and html forms which
2165: handle some of the conveniences required for authentication forms.
2166: This is not an optimal method, but it works.
2167:
2168: =over 4
2169:
2170: =item * authform_header
2171:
2172: =item * authform_authorwarning
2173:
2174: =item * authform_nochange
2175:
2176: =item * authform_kerberos
2177:
2178: =item * authform_internal
2179:
2180: =item * authform_filesystem
2181:
2182: =back
2183:
2184: See loncreateuser.pm for invocation and use examples.
2185:
2186: =cut
2187:
2188: #-------------------------------------------
2189: sub authform_header{
2190: my %in = (
2191: formname => 'cu',
2192: kerb_def_dom => '',
2193: @_,
2194: );
2195: $in{'formname'} = 'document.' . $in{'formname'};
2196: my $result='';
2197:
2198: #---------------------------------------------- Code for upper case translation
2199: my $Javascript_toUpperCase;
2200: unless ($in{kerb_def_dom}) {
2201: $Javascript_toUpperCase =<<"END";
2202: switch (choice) {
2203: case 'krb': currentform.elements[choicearg].value =
2204: currentform.elements[choicearg].value.toUpperCase();
2205: break;
2206: default:
2207: }
2208: END
2209: } else {
2210: $Javascript_toUpperCase = "";
2211: }
2212:
2213: my $radioval = "'nochange'";
2214: if (defined($in{'curr_authtype'})) {
2215: if ($in{'curr_authtype'} ne '') {
2216: $radioval = "'".$in{'curr_authtype'}."arg'";
2217: }
2218: }
2219: my $argfield = 'null';
2220: if (defined($in{'mode'})) {
2221: if ($in{'mode'} eq 'modifycourse') {
2222: if (defined($in{'curr_autharg'})) {
2223: if ($in{'curr_autharg'} ne '') {
2224: $argfield = "'$in{'curr_autharg'}'";
2225: }
2226: }
2227: }
2228: }
2229:
2230: $result.=<<"END";
2231: var current = new Object();
2232: current.radiovalue = $radioval;
2233: current.argfield = $argfield;
2234:
2235: function changed_radio(choice,currentform) {
2236: var choicearg = choice + 'arg';
2237: // If a radio button in changed, we need to change the argfield
2238: if (current.radiovalue != choice) {
2239: current.radiovalue = choice;
2240: if (current.argfield != null) {
2241: currentform.elements[current.argfield].value = '';
2242: }
2243: if (choice == 'nochange') {
2244: current.argfield = null;
2245: } else {
2246: current.argfield = choicearg;
2247: switch(choice) {
2248: case 'krb':
2249: currentform.elements[current.argfield].value =
2250: "$in{'kerb_def_dom'}";
2251: break;
2252: default:
2253: break;
2254: }
2255: }
2256: }
2257: return;
2258: }
2259:
2260: function changed_text(choice,currentform) {
2261: var choicearg = choice + 'arg';
2262: if (currentform.elements[choicearg].value !='') {
2263: $Javascript_toUpperCase
2264: // clear old field
2265: if ((current.argfield != choicearg) && (current.argfield != null)) {
2266: currentform.elements[current.argfield].value = '';
2267: }
2268: current.argfield = choicearg;
2269: }
2270: set_auth_radio_buttons(choice,currentform);
2271: return;
2272: }
2273:
2274: function set_auth_radio_buttons(newvalue,currentform) {
2275: var i=0;
2276: while (i < currentform.login.length) {
2277: if (currentform.login[i].value == newvalue) { break; }
2278: i++;
2279: }
2280: if (i == currentform.login.length) {
2281: return;
2282: }
2283: current.radiovalue = newvalue;
2284: currentform.login[i].checked = true;
2285: return;
2286: }
2287: END
2288: return $result;
2289: }
2290:
2291: sub authform_authorwarning{
2292: my $result='';
2293: $result='<i>'.
2294: &mt('As a general rule, only authors or co-authors should be '.
2295: 'filesystem authenticated '.
2296: '(which allows access to the server filesystem).')."</i>\n";
2297: return $result;
2298: }
2299:
2300: sub authform_nochange{
2301: my %in = (
2302: formname => 'document.cu',
2303: kerb_def_dom => 'MSU.EDU',
2304: @_,
2305: );
2306: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2307: my $result;
2308: if (keys(%can_assign) == 0) {
2309: $result = &mt('Under you current role you are not permitted to change login settings for this user');
2310: } else {
2311: $result = '<label>'.&mt('[_1] Do not change login data',
2312: '<input type="radio" name="login" value="nochange" '.
2313: 'checked="checked" onclick="'.
2314: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2315: '</label>';
2316: }
2317: return $result;
2318: }
2319:
2320: sub authform_kerberos {
2321: my %in = (
2322: formname => 'document.cu',
2323: kerb_def_dom => 'MSU.EDU',
2324: kerb_def_auth => 'krb4',
2325: @_,
2326: );
2327: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2328: $autharg,$jscall);
2329: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2330: if ($in{'kerb_def_auth'} eq 'krb5') {
2331: $check5 = ' checked="checked"';
2332: } else {
2333: $check4 = ' checked="checked"';
2334: }
2335: $krbarg = $in{'kerb_def_dom'};
2336: if (defined($in{'curr_authtype'})) {
2337: if ($in{'curr_authtype'} eq 'krb') {
2338: $krbcheck = ' checked="checked"';
2339: if (defined($in{'mode'})) {
2340: if ($in{'mode'} eq 'modifyuser') {
2341: $krbcheck = '';
2342: }
2343: }
2344: if (defined($in{'curr_kerb_ver'})) {
2345: if ($in{'curr_krb_ver'} eq '5') {
2346: $check5 = ' checked="checked"';
2347: $check4 = '';
2348: } else {
2349: $check4 = ' checked="checked"';
2350: $check5 = '';
2351: }
2352: }
2353: if (defined($in{'curr_autharg'})) {
2354: $krbarg = $in{'curr_autharg'};
2355: }
2356: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2357: if (defined($in{'curr_autharg'})) {
2358: $result =
2359: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2360: $in{'curr_autharg'},$krbver);
2361: } else {
2362: $result =
2363: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2364: }
2365: return $result;
2366: }
2367: }
2368: } else {
2369: if ($authnum == 1) {
2370: $authtype = '<input type="hidden" name="login" value="krb" />';
2371: }
2372: }
2373: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2374: return;
2375: } elsif ($authtype eq '') {
2376: if (defined($in{'mode'})) {
2377: if ($in{'mode'} eq 'modifycourse') {
2378: if ($authnum == 1) {
2379: $authtype = '<input type="hidden" name="login" value="krb" />';
2380: }
2381: }
2382: }
2383: }
2384: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2385: if ($authtype eq '') {
2386: $authtype = '<input type="radio" name="login" value="krb" '.
2387: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2388: $krbcheck.' />';
2389: }
2390: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2391: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2392: $in{'curr_authtype'} eq 'krb5') ||
2393: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2394: $in{'curr_authtype'} eq 'krb4')) {
2395: $result .= &mt
2396: ('[_1] Kerberos authenticated with domain [_2] '.
2397: '[_3] Version 4 [_4] Version 5 [_5]',
2398: '<label>'.$authtype,
2399: '</label><input type="text" size="10" name="krbarg" '.
2400: 'value="'.$krbarg.'" '.
2401: 'onchange="'.$jscall.'" />',
2402: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2403: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2404: '</label>');
2405: } elsif ($can_assign{'krb4'}) {
2406: $result .= &mt
2407: ('[_1] Kerberos authenticated with domain [_2] '.
2408: '[_3] Version 4 [_4]',
2409: '<label>'.$authtype,
2410: '</label><input type="text" size="10" name="krbarg" '.
2411: 'value="'.$krbarg.'" '.
2412: 'onchange="'.$jscall.'" />',
2413: '<label><input type="hidden" name="krbver" value="4" />',
2414: '</label>');
2415: } elsif ($can_assign{'krb5'}) {
2416: $result .= &mt
2417: ('[_1] Kerberos authenticated with domain [_2] '.
2418: '[_3] Version 5 [_4]',
2419: '<label>'.$authtype,
2420: '</label><input type="text" size="10" name="krbarg" '.
2421: 'value="'.$krbarg.'" '.
2422: 'onchange="'.$jscall.'" />',
2423: '<label><input type="hidden" name="krbver" value="5" />',
2424: '</label>');
2425: }
2426: return $result;
2427: }
2428:
2429: sub authform_internal{
2430: my %in = (
2431: formname => 'document.cu',
2432: kerb_def_dom => 'MSU.EDU',
2433: @_,
2434: );
2435: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2436: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2437: if (defined($in{'curr_authtype'})) {
2438: if ($in{'curr_authtype'} eq 'int') {
2439: if ($can_assign{'int'}) {
2440: $intcheck = 'checked="checked" ';
2441: if (defined($in{'mode'})) {
2442: if ($in{'mode'} eq 'modifyuser') {
2443: $intcheck = '';
2444: }
2445: }
2446: if (defined($in{'curr_autharg'})) {
2447: $intarg = $in{'curr_autharg'};
2448: }
2449: } else {
2450: $result = &mt('Currently internally authenticated.');
2451: return $result;
2452: }
2453: }
2454: } else {
2455: if ($authnum == 1) {
2456: $authtype = '<input type="hidden" name="login" value="int" />';
2457: }
2458: }
2459: if (!$can_assign{'int'}) {
2460: return;
2461: } elsif ($authtype eq '') {
2462: if (defined($in{'mode'})) {
2463: if ($in{'mode'} eq 'modifycourse') {
2464: if ($authnum == 1) {
2465: $authtype = '<input type="hidden" name="login" value="int" />';
2466: }
2467: }
2468: }
2469: }
2470: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2471: if ($authtype eq '') {
2472: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2473: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2474: }
2475: $autharg = '<input type="password" size="10" name="intarg" value="'.
2476: $intarg.'" onchange="'.$jscall.'" />';
2477: $result = &mt
2478: ('[_1] Internally authenticated (with initial password [_2])',
2479: '<label>'.$authtype,'</label>'.$autharg);
2480: $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>';
2481: return $result;
2482: }
2483:
2484: sub authform_local{
2485: my %in = (
2486: formname => 'document.cu',
2487: kerb_def_dom => 'MSU.EDU',
2488: @_,
2489: );
2490: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2491: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2492: if (defined($in{'curr_authtype'})) {
2493: if ($in{'curr_authtype'} eq 'loc') {
2494: if ($can_assign{'loc'}) {
2495: $loccheck = 'checked="checked" ';
2496: if (defined($in{'mode'})) {
2497: if ($in{'mode'} eq 'modifyuser') {
2498: $loccheck = '';
2499: }
2500: }
2501: if (defined($in{'curr_autharg'})) {
2502: $locarg = $in{'curr_autharg'};
2503: }
2504: } else {
2505: $result = &mt('Currently using local (institutional) authentication.');
2506: return $result;
2507: }
2508: }
2509: } else {
2510: if ($authnum == 1) {
2511: $authtype = '<input type="hidden" name="login" value="loc" />';
2512: }
2513: }
2514: if (!$can_assign{'loc'}) {
2515: return;
2516: } elsif ($authtype eq '') {
2517: if (defined($in{'mode'})) {
2518: if ($in{'mode'} eq 'modifycourse') {
2519: if ($authnum == 1) {
2520: $authtype = '<input type="hidden" name="login" value="loc" />';
2521: }
2522: }
2523: }
2524: }
2525: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2526: if ($authtype eq '') {
2527: $authtype = '<input type="radio" name="login" value="loc" '.
2528: $loccheck.' onchange="'.$jscall.'" onclick="'.
2529: $jscall.'" />';
2530: }
2531: $autharg = '<input type="text" size="10" name="locarg" value="'.
2532: $locarg.'" onchange="'.$jscall.'" />';
2533: $result = &mt('[_1] Local Authentication with argument [_2]',
2534: '<label>'.$authtype,'</label>'.$autharg);
2535: return $result;
2536: }
2537:
2538: sub authform_filesystem{
2539: my %in = (
2540: formname => 'document.cu',
2541: kerb_def_dom => 'MSU.EDU',
2542: @_,
2543: );
2544: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2545: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2546: if (defined($in{'curr_authtype'})) {
2547: if ($in{'curr_authtype'} eq 'fsys') {
2548: if ($can_assign{'fsys'}) {
2549: $fsyscheck = 'checked="checked" ';
2550: if (defined($in{'mode'})) {
2551: if ($in{'mode'} eq 'modifyuser') {
2552: $fsyscheck = '';
2553: }
2554: }
2555: } else {
2556: $result = &mt('Currently Filesystem Authenticated.');
2557: return $result;
2558: }
2559: }
2560: } else {
2561: if ($authnum == 1) {
2562: $authtype = '<input type="hidden" name="login" value="fsys" />';
2563: }
2564: }
2565: if (!$can_assign{'fsys'}) {
2566: return;
2567: } elsif ($authtype eq '') {
2568: if (defined($in{'mode'})) {
2569: if ($in{'mode'} eq 'modifycourse') {
2570: if ($authnum == 1) {
2571: $authtype = '<input type="hidden" name="login" value="fsys" />';
2572: }
2573: }
2574: }
2575: }
2576: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2577: if ($authtype eq '') {
2578: $authtype = '<input type="radio" name="login" value="fsys" '.
2579: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2580: $jscall.'" />';
2581: }
2582: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2583: ' onchange="'.$jscall.'" />';
2584: $result = &mt
2585: ('[_1] Filesystem Authenticated (with initial password [_2])',
2586: '<label><input type="radio" name="login" value="fsys" '.
2587: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2588: '</label><input type="password" size="10" name="fsysarg" value="" '.
2589: 'onchange="'.$jscall.'" />');
2590: return $result;
2591: }
2592:
2593: sub get_assignable_auth {
2594: my ($dom) = @_;
2595: if ($dom eq '') {
2596: $dom = $env{'request.role.domain'};
2597: }
2598: my %can_assign = (
2599: krb4 => 1,
2600: krb5 => 1,
2601: int => 1,
2602: loc => 1,
2603: );
2604: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2605: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2606: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2607: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2608: my $context;
2609: if ($env{'request.role'} =~ /^au/) {
2610: $context = 'author';
2611: } elsif ($env{'request.role'} =~ /^dc/) {
2612: $context = 'domain';
2613: } elsif ($env{'request.course.id'}) {
2614: $context = 'course';
2615: }
2616: if ($context) {
2617: if (ref($authhash->{$context}) eq 'HASH') {
2618: %can_assign = %{$authhash->{$context}};
2619: }
2620: }
2621: }
2622: }
2623: my $authnum = 0;
2624: foreach my $key (keys(%can_assign)) {
2625: if ($can_assign{$key}) {
2626: $authnum ++;
2627: }
2628: }
2629: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2630: $authnum --;
2631: }
2632: return ($authnum,%can_assign);
2633: }
2634:
2635: ###############################################################
2636: ## Get Kerberos Defaults for Domain ##
2637: ###############################################################
2638: ##
2639: ## Returns default kerberos version and an associated argument
2640: ## as listed in file domain.tab. If not listed, provides
2641: ## appropriate default domain and kerberos version.
2642: ##
2643: #-------------------------------------------
2644:
2645: =pod
2646:
2647: =item * &get_kerberos_defaults()
2648:
2649: get_kerberos_defaults($target_domain) returns the default kerberos
2650: version and domain. If not found, it defaults to version 4 and the
2651: domain of the server.
2652:
2653: =over 4
2654:
2655: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2656:
2657: =back
2658:
2659: =back
2660:
2661: =cut
2662:
2663: #-------------------------------------------
2664: sub get_kerberos_defaults {
2665: my $domain=shift;
2666: my ($krbdef,$krbdefdom);
2667: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2668: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2669: $krbdef = $domdefaults{'auth_def'};
2670: $krbdefdom = $domdefaults{'auth_arg_def'};
2671: } else {
2672: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2673: my $krbdefdom=$1;
2674: $krbdefdom=~tr/a-z/A-Z/;
2675: $krbdef = "krb4";
2676: }
2677: return ($krbdef,$krbdefdom);
2678: }
2679:
2680:
2681: ###############################################################
2682: ## Thesaurus Functions ##
2683: ###############################################################
2684:
2685: =pod
2686:
2687: =head1 Thesaurus Functions
2688:
2689: =over 4
2690:
2691: =item * &initialize_keywords()
2692:
2693: Initializes the package variable %Keywords if it is empty. Uses the
2694: package variable $thesaurus_db_file.
2695:
2696: =cut
2697:
2698: ###################################################
2699:
2700: sub initialize_keywords {
2701: return 1 if (scalar keys(%Keywords));
2702: # If we are here, %Keywords is empty, so fill it up
2703: # Make sure the file we need exists...
2704: if (! -e $thesaurus_db_file) {
2705: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2706: " failed because it does not exist");
2707: return 0;
2708: }
2709: # Set up the hash as a database
2710: my %thesaurus_db;
2711: if (! tie(%thesaurus_db,'GDBM_File',
2712: $thesaurus_db_file,&GDBM_READER(),0640)){
2713: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2714: $thesaurus_db_file);
2715: return 0;
2716: }
2717: # Get the average number of appearances of a word.
2718: my $avecount = $thesaurus_db{'average.count'};
2719: # Put keywords (those that appear > average) into %Keywords
2720: while (my ($word,$data)=each (%thesaurus_db)) {
2721: my ($count,undef) = split /:/,$data;
2722: $Keywords{$word}++ if ($count > $avecount);
2723: }
2724: untie %thesaurus_db;
2725: # Remove special values from %Keywords.
2726: foreach my $value ('total.count','average.count') {
2727: delete($Keywords{$value}) if (exists($Keywords{$value}));
2728: }
2729: return 1;
2730: }
2731:
2732: ###################################################
2733:
2734: =pod
2735:
2736: =item * &keyword($word)
2737:
2738: Returns true if $word is a keyword. A keyword is a word that appears more
2739: than the average number of times in the thesaurus database. Calls
2740: &initialize_keywords
2741:
2742: =cut
2743:
2744: ###################################################
2745:
2746: sub keyword {
2747: return if (!&initialize_keywords());
2748: my $word=lc(shift());
2749: $word=~s/\W//g;
2750: return exists($Keywords{$word});
2751: }
2752:
2753: ###############################################################
2754:
2755: =pod
2756:
2757: =item * &get_related_words()
2758:
2759: Look up a word in the thesaurus. Takes a scalar argument and returns
2760: an array of words. If the keyword is not in the thesaurus, an empty array
2761: will be returned. The order of the words returned is determined by the
2762: database which holds them.
2763:
2764: Uses global $thesaurus_db_file.
2765:
2766: =cut
2767:
2768: ###############################################################
2769: sub get_related_words {
2770: my $keyword = shift;
2771: my %thesaurus_db;
2772: if (! -e $thesaurus_db_file) {
2773: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
2774: "failed because the file does not exist");
2775: return ();
2776: }
2777: if (! tie(%thesaurus_db,'GDBM_File',
2778: $thesaurus_db_file,&GDBM_READER(),0640)){
2779: return ();
2780: }
2781: my @Words=();
2782: my $count=0;
2783: if (exists($thesaurus_db{$keyword})) {
2784: # The first element is the number of times
2785: # the word appears. We do not need it now.
2786: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
2787: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
2788: my $threshold=$mostfrequentcount/10;
2789: foreach my $possibleword (@RelatedWords) {
2790: my ($word,$wordcount)=split(/\,/,$possibleword);
2791: if ($wordcount>$threshold) {
2792: push(@Words,$word);
2793: $count++;
2794: if ($count>10) { last; }
2795: }
2796: }
2797: }
2798: untie %thesaurus_db;
2799: return @Words;
2800: }
2801:
2802: =pod
2803:
2804: =back
2805:
2806: =cut
2807:
2808: # -------------------------------------------------------------- Plaintext name
2809: =pod
2810:
2811: =head1 User Name Functions
2812:
2813: =over 4
2814:
2815: =item * &plainname($uname,$udom,$first)
2816:
2817: Takes a users logon name and returns it as a string in
2818: "first middle last generation" form
2819: if $first is set to 'lastname' then it returns it as
2820: 'lastname generation, firstname middlename' if their is a lastname
2821:
2822: =cut
2823:
2824:
2825: ###############################################################
2826: sub plainname {
2827: my ($uname,$udom,$first)=@_;
2828: return if (!defined($uname) || !defined($udom));
2829: my %names=&getnames($uname,$udom);
2830: my $name=&Apache::lonnet::format_name($names{'firstname'},
2831: $names{'middlename'},
2832: $names{'lastname'},
2833: $names{'generation'},$first);
2834: $name=~s/^\s+//;
2835: $name=~s/\s+$//;
2836: $name=~s/\s+/ /g;
2837: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
2838: return $name;
2839: }
2840:
2841: # -------------------------------------------------------------------- Nickname
2842: =pod
2843:
2844: =item * &nickname($uname,$udom)
2845:
2846: Gets a users name and returns it as a string as
2847:
2848: ""nickname""
2849:
2850: if the user has a nickname or
2851:
2852: "first middle last generation"
2853:
2854: if the user does not
2855:
2856: =cut
2857:
2858: sub nickname {
2859: my ($uname,$udom)=@_;
2860: return if (!defined($uname) || !defined($udom));
2861: my %names=&getnames($uname,$udom);
2862: my $name=$names{'nickname'};
2863: if ($name) {
2864: $name='"'.$name.'"';
2865: } else {
2866: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
2867: $names{'lastname'}.' '.$names{'generation'};
2868: $name=~s/\s+$//;
2869: $name=~s/\s+/ /g;
2870: }
2871: return $name;
2872: }
2873:
2874: sub getnames {
2875: my ($uname,$udom)=@_;
2876: return if (!defined($uname) || !defined($udom));
2877: if ($udom eq 'public' && $uname eq 'public') {
2878: return ('lastname' => &mt('Public'));
2879: }
2880: my $id=$uname.':'.$udom;
2881: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
2882: if ($cached) {
2883: return %{$names};
2884: } else {
2885: my %loadnames=&Apache::lonnet::get('environment',
2886: ['firstname','middlename','lastname','generation','nickname'],
2887: $udom,$uname);
2888: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
2889: return %loadnames;
2890: }
2891: }
2892:
2893: # -------------------------------------------------------------------- getemails
2894:
2895: =pod
2896:
2897: =item * &getemails($uname,$udom)
2898:
2899: Gets a user's email information and returns it as a hash with keys:
2900: notification, critnotification, permanentemail
2901:
2902: For notification and critnotification, values are comma-separated lists
2903: of e-mail addresses; for permanentemail, value is a single e-mail address.
2904:
2905:
2906: =cut
2907:
2908:
2909: sub getemails {
2910: my ($uname,$udom)=@_;
2911: if ($udom eq 'public' && $uname eq 'public') {
2912: return;
2913: }
2914: if (!$udom) { $udom=$env{'user.domain'}; }
2915: if (!$uname) { $uname=$env{'user.name'}; }
2916: my $id=$uname.':'.$udom;
2917: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
2918: if ($cached) {
2919: return %{$names};
2920: } else {
2921: my %loadnames=&Apache::lonnet::get('environment',
2922: ['notification','critnotification',
2923: 'permanentemail'],
2924: $udom,$uname);
2925: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
2926: return %loadnames;
2927: }
2928: }
2929:
2930: sub flush_email_cache {
2931: my ($uname,$udom)=@_;
2932: if (!$udom) { $udom =$env{'user.domain'}; }
2933: if (!$uname) { $uname=$env{'user.name'}; }
2934: return if ($udom eq 'public' && $uname eq 'public');
2935: my $id=$uname.':'.$udom;
2936: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
2937: }
2938:
2939: # -------------------------------------------------------------------- getlangs
2940:
2941: =pod
2942:
2943: =item * &getlangs($uname,$udom)
2944:
2945: Gets a user's language preference and returns it as a hash with key:
2946: language.
2947:
2948: =cut
2949:
2950:
2951: sub getlangs {
2952: my ($uname,$udom) = @_;
2953: if (!$udom) { $udom =$env{'user.domain'}; }
2954: if (!$uname) { $uname=$env{'user.name'}; }
2955: my $id=$uname.':'.$udom;
2956: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
2957: if ($cached) {
2958: return %{$langs};
2959: } else {
2960: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
2961: $udom,$uname);
2962: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
2963: return %loadlangs;
2964: }
2965: }
2966:
2967: sub flush_langs_cache {
2968: my ($uname,$udom)=@_;
2969: if (!$udom) { $udom =$env{'user.domain'}; }
2970: if (!$uname) { $uname=$env{'user.name'}; }
2971: return if ($udom eq 'public' && $uname eq 'public');
2972: my $id=$uname.':'.$udom;
2973: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
2974: }
2975:
2976: # ------------------------------------------------------------------ Screenname
2977:
2978: =pod
2979:
2980: =item * &screenname($uname,$udom)
2981:
2982: Gets a users screenname and returns it as a string
2983:
2984: =cut
2985:
2986: sub screenname {
2987: my ($uname,$udom)=@_;
2988: if ($uname eq $env{'user.name'} &&
2989: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
2990: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
2991: return $names{'screenname'};
2992: }
2993:
2994: # ------------------------------------------------------------- Confirm Wrapper
2995: =pod
2996:
2997: =item confirmwrapper
2998:
2999: Wrap messages about completion of operation in box
3000:
3001: =cut
3002:
3003: sub confirmwrapper {
3004: my ($message)=@_;
3005: if ($message) {
3006: return "\n".'<div class="LC_confirm_box">'."\n"
3007: .$message."\n"
3008: .'</div>'."\n";
3009: } else {
3010: return $message;
3011: }
3012: }
3013:
3014: # ------------------------------------------------------------- Message Wrapper
3015:
3016: sub messagewrapper {
3017: my ($link,$username,$domain,$subject,$text)=@_;
3018: return
3019: '<a href="/adm/email?compose=individual&'.
3020: 'recname='.$username.'&recdom='.$domain.
3021: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3022: 'title="'.&mt('Send message').'">'.$link.'</a>';
3023: }
3024: # --------------------------------------------------------------- Notes Wrapper
3025:
3026: sub noteswrapper {
3027: my ($link,$un,$do)=@_;
3028: return
3029: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3030: }
3031: # ------------------------------------------------------------- Aboutme Wrapper
3032:
3033: sub aboutmewrapper {
3034: my ($link,$username,$domain,$target)=@_;
3035: if (!defined($username) && !defined($domain)) {
3036: return;
3037: }
3038: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3039: ($target?' target="$target"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3040: }
3041:
3042: # ------------------------------------------------------------ Syllabus Wrapper
3043:
3044:
3045: sub syllabuswrapper {
3046: my ($linktext,$coursedir,$domain,$fontcolor)=@_;
3047: if ($fontcolor) {
3048: $linktext='<font color="'.$fontcolor.'">'.$linktext.'</font>';
3049: }
3050: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3051: }
3052:
3053: sub track_student_link {
3054: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3055: my $link ="/adm/trackstudent?";
3056: my $title = 'View recent activity';
3057: if (defined($sname) && $sname !~ /^\s*$/ &&
3058: defined($sdom) && $sdom !~ /^\s*$/) {
3059: $link .= "selected_student=$sname:$sdom";
3060: $title .= ' of this student';
3061: }
3062: if (defined($target) && $target !~ /^\s*$/) {
3063: $target = qq{target="$target"};
3064: } else {
3065: $target = '';
3066: }
3067: if ($start) { $link.='&start='.$start; }
3068: if ($only_body) { $link .= '&only_body=1'; }
3069: $title = &mt($title);
3070: $linktext = &mt($linktext);
3071: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3072: &help_open_topic('View_recent_activity');
3073: }
3074:
3075: sub slot_reservations_link {
3076: my ($linktext,$sname,$sdom,$target) = @_;
3077: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3078: my $title = 'View slot reservation history';
3079: if (defined($sname) && $sname !~ /^\s*$/ &&
3080: defined($sdom) && $sdom !~ /^\s*$/) {
3081: $link .= "&uname=$sname&udom=$sdom";
3082: $title .= ' of this student';
3083: }
3084: if (defined($target) && $target !~ /^\s*$/) {
3085: $target = qq{target="$target"};
3086: } else {
3087: $target = '';
3088: }
3089: $title = &mt($title);
3090: $linktext = &mt($linktext);
3091: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3092: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3093:
3094: }
3095:
3096: # ===================================================== Display a student photo
3097:
3098:
3099: sub student_image_tag {
3100: my ($domain,$user)=@_;
3101: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3102: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3103: return '<img src="'.$imgsrc.'" align="right" />';
3104: } else {
3105: return '';
3106: }
3107: }
3108:
3109: =pod
3110:
3111: =back
3112:
3113: =head1 Access .tab File Data
3114:
3115: =over 4
3116:
3117: =item * &languageids()
3118:
3119: returns list of all language ids
3120:
3121: =cut
3122:
3123: sub languageids {
3124: return sort(keys(%language));
3125: }
3126:
3127: =pod
3128:
3129: =item * &languagedescription()
3130:
3131: returns description of a specified language id
3132:
3133: =cut
3134:
3135: sub languagedescription {
3136: my $code=shift;
3137: return ($supported_language{$code}?'* ':'').
3138: $language{$code}.
3139: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3140: }
3141:
3142: sub plainlanguagedescription {
3143: my $code=shift;
3144: return $language{$code};
3145: }
3146:
3147: sub supportedlanguagecode {
3148: my $code=shift;
3149: return $supported_language{$code};
3150: }
3151:
3152: =pod
3153:
3154: =item * ©rightids()
3155:
3156: returns list of all copyrights
3157:
3158: =cut
3159:
3160: sub copyrightids {
3161: return sort(keys(%cprtag));
3162: }
3163:
3164: =pod
3165:
3166: =item * ©rightdescription()
3167:
3168: returns description of a specified copyright id
3169:
3170: =cut
3171:
3172: sub copyrightdescription {
3173: return &mt($cprtag{shift(@_)});
3174: }
3175:
3176: =pod
3177:
3178: =item * &source_copyrightids()
3179:
3180: returns list of all source copyrights
3181:
3182: =cut
3183:
3184: sub source_copyrightids {
3185: return sort(keys(%scprtag));
3186: }
3187:
3188: =pod
3189:
3190: =item * &source_copyrightdescription()
3191:
3192: returns description of a specified source copyright id
3193:
3194: =cut
3195:
3196: sub source_copyrightdescription {
3197: return &mt($scprtag{shift(@_)});
3198: }
3199:
3200: =pod
3201:
3202: =item * &filecategories()
3203:
3204: returns list of all file categories
3205:
3206: =cut
3207:
3208: sub filecategories {
3209: return sort(keys(%category_extensions));
3210: }
3211:
3212: =pod
3213:
3214: =item * &filecategorytypes()
3215:
3216: returns list of file types belonging to a given file
3217: category
3218:
3219: =cut
3220:
3221: sub filecategorytypes {
3222: my ($cat) = @_;
3223: return @{$category_extensions{lc($cat)}};
3224: }
3225:
3226: =pod
3227:
3228: =item * &fileembstyle()
3229:
3230: returns embedding style for a specified file type
3231:
3232: =cut
3233:
3234: sub fileembstyle {
3235: return $fe{lc(shift(@_))};
3236: }
3237:
3238: sub filemimetype {
3239: return $fm{lc(shift(@_))};
3240: }
3241:
3242:
3243: sub filecategoryselect {
3244: my ($name,$value)=@_;
3245: return &select_form($value,$name,
3246: '' => &mt('Any category'),
3247: map { $_,$_ } sort(keys(%category_extensions)));
3248: }
3249:
3250: =pod
3251:
3252: =item * &filedescription()
3253:
3254: returns description for a specified file type
3255:
3256: =cut
3257:
3258: sub filedescription {
3259: my $file_description = $fd{lc(shift())};
3260: $file_description =~ s:([\[\]]):~$1:g;
3261: return &mt($file_description);
3262: }
3263:
3264: =pod
3265:
3266: =item * &filedescriptionex()
3267:
3268: returns description for a specified file type with
3269: extra formatting
3270:
3271: =cut
3272:
3273: sub filedescriptionex {
3274: my $ex=shift;
3275: my $file_description = $fd{lc($ex)};
3276: $file_description =~ s:([\[\]]):~$1:g;
3277: return '.'.$ex.' '.&mt($file_description);
3278: }
3279:
3280: # End of .tab access
3281: =pod
3282:
3283: =back
3284:
3285: =cut
3286:
3287: # ------------------------------------------------------------------ File Types
3288: sub fileextensions {
3289: return sort(keys(%fe));
3290: }
3291:
3292: # ----------------------------------------------------------- Display Languages
3293: # returns a hash with all desired display languages
3294: #
3295:
3296: sub display_languages {
3297: my %languages=();
3298: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3299: $languages{$lang}=1;
3300: }
3301: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3302: if ($env{'form.displaylanguage'}) {
3303: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3304: $languages{$lang}=1;
3305: }
3306: }
3307: return %languages;
3308: }
3309:
3310: sub languages {
3311: my ($possible_langs) = @_;
3312: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3313: if (!ref($possible_langs)) {
3314: if( wantarray ) {
3315: return @preferred_langs;
3316: } else {
3317: return $preferred_langs[0];
3318: }
3319: }
3320: my %possibilities = map { $_ => 1 } (@$possible_langs);
3321: my @preferred_possibilities;
3322: foreach my $preferred_lang (@preferred_langs) {
3323: if (exists($possibilities{$preferred_lang})) {
3324: push(@preferred_possibilities, $preferred_lang);
3325: }
3326: }
3327: if( wantarray ) {
3328: return @preferred_possibilities;
3329: }
3330: return $preferred_possibilities[0];
3331: }
3332:
3333: sub user_lang {
3334: my ($touname,$toudom,$fromcid) = @_;
3335: my @userlangs;
3336: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3337: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3338: $env{'course.'.$fromcid.'.languages'}));
3339: } else {
3340: my %langhash = &getlangs($touname,$toudom);
3341: if ($langhash{'languages'} ne '') {
3342: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3343: } else {
3344: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3345: if ($domdefs{'lang_def'} ne '') {
3346: @userlangs = ($domdefs{'lang_def'});
3347: }
3348: }
3349: }
3350: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3351: my $user_lh = Apache::localize->get_handle(@languages);
3352: return $user_lh;
3353: }
3354:
3355: ###############################################################
3356: ## Student Answer Attempts ##
3357: ###############################################################
3358:
3359: =pod
3360:
3361: =head1 Alternate Problem Views
3362:
3363: =over 4
3364:
3365: =item * &get_previous_attempt($symb, $username, $domain, $course,
3366: $getattempt, $regexp, $gradesub)
3367:
3368: Return string with previous attempt on problem. Arguments:
3369:
3370: =over 4
3371:
3372: =item * $symb: Problem, including path
3373:
3374: =item * $username: username of the desired student
3375:
3376: =item * $domain: domain of the desired student
3377:
3378: =item * $course: Course ID
3379:
3380: =item * $getattempt: Leave blank for all attempts, otherwise put
3381: something
3382:
3383: =item * $regexp: if string matches this regexp, the string will be
3384: sent to $gradesub
3385:
3386: =item * $gradesub: routine that processes the string if it matches $regexp
3387:
3388: =back
3389:
3390: The output string is a table containing all desired attempts, if any.
3391:
3392: =cut
3393:
3394: sub get_previous_attempt {
3395: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3396: my $prevattempts='';
3397: no strict 'refs';
3398: if ($symb) {
3399: my (%returnhash)=
3400: &Apache::lonnet::restore($symb,$course,$domain,$username);
3401: if ($returnhash{'version'}) {
3402: my %lasthash=();
3403: my $version;
3404: for ($version=1;$version<=$returnhash{'version'};$version++) {
3405: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3406: $lasthash{$key}=$returnhash{$version.':'.$key};
3407: }
3408: }
3409: $prevattempts=&start_data_table().&start_data_table_header_row();
3410: $prevattempts.='<th>'.&mt('History').'</th>';
3411: foreach my $key (sort(keys(%lasthash))) {
3412: my ($ign,@parts) = split(/\./,$key);
3413: if ($#parts > 0) {
3414: my $data=$parts[-1];
3415: pop(@parts);
3416: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3417: } else {
3418: if ($#parts == 0) {
3419: $prevattempts.='<th>'.$parts[0].'</th>';
3420: } else {
3421: $prevattempts.='<th>'.$ign.'</th>';
3422: }
3423: }
3424: }
3425: $prevattempts.=&end_data_table_header_row();
3426: if ($getattempt eq '') {
3427: for ($version=1;$version<=$returnhash{'version'};$version++) {
3428: $prevattempts.=&start_data_table_row().
3429: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3430: foreach my $key (sort(keys(%lasthash))) {
3431: my $value = &format_previous_attempt_value($key,
3432: $returnhash{$version.':'.$key});
3433: $prevattempts.='<td>'.$value.' </td>';
3434: }
3435: $prevattempts.=&end_data_table_row();
3436: }
3437: }
3438: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3439: foreach my $key (sort(keys(%lasthash))) {
3440: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3441: if ($key =~/$regexp$/ && (defined &$gradesub)) {$value = &$gradesub($value)}
3442: $prevattempts.='<td>'.$value.' </td>';
3443: }
3444: $prevattempts.= &end_data_table_row().&end_data_table();
3445: } else {
3446: $prevattempts=
3447: &start_data_table().&start_data_table_row().
3448: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3449: &end_data_table_row().&end_data_table();
3450: }
3451: } else {
3452: $prevattempts=
3453: &start_data_table().&start_data_table_row().
3454: '<td>'.&mt('No data.').'</td>'.
3455: &end_data_table_row().&end_data_table();
3456: }
3457: }
3458:
3459: sub format_previous_attempt_value {
3460: my ($key,$value) = @_;
3461: if ($key =~ /timestamp/) {
3462: $value = &Apache::lonlocal::locallocaltime($value);
3463: } elsif (ref($value) eq 'ARRAY') {
3464: $value = '('.join(', ', @{ $value }).')';
3465: } else {
3466: $value = &unescape($value);
3467: }
3468: return $value;
3469: }
3470:
3471:
3472: sub relative_to_absolute {
3473: my ($url,$output)=@_;
3474: my $parser=HTML::TokeParser->new(\$output);
3475: my $token;
3476: my $thisdir=$url;
3477: my @rlinks=();
3478: while ($token=$parser->get_token) {
3479: if ($token->[0] eq 'S') {
3480: if ($token->[1] eq 'a') {
3481: if ($token->[2]->{'href'}) {
3482: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3483: }
3484: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3485: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3486: } elsif ($token->[1] eq 'base') {
3487: $thisdir=$token->[2]->{'href'};
3488: }
3489: }
3490: }
3491: $thisdir=~s-/[^/]*$--;
3492: foreach my $link (@rlinks) {
3493: unless (($link=~/^https?\:\/\//i) ||
3494: ($link=~/^\//) ||
3495: ($link=~/^javascript:/i) ||
3496: ($link=~/^mailto:/i) ||
3497: ($link=~/^\#/)) {
3498: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3499: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3500: }
3501: }
3502: # -------------------------------------------------- Deal with Applet codebases
3503: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3504: return $output;
3505: }
3506:
3507: =pod
3508:
3509: =item * &get_student_view()
3510:
3511: show a snapshot of what student was looking at
3512:
3513: =cut
3514:
3515: sub get_student_view {
3516: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3517: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3518: my (%form);
3519: my @elements=('symb','courseid','domain','username');
3520: foreach my $element (@elements) {
3521: $form{'grade_'.$element}=eval '$'.$element #'
3522: }
3523: if (defined($moreenv)) {
3524: %form=(%form,%{$moreenv});
3525: }
3526: if (defined($target)) { $form{'grade_target'} = $target; }
3527: $feedurl=&Apache::lonnet::clutter($feedurl);
3528: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3529: $userview=~s/\<body[^\>]*\>//gi;
3530: $userview=~s/\<\/body\>//gi;
3531: $userview=~s/\<html\>//gi;
3532: $userview=~s/\<\/html\>//gi;
3533: $userview=~s/\<head\>//gi;
3534: $userview=~s/\<\/head\>//gi;
3535: $userview=~s/action\s*\=/would_be_action\=/gi;
3536: $userview=&relative_to_absolute($feedurl,$userview);
3537: if (wantarray) {
3538: return ($userview,$response);
3539: } else {
3540: return $userview;
3541: }
3542: }
3543:
3544: sub get_student_view_with_retries {
3545: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
3546:
3547: my $ok = 0; # True if we got a good response.
3548: my $content;
3549: my $response;
3550:
3551: # Try to get the student_view done. within the retries count:
3552:
3553: do {
3554: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
3555: $ok = $response->is_success;
3556: if (!$ok) {
3557: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
3558: }
3559: $retries--;
3560: } while (!$ok && ($retries > 0));
3561:
3562: if (!$ok) {
3563: $content = ''; # On error return an empty content.
3564: }
3565: if (wantarray) {
3566: return ($content, $response);
3567: } else {
3568: return $content;
3569: }
3570: }
3571:
3572: =pod
3573:
3574: =item * &get_student_answers()
3575:
3576: show a snapshot of how student was answering problem
3577:
3578: =cut
3579:
3580: sub get_student_answers {
3581: my ($symb,$username,$domain,$courseid,%form) = @_;
3582: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3583: my (%moreenv);
3584: my @elements=('symb','courseid','domain','username');
3585: foreach my $element (@elements) {
3586: $moreenv{'grade_'.$element}=eval '$'.$element #'
3587: }
3588: $moreenv{'grade_target'}='answer';
3589: %moreenv=(%form,%moreenv);
3590: $feedurl = &Apache::lonnet::clutter($feedurl);
3591: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
3592: return $userview;
3593: }
3594:
3595: =pod
3596:
3597: =item * &submlink()
3598:
3599: Inputs: $text $uname $udom $symb $target
3600:
3601: Returns: A link to grades.pm such as to see the SUBM view of a student
3602:
3603: =cut
3604:
3605: ###############################################
3606: sub submlink {
3607: my ($text,$uname,$udom,$symb,$target)=@_;
3608: if (!($uname && $udom)) {
3609: (my $cursymb, my $courseid,$udom,$uname)=
3610: &Apache::lonnet::whichuser($symb);
3611: if (!$symb) { $symb=$cursymb; }
3612: }
3613: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3614: $symb=&escape($symb);
3615: if ($target) { $target="target=\"$target\""; }
3616: return '<a href="/adm/grades?&command=submission&'.
3617: 'symb='.$symb.'&student='.$uname.
3618: '&userdom='.$udom.'" '.$target.'>'.$text.'</a>';
3619: }
3620: ##############################################
3621:
3622: =pod
3623:
3624: =item * &pgrdlink()
3625:
3626: Inputs: $text $uname $udom $symb $target
3627:
3628: Returns: A link to grades.pm such as to see the PGRD view of a student
3629:
3630: =cut
3631:
3632: ###############################################
3633: sub pgrdlink {
3634: my $link=&submlink(@_);
3635: $link=~s/(&command=submission)/$1&showgrading=yes/;
3636: return $link;
3637: }
3638: ##############################################
3639:
3640: =pod
3641:
3642: =item * &pprmlink()
3643:
3644: Inputs: $text $uname $udom $symb $target
3645:
3646: Returns: A link to parmset.pm such as to see the PPRM view of a
3647: student and a specific resource
3648:
3649: =cut
3650:
3651: ###############################################
3652: sub pprmlink {
3653: my ($text,$uname,$udom,$symb,$target)=@_;
3654: if (!($uname && $udom)) {
3655: (my $cursymb, my $courseid,$udom,$uname)=
3656: &Apache::lonnet::whichuser($symb);
3657: if (!$symb) { $symb=$cursymb; }
3658: }
3659: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
3660: $symb=&escape($symb);
3661: if ($target) { $target="target=\"$target\""; }
3662: return '<a href="/adm/parmset?command=set&'.
3663: 'symb='.$symb.'&uname='.$uname.
3664: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
3665: }
3666: ##############################################
3667:
3668: =pod
3669:
3670: =back
3671:
3672: =cut
3673:
3674: ###############################################
3675:
3676:
3677: sub timehash {
3678: my ($thistime) = @_;
3679: my $timezone = &Apache::lonlocal::gettimezone();
3680: my $dt = DateTime->from_epoch(epoch => $thistime)
3681: ->set_time_zone($timezone);
3682: my $wday = $dt->day_of_week();
3683: if ($wday == 7) { $wday = 0; }
3684: return ( 'second' => $dt->second(),
3685: 'minute' => $dt->minute(),
3686: 'hour' => $dt->hour(),
3687: 'day' => $dt->day_of_month(),
3688: 'month' => $dt->month(),
3689: 'year' => $dt->year(),
3690: 'weekday' => $wday,
3691: 'dayyear' => $dt->day_of_year(),
3692: 'dlsav' => $dt->is_dst() );
3693: }
3694:
3695: sub utc_string {
3696: my ($date)=@_;
3697: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
3698: }
3699:
3700: sub maketime {
3701: my %th=@_;
3702: my ($epoch_time,$timezone,$dt);
3703: $timezone = &Apache::lonlocal::gettimezone();
3704: eval {
3705: $dt = DateTime->new( year => $th{'year'},
3706: month => $th{'month'},
3707: day => $th{'day'},
3708: hour => $th{'hour'},
3709: minute => $th{'minute'},
3710: second => $th{'second'},
3711: time_zone => $timezone,
3712: );
3713: };
3714: if (!$@) {
3715: $epoch_time = $dt->epoch;
3716: if ($epoch_time) {
3717: return $epoch_time;
3718: }
3719: }
3720: return POSIX::mktime(
3721: ($th{'seconds'},$th{'minutes'},$th{'hours'},
3722: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
3723: }
3724:
3725: #########################################
3726:
3727: sub findallcourses {
3728: my ($roles,$uname,$udom) = @_;
3729: my %roles;
3730: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
3731: my %courses;
3732: my $now=time;
3733: if (!defined($uname)) {
3734: $uname = $env{'user.name'};
3735: }
3736: if (!defined($udom)) {
3737: $udom = $env{'user.domain'};
3738: }
3739: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
3740: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
3741: if (!%roles) {
3742: %roles = (
3743: cc => 1,
3744: co => 1,
3745: in => 1,
3746: ep => 1,
3747: ta => 1,
3748: cr => 1,
3749: st => 1,
3750: );
3751: }
3752: foreach my $entry (keys(%roleshash)) {
3753: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
3754: if ($trole =~ /^cr/) {
3755: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
3756: } else {
3757: next if (!exists($roles{$trole}));
3758: }
3759: if ($tend) {
3760: next if ($tend < $now);
3761: }
3762: if ($tstart) {
3763: next if ($tstart > $now);
3764: }
3765: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role,$realsec);
3766: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
3767: if ($secpart eq '') {
3768: ($cnum,$role) = split(/_/,$cnumpart);
3769: $sec = 'none';
3770: $realsec = '';
3771: } else {
3772: $cnum = $cnumpart;
3773: ($sec,$role) = split(/_/,$secpart);
3774: $realsec = $sec;
3775: }
3776: $courses{$cdom.'_'.$cnum}{$sec} = $trole.'/'.$cdom.'/'.$cnum.'/'.$realsec;
3777: }
3778: } else {
3779: foreach my $key (keys(%env)) {
3780: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
3781: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
3782: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
3783: next if ($role eq 'ca' || $role eq 'aa');
3784: next if (%roles && !exists($roles{$role}));
3785: my ($starttime,$endtime)=split(/\./,$env{$key});
3786: my $active=1;
3787: if ($starttime) {
3788: if ($now<$starttime) { $active=0; }
3789: }
3790: if ($endtime) {
3791: if ($now>$endtime) { $active=0; }
3792: }
3793: if ($active) {
3794: if ($sec eq '') {
3795: $sec = 'none';
3796: }
3797: $courses{$cdom.'_'.$cnum}{$sec} =
3798: $role.'/'.$cdom.'/'.$cnum.'/'.$sec;
3799: }
3800: }
3801: }
3802: }
3803: return %courses;
3804: }
3805:
3806: ###############################################
3807:
3808: sub blockcheck {
3809: my ($setters,$activity,$uname,$udom) = @_;
3810:
3811: if (!defined($udom)) {
3812: $udom = $env{'user.domain'};
3813: }
3814: if (!defined($uname)) {
3815: $uname = $env{'user.name'};
3816: }
3817:
3818: # If uname and udom are for a course, check for blocks in the course.
3819:
3820: if (&Apache::lonnet::is_course($udom,$uname)) {
3821: my %records = &Apache::lonnet::dump('comm_block',$udom,$uname);
3822: my ($startblock,$endblock)=&get_blocks($setters,$activity,$udom,$uname);
3823: return ($startblock,$endblock);
3824: }
3825:
3826: my $startblock = 0;
3827: my $endblock = 0;
3828: my %live_courses = &findallcourses(undef,$uname,$udom);
3829:
3830: # If uname is for a user, and activity is course-specific, i.e.,
3831: # boards, chat or groups, check for blocking in current course only.
3832:
3833: if (($activity eq 'boards' || $activity eq 'chat' ||
3834: $activity eq 'groups') && ($env{'request.course.id'})) {
3835: foreach my $key (keys(%live_courses)) {
3836: if ($key ne $env{'request.course.id'}) {
3837: delete($live_courses{$key});
3838: }
3839: }
3840: }
3841:
3842: my $otheruser = 0;
3843: my %own_courses;
3844: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
3845: # Resource belongs to user other than current user.
3846: $otheruser = 1;
3847: # Gather courses for current user
3848: %own_courses =
3849: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
3850: }
3851:
3852: # Gather active course roles - course coordinator, instructor,
3853: # exam proctor, ta, student, or custom role.
3854:
3855: foreach my $course (keys(%live_courses)) {
3856: my ($cdom,$cnum);
3857: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
3858: $cdom = $env{'course.'.$course.'.domain'};
3859: $cnum = $env{'course.'.$course.'.num'};
3860: } else {
3861: ($cdom,$cnum) = split(/_/,$course);
3862: }
3863: my $no_ownblock = 0;
3864: my $no_userblock = 0;
3865: if ($otheruser && $activity ne 'com') {
3866: # Check if current user has 'evb' priv for this
3867: if (defined($own_courses{$course})) {
3868: foreach my $sec (keys(%{$own_courses{$course}})) {
3869: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3870: if ($sec ne 'none') {
3871: $checkrole .= '/'.$sec;
3872: }
3873: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3874: $no_ownblock = 1;
3875: last;
3876: }
3877: }
3878: }
3879: # if they have 'evb' priv and are currently not playing student
3880: next if (($no_ownblock) &&
3881: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
3882: }
3883: foreach my $sec (keys(%{$live_courses{$course}})) {
3884: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
3885: if ($sec ne 'none') {
3886: $checkrole .= '/'.$sec;
3887: }
3888: if ($otheruser) {
3889: # Resource belongs to user other than current user.
3890: # Assemble privs for that user, and check for 'evb' priv.
3891: my ($trole,$tdom,$tnum,$tsec);
3892: my $entry = $live_courses{$course}{$sec};
3893: if ($entry =~ /^cr/) {
3894: ($trole,$tdom,$tnum,$tsec) =
3895: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
3896: } else {
3897: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
3898: }
3899: my ($spec,$area,$trest,%allroles,%userroles);
3900: $area = '/'.$tdom.'/'.$tnum;
3901: $trest = $tnum;
3902: if ($tsec ne '') {
3903: $area .= '/'.$tsec;
3904: $trest .= '/'.$tsec;
3905: }
3906: $spec = $trole.'.'.$area;
3907: if ($trole =~ /^cr/) {
3908: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
3909: $tdom,$spec,$trest,$area);
3910: } else {
3911: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
3912: $tdom,$spec,$trest,$area);
3913: }
3914: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
3915: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
3916: if ($1) {
3917: $no_userblock = 1;
3918: last;
3919: }
3920: }
3921: } else {
3922: # Resource belongs to current user
3923: # Check for 'evb' priv via lonnet::allowed().
3924: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
3925: $no_ownblock = 1;
3926: last;
3927: }
3928: }
3929: }
3930: # if they have the evb priv and are currently not playing student
3931: next if (($no_ownblock) &&
3932: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
3933: next if ($no_userblock);
3934:
3935: # Retrieve blocking times and identity of blocker for course
3936: # of specified user, unless user has 'evb' privilege.
3937:
3938: my ($start,$end)=&get_blocks($setters,$activity,$cdom,$cnum);
3939: if (($start != 0) &&
3940: (($startblock == 0) || ($startblock > $start))) {
3941: $startblock = $start;
3942: }
3943: if (($end != 0) &&
3944: (($endblock == 0) || ($endblock < $end))) {
3945: $endblock = $end;
3946: }
3947: }
3948: return ($startblock,$endblock);
3949: }
3950:
3951: sub get_blocks {
3952: my ($setters,$activity,$cdom,$cnum) = @_;
3953: my $startblock = 0;
3954: my $endblock = 0;
3955: my $course = $cdom.'_'.$cnum;
3956: $setters->{$course} = {};
3957: $setters->{$course}{'staff'} = [];
3958: $setters->{$course}{'times'} = [];
3959: my %records = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
3960: foreach my $record (keys(%records)) {
3961: my ($start,$end) = ($record =~ m/^(\d+)____(\d+)$/);
3962: if ($start <= time && $end >= time) {
3963: my ($staff_name,$staff_dom,$title,$blocks) =
3964: &parse_block_record($records{$record});
3965: if ($blocks->{$activity} eq 'on') {
3966: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
3967: push(@{$$setters{$course}{'times'}}, [$start,$end]);
3968: if ( ($startblock == 0) || ($startblock > $start) ) {
3969: $startblock = $start;
3970: }
3971: if ( ($endblock == 0) || ($endblock < $end) ) {
3972: $endblock = $end;
3973: }
3974: }
3975: }
3976: }
3977: return ($startblock,$endblock);
3978: }
3979:
3980: sub parse_block_record {
3981: my ($record) = @_;
3982: my ($setuname,$setudom,$title,$blocks);
3983: if (ref($record) eq 'HASH') {
3984: ($setuname,$setudom) = split(/:/,$record->{'setter'});
3985: $title = &unescape($record->{'event'});
3986: $blocks = $record->{'blocks'};
3987: } else {
3988: my @data = split(/:/,$record,3);
3989: if (scalar(@data) eq 2) {
3990: $title = $data[1];
3991: ($setuname,$setudom) = split(/@/,$data[0]);
3992: } else {
3993: ($setuname,$setudom,$title) = @data;
3994: }
3995: $blocks = { 'com' => 'on' };
3996: }
3997: return ($setuname,$setudom,$title,$blocks);
3998: }
3999:
4000: sub build_block_table {
4001: my ($startblock,$endblock,$setters) = @_;
4002: my %lt = &Apache::lonlocal::texthash(
4003: 'cacb' => 'Currently active communication blocks',
4004: 'cour' => 'Course',
4005: 'dura' => 'Duration',
4006: 'blse' => 'Block set by'
4007: );
4008: my $output;
4009: $output = '<br />'.$lt{'cacb'}.':<br />';
4010: $output .= &start_data_table();
4011: $output .= '
4012: <tr>
4013: <th>'.$lt{'cour'}.'</th>
4014: <th>'.$lt{'dura'}.'</th>
4015: <th>'.$lt{'blse'}.'</th>
4016: </tr>
4017: ';
4018: foreach my $course (keys(%{$setters})) {
4019: my %courseinfo=&Apache::lonnet::coursedescription($course);
4020: for (my $i=0; $i<@{$$setters{$course}{staff}}; $i++) {
4021: my ($uname,$udom) = @{$$setters{$course}{staff}[$i]};
4022: my $fullname = &plainname($uname,$udom);
4023: if (defined($env{'user.name'}) && defined($env{'user.domain'})
4024: && $env{'user.name'} ne 'public'
4025: && $env{'user.domain'} ne 'public') {
4026: $fullname = &aboutmewrapper($fullname,$uname,$udom);
4027: }
4028: my ($openblock,$closeblock) = @{$$setters{$course}{times}[$i]};
4029: $openblock = &Apache::lonlocal::locallocaltime($openblock);
4030: $closeblock= &Apache::lonlocal::locallocaltime($closeblock);
4031: $output .= &Apache::loncommon::start_data_table_row().
4032: '<td>'.$courseinfo{'description'}.'</td>'.
4033: '<td>'.$openblock.' to '.$closeblock.'</td>'.
4034: '<td>'.$fullname.'</td>'.
4035: &Apache::loncommon::end_data_table_row();
4036: }
4037: }
4038: $output .= &end_data_table();
4039: }
4040:
4041: sub blocking_status {
4042: my ($activity,$uname,$udom) = @_;
4043: my %setters;
4044: my ($blocked,$output,$ownitem,$is_course);
4045: my ($startblock,$endblock)=&blockcheck(\%setters,$activity,$uname,$udom);
4046: if ($startblock && $endblock) {
4047: $blocked = 1;
4048: if (wantarray) {
4049: my $category;
4050: if ($activity eq 'boards') {
4051: $category = 'Discussion posts in this course';
4052: } elsif ($activity eq 'blogs') {
4053: $category = 'Blogs';
4054: } elsif ($activity eq 'port') {
4055: if (defined($uname) && defined($udom)) {
4056: if ($uname eq $env{'user.name'} &&
4057: $udom eq $env{'user.domain'}) {
4058: $ownitem = 1;
4059: }
4060: }
4061: $is_course = &Apache::lonnet::is_course($udom,$uname);
4062: if ($ownitem) {
4063: $category = 'Your portfolio files';
4064: } elsif ($is_course) {
4065: my $coursedesc;
4066: foreach my $course (keys(%setters)) {
4067: my %courseinfo =
4068: &Apache::lonnet::coursedescription($course);
4069: $coursedesc = $courseinfo{'description'};
4070: }
4071: $category = "Group portfolio files in the course '$coursedesc'";
4072: } else {
4073: $category = 'Portfolio files belonging to ';
4074: if ($env{'user.name'} eq 'public' &&
4075: $env{'user.domain'} eq 'public') {
4076: $category .= &plainname($uname,$udom);
4077: } else {
4078: $category .= &aboutmewrapper(&plainname($uname,$udom),$uname,$udom);
4079: }
4080: }
4081: } elsif ($activity eq 'groups') {
4082: $category = 'Groups in this course';
4083: }
4084: my $showstart = &Apache::lonlocal::locallocaltime($startblock);
4085: my $showend = &Apache::lonlocal::locallocaltime($endblock);
4086: $output = '<br />'.&mt('[_1] will be inaccessible between [_2] and [_3] because communication is being blocked.',$category,$showstart,$showend).'<br />';
4087: if (!($activity eq 'port' && !($ownitem) && !($is_course))) {
4088: $output .= &build_block_table($startblock,$endblock,\%setters);
4089: }
4090: }
4091: }
4092: if (wantarray) {
4093: return ($blocked,$output);
4094: } else {
4095: return $blocked;
4096: }
4097: }
4098:
4099: ###############################################
4100:
4101: sub check_ip_acc {
4102: my ($acc)=@_;
4103: &Apache::lonxml::debug("acc is $acc");
4104: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4105: return 1;
4106: }
4107: my $allowed=0;
4108: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4109:
4110: my $name;
4111: foreach my $pattern (split(',',$acc)) {
4112: $pattern =~ s/^\s*//;
4113: $pattern =~ s/\s*$//;
4114: if ($pattern =~ /\*$/) {
4115: #35.8.*
4116: $pattern=~s/\*//;
4117: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4118: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4119: #35.8.3.[34-56]
4120: my $low=$2;
4121: my $high=$3;
4122: $pattern=$1;
4123: if ($ip =~ /^\Q$pattern\E/) {
4124: my $last=(split(/\./,$ip))[3];
4125: if ($last <=$high && $last >=$low) { $allowed=1; }
4126: }
4127: } elsif ($pattern =~ /^\*/) {
4128: #*.msu.edu
4129: $pattern=~s/\*//;
4130: if (!defined($name)) {
4131: use Socket;
4132: my $netaddr=inet_aton($ip);
4133: ($name)=gethostbyaddr($netaddr,AF_INET);
4134: }
4135: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4136: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4137: #127.0.0.1
4138: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4139: } else {
4140: #some.name.com
4141: if (!defined($name)) {
4142: use Socket;
4143: my $netaddr=inet_aton($ip);
4144: ($name)=gethostbyaddr($netaddr,AF_INET);
4145: }
4146: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4147: }
4148: if ($allowed) { last; }
4149: }
4150: return $allowed;
4151: }
4152:
4153: ###############################################
4154:
4155: =pod
4156:
4157: =head1 Domain Template Functions
4158:
4159: =over 4
4160:
4161: =item * &determinedomain()
4162:
4163: Inputs: $domain (usually will be undef)
4164:
4165: Returns: Determines which domain should be used for designs
4166:
4167: =cut
4168:
4169: ###############################################
4170: sub determinedomain {
4171: my $domain=shift;
4172: if (! $domain) {
4173: # Determine domain if we have not been given one
4174: $domain = &Apache::lonnet::default_login_domain();
4175: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4176: if ($env{'request.role.domain'}) {
4177: $domain=$env{'request.role.domain'};
4178: }
4179: }
4180: return $domain;
4181: }
4182: ###############################################
4183:
4184: sub devalidate_domconfig_cache {
4185: my ($udom)=@_;
4186: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4187: }
4188:
4189: # ---------------------- Get domain configuration for a domain
4190: sub get_domainconf {
4191: my ($udom) = @_;
4192: my $cachetime=1800;
4193: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4194: if (defined($cached)) { return %{$result}; }
4195:
4196: my %domconfig = &Apache::lonnet::get_dom('configuration',
4197: ['login','rolecolors'],$udom);
4198: my (%designhash,%legacy);
4199: if (keys(%domconfig) > 0) {
4200: if (ref($domconfig{'login'}) eq 'HASH') {
4201: if (keys(%{$domconfig{'login'}})) {
4202: foreach my $key (keys(%{$domconfig{'login'}})) {
4203: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4204: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4205: $designhash{$udom.'.login.'.$key.'_'.$img} =
4206: $domconfig{'login'}{$key}{$img};
4207: }
4208: } else {
4209: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4210: }
4211: }
4212: } else {
4213: $legacy{'login'} = 1;
4214: }
4215: } else {
4216: $legacy{'login'} = 1;
4217: }
4218: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4219: if (keys(%{$domconfig{'rolecolors'}})) {
4220: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4221: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4222: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4223: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4224: }
4225: }
4226: }
4227: } else {
4228: $legacy{'rolecolors'} = 1;
4229: }
4230: } else {
4231: $legacy{'rolecolors'} = 1;
4232: }
4233: if (keys(%legacy) > 0) {
4234: my %legacyhash = &get_legacy_domconf($udom);
4235: foreach my $item (keys(%legacyhash)) {
4236: if ($item =~ /^\Q$udom\E\.login/) {
4237: if ($legacy{'login'}) {
4238: $designhash{$item} = $legacyhash{$item};
4239: }
4240: } else {
4241: if ($legacy{'rolecolors'}) {
4242: $designhash{$item} = $legacyhash{$item};
4243: }
4244: }
4245: }
4246: }
4247: } else {
4248: %designhash = &get_legacy_domconf($udom);
4249: }
4250: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4251: $cachetime);
4252: return %designhash;
4253: }
4254:
4255: sub get_legacy_domconf {
4256: my ($udom) = @_;
4257: my %legacyhash;
4258: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4259: my $designfile = $designdir.'/'.$udom.'.tab';
4260: if (-e $designfile) {
4261: if ( open (my $fh,"<$designfile") ) {
4262: while (my $line = <$fh>) {
4263: next if ($line =~ /^\#/);
4264: chomp($line);
4265: my ($key,$val)=(split(/\=/,$line));
4266: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4267: }
4268: close($fh);
4269: }
4270: }
4271: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
4272: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4273: }
4274: return %legacyhash;
4275: }
4276:
4277: =pod
4278:
4279: =item * &domainlogo()
4280:
4281: Inputs: $domain (usually will be undef)
4282:
4283: Returns: A link to a domain logo, if the domain logo exists.
4284: If the domain logo does not exist, a description of the domain.
4285:
4286: =cut
4287:
4288: ###############################################
4289: sub domainlogo {
4290: my $domain = &determinedomain(shift);
4291: my %designhash = &get_domainconf($domain);
4292: # See if there is a logo
4293: if ($designhash{$domain.'.login.domlogo'} ne '') {
4294: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4295: if ($imgsrc =~ m{^/(adm|res)/}) {
4296: if ($imgsrc =~ m{^/res/}) {
4297: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4298: &Apache::lonnet::repcopy($local_name);
4299: }
4300: $imgsrc = &lonhttpdurl($imgsrc);
4301: }
4302: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4303: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4304: return &Apache::lonnet::domain($domain,'description');
4305: } else {
4306: return '';
4307: }
4308: }
4309: ##############################################
4310:
4311: =pod
4312:
4313: =item * &designparm()
4314:
4315: Inputs: $which parameter; $domain (usually will be undef)
4316:
4317: Returns: value of designparamter $which
4318:
4319: =cut
4320:
4321:
4322: ##############################################
4323: sub designparm {
4324: my ($which,$domain)=@_;
4325: if ($env{'browser.blackwhite'} eq 'on') {
4326: if ($which=~/\.(font|alink|vlink|link|textcol)$/) {
4327: return '#000000';
4328: }
4329: if ($which=~/\.(pgbg|sidebg|bgcol)$/) {
4330: return '#FFFFFF';
4331: }
4332: if ($which=~/\.tabbg$/) {
4333: return '#CCCCCC';
4334: }
4335: }
4336: if (exists($env{'environment.color.'.$which})) {
4337: return $env{'environment.color.'.$which};
4338: }
4339: $domain=&determinedomain($domain);
4340: my %domdesign = &get_domainconf($domain);
4341: my $output;
4342: if ($domdesign{$domain.'.'.$which} ne '') {
4343: $output = $domdesign{$domain.'.'.$which};
4344: } else {
4345: $output = $defaultdesign{$which};
4346: }
4347: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4348: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4349: if ($output =~ m{^/(adm|res)/}) {
4350: if ($output =~ m{^/res/}) {
4351: my $local_name = &Apache::lonnet::filelocation('',$output);
4352: &Apache::lonnet::repcopy($local_name);
4353: }
4354: $output = &lonhttpdurl($output);
4355: }
4356: }
4357: return $output;
4358: }
4359:
4360: ###############################################
4361: ###############################################
4362:
4363: =pod
4364:
4365: =back
4366:
4367: =head1 HTML Helpers
4368:
4369: =over 4
4370:
4371: =item * &bodytag()
4372:
4373: Returns a uniform header for LON-CAPA web pages.
4374:
4375: Inputs:
4376:
4377: =over 4
4378:
4379: =item * $title, A title to be displayed on the page.
4380:
4381: =item * $function, the current role (can be undef).
4382:
4383: =item * $addentries, extra parameters for the <body> tag.
4384:
4385: =item * $bodyonly, if defined, only return the <body> tag.
4386:
4387: =item * $domain, if defined, force a given domain.
4388:
4389: =item * $forcereg, if page should register as content page (relevant for
4390: text interface only)
4391:
4392: =item * $customtitle, alternate text to use instead of $title
4393: in the title box that appears, this text
4394: is not auto translated like the $title is
4395:
4396: =item * $notopbar, if true, keep the 'what is this' info but remove the
4397: navigational links
4398:
4399: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
4400:
4401: =item * $notitle, if true keep the nav controls, but remove the title bar
4402:
4403: =item * $no_inline_link, if true and in remote mode, don't show the
4404: 'Switch To Inline Menu' link
4405:
4406: =item * $args, optional argument valid values are
4407: no_auto_mt_title -> prevents &mt()ing the title arg
4408: inherit_jsmath -> when creating popup window in a page,
4409: should it have jsmath forced on by the
4410: current page
4411:
4412: =back
4413:
4414: Returns: A uniform header for LON-CAPA web pages.
4415: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
4416: If $bodyonly is undef or zero, an html string containing a <body> tag and
4417: other decorations will be returned.
4418:
4419: =cut
4420:
4421: sub bodytag {
4422: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,$customtitle,
4423: $notopbar,$bgcolor,$notitle,$no_inline_link,$args)=@_;
4424:
4425: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
4426:
4427: $function = &get_users_function() if (!$function);
4428: my $img = &designparm($function.'.img',$domain);
4429: my $font = &designparm($function.'.font',$domain);
4430: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
4431:
4432: my %design = ( 'style' => 'margin-top: 0',
4433: 'bgcolor' => $pgbg,
4434: 'text' => $font,
4435: 'alink' => &designparm($function.'.alink',$domain),
4436: 'vlink' => &designparm($function.'.vlink',$domain),
4437: 'link' => &designparm($function.'.link',$domain),);
4438: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
4439:
4440: # role and realm
4441: my ($role,$realm) = split(/\./,$env{'request.role'},2);
4442: if ($role eq 'ca') {
4443: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
4444: $realm = &plainname($rname,$rdom);
4445: }
4446: # realm
4447: if ($env{'request.course.id'}) {
4448: if ($env{'request.role'} !~ /^cr/) {
4449: $role = &Apache::lonnet::plaintext($role,&course_type());
4450: }
4451: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
4452: } else {
4453: $role = &Apache::lonnet::plaintext($role);
4454: }
4455:
4456: if (!$realm) { $realm=' '; }
4457: # Set messages
4458: my $messages=&domainlogo($domain);
4459:
4460: my $extra_body_attr = &make_attr_string($forcereg,\%design);
4461:
4462: # construct main body tag
4463: my $bodytag = "<body $extra_body_attr>".
4464: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
4465:
4466: if ($bodyonly) {
4467: return $bodytag;
4468: } elsif ($env{'browser.interface'} eq 'textual') {
4469: # Accessibility
4470:
4471: $bodytag.=&Apache::lonmenu::menubuttons($forcereg,$forcereg);
4472: if (!$notitle) {
4473: $bodytag.='<h1>LON-CAPA: '.$title.'</h1>';
4474: }
4475: return $bodytag;
4476: }
4477:
4478: my $name = &plainname($env{'user.name'},$env{'user.domain'});
4479: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4480: undef($role);
4481: } else {
4482: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'});
4483: }
4484:
4485: my $roleinfo=(<<ENDROLE);
4486: <td class="LC_title_bar_who">
4487: <div class="LC_title_bar_name">
4488: $name
4489:
4490: </div>
4491: <div class="LC_title_bar_role">
4492: $role
4493: </div>
4494: <div class="LC_title_bar_realm">
4495: $realm
4496: </div>
4497: </td>
4498: ENDROLE
4499:
4500: my $titleinfo = '<span class="LC_title_bar_title">'.$title.'</span>';
4501: if ($customtitle) {
4502: $titleinfo = $customtitle;
4503: }
4504: #
4505: # Extra info if you are the DC
4506: my $dc_info = '';
4507: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
4508: $env{'course.'.$env{'request.course.id'}.
4509: '.domain'}.'/'})) {
4510: my $cid = $env{'request.course.id'};
4511: $dc_info.= $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
4512: $dc_info =~ s/\s+$//;
4513: $dc_info = '('.$dc_info.')';
4514: }
4515:
4516: if (($env{'environment.remote'} eq 'off') || ($args->{'suppress_header_logos'})) {
4517: # No Remote
4518: if ($env{'request.state'} eq 'construct') {
4519: $forcereg=1;
4520: }
4521:
4522: if (!$customtitle && $env{'request.state'} eq 'construct') {
4523: # this is for resources; directories have customtitle, and crumbs
4524: # and select recent are created in lonpubdir.pm
4525: my ($uname,$thisdisfn)=
4526: ($env{'request.filename'} =~ m|^/home/([^/]+)/public_html/(.*)|);
4527: my $formaction='/priv/'.$uname.'/'.$thisdisfn;
4528: $formaction=~s/\/+/\//g;
4529:
4530: my $parentpath = '';
4531: my $lastitem = '';
4532: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
4533: $parentpath = $1;
4534: $lastitem = $2;
4535: } else {
4536: $lastitem = $thisdisfn;
4537: }
4538: $titleinfo =
4539: &Apache::loncommon::help_open_menu('','',3,'Authoring')
4540: .'<b>'.&mt('Construction Space').'</b>: '
4541: .'<form name="dirs" method="post" action="'.$formaction
4542: .'" target="_top"><tt><b>'
4543: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv','','+1',1)."<font size=\"+1\">$lastitem</font></b></tt><br />"
4544: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
4545: .'</form>'
4546: .&Apache::lonmenu::constspaceform();
4547: }
4548:
4549: my $titletable;
4550: if (!$notitle) {
4551: $titletable =
4552: '<table id="LC_title_bar">'.
4553: "<tr><td> $titleinfo $dc_info</td>".$roleinfo.
4554: '</tr></table>';
4555: }
4556: if ($notopbar) {
4557: $bodytag .= $titletable;
4558: } else {
4559: if ($env{'request.state'} eq 'construct') {
4560: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg,
4561: $titletable);
4562: } else {
4563: $bodytag .= &Apache::lonmenu::menubuttons($forcereg,$forcereg).
4564: $titletable;
4565: }
4566: }
4567: return $bodytag;
4568: }
4569:
4570: #
4571: # Top frame rendering, Remote is up
4572: #
4573:
4574: my $imgsrc = $img;
4575: if ($img =~ /^\/adm/) {
4576: $imgsrc = &lonhttpdurl($img);
4577: }
4578: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
4579:
4580: # Explicit link to get inline menu
4581: my $menu= ($no_inline_link?''
4582: :'<br /><a href="/adm/remote?action=collapse">'.&mt('Switch to Inline Menu Mode').'</a>');
4583: #
4584: if ($notitle) {
4585: return $bodytag;
4586: }
4587: return(<<ENDBODY);
4588: $bodytag
4589: <table id="LC_title_bar" class="LC_with_remote">
4590: <tr><td class="LC_title_bar_role_logo">$upperleft</td>
4591: <td class="LC_title_bar_domain_logo">$messages </td>
4592: </tr>
4593: <tr><td>$titleinfo $dc_info $menu</td>
4594: $roleinfo
4595: </tr>
4596: </table>
4597: ENDBODY
4598: }
4599:
4600: sub make_attr_string {
4601: my ($register,$attr_ref) = @_;
4602:
4603: if ($attr_ref && !ref($attr_ref)) {
4604: die("addentries Must be a hash ref ".
4605: join(':',caller(1))." ".
4606: join(':',caller(0))." ");
4607: }
4608:
4609: if ($register) {
4610: my ($on_load,$on_unload);
4611: foreach my $key (keys(%{$attr_ref})) {
4612: if (lc($key) eq 'onload') {
4613: $on_load.=$attr_ref->{$key}.';';
4614: delete($attr_ref->{$key});
4615:
4616: } elsif (lc($key) eq 'onunload') {
4617: $on_unload.=$attr_ref->{$key}.';';
4618: delete($attr_ref->{$key});
4619: }
4620: }
4621: $attr_ref->{'onload'} =
4622: &Apache::lonmenu::loadevents(). $on_load;
4623: $attr_ref->{'onunload'}=
4624: &Apache::lonmenu::unloadevents().$on_unload;
4625: }
4626:
4627: # Accessibility font enhance
4628: if ($env{'browser.fontenhance'} eq 'on') {
4629: my $style;
4630: foreach my $key (keys(%{$attr_ref})) {
4631: if (lc($key) eq 'style') {
4632: $style.=$attr_ref->{$key}.';';
4633: delete($attr_ref->{$key});
4634: }
4635: }
4636: $attr_ref->{'style'}=$style.'; font-size: x-large;';
4637: }
4638:
4639: if ($env{'browser.blackwhite'} eq 'on') {
4640: delete($attr_ref->{'font'});
4641: delete($attr_ref->{'link'});
4642: delete($attr_ref->{'alink'});
4643: delete($attr_ref->{'vlink'});
4644: delete($attr_ref->{'bgcolor'});
4645: delete($attr_ref->{'background'});
4646: }
4647:
4648: my $attr_string;
4649: foreach my $attr (keys(%$attr_ref)) {
4650: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
4651: }
4652: return $attr_string;
4653: }
4654:
4655:
4656: ###############################################
4657: ###############################################
4658:
4659: =pod
4660:
4661: =item * &endbodytag()
4662:
4663: Returns a uniform footer for LON-CAPA web pages.
4664:
4665: Inputs: 1 - optional reference to an args hash
4666: If in the hash, key for noredirectlink has a value which evaluates to true,
4667: a 'Continue' link is not displayed if the page contains an
4668: internal redirect in the <head></head> section,
4669: i.e., $env{'internal.head.redirect'} exists
4670:
4671: =cut
4672:
4673: sub endbodytag {
4674: my ($args) = @_;
4675: my $endbodytag='</body>';
4676: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
4677: if ( exists( $env{'internal.head.redirect'} ) ) {
4678: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
4679: $endbodytag=
4680: "<br /><a href=\"$env{'internal.head.redirect'}\">".
4681: &mt('Continue').'</a>'.
4682: $endbodytag;
4683: }
4684: }
4685: return $endbodytag;
4686: }
4687:
4688: =pod
4689:
4690: =item * &standard_css()
4691:
4692: Returns a style sheet
4693:
4694: Inputs: (all optional)
4695: domain -> force to color decorate a page for a specific
4696: domain
4697: function -> force usage of a specific rolish color scheme
4698: bgcolor -> override the default page bgcolor
4699:
4700: =cut
4701:
4702: sub standard_css {
4703: my ($function,$domain,$bgcolor) = @_;
4704: $function = &get_users_function() if (!$function);
4705: my $img = &designparm($function.'.img', $domain);
4706: my $tabbg = &designparm($function.'.tabbg', $domain);
4707: my $font = &designparm($function.'.font', $domain);
4708: my $sidebg = &designparm($function.'.sidebg',$domain);
4709: my $pgbg_or_bgcolor =
4710: $bgcolor ||
4711: &designparm($function.'.pgbg', $domain);
4712: my $pgbg = &designparm($function.'.pgbg', $domain);
4713: my $alink = &designparm($function.'.alink', $domain);
4714: my $vlink = &designparm($function.'.vlink', $domain);
4715: my $link = &designparm($function.'.link', $domain);
4716:
4717: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
4718: my $mono = 'monospace';
4719: my $data_table_head = $tabbg;
4720: my $data_table_light = '#FAFAFA';
4721: my $data_table_dark = '#F0F0F0';
4722: my $data_table_darker = '#CCCCCC';
4723: my $data_table_highlight = '#FFFF00';
4724: my $mail_new = '#FFBB77';
4725: my $mail_new_hover = '#DD9955';
4726: my $mail_read = '#BBBB77';
4727: my $mail_read_hover = '#999944';
4728: my $mail_replied = '#AAAA88';
4729: my $mail_replied_hover = '#888855';
4730: my $mail_other = '#99BBBB';
4731: my $mail_other_hover = '#669999';
4732: my $table_header = '#DDDDDD';
4733: my $feedback_link_bg = '#BBBBBB';
4734: my $lg_border_color = '#C8C8C8';
4735:
4736: my $border = ($env{'browser.type'} eq 'explorer' ||
4737: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
4738: : '0 3px 0 4px';
4739:
4740:
4741: return <<END;
4742: h1, h2, h3, th { font-family: $sans }
4743: a:focus { color: red; background: yellow }
4744:
4745: hr {
4746: clear: both;
4747: color: $tabbg;
4748: background-color: $tabbg;
4749: height: 3px;
4750: border: none;
4751: }
4752:
4753: table.thinborder,
4754:
4755: table.thinborder tr th {
4756: border-style: solid;
4757: border-width: 1px;
4758: background: $tabbg;
4759: }
4760: table.thinborder tr td {
4761: border-style: solid;
4762: border-width: 1px
4763: }
4764:
4765: form, .inline { display: inline; }
4766: .center { text-align: center; }
4767: .LC_filename {font-family: $mono; white-space:pre;}
4768: .LC_error {
4769: color: red;
4770: font-size: larger;
4771: }
4772: .LC_warning,
4773: .LC_diff_removed {
4774: color: red;
4775: }
4776:
4777: .LC_info,
4778: .LC_success,
4779: .LC_diff_added {
4780: color: green;
4781: }
4782:
4783: div.LC_confirm_box {
4784: background-color: #FAFAFA;
4785: border: 1px solid $lg_border_color;
4786: margin-right: 0;
4787: padding: 5px;
4788: }
4789:
4790: div.LC_confirm_box .LC_error img,
4791: div.LC_confirm_box .LC_success img {
4792: vertical-align: middle;
4793: }
4794:
4795: .LC_icon {
4796: border: none;
4797: }
4798: .LC_indexer_icon {
4799: border: 0;
4800: height: 22px;
4801: }
4802: .LC_docs_spacer {
4803: width: 25px;
4804: height: 1px;
4805: border: none;
4806: }
4807:
4808: .LC_internal_info {
4809: color: #999999;
4810: }
4811:
4812: .LC_discussion {
4813: background: $tabbg;
4814: border: 1px solid black;
4815: margin: 2px;
4816: }
4817:
4818: .LC_disc_action_links_bar {
4819: background: $tabbg;
4820: border: none;
4821: margin: 4px;
4822: }
4823:
4824: .LC_disc_action_left {
4825: text-align: left;
4826: }
4827:
4828: .LC_disc_action_right {
4829: text-align: right;
4830: }
4831:
4832: .LC_disc_new_item {
4833: background: white;
4834: border: 2px solid red;
4835: margin: 2px;
4836: }
4837:
4838: .LC_disc_old_item {
4839: background: white;
4840: border: 1px solid black;
4841: margin: 2px;
4842: }
4843:
4844: table.LC_pastsubmission {
4845: border: 1px solid black;
4846: margin: 2px;
4847: }
4848:
4849: table#LC_top_nav, table#LC_menubuttons,table#LC_nav_location {
4850: width: 100%;
4851: background: $pgbg;
4852: border: 2px;
4853: border-collapse: separate;
4854: padding: 0;
4855: }
4856:
4857: table#LC_title_bar, table.LC_breadcrumbs,
4858: table#LC_title_bar.LC_with_remote {
4859: width: 100%;
4860: border-color: $pgbg;
4861: border-style: solid;
4862: border-width: $border;
4863:
4864: background: $pgbg;
4865: font-family: $sans;
4866: border-collapse: collapse;
4867: padding: 0;
4868: }
4869:
4870: table.LC_docs_path {
4871: width: 100%;
4872: border: 0;
4873: background: $pgbg;
4874: font-family: $sans;
4875: border-collapse: collapse;
4876: padding: 0;
4877: }
4878:
4879: table#LC_title_bar td {
4880: background: $tabbg;
4881: }
4882: table#LC_title_bar td.LC_title_bar_who {
4883: background: $tabbg;
4884: color: $font;
4885: font: small $sans;
4886: text-align: right;
4887: }
4888: span.LC_metadata {
4889: font-family: $sans;
4890: }
4891: span.LC_title_bar_title {
4892: font: bold x-large $sans;
4893: }
4894: table#LC_title_bar td.LC_title_bar_domain_logo {
4895: background: $sidebg;
4896: text-align: right;
4897: padding: 0;
4898: }
4899: table#LC_title_bar td.LC_title_bar_role_logo {
4900: background: $sidebg;
4901: padding: 0;
4902: }
4903:
4904: table#LC_menubuttons_mainmenu {
4905: width: 100%;
4906: border: 0;
4907: border-spacing: 1px;
4908: padding: 0 1px;
4909: margin: 0;
4910: border-collapse: separate;
4911: }
4912: table#LC_menubuttons img, table#LC_menubuttons_mainmenu img {
4913: border: none;
4914: }
4915: table#LC_top_nav td {
4916: background: $tabbg;
4917: border: none;
4918: font-size: small;
4919: }
4920: table#LC_top_nav td a, div#LC_top_nav a {
4921: color: $font;
4922: font-family: $sans;
4923: }
4924: table#LC_top_nav td.LC_top_nav_logo {
4925: background: $tabbg;
4926: text-align: left;
4927: white-space: nowrap;
4928: width: 31px;
4929: }
4930: table#LC_top_nav td.LC_top_nav_logo img {
4931: border: none;
4932: vertical-align: bottom;
4933: }
4934: table#LC_top_nav td.LC_top_nav_exit,
4935: table#LC_top_nav td.LC_top_nav_help {
4936: width: 2.0em;
4937: }
4938: table#LC_top_nav td.LC_top_nav_login {
4939: width: 4.0em;
4940: text-align: center;
4941: }
4942: table.LC_breadcrumbs td, table.LC_docs_path td {
4943: background: $tabbg;
4944: color: $font;
4945: font-family: $sans;
4946: font-size: smaller;
4947: }
4948: table.LC_breadcrumbs td.LC_breadcrumbs_component,
4949: table.LC_docs_path td.LC_docs_path_component {
4950: background: $tabbg;
4951: color: $font;
4952: font-family: $sans;
4953: font-size: larger;
4954: text-align: right;
4955: }
4956: td.LC_table_cell_checkbox {
4957: text-align: center;
4958: }
4959: table#LC_mainmenu td.LC_mainmenu_column {
4960: vertical-align: top;
4961: }
4962:
4963: .LC_menubuttons_inline_text {
4964: color: $font;
4965: font-family: $sans;
4966: font-size: smaller;
4967: }
4968:
4969: .LC_menubuttons_link {
4970: text-decoration: none;
4971: }
4972: /*2008--9-5: new menu style sheet.Changed category*/
4973: .LC_menubuttons_category {
4974: color: $font;
4975: background: $pgbg;
4976: font-family: $sans;
4977: font-size: larger;
4978: font-weight: bold;
4979: }
4980:
4981: td.LC_menubuttons_text {
4982: width: 90%;
4983: color: $font;
4984: font-family: $sans;
4985: }
4986:
4987: td.LC_menubuttons_img {
4988: }
4989:
4990: .LC_current_location {
4991: font-family: $sans;
4992: background: $tabbg;
4993: }
4994: .LC_new_mail {
4995: font-family: $sans;
4996: background: $tabbg;
4997: font-weight: bold;
4998: }
4999:
5000: .LC_dropadd_labeltext {
5001: font-family: $sans;
5002: text-align: right;
5003: }
5004:
5005: .LC_preferences_labeltext {
5006: font-family: $sans;
5007: text-align: right;
5008: }
5009:
5010: .LC_roleslog_note {
5011: font-size: smaller;
5012: }
5013:
5014: .LC_mail_functions {
5015: font-weight: bold;
5016: }
5017:
5018: table.LC_aboutme_port {
5019: border: none;
5020: border-collapse: collapse;
5021: border-spacing: 0;
5022: }
5023: table.LC_data_table, table.LC_mail_list {
5024: border: 1px solid #000000;
5025: border-collapse: separate;
5026: border-spacing: 1px;
5027: background: $pgbg;
5028: }
5029: .LC_data_table_dense {
5030: font-size: small;
5031: }
5032: table.LC_nested_outer {
5033: border: 1px solid #000000;
5034: border-collapse: collapse;
5035: border-spacing: 0;
5036: width: 100%;
5037: }
5038: table.LC_innerpickbox,
5039: table.LC_nested {
5040: border: none;
5041: border-collapse: collapse;
5042: border-spacing: 0;
5043: width: 100%;
5044: }
5045: table.LC_data_table tr th, table.LC_calendar tr th, table.LC_mail_list tr th,
5046: table.LC_prior_tries tr th,
5047: table.LC_innerpickbox tr th {
5048: font-weight: bold;
5049: background-color: $data_table_head;
5050: font-size: smaller;
5051: }
5052: table.LC_innerpickbox tr th,
5053: table.LC_innerpickbox tr td {
5054: vertical-align: top;
5055: }
5056: table.LC_data_table tr.LC_info_row > td {
5057: background-color: #CCCCCC;
5058: font-weight: bold;
5059: text-align: left;
5060: }
5061: table.LC_data_table tr.LC_odd_row > td,
5062: table.LC_pick_box tr > td.LC_odd_row,
5063: table.LC_aboutme_port tr td {
5064: background-color: $data_table_light;
5065: padding: 2px;
5066: }
5067: table.LC_data_table tr.LC_even_row > td,
5068: table.LC_pick_box tr > td.LC_even_row,
5069: table.LC_aboutme_port tr.LC_even_row td {
5070: background-color: $data_table_dark;
5071: padding: 2px;
5072: }
5073: table.LC_data_table tr.LC_data_table_highlight td {
5074: background-color: $data_table_darker;
5075: }
5076: table.LC_data_table tr td.LC_leftcol_header {
5077: background-color: $data_table_head;
5078: font-weight: bold;
5079: }
5080: table.LC_data_table tr.LC_empty_row td,
5081: table.LC_nested tr.LC_empty_row td {
5082: background-color: #FFFFFF;
5083: font-weight: bold;
5084: font-style: italic;
5085: text-align: center;
5086: padding: 8px;
5087: }
5088: table.LC_nested tr.LC_empty_row td {
5089: padding: 4ex
5090: }
5091: table.LC_nested_outer tr th {
5092: font-weight: bold;
5093: background-color: $data_table_head;
5094: font-size: smaller;
5095: border-bottom: 1px solid #000000;
5096: }
5097: table.LC_nested_outer tr td.LC_subheader {
5098: background-color: $data_table_head;
5099: font-weight: bold;
5100: font-size: small;
5101: border-bottom: 1px solid #000000;
5102: text-align: right;
5103: }
5104: table.LC_nested tr.LC_info_row td {
5105: background-color: #CCCCCC;
5106: font-weight: bold;
5107: font-size: small;
5108: text-align: center;
5109: }
5110: table.LC_nested tr.LC_info_row td.LC_left_item,
5111: table.LC_nested_outer tr th.LC_left_item {
5112: text-align: left;
5113: }
5114: table.LC_nested td {
5115: background-color: #FFFFFF;
5116: font-size: small;
5117: }
5118: table.LC_nested_outer tr th.LC_right_item,
5119: table.LC_nested tr.LC_info_row td.LC_right_item,
5120: table.LC_nested tr.LC_odd_row td.LC_right_item,
5121: table.LC_nested tr td.LC_right_item {
5122: text-align: right;
5123: }
5124:
5125: table.LC_nested tr.LC_odd_row td {
5126: background-color: #EEEEEE;
5127: }
5128:
5129: table.LC_createuser {
5130: }
5131:
5132: table.LC_createuser tr.LC_section_row td {
5133: font-size: smaller;
5134: }
5135:
5136: table.LC_createuser tr.LC_info_row td {
5137: background-color: #CCCCCC;
5138: font-weight: bold;
5139: text-align: center;
5140: }
5141:
5142: table.LC_calendar {
5143: border: 1px solid #000000;
5144: border-collapse: collapse;
5145: }
5146: table.LC_calendar_pickdate {
5147: font-size: xx-small;
5148: }
5149: table.LC_calendar tr td {
5150: border: 1px solid #000000;
5151: vertical-align: top;
5152: }
5153: table.LC_calendar tr td.LC_calendar_day_empty {
5154: background-color: $data_table_dark;
5155: }
5156: table.LC_calendar tr td.LC_calendar_day_current {
5157: background-color: $data_table_highlight;
5158: }
5159:
5160: table.LC_mail_list tr.LC_mail_new {
5161: background-color: $mail_new;
5162: }
5163: table.LC_mail_list tr.LC_mail_new:hover {
5164: background-color: $mail_new_hover;
5165: }
5166: table.LC_mail_list tr.LC_mail_read {
5167: background-color: $mail_read;
5168: }
5169: table.LC_mail_list tr.LC_mail_read:hover {
5170: background-color: $mail_read_hover;
5171: }
5172: table.LC_mail_list tr.LC_mail_replied {
5173: background-color: $mail_replied;
5174: }
5175: table.LC_mail_list tr.LC_mail_replied:hover {
5176: background-color: $mail_replied_hover;
5177: }
5178: table.LC_mail_list tr.LC_mail_other {
5179: background-color: $mail_other;
5180: }
5181: table.LC_mail_list tr.LC_mail_other:hover {
5182: background-color: $mail_other_hover;
5183: }
5184: table.LC_mail_list tr.LC_mail_even {
5185: }
5186: table.LC_mail_list tr.LC_mail_odd {
5187: }
5188:
5189:
5190: table#LC_portfolio_actions {
5191: width: auto;
5192: background: $pgbg;
5193: border: none;
5194: border-spacing: 2px 2px;
5195: padding: 0;
5196: margin: 0;
5197: border-collapse: separate;
5198: }
5199: table#LC_portfolio_actions td.LC_label {
5200: background: $tabbg;
5201: text-align: right;
5202: }
5203: table#LC_portfolio_actions td.LC_value {
5204: background: $tabbg;
5205: }
5206:
5207: table#LC_cstr_controls {
5208: width: 100%;
5209: border-collapse: collapse;
5210: }
5211: table#LC_cstr_controls tr td {
5212: border: 4px solid $pgbg;
5213: padding: 4px;
5214: text-align: center;
5215: background: $tabbg;
5216: }
5217: table#LC_cstr_controls tr th {
5218: border: 4px solid $pgbg;
5219: background: $table_header;
5220: text-align: center;
5221: font-family: $sans;
5222: font-size: smaller;
5223: }
5224:
5225: table#LC_browser {
5226:
5227: }
5228: table#LC_browser tr th {
5229: background: $table_header;
5230: }
5231: table#LC_browser tr td {
5232: padding: 2px;
5233: }
5234: table#LC_browser tr.LC_browser_file,
5235: table#LC_browser tr.LC_browser_file_published {
5236: background: #CCFF88;
5237: }
5238: table#LC_browser tr.LC_browser_file_locked,
5239: table#LC_browser tr.LC_browser_file_unpublished {
5240: background: #FFAA99;
5241: }
5242: table#LC_browser tr.LC_browser_file_obsolete {
5243: background: #AAAAAA;
5244: }
5245: table#LC_browser tr.LC_browser_file_modified,
5246: table#LC_browser tr.LC_browser_file_metamodified {
5247: background: #FFFF77;
5248: }
5249: table#LC_browser tr.LC_browser_folder {
5250: background: #CCCCFF;
5251: }
5252:
5253: table.LC_data_table tr > td.LC_roles_is {
5254: /* background: #77FF77; */
5255: }
5256: table.LC_data_table tr > td.LC_roles_future {
5257: background: #FFFF77;
5258: }
5259: table.LC_data_table tr > td.LC_roles_will {
5260: background: #FFAA77;
5261: }
5262: table.LC_data_table tr > td.LC_roles_expired {
5263: background: #FF7777;
5264: }
5265: table.LC_data_table tr > td.LC_roles_will_not {
5266: background: #AAFF77;
5267: }
5268: table.LC_data_table tr > td.LC_roles_selected {
5269: background: #11CC55;
5270: }
5271:
5272: span.LC_current_location {
5273: font-size: x-large;
5274: background: $pgbg;
5275: }
5276:
5277: span.LC_parm_menu_item {
5278: font-size: larger;
5279: font-family: $sans;
5280: }
5281: span.LC_parm_scope_all {
5282: color: red;
5283: }
5284: span.LC_parm_scope_folder {
5285: color: green;
5286: }
5287: span.LC_parm_scope_resource {
5288: color: orange;
5289: }
5290: span.LC_parm_part {
5291: color: blue;
5292: }
5293: span.LC_parm_folder, span.LC_parm_symb {
5294: font-size: x-small;
5295: font-family: $mono;
5296: color: #AAAAAA;
5297: }
5298:
5299: td.LC_parm_overview_level_menu, td.LC_parm_overview_map_menu,
5300: td.LC_parm_overview_parm_selectors, td.LC_parm_overview_parm_restrictions {
5301: border: 1px solid black;
5302: border-collapse: collapse;
5303: }
5304: table.LC_parm_overview_restrictions td {
5305: border-width: 1px 4px 1px 4px;
5306: border-style: solid;
5307: border-color: $pgbg;
5308: text-align: center;
5309: }
5310: table.LC_parm_overview_restrictions th {
5311: background: $tabbg;
5312: border-width: 1px 4px 1px 4px;
5313: border-style: solid;
5314: border-color: $pgbg;
5315: }
5316: table#LC_helpmenu {
5317: border: none;
5318: height: 55px;
5319: border-spacing: 0;
5320: }
5321:
5322: table#LC_helpmenu fieldset legend {
5323: font-size: larger;
5324: font-weight: bold;
5325: }
5326: table#LC_helpmenu_links {
5327: width: 100%;
5328: border: 1px solid black;
5329: background: $pgbg;
5330: padding: 0;
5331: border-spacing: 1px;
5332: }
5333: table#LC_helpmenu_links tr td {
5334: padding: 1px;
5335: background: $tabbg;
5336: text-align: center;
5337: font-weight: bold;
5338: }
5339:
5340: table#LC_helpmenu_links a:link, table#LC_helpmenu_links a:visited,
5341: table#LC_helpmenu_links a:active {
5342: text-decoration: none;
5343: color: $font;
5344: }
5345: table#LC_helpmenu_links a:hover {
5346: text-decoration: underline;
5347: color: $vlink;
5348: }
5349:
5350: .LC_chrt_popup_exists {
5351: border: 1px solid #339933;
5352: margin: -1px;
5353: }
5354: .LC_chrt_popup_up {
5355: border: 1px solid yellow;
5356: margin: -1px;
5357: }
5358: .LC_chrt_popup {
5359: border: 1px solid #8888FF;
5360: background: #CCCCFF;
5361: }
5362: table.LC_pick_box {
5363: border-collapse: separate;
5364: background: white;
5365: border: 1px solid black;
5366: border-spacing: 1px;
5367: }
5368: table.LC_pick_box td.LC_pick_box_title {
5369: background: $tabbg;
5370: font-weight: bold;
5371: text-align: right;
5372: vertical-align: top;
5373: width: 184px;
5374: padding: 8px;
5375: }
5376: table.LC_pick_box td.LC_selfenroll_pick_box_title {
5377: background: $tabbg;
5378: font-weight: bold;
5379: text-align: right;
5380: width: 350px;
5381: padding: 8px;
5382: }
5383:
5384: table.LC_pick_box td.LC_pick_box_value {
5385: text-align: left;
5386: padding: 8px;
5387: }
5388: table.LC_pick_box td.LC_pick_box_select {
5389: text-align: left;
5390: padding: 8px;
5391: }
5392: table.LC_pick_box td.LC_pick_box_separator {
5393: padding: 0;
5394: height: 1px;
5395: background: black;
5396: }
5397: table.LC_pick_box td.LC_pick_box_submit {
5398: text-align: right;
5399: }
5400: table.LC_pick_box td.LC_evenrow_value {
5401: text-align: left;
5402: padding: 8px;
5403: background-color: $data_table_light;
5404: }
5405: table.LC_pick_box td.LC_oddrow_value {
5406: text-align: left;
5407: padding: 8px;
5408: background-color: $data_table_light;
5409: }
5410: table.LC_helpform_receipt {
5411: width: 620px;
5412: border-collapse: separate;
5413: background: white;
5414: border: 1px solid black;
5415: border-spacing: 1px;
5416: }
5417: table.LC_helpform_receipt td.LC_pick_box_title {
5418: background: $tabbg;
5419: font-weight: bold;
5420: text-align: right;
5421: width: 184px;
5422: padding: 8px;
5423: }
5424: table.LC_helpform_receipt td.LC_evenrow_value {
5425: text-align: left;
5426: padding: 8px;
5427: background-color: $data_table_light;
5428: }
5429: table.LC_helpform_receipt td.LC_oddrow_value {
5430: text-align: left;
5431: padding: 8px;
5432: background-color: $data_table_light;
5433: }
5434: table.LC_helpform_receipt td.LC_pick_box_separator {
5435: padding: 0;
5436: height: 1px;
5437: background: black;
5438: }
5439: span.LC_helpform_receipt_cat {
5440: font-weight: bold;
5441: }
5442: table.LC_group_priv_box {
5443: background: white;
5444: border: 1px solid black;
5445: border-spacing: 1px;
5446: }
5447: table.LC_group_priv_box td.LC_pick_box_title {
5448: background: $tabbg;
5449: font-weight: bold;
5450: text-align: right;
5451: width: 184px;
5452: }
5453: table.LC_group_priv_box td.LC_groups_fixed {
5454: background: $data_table_light;
5455: text-align: center;
5456: }
5457: table.LC_group_priv_box td.LC_groups_optional {
5458: background: $data_table_dark;
5459: text-align: center;
5460: }
5461: table.LC_group_priv_box td.LC_groups_functionality {
5462: background: $data_table_darker;
5463: text-align: center;
5464: font-weight: bold;
5465: }
5466: table.LC_group_priv td {
5467: text-align: left;
5468: padding: 0;
5469: }
5470:
5471: table.LC_notify_front_page {
5472: background: white;
5473: border: 1px solid black;
5474: padding: 8px;
5475: }
5476: table.LC_notify_front_page td {
5477: padding: 8px;
5478: }
5479: .LC_navbuttons {
5480: margin: 2ex 0ex 2ex 0ex;
5481: }
5482: .LC_topic_bar {
5483: font-family: $sans;
5484: font-weight: bold;
5485: width: 100%;
5486: background: $tabbg;
5487: vertical-align: middle;
5488: margin: 2ex 0ex 2ex 0ex;
5489: padding: 3px;
5490: }
5491: .LC_topic_bar span {
5492: vertical-align: middle;
5493: }
5494: .LC_topic_bar img {
5495: vertical-align: bottom;
5496: }
5497: table.LC_course_group_status {
5498: margin: 20px;
5499: }
5500: table.LC_status_selector td {
5501: vertical-align: top;
5502: text-align: center;
5503: padding: 4px;
5504: }
5505: table.LC_descriptive_input td.LC_description {
5506: vertical-align: top;
5507: text-align: right;
5508: font-weight: bold;
5509: }
5510: div.LC_feedback_link {
5511: clear: both;
5512: background: white;
5513: width: 100%;
5514: }
5515: span.LC_feedback_link {
5516: background: $feedback_link_bg;
5517: font-size: larger;
5518: }
5519: span.LC_message_link {
5520: background: $feedback_link_bg;
5521: font-size: larger;
5522: position: absolute;
5523: right: 1em;
5524: }
5525:
5526: table.LC_prior_tries {
5527: border: 1px solid #000000;
5528: border-collapse: separate;
5529: border-spacing: 1px;
5530: }
5531:
5532: table.LC_prior_tries td {
5533: padding: 2px;
5534: }
5535:
5536: .LC_answer_correct {
5537: background: #AAFFAA;
5538: color: black;
5539: }
5540: .LC_answer_charged_try {
5541: background: #FFAAAA ! important;
5542: color: black;
5543: }
5544: .LC_answer_not_charged_try,
5545: .LC_answer_no_grade,
5546: .LC_answer_late {
5547: background: #FFFFAA;
5548: color: black;
5549: }
5550: .LC_answer_previous {
5551: background: #AAAAFF;
5552: color: black;
5553: }
5554: .LC_answer_no_message {
5555: background: #FFFFFF;
5556: color: black;
5557: }
5558: .LC_answer_unknown {
5559: background: orange;
5560: color: black;
5561: }
5562:
5563:
5564: span.LC_prior_numerical,
5565: span.LC_prior_string,
5566: span.LC_prior_custom,
5567: span.LC_prior_reaction,
5568: span.LC_prior_math {
5569: font-family: monospace;
5570: white-space: pre;
5571: }
5572:
5573: span.LC_prior_string {
5574: font-family: monospace;
5575: white-space: pre;
5576: }
5577:
5578: table.LC_prior_option {
5579: width: 100%;
5580: border-collapse: collapse;
5581: }
5582: table.LC_prior_rank, table.LC_prior_match {
5583: border-collapse: collapse;
5584: }
5585: table.LC_prior_option tr td,
5586: table.LC_prior_rank tr td,
5587: table.LC_prior_match tr td {
5588: border: 1px solid #000000;
5589: }
5590:
5591: span.LC_nobreak {
5592: white-space: nowrap;
5593: }
5594:
5595: span.LC_cusr_emph {
5596: font-style: italic;
5597: }
5598:
5599: span.LC_cusr_subheading {
5600: font-weight: normal;
5601: font-size: 85%;
5602: }
5603:
5604: table.LC_docs_documents {
5605: background: #BBBBBB;
5606: border-width: 0;
5607: border-collapse: collapse;
5608: }
5609:
5610: table.LC_docs_documents td.LC_docs_document {
5611: border: 2px solid black;
5612: padding: 4px;
5613: }
5614:
5615: .LC_docs_course_commands div {
5616: float: left;
5617: border: 4px solid #AAAAAA;
5618: padding: 4px;
5619: background: #DDDDCC;
5620: }
5621:
5622: .LC_docs_entry_move {
5623: border: none;
5624: border-collapse: collapse;
5625: }
5626:
5627: .LC_docs_entry_move td {
5628: border: 2px solid #BBBBBB;
5629: background: #DDDDDD;
5630: }
5631:
5632: .LC_docs_editor td.LC_docs_entry_commands {
5633: background: #DDDDDD;
5634: font-size: x-small;
5635: }
5636: .LC_docs_copy {
5637: color: #000099;
5638: }
5639: .LC_docs_cut {
5640: color: #550044;
5641: }
5642: .LC_docs_rename {
5643: color: #009900;
5644: }
5645: .LC_docs_remove {
5646: color: #990000;
5647: }
5648:
5649: .LC_docs_reinit_warn,
5650: .LC_docs_ext_edit {
5651: font-size: x-small;
5652: }
5653:
5654: .LC_docs_editor td.LC_docs_entry_title,
5655: .LC_docs_editor td.LC_docs_entry_icon {
5656: background: #FFFFBB;
5657: }
5658: .LC_docs_editor td.LC_docs_entry_parameter {
5659: background: #BBBBFF;
5660: font-size: x-small;
5661: white-space: nowrap;
5662: }
5663:
5664: table.LC_docs_adddocs td,
5665: table.LC_docs_adddocs th {
5666: border: 1px solid #BBBBBB;
5667: padding: 4px;
5668: background: #DDDDDD;
5669: }
5670:
5671: table.LC_sty_begin {
5672: background: #BBFFBB;
5673: }
5674: table.LC_sty_end {
5675: background: #FFBBBB;
5676: }
5677:
5678: table.LC_double_column {
5679: border-width: 0;
5680: border-collapse: collapse;
5681: width: 100%;
5682: padding: 2px;
5683: }
5684:
5685: table.LC_double_column tr td.LC_left_col {
5686: top: 2px;
5687: left: 2px;
5688: width: 47%;
5689: vertical-align: top;
5690: }
5691:
5692: table.LC_double_column tr td.LC_right_col {
5693: top: 2px;
5694: right: 2px;
5695: width: 47%;
5696: vertical-align: top;
5697: }
5698:
5699: span.LC_role_level {
5700: font-weight: bold;
5701: }
5702:
5703: div.LC_left_float {
5704: float: left;
5705: padding-right: 5%;
5706: padding-bottom: 4px;
5707: }
5708:
5709: div.LC_clear_float_header {
5710: padding-bottom: 2px;
5711: }
5712:
5713: div.LC_clear_float_footer {
5714: padding-top: 10px;
5715: clear: both;
5716: }
5717:
5718:
5719: div.LC_grade_select_mode {
5720: font-family: $sans;
5721: }
5722: div.LC_grade_select_mode div div {
5723: margin: 5px;
5724: }
5725: div.LC_grade_select_mode_selector {
5726: margin: 5px;
5727: float: left;
5728: }
5729: div.LC_grade_select_mode_selector_header {
5730: font: bold medium $sans;
5731: }
5732: div.LC_grade_select_mode_type {
5733: clear: left;
5734: }
5735:
5736: div.LC_grade_show_user {
5737: margin-top: 20px;
5738: border: 1px solid black;
5739: }
5740: div.LC_grade_user_name {
5741: background: #DDDDEE;
5742: border-bottom: 1px solid black;
5743: font: bold large $sans;
5744: }
5745: div.LC_grade_show_user_odd_row div.LC_grade_user_name {
5746: background: #DDEEDD;
5747: }
5748:
5749: div.LC_grade_show_problem,
5750: div.LC_grade_submissions,
5751: div.LC_grade_message_center,
5752: div.LC_grade_info_links,
5753: div.LC_grade_assign {
5754: margin: 5px;
5755: width: 99%;
5756: background: #FFFFFF;
5757: }
5758: div.LC_grade_show_problem_header,
5759: div.LC_grade_submissions_header,
5760: div.LC_grade_message_center_header,
5761: div.LC_grade_assign_header {
5762: font: bold large $sans;
5763: }
5764: div.LC_grade_show_problem_problem,
5765: div.LC_grade_submissions_body,
5766: div.LC_grade_message_center_body,
5767: div.LC_grade_assign_body {
5768: border: 1px solid black;
5769: width: 99%;
5770: background: #FFFFFF;
5771: }
5772: span.LC_grade_check_note {
5773: font: normal medium $sans;
5774: display: inline;
5775: position: absolute;
5776: right: 1em;
5777: }
5778:
5779: table.LC_scantron_action {
5780: width: 100%;
5781: }
5782: table.LC_scantron_action tr th {
5783: font: normal bold $sans;
5784: }
5785:
5786: div.LC_edit_problem_header,
5787: div.LC_edit_problem_footer {
5788: font: normal medium $sans;
5789: margin: 2px;
5790: }
5791: div.LC_edit_problem_header,
5792: div.LC_edit_problem_header div,
5793: div.LC_edit_problem_footer,
5794: div.LC_edit_problem_footer div,
5795: div.LC_edit_problem_editxml_header,
5796: div.LC_edit_problem_editxml_header div {
5797: margin-top: 5px;
5798: }
5799: div.LC_edit_problem_header_edit_row {
5800: background: $tabbg;
5801: padding: 3px;
5802: margin-bottom: 5px;
5803: }
5804: div.LC_edit_problem_header_title {
5805: font: larger bold $sans;
5806: background: $tabbg;
5807: padding: 3px;
5808: }
5809: table.LC_edit_problem_header_title {
5810: font: larger bold $sans;
5811: width: 100%;
5812: border-color: $pgbg;
5813: border-style: solid;
5814: border-width: $border;
5815:
5816: background: $tabbg;
5817: border-collapse: collapse;
5818: padding: 0;
5819: }
5820:
5821: div.LC_edit_problem_discards {
5822: float: left;
5823: padding-bottom: 5px;
5824: }
5825: div.LC_edit_problem_saves {
5826: float: right;
5827: padding-bottom: 5px;
5828: }
5829: hr.LC_edit_problem_divide {
5830: clear: both;
5831: color: $tabbg;
5832: background-color: $tabbg;
5833: height: 3px;
5834: border: none;
5835: }
5836: img.stift{
5837: border-width:0;
5838: vertical-align:middle;
5839: }
5840:
5841: table#LC_mainmenu{
5842: margin-top:10px;
5843: width:80%;
5844:
5845: }
5846:
5847: table#LC_mainmenu td.LC_mainmenu_col_fieldset{
5848: vertical-align: top;
5849: width: 45%;
5850: }
5851: .LC_mainmenu_fieldset_category {
5852: color: $font;
5853: background: $pgbg;
5854: font-family: $sans;
5855: font-size: small;
5856: font-weight: bold;
5857: }
5858: fieldset#LC_mainmenu_fieldset {
5859: margin:0 10px 10px 0;
5860:
5861: }
5862:
5863: div.LC_createcourse {
5864: margin: 10px 10px 10px 10px;
5865: }
5866:
5867: END
5868: }
5869:
5870: =pod
5871:
5872: =item * &headtag()
5873:
5874: Returns a uniform footer for LON-CAPA web pages.
5875:
5876: Inputs: $title - optional title for the head
5877: $head_extra - optional extra HTML to put inside the <head>
5878: $args - optional arguments
5879: force_register - if is true call registerurl so the remote is
5880: informed
5881: redirect -> array ref of
5882: 1- seconds before redirect occurs
5883: 2- url to redirect to
5884: 3- whether the side effect should occur
5885: (side effect of setting
5886: $env{'internal.head.redirect'} to the url
5887: redirected too)
5888: domain -> force to color decorate a page for a specific
5889: domain
5890: function -> force usage of a specific rolish color scheme
5891: bgcolor -> override the default page bgcolor
5892: no_auto_mt_title
5893: -> prevent &mt()ing the title arg
5894:
5895: =cut
5896:
5897: sub headtag {
5898: my ($title,$head_extra,$args) = @_;
5899:
5900: my $function = $args->{'function'} || &get_users_function();
5901: my $domain = $args->{'domain'} || &determinedomain();
5902: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
5903: my $url = join(':',$env{'user.name'},$env{'user.domain'},
5904: $Apache::lonnet::perlvar{'lonVersion'},
5905: #time(),
5906: $env{'environment.color.timestamp'},
5907: $function,$domain,$bgcolor);
5908:
5909: $url = '/adm/css/'.&escape($url).'.css';
5910:
5911: my $result =
5912: '<head>'.
5913: &font_settings();
5914:
5915: if (!$args->{'frameset'}) {
5916: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
5917: }
5918: if ($args->{'force_register'}) {
5919: $result .= &Apache::lonmenu::registerurl(1);
5920: }
5921: if (!$args->{'no_nav_bar'}
5922: && !$args->{'only_body'}
5923: && !$args->{'frameset'}) {
5924: $result .= &help_menu_js();
5925: }
5926:
5927: if (ref($args->{'redirect'})) {
5928: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
5929: $url = &Apache::lonenc::check_encrypt($url);
5930: if (!$inhibit_continue) {
5931: $env{'internal.head.redirect'} = $url;
5932: }
5933: $result.=<<ADDMETA
5934: <meta http-equiv="pragma" content="no-cache" />
5935: <meta http-equiv="Refresh" content="$time; url=$url" />
5936: ADDMETA
5937: }
5938: if (!defined($title)) {
5939: $title = 'The LearningOnline Network with CAPA';
5940: }
5941: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5942: $result .= '<title> LON-CAPA '.$title.'</title>'
5943: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
5944: .$head_extra;
5945: return $result;
5946: }
5947:
5948: =pod
5949:
5950: =item * &font_settings()
5951:
5952: Returns neccessary <meta> to set the proper encoding
5953:
5954: Inputs: none
5955:
5956: =cut
5957:
5958: sub font_settings {
5959: my $headerstring='';
5960: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
5961: $headerstring.=
5962: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
5963: }
5964: return $headerstring;
5965: }
5966:
5967: =pod
5968:
5969: =item * &xml_begin()
5970:
5971: Returns the needed doctype and <html>
5972:
5973: Inputs: none
5974:
5975: =cut
5976:
5977: sub xml_begin {
5978: my $output='';
5979:
5980: if ($env{'internal.start_page'}==1) {
5981: &Apache::lonhtmlcommon::init_htmlareafields();
5982: }
5983:
5984: if ($env{'browser.mathml'}) {
5985: $output='<?xml version="1.0"?>'
5986: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
5987: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
5988:
5989: # .'<!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">] >'
5990: .'<!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">'
5991: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
5992: .'xmlns="http://www.w3.org/1999/xhtml">';
5993: } else {
5994: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.
5995: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
5996: }
5997: return $output;
5998: }
5999:
6000: =pod
6001:
6002: =item * &endheadtag()
6003:
6004: Returns a uniform </head> for LON-CAPA web pages.
6005:
6006: Inputs: none
6007:
6008: =cut
6009:
6010: sub endheadtag {
6011: return '</head>';
6012: }
6013:
6014: =pod
6015:
6016: =item * &head()
6017:
6018: Returns a uniform complete <head>..</head> section for LON-CAPA web pages.
6019:
6020: Inputs:
6021:
6022: =over 4
6023:
6024: $title - optional title for the page
6025:
6026: $head_extra - optional extra HTML to put inside the <head>
6027:
6028: =back
6029:
6030: =cut
6031:
6032: sub head {
6033: my ($title,$head_extra,$args) = @_;
6034: return &headtag($title,$head_extra,$args).&endheadtag();
6035: }
6036:
6037: =pod
6038:
6039: =item * &start_page()
6040:
6041: Returns a complete <html> .. <body> section for LON-CAPA web pages.
6042:
6043: Inputs:
6044:
6045: =over 4
6046:
6047: $title - optional title for the page
6048:
6049: $head_extra - optional extra HTML to incude inside the <head>
6050:
6051: $args - additional optional args supported are:
6052:
6053: =over 8
6054:
6055: only_body -> is true will set &bodytag() onlybodytag
6056: arg on
6057: no_nav_bar -> is true will set &bodytag() notopbar arg on
6058: add_entries -> additional attributes to add to the <body>
6059: domain -> force to color decorate a page for a
6060: specific domain
6061: function -> force usage of a specific rolish color
6062: scheme
6063: redirect -> see &headtag()
6064: bgcolor -> override the default page bg color
6065: js_ready -> return a string ready for being used in
6066: a javascript writeln
6067: html_encode -> return a string ready for being used in
6068: a html attribute
6069: force_register -> if is true will turn on the &bodytag()
6070: $forcereg arg
6071: body_title -> alternate text to use instead of $title
6072: in the title box that appears, this text
6073: is not auto translated like the $title is
6074: frameset -> if true will start with a <frameset>
6075: rather than <body>
6076: no_title -> if true the title bar won't be shown
6077: skip_phases -> hash ref of
6078: head -> skip the <html><head> generation
6079: body -> skip all <body> generation
6080: no_inline_link -> if true and in remote mode, don't show the
6081: 'Switch To Inline Menu' link
6082: no_auto_mt_title -> prevent &mt()ing the title arg
6083: inherit_jsmath -> when creating popup window in a page,
6084: should it have jsmath forced on by the
6085: current page
6086:
6087: =back
6088:
6089: =back
6090:
6091: =cut
6092:
6093: sub start_page {
6094: my ($title,$head_extra,$args) = @_;
6095: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
6096: my %head_args;
6097: foreach my $arg ('redirect','force_register','domain','function',
6098: 'bgcolor','frameset','no_nav_bar','only_body',
6099: 'no_auto_mt_title') {
6100: if (defined($args->{$arg})) {
6101: $head_args{$arg} = $args->{$arg};
6102: }
6103: }
6104:
6105: $env{'internal.start_page'}++;
6106: my $result;
6107: if (! exists($args->{'skip_phases'}{'head'}) ) {
6108: $result.=
6109: &xml_begin().
6110: &headtag($title,$head_extra,\%head_args).&endheadtag();
6111: }
6112:
6113: if (! exists($args->{'skip_phases'}{'body'}) ) {
6114: if ($args->{'frameset'}) {
6115: my $attr_string = &make_attr_string($args->{'force_register'},
6116: $args->{'add_entries'});
6117: $result .= "\n<frameset $attr_string>\n";
6118: } else {
6119: $result .=
6120: &bodytag($title,
6121: $args->{'function'}, $args->{'add_entries'},
6122: $args->{'only_body'}, $args->{'domain'},
6123: $args->{'force_register'}, $args->{'body_title'},
6124: $args->{'no_nav_bar'}, $args->{'bgcolor'},
6125: $args->{'no_title'}, $args->{'no_inline_link'},
6126: $args);
6127: }
6128: }
6129:
6130: if ($args->{'js_ready'}) {
6131: $result = &js_ready($result);
6132: }
6133: if ($args->{'html_encode'}) {
6134: $result = &html_encode($result);
6135: }
6136: #Breadcrumbs
6137: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
6138: &Apache::lonhtmlcommon::clear_breadcrumbs();
6139: #if any br links exists, add them to the breadcrumbs
6140: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
6141: foreach my $crumb (@{$args->{'bread_crumbs'}}){
6142: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
6143: }
6144: }
6145:
6146: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
6147: if (exists($args->{'bread_crumbs_component'})){
6148: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
6149: } else {
6150: $result .= &Apache::lonhtmlcommon::breadcrumbs();
6151: }
6152: }
6153: return $result;
6154: }
6155:
6156: =pod
6157:
6158: =item * &head()
6159:
6160: Returns a complete </body></html> section for LON-CAPA web pages.
6161:
6162: Inputs: $args - additional optional args supported are:
6163: js_ready -> return a string ready for being used in
6164: a javascript writeln
6165: html_encode -> return a string ready for being used in
6166: a html attribute
6167: frameset -> if true will start with a <frameset>
6168: rather than <body>
6169: dicsussion -> if true will get discussion from
6170: lonxml::xmlend
6171: (you can pass the target and parser arguments
6172: through optional 'target' and 'parser' args
6173: to this routine)
6174:
6175: =cut
6176:
6177: sub end_page {
6178: my ($args) = @_;
6179: $env{'internal.end_page'}++;
6180: my $result;
6181: if ($args->{'discussion'}) {
6182: my ($target,$parser);
6183: if (ref($args->{'discussion'})) {
6184: ($target,$parser) =($args->{'discussion'}{'target'},
6185: $args->{'discussion'}{'parser'});
6186: }
6187: $result .= &Apache::lonxml::xmlend($target,$parser);
6188: }
6189:
6190: if ($args->{'frameset'}) {
6191: $result .= '</frameset>';
6192: } else {
6193: $result .= &endbodytag($args);
6194: }
6195: $result .= "\n</html>";
6196:
6197: if ($args->{'js_ready'}) {
6198: $result = &js_ready($result);
6199: }
6200:
6201: if ($args->{'html_encode'}) {
6202: $result = &html_encode($result);
6203: }
6204:
6205: return $result;
6206: }
6207:
6208: sub html_encode {
6209: my ($result) = @_;
6210:
6211: $result = &HTML::Entities::encode($result,'<>&"');
6212:
6213: return $result;
6214: }
6215: sub js_ready {
6216: my ($result) = @_;
6217:
6218: $result =~ s/[\n\r]/ /xmsg;
6219: $result =~ s/\\/\\\\/xmsg;
6220: $result =~ s/'/\\'/xmsg;
6221: $result =~ s{</}{<\\/}xmsg;
6222:
6223: return $result;
6224: }
6225:
6226: sub validate_page {
6227: if ( exists($env{'internal.start_page'})
6228: && $env{'internal.start_page'} > 1) {
6229: &Apache::lonnet::logthis('start_page called multiple times '.
6230: $env{'internal.start_page'}.' '.
6231: $ENV{'request.filename'});
6232: }
6233: if ( exists($env{'internal.end_page'})
6234: && $env{'internal.end_page'} > 1) {
6235: &Apache::lonnet::logthis('end_page called multiple times '.
6236: $env{'internal.end_page'}.' '.
6237: $env{'request.filename'});
6238: }
6239: if ( exists($env{'internal.start_page'})
6240: && ! exists($env{'internal.end_page'})) {
6241: &Apache::lonnet::logthis('start_page called without end_page '.
6242: $env{'request.filename'});
6243: }
6244: if ( ! exists($env{'internal.start_page'})
6245: && exists($env{'internal.end_page'})) {
6246: &Apache::lonnet::logthis('end_page called without start_page'.
6247: $env{'request.filename'});
6248: }
6249: }
6250:
6251: sub simple_error_page {
6252: my ($r,$title,$msg) = @_;
6253: my $page =
6254: &Apache::loncommon::start_page($title).
6255: &mt($msg).
6256: &Apache::loncommon::end_page();
6257: if (ref($r)) {
6258: $r->print($page);
6259: return;
6260: }
6261: return $page;
6262: }
6263:
6264: {
6265: my @row_count;
6266: sub start_data_table {
6267: my ($add_class) = @_;
6268: my $css_class = (join(' ','LC_data_table',$add_class));
6269: unshift(@row_count,0);
6270: return '<table class="'.$css_class.'">'."\n";
6271: }
6272:
6273: sub end_data_table {
6274: shift(@row_count);
6275: return '</table>'."\n";;
6276: }
6277:
6278: sub start_data_table_row {
6279: my ($add_class) = @_;
6280: $row_count[0]++;
6281: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6282: $css_class = (join(' ',$css_class,$add_class));
6283: return '<tr class="'.$css_class.'">'."\n";;
6284: }
6285:
6286: sub continue_data_table_row {
6287: my ($add_class) = @_;
6288: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
6289: $css_class = (join(' ',$css_class,$add_class));
6290: return '<tr class="'.$css_class.'">'."\n";;
6291: }
6292:
6293: sub end_data_table_row {
6294: return '</tr>'."\n";;
6295: }
6296:
6297: sub start_data_table_empty_row {
6298: $row_count[0]++;
6299: return '<tr class="LC_empty_row" >'."\n";;
6300: }
6301:
6302: sub end_data_table_empty_row {
6303: return '</tr>'."\n";;
6304: }
6305:
6306: sub start_data_table_header_row {
6307: return '<tr class="LC_header_row">'."\n";;
6308: }
6309:
6310: sub end_data_table_header_row {
6311: return '</tr>'."\n";;
6312: }
6313: }
6314:
6315: =pod
6316:
6317: =item * &inhibit_menu_check($arg)
6318:
6319: Checks for a inhibitmenu state and generates output to preserve it
6320:
6321: Inputs: $arg - can be any of
6322: - undef - in which case the return value is a string
6323: to add into arguments list of a uri
6324: - 'input' - in which case the return value is a HTML
6325: <form> <input> field of type hidden to
6326: preserve the value
6327: - a url - in which case the return value is the url with
6328: the neccesary cgi args added to preserve the
6329: inhibitmenu state
6330: - a ref to a url - no return value, but the string is
6331: updated to include the neccessary cgi
6332: args to preserve the inhibitmenu state
6333:
6334: =cut
6335:
6336: sub inhibit_menu_check {
6337: my ($arg) = @_;
6338: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
6339: if ($arg eq 'input') {
6340: if ($env{'form.inhibitmenu'}) {
6341: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
6342: } else {
6343: return
6344: }
6345: }
6346: if ($env{'form.inhibitmenu'}) {
6347: if (ref($arg)) {
6348: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6349: } elsif ($arg eq '') {
6350: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
6351: } else {
6352: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
6353: }
6354: }
6355: if (!ref($arg)) {
6356: return $arg;
6357: }
6358: }
6359:
6360: ###############################################
6361:
6362: =pod
6363:
6364: =back
6365:
6366: =head1 User Information Routines
6367:
6368: =over 4
6369:
6370: =item * &get_users_function()
6371:
6372: Used by &bodytag to determine the current users primary role.
6373: Returns either 'student','coordinator','admin', or 'author'.
6374:
6375: =cut
6376:
6377: ###############################################
6378: sub get_users_function {
6379: my $function = 'student';
6380: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/
6381: $function='coordinator';
6382: }
6383: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
6384: $function='admin';
6385: }
6386: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
6387: ($ENV{'REQUEST_URI'}=~/^(\/priv|\~)/)) {
6388: $function='author';
6389: }
6390: return $function;
6391: }
6392:
6393: ###############################################
6394:
6395: =pod
6396:
6397: =item * &show_course()
6398:
6399: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
6400: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
6401: Inputs:
6402: None
6403:
6404: Outputs:
6405: Scalar: 1 if 'Course' to be used, 0 otherwise.
6406:
6407: =cut
6408:
6409: ###############################################
6410: sub show_course {
6411: my $course = !$env{'user.adv'};
6412: if (!$env{'user.adv'}) {
6413: foreach my $env (keys(%env)) {
6414: next if ($env !~ m/^user\.priv\./);
6415: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
6416: $course = 0;
6417: last;
6418: }
6419: }
6420: }
6421: return $course;
6422: }
6423:
6424: ###############################################
6425:
6426: =pod
6427:
6428: =item * &check_user_status()
6429:
6430: Determines current status of supplied role for a
6431: specific user. Roles can be active, previous or future.
6432:
6433: Inputs:
6434: user's domain, user's username, course's domain,
6435: course's number, optional section ID.
6436:
6437: Outputs:
6438: role status: active, previous or future.
6439:
6440: =cut
6441:
6442: sub check_user_status {
6443: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
6444: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
6445: my @uroles = keys %userinfo;
6446: my $srchstr;
6447: my $active_chk = 'none';
6448: my $now = time;
6449: if (@uroles > 0) {
6450: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
6451: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
6452: } else {
6453: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
6454: }
6455: if (grep/^\Q$srchstr\E$/,@uroles) {
6456: my $role_end = 0;
6457: my $role_start = 0;
6458: $active_chk = 'active';
6459: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
6460: $role_end = $1;
6461: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
6462: $role_start = $1;
6463: }
6464: }
6465: if ($role_start > 0) {
6466: if ($now < $role_start) {
6467: $active_chk = 'future';
6468: }
6469: }
6470: if ($role_end > 0) {
6471: if ($now > $role_end) {
6472: $active_chk = 'previous';
6473: }
6474: }
6475: }
6476: }
6477: return $active_chk;
6478: }
6479:
6480: ###############################################
6481:
6482: =pod
6483:
6484: =item * &get_sections()
6485:
6486: Determines all the sections for a course including
6487: sections with students and sections containing other roles.
6488: Incoming parameters:
6489:
6490: 1. domain
6491: 2. course number
6492: 3. reference to array containing roles for which sections should
6493: be gathered (optional).
6494: 4. reference to array containing status types for which sections
6495: should be gathered (optional).
6496:
6497: If the third argument is undefined, sections are gathered for any role.
6498: If the fourth argument is undefined, sections are gathered for any status.
6499: Permissible values are 'active' or 'future' or 'previous'.
6500:
6501: Returns section hash (keys are section IDs, values are
6502: number of users in each section), subject to the
6503: optional roles filter, optional status filter
6504:
6505: =cut
6506:
6507: ###############################################
6508: sub get_sections {
6509: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
6510: if (!defined($cdom) || !defined($cnum)) {
6511: my $cid = $env{'request.course.id'};
6512:
6513: return if (!defined($cid));
6514:
6515: $cdom = $env{'course.'.$cid.'.domain'};
6516: $cnum = $env{'course.'.$cid.'.num'};
6517: }
6518:
6519: my %sectioncount;
6520: my $now = time;
6521:
6522: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
6523: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
6524: my $sec_index = &Apache::loncoursedata::CL_SECTION();
6525: my $status_index = &Apache::loncoursedata::CL_STATUS();
6526: my $start_index = &Apache::loncoursedata::CL_START();
6527: my $end_index = &Apache::loncoursedata::CL_END();
6528: my $status;
6529: while (my ($student,$data) = each(%$classlist)) {
6530: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
6531: $data->[$status_index],
6532: $data->[$start_index],
6533: $data->[$end_index]);
6534: if ($stu_status eq 'Active') {
6535: $status = 'active';
6536: } elsif ($end < $now) {
6537: $status = 'previous';
6538: } elsif ($start > $now) {
6539: $status = 'future';
6540: }
6541: if ($section ne '-1' && $section !~ /^\s*$/) {
6542: if ((!defined($possible_status)) || (($status ne '') &&
6543: (grep/^\Q$status\E$/,@{$possible_status}))) {
6544: $sectioncount{$section}++;
6545: }
6546: }
6547: }
6548: }
6549: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6550: foreach my $user (sort(keys(%courseroles))) {
6551: if ($user !~ /^(\w{2})/) { next; }
6552: my ($role) = ($user =~ /^(\w{2})/);
6553: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
6554: my ($section,$status);
6555: if ($role eq 'cr' &&
6556: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
6557: $section=$1;
6558: }
6559: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
6560: if (!defined($section) || $section eq '-1') { next; }
6561: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
6562: if ($end == -1 && $start == -1) {
6563: next; #deleted role
6564: }
6565: if (!defined($possible_status)) {
6566: $sectioncount{$section}++;
6567: } else {
6568: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
6569: $status = 'active';
6570: } elsif ($end < $now) {
6571: $status = 'future';
6572: } elsif ($start > $now) {
6573: $status = 'previous';
6574: }
6575: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
6576: $sectioncount{$section}++;
6577: }
6578: }
6579: }
6580: return %sectioncount;
6581: }
6582:
6583: ###############################################
6584:
6585: =pod
6586:
6587: =item * &get_course_users()
6588:
6589: Retrieves usernames:domains for users in the specified course
6590: with specific role(s), and access status.
6591:
6592: Incoming parameters:
6593: 1. course domain
6594: 2. course number
6595: 3. access status: users must have - either active,
6596: previous, future, or all.
6597: 4. reference to array of permissible roles
6598: 5. reference to array of section restrictions (optional)
6599: 6. reference to results object (hash of hashes).
6600: 7. reference to optional userdata hash
6601: 8. reference to optional statushash
6602: 9. flag if privileged users (except those set to unhide in
6603: course settings) should be excluded
6604: Keys of top level results hash are roles.
6605: Keys of inner hashes are username:domain, with
6606: values set to access type.
6607: Optional userdata hash returns an array with arguments in the
6608: same order as loncoursedata::get_classlist() for student data.
6609:
6610: Optional statushash returns
6611:
6612: Entries for end, start, section and status are blank because
6613: of the possibility of multiple values for non-student roles.
6614:
6615: =cut
6616:
6617: ###############################################
6618:
6619: sub get_course_users {
6620: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
6621: my %idx = ();
6622: my %seclists;
6623:
6624: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
6625: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
6626: $idx{end} = &Apache::loncoursedata::CL_END();
6627: $idx{start} = &Apache::loncoursedata::CL_START();
6628: $idx{id} = &Apache::loncoursedata::CL_ID();
6629: $idx{section} = &Apache::loncoursedata::CL_SECTION();
6630: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
6631: $idx{status} = &Apache::loncoursedata::CL_STATUS();
6632:
6633: if (grep(/^st$/,@{$roles})) {
6634: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
6635: my $now = time;
6636: foreach my $student (keys(%{$classlist})) {
6637: my $match = 0;
6638: my $secmatch = 0;
6639: my $section = $$classlist{$student}[$idx{section}];
6640: my $status = $$classlist{$student}[$idx{status}];
6641: if ($section eq '') {
6642: $section = 'none';
6643: }
6644: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6645: if (grep(/^all$/,@{$sections})) {
6646: $secmatch = 1;
6647: } elsif ($$classlist{$student}[$idx{section}] eq '') {
6648: if (grep(/^none$/,@{$sections})) {
6649: $secmatch = 1;
6650: }
6651: } else {
6652: if (grep(/^\Q$section\E$/,@{$sections})) {
6653: $secmatch = 1;
6654: }
6655: }
6656: if (!$secmatch) {
6657: next;
6658: }
6659: }
6660: if (defined($$types{'active'})) {
6661: if ($$classlist{$student}[$idx{status}] eq 'Active') {
6662: push(@{$$users{st}{$student}},'active');
6663: $match = 1;
6664: }
6665: }
6666: if (defined($$types{'previous'})) {
6667: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
6668: push(@{$$users{st}{$student}},'previous');
6669: $match = 1;
6670: }
6671: }
6672: if (defined($$types{'future'})) {
6673: if ($$classlist{$student}[$idx{status}] eq 'Future') {
6674: push(@{$$users{st}{$student}},'future');
6675: $match = 1;
6676: }
6677: }
6678: if ($match) {
6679: push(@{$seclists{$student}},$section);
6680: if (ref($userdata) eq 'HASH') {
6681: $$userdata{$student} = $$classlist{$student};
6682: }
6683: if (ref($statushash) eq 'HASH') {
6684: $statushash->{$student}{'st'}{$section} = $status;
6685: }
6686: }
6687: }
6688: }
6689: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
6690: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
6691: my $now = time;
6692: my %displaystatus = ( previous => 'Expired',
6693: active => 'Active',
6694: future => 'Future',
6695: );
6696: my %nothide;
6697: if ($hidepriv) {
6698: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
6699: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
6700: if ($user !~ /:/) {
6701: $nothide{join(':',split(/[\@]/,$user))}=1;
6702: } else {
6703: $nothide{$user} = 1;
6704: }
6705: }
6706: }
6707: foreach my $person (sort(keys(%coursepersonnel))) {
6708: my $match = 0;
6709: my $secmatch = 0;
6710: my $status;
6711: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
6712: $user =~ s/:$//;
6713: my ($end,$start) = split(/:/,$coursepersonnel{$person});
6714: if ($end == -1 || $start == -1) {
6715: next;
6716: }
6717: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
6718: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
6719: my ($uname,$udom) = split(/:/,$user);
6720: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
6721: if (grep(/^all$/,@{$sections})) {
6722: $secmatch = 1;
6723: } elsif ($usec eq '') {
6724: if (grep(/^none$/,@{$sections})) {
6725: $secmatch = 1;
6726: }
6727: } else {
6728: if (grep(/^\Q$usec\E$/,@{$sections})) {
6729: $secmatch = 1;
6730: }
6731: }
6732: if (!$secmatch) {
6733: next;
6734: }
6735: }
6736: if ($usec eq '') {
6737: $usec = 'none';
6738: }
6739: if ($uname ne '' && $udom ne '') {
6740: if ($hidepriv) {
6741: if ((&Apache::lonnet::privileged($uname,$udom)) &&
6742: (!$nothide{$uname.':'.$udom})) {
6743: next;
6744: }
6745: }
6746: if ($end > 0 && $end < $now) {
6747: $status = 'previous';
6748: } elsif ($start > $now) {
6749: $status = 'future';
6750: } else {
6751: $status = 'active';
6752: }
6753: foreach my $type (keys(%{$types})) {
6754: if ($status eq $type) {
6755: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
6756: push(@{$$users{$role}{$user}},$type);
6757: }
6758: $match = 1;
6759: }
6760: }
6761: if (($match) && (ref($userdata) eq 'HASH')) {
6762: if (!exists($$userdata{$uname.':'.$udom})) {
6763: &get_user_info($udom,$uname,\%idx,$userdata);
6764: }
6765: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
6766: push(@{$seclists{$uname.':'.$udom}},$usec);
6767: }
6768: if (ref($statushash) eq 'HASH') {
6769: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
6770: }
6771: }
6772: }
6773: }
6774: }
6775: if (grep(/^ow$/,@{$roles})) {
6776: if ((defined($cdom)) && (defined($cnum))) {
6777: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
6778: if ( defined($csettings{'internal.courseowner'}) ) {
6779: my $owner = $csettings{'internal.courseowner'};
6780: next if ($owner eq '');
6781: my ($ownername,$ownerdom);
6782: if ($owner =~ /^([^:]+):([^:]+)$/) {
6783: $ownername = $1;
6784: $ownerdom = $2;
6785: } else {
6786: $ownername = $owner;
6787: $ownerdom = $cdom;
6788: $owner = $ownername.':'.$ownerdom;
6789: }
6790: @{$$users{'ow'}{$owner}} = 'any';
6791: if (defined($userdata) &&
6792: !exists($$userdata{$owner})) {
6793: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
6794: if (!grep(/^none$/,@{$seclists{$owner}})) {
6795: push(@{$seclists{$owner}},'none');
6796: }
6797: if (ref($statushash) eq 'HASH') {
6798: $statushash->{$owner}{'ow'}{'none'} = 'Any';
6799: }
6800: }
6801: }
6802: }
6803: }
6804: foreach my $user (keys(%seclists)) {
6805: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
6806: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
6807: }
6808: }
6809: return;
6810: }
6811:
6812: sub get_user_info {
6813: my ($udom,$uname,$idx,$userdata) = @_;
6814: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
6815: &plainname($uname,$udom,'lastname');
6816: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
6817: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
6818: my %idhash = &Apache::lonnet::idrget($udom,($uname));
6819: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
6820: return;
6821: }
6822:
6823: ###############################################
6824:
6825: =pod
6826:
6827: =item * &get_user_quota()
6828:
6829: Retrieves quota assigned for storage of portfolio files for a user
6830:
6831: Incoming parameters:
6832: 1. user's username
6833: 2. user's domain
6834:
6835: Returns:
6836: 1. Disk quota (in Mb) assigned to student.
6837: 2. (Optional) Type of setting: custom or default
6838: (individually assigned or default for user's
6839: institutional status).
6840: 3. (Optional) - User's institutional status (e.g., faculty, staff
6841: or student - types as defined in localenroll::inst_usertypes
6842: for user's domain, which determines default quota for user.
6843: 4. (Optional) - Default quota which would apply to the user.
6844:
6845: If a value has been stored in the user's environment,
6846: it will return that, otherwise it returns the maximal default
6847: defined for the user's instituional status(es) in the domain.
6848:
6849: =cut
6850:
6851: ###############################################
6852:
6853:
6854: sub get_user_quota {
6855: my ($uname,$udom) = @_;
6856: my ($quota,$quotatype,$settingstatus,$defquota);
6857: if (!defined($udom)) {
6858: $udom = $env{'user.domain'};
6859: }
6860: if (!defined($uname)) {
6861: $uname = $env{'user.name'};
6862: }
6863: if (($udom eq '' || $uname eq '') ||
6864: ($udom eq 'public') && ($uname eq 'public')) {
6865: $quota = 0;
6866: $quotatype = 'default';
6867: $defquota = 0;
6868: } else {
6869: my $inststatus;
6870: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
6871: $quota = $env{'environment.portfolioquota'};
6872: $inststatus = $env{'environment.inststatus'};
6873: } else {
6874: my %userenv =
6875: &Apache::lonnet::get('environment',['portfolioquota',
6876: 'inststatus'],$udom,$uname);
6877: my ($tmp) = keys(%userenv);
6878: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6879: $quota = $userenv{'portfolioquota'};
6880: $inststatus = $userenv{'inststatus'};
6881: } else {
6882: undef(%userenv);
6883: }
6884: }
6885: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
6886: if ($quota eq '') {
6887: $quota = $defquota;
6888: $quotatype = 'default';
6889: } else {
6890: $quotatype = 'custom';
6891: }
6892: }
6893: if (wantarray) {
6894: return ($quota,$quotatype,$settingstatus,$defquota);
6895: } else {
6896: return $quota;
6897: }
6898: }
6899:
6900: ###############################################
6901:
6902: =pod
6903:
6904: =item * &default_quota()
6905:
6906: Retrieves default quota assigned for storage of user portfolio files,
6907: given an (optional) user's institutional status.
6908:
6909: Incoming parameters:
6910: 1. domain
6911: 2. (Optional) institutional status(es). This is a : separated list of
6912: status types (e.g., faculty, staff, student etc.)
6913: which apply to the user for whom the default is being retrieved.
6914: If the institutional status string in undefined, the domain
6915: default quota will be returned.
6916:
6917: Returns:
6918: 1. Default disk quota (in Mb) for user portfolios in the domain.
6919: 2. (Optional) institutional type which determined the value of the
6920: default quota.
6921:
6922: If a value has been stored in the domain's configuration db,
6923: it will return that, otherwise it returns 20 (for backwards
6924: compatibility with domains which have not set up a configuration
6925: db file; the original statically defined portfolio quota was 20 Mb).
6926:
6927: If the user's status includes multiple types (e.g., staff and student),
6928: the largest default quota which applies to the user determines the
6929: default quota returned.
6930:
6931: =back
6932:
6933: =cut
6934:
6935: ###############################################
6936:
6937:
6938: sub default_quota {
6939: my ($udom,$inststatus) = @_;
6940: my ($defquota,$settingstatus);
6941: my %quotahash = &Apache::lonnet::get_dom('configuration',
6942: ['quotas'],$udom);
6943: if (ref($quotahash{'quotas'}) eq 'HASH') {
6944: if ($inststatus ne '') {
6945: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
6946: foreach my $item (@statuses) {
6947: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
6948: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
6949: if ($defquota eq '') {
6950: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
6951: $settingstatus = $item;
6952: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
6953: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
6954: $settingstatus = $item;
6955: }
6956: }
6957: } else {
6958: if ($quotahash{'quotas'}{$item} ne '') {
6959: if ($defquota eq '') {
6960: $defquota = $quotahash{'quotas'}{$item};
6961: $settingstatus = $item;
6962: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
6963: $defquota = $quotahash{'quotas'}{$item};
6964: $settingstatus = $item;
6965: }
6966: }
6967: }
6968: }
6969: }
6970: if ($defquota eq '') {
6971: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
6972: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
6973: } else {
6974: $defquota = $quotahash{'quotas'}{'default'};
6975: }
6976: $settingstatus = 'default';
6977: }
6978: } else {
6979: $settingstatus = 'default';
6980: $defquota = 20;
6981: }
6982: if (wantarray) {
6983: return ($defquota,$settingstatus);
6984: } else {
6985: return $defquota;
6986: }
6987: }
6988:
6989: sub get_secgrprole_info {
6990: my ($cdom,$cnum,$needroles,$type) = @_;
6991: my %sections_count = &get_sections($cdom,$cnum);
6992: my @sections = (sort {$a <=> $b} keys(%sections_count));
6993: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
6994: my @groups = sort(keys(%curr_groups));
6995: my $allroles = [];
6996: my $rolehash;
6997: my $accesshash = {
6998: active => 'Currently has access',
6999: future => 'Will have future access',
7000: previous => 'Previously had access',
7001: };
7002: if ($needroles) {
7003: $rolehash = {'all' => 'all'};
7004: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
7005: if (&Apache::lonnet::error(%user_roles)) {
7006: undef(%user_roles);
7007: }
7008: foreach my $item (keys(%user_roles)) {
7009: my ($role)=split(/\:/,$item,2);
7010: if ($role eq 'cr') { next; }
7011: if ($role =~ /^cr/) {
7012: $$rolehash{$role} = (split('/',$role))[3];
7013: } else {
7014: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
7015: }
7016: }
7017: foreach my $key (sort(keys(%{$rolehash}))) {
7018: push(@{$allroles},$key);
7019: }
7020: push (@{$allroles},'st');
7021: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
7022: }
7023: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
7024: }
7025:
7026: sub user_picker {
7027: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype) = @_;
7028: my $currdom = $dom;
7029: my %curr_selected = (
7030: srchin => 'dom',
7031: srchby => 'lastname',
7032: );
7033: my $srchterm;
7034: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
7035: if ($srch->{'srchby'} ne '') {
7036: $curr_selected{'srchby'} = $srch->{'srchby'};
7037: }
7038: if ($srch->{'srchin'} ne '') {
7039: $curr_selected{'srchin'} = $srch->{'srchin'};
7040: }
7041: if ($srch->{'srchtype'} ne '') {
7042: $curr_selected{'srchtype'} = $srch->{'srchtype'};
7043: }
7044: if ($srch->{'srchdomain'} ne '') {
7045: $currdom = $srch->{'srchdomain'};
7046: }
7047: $srchterm = $srch->{'srchterm'};
7048: }
7049: my %lt=&Apache::lonlocal::texthash(
7050: 'usr' => 'Search criteria',
7051: 'doma' => 'Domain/institution to search',
7052: 'uname' => 'username',
7053: 'lastname' => 'last name',
7054: 'lastfirst' => 'last name, first name',
7055: 'crs' => 'in this course',
7056: 'dom' => 'in selected LON-CAPA domain',
7057: 'alc' => 'all LON-CAPA',
7058: 'instd' => 'in institutional directory for selected domain',
7059: 'exact' => 'is',
7060: 'contains' => 'contains',
7061: 'begins' => 'begins with',
7062: 'youm' => "You must include some text to search for.",
7063: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
7064: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
7065: 'yomc' => "You must choose a domain when using an institutional directory search.",
7066: 'ymcd' => "You must choose a domain when using a domain search.",
7067: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
7068: 'whse' => "When searching by last,first you must include at least one character in the first name.",
7069: 'thfo' => "The following need to be corrected before the search can be run:",
7070: );
7071: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
7072: my $srchinsel = ' <select name="srchin">';
7073:
7074: my @srchins = ('crs','dom','alc','instd');
7075:
7076: foreach my $option (@srchins) {
7077: # FIXME 'alc' option unavailable until
7078: # loncreateuser::print_user_query_page()
7079: # has been completed.
7080: next if ($option eq 'alc');
7081: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
7082: next if ($option eq 'crs' && !$env{'request.course.id'});
7083: if ($curr_selected{'srchin'} eq $option) {
7084: $srchinsel .= '
7085: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7086: } else {
7087: $srchinsel .= '
7088: <option value="'.$option.'">'.$lt{$option}.'</option>';
7089: }
7090: }
7091: $srchinsel .= "\n </select>\n";
7092:
7093: my $srchbysel = ' <select name="srchby">';
7094: foreach my $option ('lastname','lastfirst','uname') {
7095: if ($curr_selected{'srchby'} eq $option) {
7096: $srchbysel .= '
7097: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7098: } else {
7099: $srchbysel .= '
7100: <option value="'.$option.'">'.$lt{$option}.'</option>';
7101: }
7102: }
7103: $srchbysel .= "\n </select>\n";
7104:
7105: my $srchtypesel = ' <select name="srchtype">';
7106: foreach my $option ('begins','contains','exact') {
7107: if ($curr_selected{'srchtype'} eq $option) {
7108: $srchtypesel .= '
7109: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
7110: } else {
7111: $srchtypesel .= '
7112: <option value="'.$option.'">'.$lt{$option}.'</option>';
7113: }
7114: }
7115: $srchtypesel .= "\n </select>\n";
7116:
7117: my ($newuserscript,$new_user_create);
7118:
7119: if ($forcenewuser) {
7120: if (ref($srch) eq 'HASH') {
7121: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $env{'request.role.domain'}) {
7122: if ($cancreate) {
7123: $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>';
7124: } else {
7125: my $helplink = 'javascript:helpMenu('."'display'".')';
7126: my %usertypetext = (
7127: official => 'institutional',
7128: unofficial => 'non-institutional',
7129: );
7130: $new_user_create = '<p class="LC_warning">'.
7131: &mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.").' '.
7132: &mt('Please contact the [_1]helpdesk[_2] for assistance.','<a href="'.$helplink.'">','</a>').'</p><br />';
7133: }
7134: }
7135: }
7136:
7137: $newuserscript = <<"ENDSCRIPT";
7138:
7139: function setSearch(createnew,callingForm) {
7140: if (createnew == 1) {
7141: for (var i=0; i<callingForm.srchby.length; i++) {
7142: if (callingForm.srchby.options[i].value == 'uname') {
7143: callingForm.srchby.selectedIndex = i;
7144: }
7145: }
7146: for (var i=0; i<callingForm.srchin.length; i++) {
7147: if ( callingForm.srchin.options[i].value == 'dom') {
7148: callingForm.srchin.selectedIndex = i;
7149: }
7150: }
7151: for (var i=0; i<callingForm.srchtype.length; i++) {
7152: if (callingForm.srchtype.options[i].value == 'exact') {
7153: callingForm.srchtype.selectedIndex = i;
7154: }
7155: }
7156: for (var i=0; i<callingForm.srchdomain.length; i++) {
7157: if (callingForm.srchdomain.options[i].value == '$env{'request.role.domain'}') {
7158: callingForm.srchdomain.selectedIndex = i;
7159: }
7160: }
7161: }
7162: }
7163: ENDSCRIPT
7164:
7165: }
7166:
7167: my $output = <<"END_BLOCK";
7168: <script type="text/javascript">
7169: // <![CDATA[
7170: function validateEntry(callingForm) {
7171:
7172: var checkok = 1;
7173: var srchin;
7174: for (var i=0; i<callingForm.srchin.length; i++) {
7175: if ( callingForm.srchin[i].checked ) {
7176: srchin = callingForm.srchin[i].value;
7177: }
7178: }
7179:
7180: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
7181: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
7182: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
7183: var srchterm = callingForm.srchterm.value;
7184: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
7185: var msg = "";
7186:
7187: if (srchterm == "") {
7188: checkok = 0;
7189: msg += "$lt{'youm'}\\n";
7190: }
7191:
7192: if (srchtype== 'begins') {
7193: if (srchterm.length < 2) {
7194: checkok = 0;
7195: msg += "$lt{'thte'}\\n";
7196: }
7197: }
7198:
7199: if (srchtype== 'contains') {
7200: if (srchterm.length < 3) {
7201: checkok = 0;
7202: msg += "$lt{'thet'}\\n";
7203: }
7204: }
7205: if (srchin == 'instd') {
7206: if (srchdomain == '') {
7207: checkok = 0;
7208: msg += "$lt{'yomc'}\\n";
7209: }
7210: }
7211: if (srchin == 'dom') {
7212: if (srchdomain == '') {
7213: checkok = 0;
7214: msg += "$lt{'ymcd'}\\n";
7215: }
7216: }
7217: if (srchby == 'lastfirst') {
7218: if (srchterm.indexOf(",") == -1) {
7219: checkok = 0;
7220: msg += "$lt{'whus'}\\n";
7221: }
7222: if (srchterm.indexOf(",") == srchterm.length -1) {
7223: checkok = 0;
7224: msg += "$lt{'whse'}\\n";
7225: }
7226: }
7227: if (checkok == 0) {
7228: alert("$lt{'thfo'}\\n"+msg);
7229: return;
7230: }
7231: if (checkok == 1) {
7232: callingForm.submit();
7233: }
7234: }
7235:
7236: $newuserscript
7237:
7238: // ]]>
7239: </script>
7240:
7241: $new_user_create
7242:
7243: END_BLOCK
7244:
7245: $output .= &Apache::lonhtmlcommon::start_pick_box().
7246: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
7247: $domform.
7248: &Apache::lonhtmlcommon::row_closure().
7249: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
7250: $srchbysel.
7251: $srchtypesel.
7252: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
7253: $srchinsel.
7254: &Apache::lonhtmlcommon::row_closure(1).
7255: &Apache::lonhtmlcommon::end_pick_box().
7256: '<br />';
7257: return $output;
7258: }
7259:
7260: sub user_rule_check {
7261: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
7262: my $response;
7263: if (ref($usershash) eq 'HASH') {
7264: foreach my $user (keys(%{$usershash})) {
7265: my ($uname,$udom) = split(/:/,$user);
7266: next if ($udom eq '' || $uname eq '');
7267: my ($id,$newuser);
7268: if (ref($usershash->{$user}) eq 'HASH') {
7269: $newuser = $usershash->{$user}->{'newuser'};
7270: $id = $usershash->{$user}->{'id'};
7271: }
7272: my $inst_response;
7273: if (ref($checks) eq 'HASH') {
7274: if (defined($checks->{'username'})) {
7275: ($inst_response,%{$inst_results->{$user}}) =
7276: &Apache::lonnet::get_instuser($udom,$uname);
7277: } elsif (defined($checks->{'id'})) {
7278: ($inst_response,%{$inst_results->{$user}}) =
7279: &Apache::lonnet::get_instuser($udom,undef,$id);
7280: }
7281: } else {
7282: ($inst_response,%{$inst_results->{$user}}) =
7283: &Apache::lonnet::get_instuser($udom,$uname);
7284: return;
7285: }
7286: if (!$got_rules->{$udom}) {
7287: my %domconfig = &Apache::lonnet::get_dom('configuration',
7288: ['usercreation'],$udom);
7289: if (ref($domconfig{'usercreation'}) eq 'HASH') {
7290: foreach my $item ('username','id') {
7291: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
7292: $$curr_rules{$udom}{$item} =
7293: $domconfig{'usercreation'}{$item.'_rule'};
7294: }
7295: }
7296: }
7297: $got_rules->{$udom} = 1;
7298: }
7299: foreach my $item (keys(%{$checks})) {
7300: if (ref($$curr_rules{$udom}) eq 'HASH') {
7301: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
7302: if (@{$$curr_rules{$udom}{$item}} > 0) {
7303: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
7304: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
7305: if ($rule_check{$rule}) {
7306: $$rulematch{$user}{$item} = $rule;
7307: if ($inst_response eq 'ok') {
7308: if (ref($inst_results) eq 'HASH') {
7309: if (ref($inst_results->{$user}) eq 'HASH') {
7310: if (keys(%{$inst_results->{$user}}) == 0) {
7311: $$alerts{$item}{$udom}{$uname} = 1;
7312: }
7313: }
7314: }
7315: }
7316: last;
7317: }
7318: }
7319: }
7320: }
7321: }
7322: }
7323: }
7324: }
7325: return;
7326: }
7327:
7328: sub user_rule_formats {
7329: my ($domain,$domdesc,$curr_rules,$check) = @_;
7330: my %text = (
7331: 'username' => 'Usernames',
7332: 'id' => 'IDs',
7333: );
7334: my $output;
7335: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
7336: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
7337: if (@{$ruleorder} > 0) {
7338: $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>';
7339: foreach my $rule (@{$ruleorder}) {
7340: if (ref($curr_rules) eq 'ARRAY') {
7341: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
7342: if (ref($rules->{$rule}) eq 'HASH') {
7343: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
7344: $rules->{$rule}{'desc'}.'</li>';
7345: }
7346: }
7347: }
7348: }
7349: $output .= '</ul>';
7350: }
7351: }
7352: return $output;
7353: }
7354:
7355: sub instrule_disallow_msg {
7356: my ($checkitem,$domdesc,$count,$mode) = @_;
7357: my $response;
7358: my %text = (
7359: item => 'username',
7360: items => 'usernames',
7361: match => 'matches',
7362: do => 'does',
7363: action => 'a username',
7364: one => 'one',
7365: );
7366: if ($count > 1) {
7367: $text{'item'} = 'usernames';
7368: $text{'match'} ='match';
7369: $text{'do'} = 'do';
7370: $text{'action'} = 'usernames',
7371: $text{'one'} = 'ones';
7372: }
7373: if ($checkitem eq 'id') {
7374: $text{'items'} = 'IDs';
7375: $text{'item'} = 'ID';
7376: $text{'action'} = 'an ID';
7377: if ($count > 1) {
7378: $text{'item'} = 'IDs';
7379: $text{'action'} = 'IDs';
7380: }
7381: }
7382: $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 />';
7383: if ($mode eq 'upload') {
7384: if ($checkitem eq 'username') {
7385: $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'}.");
7386: } elsif ($checkitem eq 'id') {
7387: $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.");
7388: }
7389: } elsif ($mode eq 'selfcreate') {
7390: if ($checkitem eq 'id') {
7391: $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.");
7392: }
7393: } else {
7394: if ($checkitem eq 'username') {
7395: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
7396: } elsif ($checkitem eq 'id') {
7397: $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.");
7398: }
7399: }
7400: return $response;
7401: }
7402:
7403: sub personal_data_fieldtitles {
7404: my %fieldtitles = &Apache::lonlocal::texthash (
7405: id => 'Student/Employee ID',
7406: permanentemail => 'E-mail address',
7407: lastname => 'Last Name',
7408: firstname => 'First Name',
7409: middlename => 'Middle Name',
7410: generation => 'Generation',
7411: gen => 'Generation',
7412: inststatus => 'Affiliation',
7413: );
7414: return %fieldtitles;
7415: }
7416:
7417: sub sorted_inst_types {
7418: my ($dom) = @_;
7419: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
7420: my $othertitle = &mt('All users');
7421: if ($env{'request.course.id'}) {
7422: $othertitle = &mt('Any users');
7423: }
7424: my @types;
7425: if (ref($order) eq 'ARRAY') {
7426: @types = @{$order};
7427: }
7428: if (@types == 0) {
7429: if (ref($usertypes) eq 'HASH') {
7430: @types = sort(keys(%{$usertypes}));
7431: }
7432: }
7433: if (keys(%{$usertypes}) > 0) {
7434: $othertitle = &mt('Other users');
7435: }
7436: return ($othertitle,$usertypes,\@types);
7437: }
7438:
7439: sub get_institutional_codes {
7440: my ($settings,$allcourses,$LC_code) = @_;
7441: # Get complete list of course sections to update
7442: my @currsections = ();
7443: my @currxlists = ();
7444: my $coursecode = $$settings{'internal.coursecode'};
7445:
7446: if ($$settings{'internal.sectionnums'} ne '') {
7447: @currsections = split(/,/,$$settings{'internal.sectionnums'});
7448: }
7449:
7450: if ($$settings{'internal.crosslistings'} ne '') {
7451: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
7452: }
7453:
7454: if (@currxlists > 0) {
7455: foreach (@currxlists) {
7456: if (m/^([^:]+):(\w*)$/) {
7457: unless (grep/^$1$/,@{$allcourses}) {
7458: push @{$allcourses},$1;
7459: $$LC_code{$1} = $2;
7460: }
7461: }
7462: }
7463: }
7464:
7465: if (@currsections > 0) {
7466: foreach (@currsections) {
7467: if (m/^(\w+):(\w*)$/) {
7468: my $sec = $coursecode.$1;
7469: my $lc_sec = $2;
7470: unless (grep/^$sec$/,@{$allcourses}) {
7471: push @{$allcourses},$sec;
7472: $$LC_code{$sec} = $lc_sec;
7473: }
7474: }
7475: }
7476: }
7477: return;
7478: }
7479:
7480: =pod
7481:
7482: =head1 Slot Helpers
7483:
7484: =over 4
7485:
7486: =item * sorted_slots()
7487:
7488: Sorts an array of slot names in order of slot start time (earliest first).
7489:
7490: Inputs:
7491:
7492: =over 4
7493:
7494: slotsarr - Reference to array of unsorted slot names.
7495:
7496: slots - Reference to hash of hash, where outer hash keys are slot names.
7497:
7498: =back
7499:
7500: Returns:
7501:
7502: =over 4
7503:
7504: sorted - An array of slot names sorted by the start time of the slot.
7505:
7506: =back
7507:
7508: =back
7509:
7510: =cut
7511:
7512:
7513: sub sorted_slots {
7514: my ($slotsarr,$slots) = @_;
7515: my @sorted;
7516: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
7517: @sorted =
7518: sort {
7519: if (ref($slots->{$a}) && ref($slots->{$b})) {
7520: return $slots->{$a}{'starttime'} <=> $slots->{$b}{'starttime'}
7521: }
7522: if (ref($slots->{$a})) { return -1;}
7523: if (ref($slots->{$b})) { return 1;}
7524: return 0;
7525: } @{$slotsarr};
7526: }
7527: return @sorted;
7528: }
7529:
7530: =pod
7531:
7532: =head1 HTTP Helpers
7533:
7534: =over 4
7535:
7536: =item * &get_unprocessed_cgi($query,$possible_names)
7537:
7538: Modify the %env hash to contain unprocessed CGI form parameters held in
7539: $query. The parameters listed in $possible_names (an array reference),
7540: will be set in $env{'form.name'} if they do not already exist.
7541:
7542: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
7543: $possible_names is an ref to an array of form element names. As an example:
7544: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
7545: will result in $env{'form.uname'} and $env{'form.udom'} being set.
7546:
7547: =cut
7548:
7549: sub get_unprocessed_cgi {
7550: my ($query,$possible_names)= @_;
7551: # $Apache::lonxml::debug=1;
7552: foreach my $pair (split(/&/,$query)) {
7553: my ($name, $value) = split(/=/,$pair);
7554: $name = &unescape($name);
7555: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
7556: $value =~ tr/+/ /;
7557: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
7558: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
7559: }
7560: }
7561: }
7562:
7563: =pod
7564:
7565: =item * &cacheheader()
7566:
7567: returns cache-controlling header code
7568:
7569: =cut
7570:
7571: sub cacheheader {
7572: unless ($env{'request.method'} eq 'GET') { return ''; }
7573: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
7574: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
7575: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
7576: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
7577: return $output;
7578: }
7579:
7580: =pod
7581:
7582: =item * &no_cache($r)
7583:
7584: specifies header code to not have cache
7585:
7586: =cut
7587:
7588: sub no_cache {
7589: my ($r) = @_;
7590: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
7591: $env{'request.method'} ne 'GET') { return ''; }
7592: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
7593: $r->no_cache(1);
7594: $r->header_out("Expires" => $date);
7595: $r->header_out("Pragma" => "no-cache");
7596: }
7597:
7598: sub content_type {
7599: my ($r,$type,$charset) = @_;
7600: if ($r) {
7601: # Note that printout.pl calls this with undef for $r.
7602: &no_cache($r);
7603: }
7604: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
7605: unless ($charset) {
7606: $charset=&Apache::lonlocal::current_encoding;
7607: }
7608: if ($charset) { $type.='; charset='.$charset; }
7609: if ($r) {
7610: $r->content_type($type);
7611: } else {
7612: print("Content-type: $type\n\n");
7613: }
7614: }
7615:
7616: =pod
7617:
7618: =item * &add_to_env($name,$value)
7619:
7620: adds $name to the %env hash with value
7621: $value, if $name already exists, the entry is converted to an array
7622: reference and $value is added to the array.
7623:
7624: =cut
7625:
7626: sub add_to_env {
7627: my ($name,$value)=@_;
7628: if (defined($env{$name})) {
7629: if (ref($env{$name})) {
7630: #already have multiple values
7631: push(@{ $env{$name} },$value);
7632: } else {
7633: #first time seeing multiple values, convert hash entry to an arrayref
7634: my $first=$env{$name};
7635: undef($env{$name});
7636: push(@{ $env{$name} },$first,$value);
7637: }
7638: } else {
7639: $env{$name}=$value;
7640: }
7641: }
7642:
7643: =pod
7644:
7645: =item * &get_env_multiple($name)
7646:
7647: gets $name from the %env hash, it seemlessly handles the cases where multiple
7648: values may be defined and end up as an array ref.
7649:
7650: returns an array of values
7651:
7652: =cut
7653:
7654: sub get_env_multiple {
7655: my ($name) = @_;
7656: my @values;
7657: if (defined($env{$name})) {
7658: # exists is it an array
7659: if (ref($env{$name})) {
7660: @values=@{ $env{$name} };
7661: } else {
7662: $values[0]=$env{$name};
7663: }
7664: }
7665: return(@values);
7666: }
7667:
7668: sub ask_for_embedded_content {
7669: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
7670: my $upload_output = '
7671: <form name="upload_embedded" action="'.$actionurl.'"
7672: method="post" enctype="multipart/form-data">';
7673: $upload_output .= $state;
7674: $upload_output .= '<b>Upload embedded files</b>:<br />'.&start_data_table();
7675:
7676: my $num = 0;
7677: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%{$allfiles})) {
7678: $upload_output .= &start_data_table_row().
7679: '<td>'.$embed_file.'</td><td>';
7680: if ($args->{'ignore_remote_references'}
7681: && $embed_file =~ m{^\w+://}) {
7682: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
7683: } elsif ($args->{'error_on_invalid_names'}
7684: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
7685:
7686: $upload_output.='<span class="LC_warning">'.&mt("Invalid characters").'</span>';
7687:
7688: } else {
7689: $upload_output .='
7690: <input name="embedded_item_'.$num.'" type="file" value="" />
7691: <input name="embedded_orig_'.$num.'" type="hidden" value="'.&escape($embed_file).'" />';
7692: my $attrib = join(':',@{$$allfiles{$embed_file}});
7693: $upload_output .=
7694: "\n\t\t".
7695: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
7696: $attrib.'" />';
7697: if (exists($$codebase{$embed_file})) {
7698: $upload_output .=
7699: "\n\t\t".
7700: '<input name="codebase_'.$num.'" type="hidden" value="'.
7701: &escape($$codebase{$embed_file}).'" />';
7702: }
7703: }
7704: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row();
7705: $num++;
7706: }
7707: $upload_output .= &Apache::loncommon::end_data_table().'<br />
7708: <input type ="hidden" name="number_embedded_items" value="'.$num.'" />
7709: <input type ="submit" value="'.&mt('Upload Listed Files').'" />
7710: '.&mt('(only files for which a location has been provided will be uploaded)').'
7711: </form>';
7712: return $upload_output;
7713: }
7714:
7715: sub upload_embedded {
7716: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
7717: $current_disk_usage) = @_;
7718: my $output;
7719: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
7720: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
7721: my $orig_uploaded_filename =
7722: $env{'form.embedded_item_'.$i.'.filename'};
7723:
7724: $env{'form.embedded_orig_'.$i} =
7725: &unescape($env{'form.embedded_orig_'.$i});
7726: my ($path,$fname) =
7727: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
7728: # no path, whole string is fname
7729: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
7730:
7731: $path = $env{'form.currentpath'}.$path;
7732: $fname = &Apache::lonnet::clean_filename($fname);
7733: # See if there is anything left
7734: next if ($fname eq '');
7735:
7736: # Check if file already exists as a file or directory.
7737: my ($state,$msg);
7738: if ($context eq 'portfolio') {
7739: my $port_path = $dirpath;
7740: if ($group ne '') {
7741: $port_path = "groups/$group/$port_path";
7742: }
7743: ($state,$msg) = &check_for_upload($path,$fname,$group,'embedded_item_'.$i,
7744: $dir_root,$port_path,$disk_quota,
7745: $current_disk_usage,$uname,$udom);
7746: if ($state eq 'will_exceed_quota'
7747: || $state eq 'file_locked'
7748: || $state eq 'file_exists' ) {
7749: $output .= $msg;
7750: next;
7751: }
7752: } elsif (($context eq 'author') || ($context eq 'testbank')) {
7753: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
7754: if ($state eq 'exists') {
7755: $output .= $msg;
7756: next;
7757: }
7758: }
7759: # Check if extension is valid
7760: if (($fname =~ /\.(\w+)$/) &&
7761: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
7762: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1);
7763: next;
7764: } elsif (($fname =~ /\.(\w+)$/) &&
7765: (!defined(&Apache::loncommon::fileembstyle($1)))) {
7766: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
7767: next;
7768: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
7769: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
7770: next;
7771: }
7772:
7773: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
7774: if ($context eq 'portfolio') {
7775: my $result=
7776: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
7777: $dirpath.$path);
7778: if ($result !~ m|^/uploaded/|) {
7779: $output .= '<span class="LC_error">'
7780: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
7781: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
7782: .'</span><br />';
7783: next;
7784: } else {
7785: $output .= '<p>'.&mt('Uploaded [_1]','<span class="LC_filename">'.
7786: $path.$fname.'</span>').'</p>';
7787: }
7788: } else {
7789: # Save the file
7790: my $target = $env{'form.embedded_item_'.$i};
7791: my $fullpath = $dir_root.$dirpath.'/'.$path;
7792: my $dest = $fullpath.$fname;
7793: my $url = $url_root.$dirpath.'/'.$path.$fname;
7794: my @parts=split(/\//,$fullpath);
7795: my $count;
7796: my $filepath = $dir_root;
7797: for ($count=4;$count<=$#parts;$count++) {
7798: $filepath .= "/$parts[$count]";
7799: if ((-e $filepath)!=1) {
7800: mkdir($filepath,0770);
7801: }
7802: }
7803: my $fh;
7804: if (!open($fh,'>'.$dest)) {
7805: &Apache::lonnet::logthis('Failed to create '.$dest);
7806: $output .= '<span class="LC_error">'.
7807: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7808: '</span><br />';
7809: } else {
7810: if (!print $fh $env{'form.embedded_item_'.$i}) {
7811: &Apache::lonnet::logthis('Failed to write to '.$dest);
7812: $output .= '<span class="LC_error">'.
7813: &mt('An error occurred while writing the file [_1] for embedded element [_2].',$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
7814: '</span><br />';
7815: } else {
7816: if ($context eq 'testbank') {
7817: $output .= &mt('Embedded file uploaded successfully:').
7818: ' <a href="'.$url.'">'.
7819: $orig_uploaded_filename.'</a><br />';
7820: } else {
7821: $output .= '<font size="+2">'.
7822: &mt('View embedded file: [_1]','<a href="'.$url.'">'.
7823: $orig_uploaded_filename.'</a>').'</font><br />';
7824: }
7825: }
7826: close($fh);
7827: }
7828: }
7829: }
7830: return $output;
7831: }
7832:
7833: sub check_for_existing {
7834: my ($path,$fname,$element) = @_;
7835: my ($state,$msg);
7836: if (-d $path.'/'.$fname) {
7837: $state = 'exists';
7838: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7839: } elsif (-e $path.'/'.$fname) {
7840: $state = 'exists';
7841: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
7842: }
7843: if ($state eq 'exists') {
7844: $msg = '<span class="LC_error">'.$msg.'</span><br />';
7845: }
7846: return ($state,$msg);
7847: }
7848:
7849: sub check_for_upload {
7850: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
7851: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
7852: my $filesize = (length($env{'form.'.$element})) / 1000; #express in k (1024?)
7853: my $getpropath = 1;
7854: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,
7855: $getpropath);
7856: my $found_file = 0;
7857: my $locked_file = 0;
7858: foreach my $line (@dir_list) {
7859: my ($file_name)=split(/\&/,$line,2);
7860: if ($file_name eq $fname){
7861: $file_name = $path.$file_name;
7862: if ($group ne '') {
7863: $file_name = $group.$file_name;
7864: }
7865: $found_file = 1;
7866: if (&Apache::lonnet::is_locked($file_name,$udom,$uname) eq 'true') {
7867: $locked_file = 1;
7868: }
7869: }
7870: }
7871: if (($current_disk_usage + $filesize) > $disk_quota){
7872: my $msg = '<span class="LC_error">'.
7873: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
7874: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
7875: return ('will_exceed_quota',$msg);
7876: } elsif ($found_file) {
7877: if ($locked_file) {
7878: my $msg = '<span class="LC_error">';
7879: $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>');
7880: $msg .= '</span><br />';
7881: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
7882: return ('file_locked',$msg);
7883: } else {
7884: my $msg = '<span class="LC_error">';
7885: $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'});
7886: $msg .= '</span>';
7887: $msg .= '<br />';
7888: $msg .= &mt('To upload, rename or delete existing [_1] in [_2].','<span class="LC_filename">'.$fname.'</span>', $port_path.$env{'form.currentpath'});
7889: return ('file_exists',$msg);
7890: }
7891: }
7892: }
7893:
7894:
7895: =pod
7896:
7897: =back
7898:
7899: =head1 CSV Upload/Handling functions
7900:
7901: =over 4
7902:
7903: =item * &upfile_store($r)
7904:
7905: Store uploaded file, $r should be the HTTP Request object,
7906: needs $env{'form.upfile'}
7907: returns $datatoken to be put into hidden field
7908:
7909: =cut
7910:
7911: sub upfile_store {
7912: my $r=shift;
7913: $env{'form.upfile'}=~s/\r/\n/gs;
7914: $env{'form.upfile'}=~s/\f/\n/gs;
7915: $env{'form.upfile'}=~s/\n+/\n/gs;
7916: $env{'form.upfile'}=~s/\n+$//gs;
7917:
7918: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
7919: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
7920: {
7921: my $datafile = $r->dir_config('lonDaemons').
7922: '/tmp/'.$datatoken.'.tmp';
7923: if ( open(my $fh,">$datafile") ) {
7924: print $fh $env{'form.upfile'};
7925: close($fh);
7926: }
7927: }
7928: return $datatoken;
7929: }
7930:
7931: =pod
7932:
7933: =item * &load_tmp_file($r)
7934:
7935: Load uploaded file from tmp, $r should be the HTTP Request object,
7936: needs $env{'form.datatoken'},
7937: sets $env{'form.upfile'} to the contents of the file
7938:
7939: =cut
7940:
7941: sub load_tmp_file {
7942: my $r=shift;
7943: my @studentdata=();
7944: {
7945: my $studentfile = $r->dir_config('lonDaemons').
7946: '/tmp/'.$env{'form.datatoken'}.'.tmp';
7947: if ( open(my $fh,"<$studentfile") ) {
7948: @studentdata=<$fh>;
7949: close($fh);
7950: }
7951: }
7952: $env{'form.upfile'}=join('',@studentdata);
7953: }
7954:
7955: =pod
7956:
7957: =item * &upfile_record_sep()
7958:
7959: Separate uploaded file into records
7960: returns array of records,
7961: needs $env{'form.upfile'} and $env{'form.upfiletype'}
7962:
7963: =cut
7964:
7965: sub upfile_record_sep {
7966: if ($env{'form.upfiletype'} eq 'xml') {
7967: } else {
7968: my @records;
7969: foreach my $line (split(/\n/,$env{'form.upfile'})) {
7970: if ($line=~/^\s*$/) { next; }
7971: push(@records,$line);
7972: }
7973: return @records;
7974: }
7975: }
7976:
7977: =pod
7978:
7979: =item * &record_sep($record)
7980:
7981: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
7982:
7983: =cut
7984:
7985: sub takeleft {
7986: my $index=shift;
7987: return substr('0000'.$index,-4,4);
7988: }
7989:
7990: sub record_sep {
7991: my $record=shift;
7992: my %components=();
7993: if ($env{'form.upfiletype'} eq 'xml') {
7994: } elsif ($env{'form.upfiletype'} eq 'space') {
7995: my $i=0;
7996: foreach my $field (split(/\s+/,$record)) {
7997: $field=~s/^(\"|\')//;
7998: $field=~s/(\"|\')$//;
7999: $components{&takeleft($i)}=$field;
8000: $i++;
8001: }
8002: } elsif ($env{'form.upfiletype'} eq 'tab') {
8003: my $i=0;
8004: foreach my $field (split(/\t/,$record)) {
8005: $field=~s/^(\"|\')//;
8006: $field=~s/(\"|\')$//;
8007: $components{&takeleft($i)}=$field;
8008: $i++;
8009: }
8010: } else {
8011: my $separator=',';
8012: if ($env{'form.upfiletype'} eq 'semisv') {
8013: $separator=';';
8014: }
8015: my $i=0;
8016: # the character we are looking for to indicate the end of a quote or a record
8017: my $looking_for=$separator;
8018: # do not add the characters to the fields
8019: my $ignore=0;
8020: # we just encountered a separator (or the beginning of the record)
8021: my $just_found_separator=1;
8022: # store the field we are working on here
8023: my $field='';
8024: # work our way through all characters in record
8025: foreach my $character ($record=~/(.)/g) {
8026: if ($character eq $looking_for) {
8027: if ($character ne $separator) {
8028: # Found the end of a quote, again looking for separator
8029: $looking_for=$separator;
8030: $ignore=1;
8031: } else {
8032: # Found a separator, store away what we got
8033: $components{&takeleft($i)}=$field;
8034: $i++;
8035: $just_found_separator=1;
8036: $ignore=0;
8037: $field='';
8038: }
8039: next;
8040: }
8041: # single or double quotation marks after a separator indicate beginning of a quote
8042: # we are now looking for the end of the quote and need to ignore separators
8043: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
8044: $looking_for=$character;
8045: next;
8046: }
8047: # ignore would be true after we reached the end of a quote
8048: if ($ignore) { next; }
8049: if (($just_found_separator) && ($character=~/\s/)) { next; }
8050: $field.=$character;
8051: $just_found_separator=0;
8052: }
8053: # catch the very last entry, since we never encountered the separator
8054: $components{&takeleft($i)}=$field;
8055: }
8056: return %components;
8057: }
8058:
8059: ######################################################
8060: ######################################################
8061:
8062: =pod
8063:
8064: =item * &upfile_select_html()
8065:
8066: Return HTML code to select a file from the users machine and specify
8067: the file type.
8068:
8069: =cut
8070:
8071: ######################################################
8072: ######################################################
8073: sub upfile_select_html {
8074: my %Types = (
8075: csv => &mt('CSV (comma separated values, spreadsheet)'),
8076: semisv => &mt('Semicolon separated values'),
8077: space => &mt('Space separated'),
8078: tab => &mt('Tabulator separated'),
8079: # xml => &mt('HTML/XML'),
8080: );
8081: my $Str = '<input type="file" name="upfile" size="50" />'.
8082: '<br />'.&mt('Type').': <select name="upfiletype">';
8083: foreach my $type (sort(keys(%Types))) {
8084: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
8085: }
8086: $Str .= "</select>\n";
8087: return $Str;
8088: }
8089:
8090: sub get_samples {
8091: my ($records,$toget) = @_;
8092: my @samples=({});
8093: my $got=0;
8094: foreach my $rec (@$records) {
8095: my %temp = &record_sep($rec);
8096: if (! grep(/\S/, values(%temp))) { next; }
8097: if (%temp) {
8098: $samples[$got]=\%temp;
8099: $got++;
8100: if ($got == $toget) { last; }
8101: }
8102: }
8103: return \@samples;
8104: }
8105:
8106: ######################################################
8107: ######################################################
8108:
8109: =pod
8110:
8111: =item * &csv_print_samples($r,$records)
8112:
8113: Prints a table of sample values from each column uploaded $r is an
8114: Apache Request ref, $records is an arrayref from
8115: &Apache::loncommon::upfile_record_sep
8116:
8117: =cut
8118:
8119: ######################################################
8120: ######################################################
8121: sub csv_print_samples {
8122: my ($r,$records) = @_;
8123: my $samples = &get_samples($records,5);
8124:
8125: $r->print(&mt('Samples').'<br />'.&start_data_table().
8126: &start_data_table_header_row());
8127: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8128: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>');
8129: }
8130: $r->print(&end_data_table_header_row());
8131: foreach my $hash (@$samples) {
8132: $r->print(&start_data_table_row());
8133: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8134: $r->print('<td>');
8135: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
8136: $r->print('</td>');
8137: }
8138: $r->print(&end_data_table_row());
8139: }
8140: $r->print(&end_data_table().'<br />'."\n");
8141: }
8142:
8143: ######################################################
8144: ######################################################
8145:
8146: =pod
8147:
8148: =item * &csv_print_select_table($r,$records,$d)
8149:
8150: Prints a table to create associations between values and table columns.
8151:
8152: $r is an Apache Request ref,
8153: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8154: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
8155:
8156: =cut
8157:
8158: ######################################################
8159: ######################################################
8160: sub csv_print_select_table {
8161: my ($r,$records,$d) = @_;
8162: my $i=0;
8163: my $samples = &get_samples($records,1);
8164: $r->print(&mt('Associate columns with student attributes.')."\n".
8165: &start_data_table().&start_data_table_header_row().
8166: '<th>'.&mt('Attribute').'</th>'.
8167: '<th>'.&mt('Column').'</th>'.
8168: &end_data_table_header_row()."\n");
8169: foreach my $array_ref (@$d) {
8170: my ($value,$display,$defaultcol)=@{ $array_ref };
8171: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
8172:
8173: $r->print('<td><select name"f'.$i.'"'.
8174: ' onchange="javascript:flip(this.form,'.$i.');">');
8175: $r->print('<option value="none"></option>');
8176: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
8177: $r->print('<option value="'.$sample.'"'.
8178: ($sample eq $defaultcol ? ' selected="selected" ' : '').
8179: '>'.&mt('Column [_1]',($sample+1)).'</option>');
8180: }
8181: $r->print('</select></td>'.&end_data_table_row()."\n");
8182: $i++;
8183: }
8184: $r->print(&end_data_table());
8185: $i--;
8186: return $i;
8187: }
8188:
8189: ######################################################
8190: ######################################################
8191:
8192: =pod
8193:
8194: =item * &csv_samples_select_table($r,$records,$d)
8195:
8196: Prints a table of sample values from the upload and can make associate samples to internal names.
8197:
8198: $r is an Apache Request ref,
8199: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
8200: $d is an array of 2 element arrays (internal name, displayed name)
8201:
8202: =cut
8203:
8204: ######################################################
8205: ######################################################
8206: sub csv_samples_select_table {
8207: my ($r,$records,$d) = @_;
8208: my $i=0;
8209: #
8210: my $max_samples = 5;
8211: my $samples = &get_samples($records,$max_samples);
8212: $r->print(&start_data_table().
8213: &start_data_table_header_row().'<th>'.
8214: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
8215: &end_data_table_header_row());
8216:
8217: foreach my $key (sort(keys(%{ $samples->[0] }))) {
8218: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
8219: ' onchange="javascript:flip(this.form,'.$i.');">');
8220: foreach my $option (@$d) {
8221: my ($value,$display,$defaultcol)=@{ $option };
8222: $r->print('<option value="'.$value.'"'.
8223: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
8224: $display.'</option>');
8225: }
8226: $r->print('</select></td><td>');
8227: foreach my $line (0..($max_samples-1)) {
8228: if (defined($samples->[$line]{$key})) {
8229: $r->print($samples->[$line]{$key}."<br />\n");
8230: }
8231: }
8232: $r->print('</td>'.&end_data_table_row());
8233: $i++;
8234: }
8235: $r->print(&end_data_table());
8236: $i--;
8237: return($i);
8238: }
8239:
8240: ######################################################
8241: ######################################################
8242:
8243: =pod
8244:
8245: =item * &clean_excel_name($name)
8246:
8247: Returns a replacement for $name which does not contain any illegal characters.
8248:
8249: =cut
8250:
8251: ######################################################
8252: ######################################################
8253: sub clean_excel_name {
8254: my ($name) = @_;
8255: $name =~ s/[:\*\?\/\\]//g;
8256: if (length($name) > 31) {
8257: $name = substr($name,0,31);
8258: }
8259: return $name;
8260: }
8261:
8262: =pod
8263:
8264: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
8265:
8266: Returns either 1 or undef
8267:
8268: 1 if the part is to be hidden, undef if it is to be shown
8269:
8270: Arguments are:
8271:
8272: $id the id of the part to be checked
8273: $symb, optional the symb of the resource to check
8274: $udom, optional the domain of the user to check for
8275: $uname, optional the username of the user to check for
8276:
8277: =cut
8278:
8279: sub check_if_partid_hidden {
8280: my ($id,$symb,$udom,$uname) = @_;
8281: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
8282: $symb,$udom,$uname);
8283: my $truth=1;
8284: #if the string starts with !, then the list is the list to show not hide
8285: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
8286: my @hiddenlist=split(/,/,$hiddenparts);
8287: foreach my $checkid (@hiddenlist) {
8288: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
8289: }
8290: return !$truth;
8291: }
8292:
8293:
8294: ############################################################
8295: ############################################################
8296:
8297: =pod
8298:
8299: =back
8300:
8301: =head1 cgi-bin script and graphing routines
8302:
8303: =over 4
8304:
8305: =item * &get_cgi_id()
8306:
8307: Inputs: none
8308:
8309: Returns an id which can be used to pass environment variables
8310: to various cgi-bin scripts. These environment variables will
8311: be removed from the users environment after a given time by
8312: the routine &Apache::lonnet::transfer_profile_to_env.
8313:
8314: =cut
8315:
8316: ############################################################
8317: ############################################################
8318: my $uniq=0;
8319: sub get_cgi_id {
8320: $uniq=($uniq+1)%100000;
8321: return (time.'_'.$$.'_'.$uniq);
8322: }
8323:
8324: ############################################################
8325: ############################################################
8326:
8327: =pod
8328:
8329: =item * &DrawBarGraph()
8330:
8331: Facilitates the plotting of data in a (stacked) bar graph.
8332: Puts plot definition data into the users environment in order for
8333: graph.png to plot it. Returns an <img> tag for the plot.
8334: The bars on the plot are labeled '1','2',...,'n'.
8335:
8336: Inputs:
8337:
8338: =over 4
8339:
8340: =item $Title: string, the title of the plot
8341:
8342: =item $xlabel: string, text describing the X-axis of the plot
8343:
8344: =item $ylabel: string, text describing the Y-axis of the plot
8345:
8346: =item $Max: scalar, the maximum Y value to use in the plot
8347: If $Max is < any data point, the graph will not be rendered.
8348:
8349: =item $colors: array ref holding the colors to be used for the data sets when
8350: they are plotted. If undefined, default values will be used.
8351:
8352: =item $labels: array ref holding the labels to use on the x-axis for the bars.
8353:
8354: =item @Values: An array of array references. Each array reference holds data
8355: to be plotted in a stacked bar chart.
8356:
8357: =item If the final element of @Values is a hash reference the key/value
8358: pairs will be added to the graph definition.
8359:
8360: =back
8361:
8362: Returns:
8363:
8364: An <img> tag which references graph.png and the appropriate identifying
8365: information for the plot.
8366:
8367: =cut
8368:
8369: ############################################################
8370: ############################################################
8371: sub DrawBarGraph {
8372: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
8373: #
8374: if (! defined($colors)) {
8375: $colors = ['#33ff00',
8376: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
8377: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
8378: ];
8379: }
8380: my $extra_settings = {};
8381: if (ref($Values[-1]) eq 'HASH') {
8382: $extra_settings = pop(@Values);
8383: }
8384: #
8385: my $identifier = &get_cgi_id();
8386: my $id = 'cgi.'.$identifier;
8387: if (! @Values || ref($Values[0]) ne 'ARRAY') {
8388: return '';
8389: }
8390: #
8391: my @Labels;
8392: if (defined($labels)) {
8393: @Labels = @$labels;
8394: } else {
8395: for (my $i=0;$i<@{$Values[0]};$i++) {
8396: push (@Labels,$i+1);
8397: }
8398: }
8399: #
8400: my $NumBars = scalar(@{$Values[0]});
8401: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
8402: my %ValuesHash;
8403: my $NumSets=1;
8404: foreach my $array (@Values) {
8405: next if (! ref($array));
8406: $ValuesHash{$id.'.data.'.$NumSets++} =
8407: join(',',@$array);
8408: }
8409: #
8410: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
8411: if ($NumBars < 3) {
8412: $width = 120+$NumBars*32;
8413: $xskip = 1;
8414: $bar_width = 30;
8415: } elsif ($NumBars < 5) {
8416: $width = 120+$NumBars*20;
8417: $xskip = 1;
8418: $bar_width = 20;
8419: } elsif ($NumBars < 10) {
8420: $width = 120+$NumBars*15;
8421: $xskip = 1;
8422: $bar_width = 15;
8423: } elsif ($NumBars <= 25) {
8424: $width = 120+$NumBars*11;
8425: $xskip = 5;
8426: $bar_width = 8;
8427: } elsif ($NumBars <= 50) {
8428: $width = 120+$NumBars*8;
8429: $xskip = 5;
8430: $bar_width = 4;
8431: } else {
8432: $width = 120+$NumBars*8;
8433: $xskip = 5;
8434: $bar_width = 4;
8435: }
8436: #
8437: $Max = 1 if ($Max < 1);
8438: if ( int($Max) < $Max ) {
8439: $Max++;
8440: $Max = int($Max);
8441: }
8442: $Title = '' if (! defined($Title));
8443: $xlabel = '' if (! defined($xlabel));
8444: $ylabel = '' if (! defined($ylabel));
8445: $ValuesHash{$id.'.title'} = &escape($Title);
8446: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
8447: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
8448: $ValuesHash{$id.'.y_max_value'} = $Max;
8449: $ValuesHash{$id.'.NumBars'} = $NumBars;
8450: $ValuesHash{$id.'.NumSets'} = $NumSets;
8451: $ValuesHash{$id.'.PlotType'} = 'bar';
8452: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8453: $ValuesHash{$id.'.height'} = $height;
8454: $ValuesHash{$id.'.width'} = $width;
8455: $ValuesHash{$id.'.xskip'} = $xskip;
8456: $ValuesHash{$id.'.bar_width'} = $bar_width;
8457: $ValuesHash{$id.'.labels'} = join(',',@Labels);
8458: #
8459: # Deal with other parameters
8460: while (my ($key,$value) = each(%$extra_settings)) {
8461: $ValuesHash{$id.'.'.$key} = $value;
8462: }
8463: #
8464: &Apache::lonnet::appenv(\%ValuesHash);
8465: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8466: }
8467:
8468: ############################################################
8469: ############################################################
8470:
8471: =pod
8472:
8473: =item * &DrawXYGraph()
8474:
8475: Facilitates the plotting of data in an XY graph.
8476: Puts plot definition data into the users environment in order for
8477: graph.png to plot it. Returns an <img> tag for the plot.
8478:
8479: Inputs:
8480:
8481: =over 4
8482:
8483: =item $Title: string, the title of the plot
8484:
8485: =item $xlabel: string, text describing the X-axis of the plot
8486:
8487: =item $ylabel: string, text describing the Y-axis of the plot
8488:
8489: =item $Max: scalar, the maximum Y value to use in the plot
8490: If $Max is < any data point, the graph will not be rendered.
8491:
8492: =item $colors: Array ref containing the hex color codes for the data to be
8493: plotted in. If undefined, default values will be used.
8494:
8495: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8496:
8497: =item $Ydata: Array ref containing Array refs.
8498: Each of the contained arrays will be plotted as a separate curve.
8499:
8500: =item %Values: hash indicating or overriding any default values which are
8501: passed to graph.png.
8502: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8503:
8504: =back
8505:
8506: Returns:
8507:
8508: An <img> tag which references graph.png and the appropriate identifying
8509: information for the plot.
8510:
8511: =cut
8512:
8513: ############################################################
8514: ############################################################
8515: sub DrawXYGraph {
8516: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
8517: #
8518: # Create the identifier for the graph
8519: my $identifier = &get_cgi_id();
8520: my $id = 'cgi.'.$identifier;
8521: #
8522: $Title = '' if (! defined($Title));
8523: $xlabel = '' if (! defined($xlabel));
8524: $ylabel = '' if (! defined($ylabel));
8525: my %ValuesHash =
8526: (
8527: $id.'.title' => &escape($Title),
8528: $id.'.xlabel' => &escape($xlabel),
8529: $id.'.ylabel' => &escape($ylabel),
8530: $id.'.y_max_value'=> $Max,
8531: $id.'.labels' => join(',',@$Xlabels),
8532: $id.'.PlotType' => 'XY',
8533: );
8534: #
8535: if (defined($colors) && ref($colors) eq 'ARRAY') {
8536: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8537: }
8538: #
8539: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
8540: return '';
8541: }
8542: my $NumSets=1;
8543: foreach my $array (@{$Ydata}){
8544: next if (! ref($array));
8545: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8546: }
8547: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
8548: #
8549: # Deal with other parameters
8550: while (my ($key,$value) = each(%Values)) {
8551: $ValuesHash{$id.'.'.$key} = $value;
8552: }
8553: #
8554: &Apache::lonnet::appenv(\%ValuesHash);
8555: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8556: }
8557:
8558: ############################################################
8559: ############################################################
8560:
8561: =pod
8562:
8563: =item * &DrawXYYGraph()
8564:
8565: Facilitates the plotting of data in an XY graph with two Y axes.
8566: Puts plot definition data into the users environment in order for
8567: graph.png to plot it. Returns an <img> tag for the plot.
8568:
8569: Inputs:
8570:
8571: =over 4
8572:
8573: =item $Title: string, the title of the plot
8574:
8575: =item $xlabel: string, text describing the X-axis of the plot
8576:
8577: =item $ylabel: string, text describing the Y-axis of the plot
8578:
8579: =item $colors: Array ref containing the hex color codes for the data to be
8580: plotted in. If undefined, default values will be used.
8581:
8582: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
8583:
8584: =item $Ydata1: The first data set
8585:
8586: =item $Min1: The minimum value of the left Y-axis
8587:
8588: =item $Max1: The maximum value of the left Y-axis
8589:
8590: =item $Ydata2: The second data set
8591:
8592: =item $Min2: The minimum value of the right Y-axis
8593:
8594: =item $Max2: The maximum value of the left Y-axis
8595:
8596: =item %Values: hash indicating or overriding any default values which are
8597: passed to graph.png.
8598: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
8599:
8600: =back
8601:
8602: Returns:
8603:
8604: An <img> tag which references graph.png and the appropriate identifying
8605: information for the plot.
8606:
8607: =cut
8608:
8609: ############################################################
8610: ############################################################
8611: sub DrawXYYGraph {
8612: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
8613: $Ydata2,$Min2,$Max2,%Values)=@_;
8614: #
8615: # Create the identifier for the graph
8616: my $identifier = &get_cgi_id();
8617: my $id = 'cgi.'.$identifier;
8618: #
8619: $Title = '' if (! defined($Title));
8620: $xlabel = '' if (! defined($xlabel));
8621: $ylabel = '' if (! defined($ylabel));
8622: my %ValuesHash =
8623: (
8624: $id.'.title' => &escape($Title),
8625: $id.'.xlabel' => &escape($xlabel),
8626: $id.'.ylabel' => &escape($ylabel),
8627: $id.'.labels' => join(',',@$Xlabels),
8628: $id.'.PlotType' => 'XY',
8629: $id.'.NumSets' => 2,
8630: $id.'.two_axes' => 1,
8631: $id.'.y1_max_value' => $Max1,
8632: $id.'.y1_min_value' => $Min1,
8633: $id.'.y2_max_value' => $Max2,
8634: $id.'.y2_min_value' => $Min2,
8635: );
8636: #
8637: if (defined($colors) && ref($colors) eq 'ARRAY') {
8638: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
8639: }
8640: #
8641: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
8642: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
8643: return '';
8644: }
8645: my $NumSets=1;
8646: foreach my $array ($Ydata1,$Ydata2){
8647: next if (! ref($array));
8648: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
8649: }
8650: #
8651: # Deal with other parameters
8652: while (my ($key,$value) = each(%Values)) {
8653: $ValuesHash{$id.'.'.$key} = $value;
8654: }
8655: #
8656: &Apache::lonnet::appenv(\%ValuesHash);
8657: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
8658: }
8659:
8660: ############################################################
8661: ############################################################
8662:
8663: =pod
8664:
8665: =back
8666:
8667: =head1 Statistics helper routines?
8668:
8669: Bad place for them but what the hell.
8670:
8671: =over 4
8672:
8673: =item * &chartlink()
8674:
8675: Returns a link to the chart for a specific student.
8676:
8677: Inputs:
8678:
8679: =over 4
8680:
8681: =item $linktext: The text of the link
8682:
8683: =item $sname: The students username
8684:
8685: =item $sdomain: The students domain
8686:
8687: =back
8688:
8689: =back
8690:
8691: =cut
8692:
8693: ############################################################
8694: ############################################################
8695: sub chartlink {
8696: my ($linktext, $sname, $sdomain) = @_;
8697: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
8698: '&SelectedStudent='.&escape($sname.':'.$sdomain).
8699: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
8700: '">'.$linktext.'</a>';
8701: }
8702:
8703: #######################################################
8704: #######################################################
8705:
8706: =pod
8707:
8708: =head1 Course Environment Routines
8709:
8710: =over 4
8711:
8712: =item * &restore_course_settings()
8713:
8714: =item * &store_course_settings()
8715:
8716: Restores/Store indicated form parameters from the course environment.
8717: Will not overwrite existing values of the form parameters.
8718:
8719: Inputs:
8720: a scalar describing the data (e.g. 'chart', 'problem_analysis')
8721:
8722: a hash ref describing the data to be stored. For example:
8723:
8724: %Save_Parameters = ('Status' => 'scalar',
8725: 'chartoutputmode' => 'scalar',
8726: 'chartoutputdata' => 'scalar',
8727: 'Section' => 'array',
8728: 'Group' => 'array',
8729: 'StudentData' => 'array',
8730: 'Maps' => 'array');
8731:
8732: Returns: both routines return nothing
8733:
8734: =back
8735:
8736: =cut
8737:
8738: #######################################################
8739: #######################################################
8740: sub store_course_settings {
8741: return &store_settings($env{'request.course.id'},@_);
8742: }
8743:
8744: sub store_settings {
8745: # save to the environment
8746: # appenv the same items, just to be safe
8747: my $udom = $env{'user.domain'};
8748: my $uname = $env{'user.name'};
8749: my ($context,$prefix,$Settings) = @_;
8750: my %SaveHash;
8751: my %AppHash;
8752: while (my ($setting,$type) = each(%$Settings)) {
8753: my $basename = join('.','internal',$context,$prefix,$setting);
8754: my $envname = 'environment.'.$basename;
8755: if (exists($env{'form.'.$setting})) {
8756: # Save this value away
8757: if ($type eq 'scalar' &&
8758: (! exists($env{$envname}) ||
8759: $env{$envname} ne $env{'form.'.$setting})) {
8760: $SaveHash{$basename} = $env{'form.'.$setting};
8761: $AppHash{$envname} = $env{'form.'.$setting};
8762: } elsif ($type eq 'array') {
8763: my $stored_form;
8764: if (ref($env{'form.'.$setting})) {
8765: $stored_form = join(',',
8766: map {
8767: &escape($_);
8768: } sort(@{$env{'form.'.$setting}}));
8769: } else {
8770: $stored_form =
8771: &escape($env{'form.'.$setting});
8772: }
8773: # Determine if the array contents are the same.
8774: if ($stored_form ne $env{$envname}) {
8775: $SaveHash{$basename} = $stored_form;
8776: $AppHash{$envname} = $stored_form;
8777: }
8778: }
8779: }
8780: }
8781: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
8782: $udom,$uname);
8783: if ($put_result !~ /^(ok|delayed)/) {
8784: &Apache::lonnet::logthis('unable to save form parameters, '.
8785: 'got error:'.$put_result);
8786: }
8787: # Make sure these settings stick around in this session, too
8788: &Apache::lonnet::appenv(\%AppHash);
8789: return;
8790: }
8791:
8792: sub restore_course_settings {
8793: return &restore_settings($env{'request.course.id'},@_);
8794: }
8795:
8796: sub restore_settings {
8797: my ($context,$prefix,$Settings) = @_;
8798: while (my ($setting,$type) = each(%$Settings)) {
8799: next if (exists($env{'form.'.$setting}));
8800: my $envname = 'environment.internal.'.$context.'.'.$prefix.
8801: '.'.$setting;
8802: if (exists($env{$envname})) {
8803: if ($type eq 'scalar') {
8804: $env{'form.'.$setting} = $env{$envname};
8805: } elsif ($type eq 'array') {
8806: $env{'form.'.$setting} = [
8807: map {
8808: &unescape($_);
8809: } split(',',$env{$envname})
8810: ];
8811: }
8812: }
8813: }
8814: }
8815:
8816: #######################################################
8817: #######################################################
8818:
8819: =pod
8820:
8821: =head1 Domain E-mail Routines
8822:
8823: =over 4
8824:
8825: =item * &build_recipient_list()
8826:
8827: Build recipient lists for five types of e-mail:
8828: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
8829: (d) Help requests, (e) Course requests needing approval, generated by
8830: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
8831: loncoursequeueadmin.pm respectively.
8832:
8833: Inputs:
8834: defmail (scalar - email address of default recipient),
8835: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
8836: defdom (domain for which to retrieve configuration settings),
8837: origmail (scalar - email address of recipient from loncapa.conf,
8838: i.e., predates configuration by DC via domainprefs.pm
8839:
8840: Returns: comma separated list of addresses to which to send e-mail.
8841:
8842: =back
8843:
8844: =cut
8845:
8846: ############################################################
8847: ############################################################
8848: sub build_recipient_list {
8849: my ($defmail,$mailing,$defdom,$origmail) = @_;
8850: my @recipients;
8851: my $otheremails;
8852: my %domconfig =
8853: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
8854: if (ref($domconfig{'contacts'}) eq 'HASH') {
8855: if (exists($domconfig{'contacts'}{$mailing})) {
8856: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
8857: my @contacts = ('adminemail','supportemail');
8858: foreach my $item (@contacts) {
8859: if ($domconfig{'contacts'}{$mailing}{$item}) {
8860: my $addr = $domconfig{'contacts'}{$item};
8861: if (!grep(/^\Q$addr\E$/,@recipients)) {
8862: push(@recipients,$addr);
8863: }
8864: }
8865: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
8866: }
8867: }
8868: } elsif ($origmail ne '') {
8869: push(@recipients,$origmail);
8870: }
8871: } elsif ($origmail ne '') {
8872: push(@recipients,$origmail);
8873: }
8874: if (defined($defmail)) {
8875: if ($defmail ne '') {
8876: push(@recipients,$defmail);
8877: }
8878: }
8879: if ($otheremails) {
8880: my @others;
8881: if ($otheremails =~ /,/) {
8882: @others = split(/,/,$otheremails);
8883: } else {
8884: push(@others,$otheremails);
8885: }
8886: foreach my $addr (@others) {
8887: if (!grep(/^\Q$addr\E$/,@recipients)) {
8888: push(@recipients,$addr);
8889: }
8890: }
8891: }
8892: my $recipientlist = join(',',@recipients);
8893: return $recipientlist;
8894: }
8895:
8896: ############################################################
8897: ############################################################
8898:
8899: =pod
8900:
8901: =head1 Course Catalog Routines
8902:
8903: =over 4
8904:
8905: =item * &gather_categories()
8906:
8907: Converts category definitions - keys of categories hash stored in
8908: coursecategories in configuration.db on the primary library server in a
8909: domain - to an array. Also generates javascript and idx hash used to
8910: generate Domain Coordinator interface for editing Course Categories.
8911:
8912: Inputs:
8913:
8914: categories (reference to hash of category definitions).
8915:
8916: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8917: categories and subcategories).
8918:
8919: idx (reference to hash of counters used in Domain Coordinator interface for
8920: editing Course Categories).
8921:
8922: jsarray (reference to array of categories used to create Javascript arrays for
8923: Domain Coordinator interface for editing Course Categories).
8924:
8925: Returns: nothing
8926:
8927: Side effects: populates cats, idx and jsarray.
8928:
8929: =cut
8930:
8931: sub gather_categories {
8932: my ($categories,$cats,$idx,$jsarray) = @_;
8933: my %counters;
8934: my $num = 0;
8935: foreach my $item (keys(%{$categories})) {
8936: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
8937: if ($container eq '' && $depth == 0) {
8938: $cats->[$depth][$categories->{$item}] = $cat;
8939: } else {
8940: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
8941: }
8942: my ($escitem,$tail) = split(/:/,$item,2);
8943: if ($counters{$tail} eq '') {
8944: $counters{$tail} = $num;
8945: $num ++;
8946: }
8947: if (ref($idx) eq 'HASH') {
8948: $idx->{$item} = $counters{$tail};
8949: }
8950: if (ref($jsarray) eq 'ARRAY') {
8951: push(@{$jsarray->[$counters{$tail}]},$item);
8952: }
8953: }
8954: return;
8955: }
8956:
8957: =pod
8958:
8959: =item * &extract_categories()
8960:
8961: Used to generate breadcrumb trails for course categories.
8962:
8963: Inputs:
8964:
8965: categories (reference to hash of category definitions).
8966:
8967: cats (reference to array of arrays/hashes which encapsulates hierarchy of
8968: categories and subcategories).
8969:
8970: trails (reference to array of breacrumb trails for each category).
8971:
8972: allitems (reference to hash - key is category key
8973: (format: escaped(name):escaped(parent category):depth in hierarchy).
8974:
8975: idx (reference to hash of counters used in Domain Coordinator interface for
8976: editing Course Categories).
8977:
8978: jsarray (reference to array of categories used to create Javascript arrays for
8979: Domain Coordinator interface for editing Course Categories).
8980:
8981: subcats (reference to hash of arrays containing all subcategories within each
8982: category, -recursive)
8983:
8984: Returns: nothing
8985:
8986: Side effects: populates trails and allitems hash references.
8987:
8988: =cut
8989:
8990: sub extract_categories {
8991: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
8992: if (ref($categories) eq 'HASH') {
8993: &gather_categories($categories,$cats,$idx,$jsarray);
8994: if (ref($cats->[0]) eq 'ARRAY') {
8995: for (my $i=0; $i<@{$cats->[0]}; $i++) {
8996: my $name = $cats->[0][$i];
8997: my $item = &escape($name).'::0';
8998: my $trailstr;
8999: if ($name eq 'instcode') {
9000: $trailstr = &mt('Official courses (with institutional codes)');
9001: } elsif ($name eq 'communities') {
9002: $trailstr = &mt('Communities');
9003: } else {
9004: $trailstr = $name;
9005: }
9006: if ($allitems->{$item} eq '') {
9007: push(@{$trails},$trailstr);
9008: $allitems->{$item} = scalar(@{$trails})-1;
9009: }
9010: my @parents = ($name);
9011: if (ref($cats->[1]{$name}) eq 'ARRAY') {
9012: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
9013: my $category = $cats->[1]{$name}[$j];
9014: if (ref($subcats) eq 'HASH') {
9015: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
9016: }
9017: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
9018: }
9019: } else {
9020: if (ref($subcats) eq 'HASH') {
9021: $subcats->{$item} = [];
9022: }
9023: }
9024: }
9025: }
9026: }
9027: return;
9028: }
9029:
9030: =pod
9031:
9032: =item *&recurse_categories()
9033:
9034: Recursively used to generate breadcrumb trails for course categories.
9035:
9036: Inputs:
9037:
9038: cats (reference to array of arrays/hashes which encapsulates hierarchy of
9039: categories and subcategories).
9040:
9041: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
9042:
9043: category (current course category, for which breadcrumb trail is being generated).
9044:
9045: trails (reference to array of breadcrumb trails for each category).
9046:
9047: allitems (reference to hash - key is category key
9048: (format: escaped(name):escaped(parent category):depth in hierarchy).
9049:
9050: parents (array containing containers directories for current category,
9051: back to top level).
9052:
9053: Returns: nothing
9054:
9055: Side effects: populates trails and allitems hash references
9056:
9057: =cut
9058:
9059: sub recurse_categories {
9060: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
9061: my $shallower = $depth - 1;
9062: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
9063: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
9064: my $name = $cats->[$depth]{$category}[$k];
9065: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9066: my $trailstr = join(' -> ',(@{$parents},$category));
9067: if ($allitems->{$item} eq '') {
9068: push(@{$trails},$trailstr);
9069: $allitems->{$item} = scalar(@{$trails})-1;
9070: }
9071: my $deeper = $depth+1;
9072: push(@{$parents},$category);
9073: if (ref($subcats) eq 'HASH') {
9074: my $subcat = &escape($name).':'.$category.':'.$depth;
9075: for (my $j=@{$parents}; $j>=0; $j--) {
9076: my $higher;
9077: if ($j > 0) {
9078: $higher = &escape($parents->[$j]).':'.
9079: &escape($parents->[$j-1]).':'.$j;
9080: } else {
9081: $higher = &escape($parents->[$j]).'::'.$j;
9082: }
9083: push(@{$subcats->{$higher}},$subcat);
9084: }
9085: }
9086: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
9087: $subcats);
9088: pop(@{$parents});
9089: }
9090: } else {
9091: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
9092: my $trailstr = join(' -> ',(@{$parents},$category));
9093: if ($allitems->{$item} eq '') {
9094: push(@{$trails},$trailstr);
9095: $allitems->{$item} = scalar(@{$trails})-1;
9096: }
9097: }
9098: return;
9099: }
9100:
9101: =pod
9102:
9103: =item *&assign_categories_table()
9104:
9105: Create a datatable for display of hierarchical categories in a domain,
9106: with checkboxes to allow a course to be categorized.
9107:
9108: Inputs:
9109:
9110: cathash - reference to hash of categories defined for the domain (from
9111: configuration.db)
9112:
9113: currcat - scalar with an & separated list of categories assigned to a course.
9114:
9115: type - scalar contains course type (Course or Community).
9116:
9117: Returns: $output (markup to be displayed)
9118:
9119: =cut
9120:
9121: sub assign_categories_table {
9122: my ($cathash,$currcat,$type) = @_;
9123: my $output;
9124: if (ref($cathash) eq 'HASH') {
9125: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
9126: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
9127: $maxdepth = scalar(@cats);
9128: if (@cats > 0) {
9129: my $itemcount = 0;
9130: if (ref($cats[0]) eq 'ARRAY') {
9131: my @currcategories;
9132: if ($currcat ne '') {
9133: @currcategories = split('&',$currcat);
9134: }
9135: my $table;
9136: for (my $i=0; $i<@{$cats[0]}; $i++) {
9137: my $parent = $cats[0][$i];
9138: next if ($parent eq 'instcode');
9139: if ($type eq 'Community') {
9140: next unless ($parent eq 'communities');
9141: } else {
9142: next if ($parent eq 'communities');
9143: }
9144: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9145: my $item = &escape($parent).'::0';
9146: my $checked = '';
9147: if (@currcategories > 0) {
9148: if (grep(/^\Q$item\E$/,@currcategories)) {
9149: $checked = ' checked="checked" ';
9150: }
9151: }
9152: my $parent_title = $parent;
9153: if ($parent eq 'communities') {
9154: $parent_title = &mt('Communities');
9155: }
9156: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
9157: '<input type="checkbox" name="usecategory" value="'.
9158: $item.'"'.$checked.' />'.$parent_title.'</span>'.
9159: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
9160: my $depth = 1;
9161: push(@path,$parent);
9162: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
9163: pop(@path);
9164: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
9165: $itemcount ++;
9166: }
9167: if ($itemcount) {
9168: $output = &Apache::loncommon::start_data_table().
9169: $table.
9170: &Apache::loncommon::end_data_table();
9171: }
9172: }
9173: }
9174: }
9175: return $output;
9176: }
9177:
9178: =pod
9179:
9180: =item *&assign_category_rows()
9181:
9182: Create a datatable row for display of nested categories in a domain,
9183: with checkboxes to allow a course to be categorized,called recursively.
9184:
9185: Inputs:
9186:
9187: itemcount - track row number for alternating colors
9188:
9189: cats - reference to array of arrays/hashes which encapsulates hierarchy of
9190: categories and subcategories.
9191:
9192: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
9193:
9194: parent - parent of current category item
9195:
9196: path - Array containing all categories back up through the hierarchy from the
9197: current category to the top level.
9198:
9199: currcategories - reference to array of current categories assigned to the course
9200:
9201: Returns: $output (markup to be displayed).
9202:
9203: =cut
9204:
9205: sub assign_category_rows {
9206: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
9207: my ($text,$name,$item,$chgstr);
9208: if (ref($cats) eq 'ARRAY') {
9209: my $maxdepth = scalar(@{$cats});
9210: if (ref($cats->[$depth]) eq 'HASH') {
9211: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
9212: my $numchildren = @{$cats->[$depth]{$parent}};
9213: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
9214: $text .= '<td><table class="LC_datatable">';
9215: for (my $j=0; $j<$numchildren; $j++) {
9216: $name = $cats->[$depth]{$parent}[$j];
9217: $item = &escape($name).':'.&escape($parent).':'.$depth;
9218: my $deeper = $depth+1;
9219: my $checked = '';
9220: if (ref($currcategories) eq 'ARRAY') {
9221: if (@{$currcategories} > 0) {
9222: if (grep(/^\Q$item\E$/,@{$currcategories})) {
9223: $checked = ' checked="checked" ';
9224: }
9225: }
9226: }
9227: $text .= '<tr><td><span class="LC_nobreak"><label>'.
9228: '<input type="checkbox" name="usecategory" value="'.
9229: $item.'"'.$checked.' />'.$name.'</label></span>'.
9230: '<input type="hidden" name="catname" value="'.$name.'" />'.
9231: '</td><td>';
9232: if (ref($path) eq 'ARRAY') {
9233: push(@{$path},$name);
9234: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
9235: pop(@{$path});
9236: }
9237: $text .= '</td></tr>';
9238: }
9239: $text .= '</table></td>';
9240: }
9241: }
9242: }
9243: return $text;
9244: }
9245:
9246: ############################################################
9247: ############################################################
9248:
9249:
9250: sub commit_customrole {
9251: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
9252: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
9253: ($start?', '.&mt('starting').' '.localtime($start):'').
9254: ($end?', ending '.localtime($end):'').': <b>'.
9255: &Apache::lonnet::assigncustomrole(
9256: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
9257: '</b><br />';
9258: return $output;
9259: }
9260:
9261: sub commit_standardrole {
9262: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9263: my ($output,$logmsg,$linefeed);
9264: if ($context eq 'auto') {
9265: $linefeed = "\n";
9266: } else {
9267: $linefeed = "<br />\n";
9268: }
9269: if ($three eq 'st') {
9270: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
9271: $one,$two,$sec,$context);
9272: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
9273: ($result eq 'unknown_course') || ($result eq 'refused')) {
9274: $output = $logmsg.' '.&mt('Error: ').$result."\n";
9275: } else {
9276: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
9277: ($start?', '.&mt('starting').' '.localtime($start):'').
9278: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9279: if ($context eq 'auto') {
9280: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
9281: } else {
9282: $output .= '<b>'.$result.'</b>'.$linefeed.
9283: &mt('Add to classlist').': <b>ok</b>';
9284: }
9285: $output .= $linefeed;
9286: }
9287: } else {
9288: $output = &mt('Assigning').' '.$three.' in '.$url.
9289: ($start?', '.&mt('starting').' '.localtime($start):'').
9290: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
9291: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
9292: if ($context eq 'auto') {
9293: $output .= $result.$linefeed;
9294: } else {
9295: $output .= '<b>'.$result.'</b>'.$linefeed;
9296: }
9297: }
9298: return $output;
9299: }
9300:
9301: sub commit_studentrole {
9302: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
9303: my ($result,$linefeed,$oldsecurl,$newsecurl);
9304: if ($context eq 'auto') {
9305: $linefeed = "\n";
9306: } else {
9307: $linefeed = '<br />'."\n";
9308: }
9309: if (defined($one) && defined($two)) {
9310: my $cid=$one.'_'.$two;
9311: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
9312: my $secchange = 0;
9313: my $expire_role_result;
9314: my $modify_section_result;
9315: if ($oldsec ne '-1') {
9316: if ($oldsec ne $sec) {
9317: $secchange = 1;
9318: my $now = time;
9319: my $uurl='/'.$cid;
9320: $uurl=~s/\_/\//g;
9321: if ($oldsec) {
9322: $uurl.='/'.$oldsec;
9323: }
9324: $oldsecurl = $uurl;
9325: $expire_role_result =
9326: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
9327: if ($env{'request.course.sec'} ne '') {
9328: if ($expire_role_result eq 'refused') {
9329: my @roles = ('st');
9330: my @statuses = ('previous');
9331: my @roledoms = ($one);
9332: my $withsec = 1;
9333: my %roleshash =
9334: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
9335: \@statuses,\@roles,\@roledoms,$withsec);
9336: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
9337: my ($oldstart,$oldend) =
9338: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
9339: if ($oldend > 0 && $oldend <= $now) {
9340: $expire_role_result = 'ok';
9341: }
9342: }
9343: }
9344: }
9345: $result = $expire_role_result;
9346: }
9347: }
9348: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
9349: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
9350: if ($modify_section_result =~ /^ok/) {
9351: if ($secchange == 1) {
9352: if ($sec eq '') {
9353: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
9354: } else {
9355: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
9356: }
9357: } elsif ($oldsec eq '-1') {
9358: if ($sec eq '') {
9359: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
9360: } else {
9361: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9362: }
9363: } else {
9364: if ($sec eq '') {
9365: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
9366: } else {
9367: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
9368: }
9369: }
9370: } else {
9371: if ($secchange) {
9372: $$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;
9373: } else {
9374: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
9375: }
9376: }
9377: $result = $modify_section_result;
9378: } elsif ($secchange == 1) {
9379: if ($oldsec eq '') {
9380: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
9381: } else {
9382: $$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;
9383: }
9384: if ($expire_role_result eq 'refused') {
9385: my $newsecurl = '/'.$cid;
9386: $newsecurl =~ s/\_/\//g;
9387: if ($sec ne '') {
9388: $newsecurl.='/'.$sec;
9389: }
9390: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
9391: if ($sec eq '') {
9392: $$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;
9393: } else {
9394: $$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;
9395: }
9396: }
9397: }
9398: }
9399: } else {
9400: $$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;
9401: $result = "error: incomplete course id\n";
9402: }
9403: return $result;
9404: }
9405:
9406: ############################################################
9407: ############################################################
9408:
9409: sub check_clone {
9410: my ($args,$linefeed) = @_;
9411: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
9412: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
9413: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
9414: my $clonemsg;
9415: my $can_clone = 0;
9416: my $lctype = lc($args->{'type'});
9417: if ($lctype ne 'community') {
9418: $lctype = 'course';
9419: }
9420: if ($clonehome eq 'no_host') {
9421: if ($args->{'type'} eq 'Community') {
9422: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
9423: } else {
9424: $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'});
9425: }
9426: } else {
9427: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
9428: if ($args->{'type'} eq 'Community') {
9429: if ($clonedesc{'type'} ne 'Community') {
9430: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
9431: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9432: }
9433: }
9434: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
9435: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
9436: $can_clone = 1;
9437: } else {
9438: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
9439: $args->{'clonedomain'},$args->{'clonecourse'});
9440: my @cloners = split(/,/,$clonehash{'cloners'});
9441: if (grep(/^\*$/,@cloners)) {
9442: $can_clone = 1;
9443: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
9444: $can_clone = 1;
9445: } else {
9446: my $ccrole = 'cc';
9447: if ($args->{'type'} eq 'Community') {
9448: $ccrole = 'co';
9449: }
9450: my %roleshash =
9451: &Apache::lonnet::get_my_roles($args->{'ccuname'},
9452: $args->{'ccdomain'},
9453: 'userroles',['active'],[$ccrole],
9454: [$args->{'clonedomain'}]);
9455: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
9456: $can_clone = 1;
9457: } else {
9458: if ($args->{'type'} eq 'Community') {
9459: $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
9460: } else {
9461: $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'});
9462: }
9463: }
9464: }
9465: }
9466: }
9467: return ($can_clone, $clonemsg, $cloneid, $clonehome);
9468: }
9469:
9470: sub construct_course {
9471: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
9472: my $outcome;
9473: my $linefeed = '<br />'."\n";
9474: if ($context eq 'auto') {
9475: $linefeed = "\n";
9476: }
9477:
9478: #
9479: # Are we cloning?
9480: #
9481: my ($can_clone, $clonemsg, $cloneid, $clonehome);
9482: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
9483: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
9484: if ($context ne 'auto') {
9485: if ($clonemsg ne '') {
9486: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
9487: }
9488: }
9489: $outcome .= $clonemsg.$linefeed;
9490:
9491: if (!$can_clone) {
9492: return (0,$outcome);
9493: }
9494: }
9495:
9496: #
9497: # Open course
9498: #
9499: my $crstype = lc($args->{'crstype'});
9500: my %cenv=();
9501: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
9502: $args->{'cdescr'},
9503: $args->{'curl'},
9504: $args->{'course_home'},
9505: $args->{'nonstandard'},
9506: $args->{'crscode'},
9507: $args->{'ccuname'}.':'.
9508: $args->{'ccdomain'},
9509: $args->{'crstype'},
9510: $cnum,$context,$category);
9511:
9512:
9513: # Note: The testing routines depend on this being output; see
9514: # Utils::Course. This needs to at least be output as a comment
9515: # if anyone ever decides to not show this, and Utils::Course::new
9516: # will need to be suitably modified.
9517: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
9518: #
9519: # Check if created correctly
9520: #
9521: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
9522: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
9523: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
9524:
9525: #
9526: # Do the cloning
9527: #
9528: if ($can_clone && $cloneid) {
9529: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
9530: if ($context ne 'auto') {
9531: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
9532: }
9533: $outcome .= $clonemsg.$linefeed;
9534: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
9535: # Copy all files
9536: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
9537: # Restore URL
9538: $cenv{'url'}=$oldcenv{'url'};
9539: # Restore title
9540: $cenv{'description'}=$oldcenv{'description'};
9541: # Mark as cloned
9542: $cenv{'clonedfrom'}=$cloneid;
9543: # Need to clone grading mode
9544: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
9545: $cenv{'grading'}=$newenv{'grading'};
9546: # Do not clone these environment entries
9547: &Apache::lonnet::del('environment',
9548: ['default_enrollment_start_date',
9549: 'default_enrollment_end_date',
9550: 'question.email',
9551: 'policy.email',
9552: 'comment.email',
9553: 'pch.users.denied',
9554: 'plc.users.denied',
9555: 'hidefromcat',
9556: 'categories'],
9557: $$crsudom,$$crsunum);
9558: }
9559:
9560: #
9561: # Set environment (will override cloned, if existing)
9562: #
9563: my @sections = ();
9564: my @xlists = ();
9565: if ($args->{'crstype'}) {
9566: $cenv{'type'}=$args->{'crstype'};
9567: }
9568: if ($args->{'crsid'}) {
9569: $cenv{'courseid'}=$args->{'crsid'};
9570: }
9571: if ($args->{'crscode'}) {
9572: $cenv{'internal.coursecode'}=$args->{'crscode'};
9573: }
9574: if ($args->{'crsquota'} ne '') {
9575: $cenv{'internal.coursequota'}=$args->{'crsquota'};
9576: } else {
9577: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
9578: }
9579: if ($args->{'ccuname'}) {
9580: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
9581: ':'.$args->{'ccdomain'};
9582: } else {
9583: $cenv{'internal.courseowner'} = $args->{'curruser'};
9584: }
9585: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
9586: if ($args->{'crssections'}) {
9587: $cenv{'internal.sectionnums'} = '';
9588: if ($args->{'crssections'} =~ m/,/) {
9589: @sections = split/,/,$args->{'crssections'};
9590: } else {
9591: $sections[0] = $args->{'crssections'};
9592: }
9593: if (@sections > 0) {
9594: foreach my $item (@sections) {
9595: my ($sec,$gp) = split/:/,$item;
9596: my $class = $args->{'crscode'}.$sec;
9597: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
9598: $cenv{'internal.sectionnums'} .= $item.',';
9599: unless ($addcheck eq 'ok') {
9600: push @badclasses, $class;
9601: }
9602: }
9603: $cenv{'internal.sectionnums'} =~ s/,$//;
9604: }
9605: }
9606: # do not hide course coordinator from staff listing,
9607: # even if privileged
9608: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9609: # add crosslistings
9610: if ($args->{'crsxlist'}) {
9611: $cenv{'internal.crosslistings'}='';
9612: if ($args->{'crsxlist'} =~ m/,/) {
9613: @xlists = split/,/,$args->{'crsxlist'};
9614: } else {
9615: $xlists[0] = $args->{'crsxlist'};
9616: }
9617: if (@xlists > 0) {
9618: foreach my $item (@xlists) {
9619: my ($xl,$gp) = split/:/,$item;
9620: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
9621: $cenv{'internal.crosslistings'} .= $item.',';
9622: unless ($addcheck eq 'ok') {
9623: push @badclasses, $xl;
9624: }
9625: }
9626: $cenv{'internal.crosslistings'} =~ s/,$//;
9627: }
9628: }
9629: if ($args->{'autoadds'}) {
9630: $cenv{'internal.autoadds'}=$args->{'autoadds'};
9631: }
9632: if ($args->{'autodrops'}) {
9633: $cenv{'internal.autodrops'}=$args->{'autodrops'};
9634: }
9635: # check for notification of enrollment changes
9636: my @notified = ();
9637: if ($args->{'notify_owner'}) {
9638: if ($args->{'ccuname'} ne '') {
9639: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
9640: }
9641: }
9642: if ($args->{'notify_dc'}) {
9643: if ($uname ne '') {
9644: push(@notified,$uname.':'.$udom);
9645: }
9646: }
9647: if (@notified > 0) {
9648: my $notifylist;
9649: if (@notified > 1) {
9650: $notifylist = join(',',@notified);
9651: } else {
9652: $notifylist = $notified[0];
9653: }
9654: $cenv{'internal.notifylist'} = $notifylist;
9655: }
9656: if (@badclasses > 0) {
9657: my %lt=&Apache::lonlocal::texthash(
9658: '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',
9659: 'dnhr' => 'does not have rights to access enrollment in these classes',
9660: 'adby' => 'as determined by the policies of your institution on access to official classlists'
9661: );
9662: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
9663: ' ('.$lt{'adby'}.')';
9664: if ($context eq 'auto') {
9665: $outcome .= $badclass_msg.$linefeed;
9666: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
9667: foreach my $item (@badclasses) {
9668: if ($context eq 'auto') {
9669: $outcome .= " - $item\n";
9670: } else {
9671: $outcome .= "<li>$item</li>\n";
9672: }
9673: }
9674: if ($context eq 'auto') {
9675: $outcome .= $linefeed;
9676: } else {
9677: $outcome .= "</ul><br /><br /></div>\n";
9678: }
9679: }
9680: }
9681: if ($args->{'no_end_date'}) {
9682: $args->{'endaccess'} = 0;
9683: }
9684: $cenv{'internal.autostart'}=$args->{'enrollstart'};
9685: $cenv{'internal.autoend'}=$args->{'enrollend'};
9686: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
9687: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
9688: if ($args->{'showphotos'}) {
9689: $cenv{'internal.showphotos'}=$args->{'showphotos'};
9690: }
9691: $cenv{'internal.authtype'} = $args->{'authtype'};
9692: $cenv{'internal.autharg'} = $args->{'autharg'};
9693: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
9694: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
9695: 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');
9696: if ($context eq 'auto') {
9697: $outcome .= $krb_msg;
9698: } else {
9699: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
9700: }
9701: $outcome .= $linefeed;
9702: }
9703: }
9704: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
9705: if ($args->{'setpolicy'}) {
9706: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9707: }
9708: if ($args->{'setcontent'}) {
9709: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
9710: }
9711: }
9712: if ($args->{'reshome'}) {
9713: $cenv{'reshome'}=$args->{'reshome'}.'/';
9714: $cenv{'reshome'}=~s/\/+$/\//;
9715: }
9716: #
9717: # course has keyed access
9718: #
9719: if ($args->{'setkeys'}) {
9720: $cenv{'keyaccess'}='yes';
9721: }
9722: # if specified, key authority is not course, but user
9723: # only active if keyaccess is yes
9724: if ($args->{'keyauth'}) {
9725: my ($user,$domain) = split(':',$args->{'keyauth'});
9726: $user = &LONCAPA::clean_username($user);
9727: $domain = &LONCAPA::clean_username($domain);
9728: if ($user ne '' && $domain ne '') {
9729: $cenv{'keyauth'}=$user.':'.$domain;
9730: }
9731: }
9732:
9733: if ($args->{'disresdis'}) {
9734: $cenv{'pch.roles.denied'}='st';
9735: }
9736: if ($args->{'disablechat'}) {
9737: $cenv{'plc.roles.denied'}='st';
9738: }
9739:
9740: # Record we've not yet viewed the Course Initialization Helper for this
9741: # course
9742: $cenv{'course.helper.not.run'} = 1;
9743: #
9744: # Use new Randomseed
9745: #
9746: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
9747: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
9748: #
9749: # The encryption code and receipt prefix for this course
9750: #
9751: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
9752: $cenv{'internal.encpref'}=100+int(9*rand(99));
9753: #
9754: # By default, use standard grading
9755: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
9756:
9757: $outcome .= $linefeed.&mt('Setting environment').': '.
9758: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
9759: #
9760: # Open all assignments
9761: #
9762: if ($args->{'openall'}) {
9763: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
9764: my %storecontent = ($storeunder => time,
9765: $storeunder.'.type' => 'date_start');
9766:
9767: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
9768: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
9769: }
9770: #
9771: # Set first page
9772: #
9773: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
9774: || ($cloneid)) {
9775: use LONCAPA::map;
9776: $outcome .= &mt('Setting first resource').': ';
9777:
9778: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
9779: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
9780:
9781: $outcome .= ($fatal?$errtext:'read ok').' - ';
9782: my $title; my $url;
9783: if ($args->{'firstres'} eq 'syl') {
9784: $title=&mt('Syllabus');
9785: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
9786: } else {
9787: $title=&mt('Navigate Contents');
9788: $url='/adm/navmaps';
9789: }
9790:
9791: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
9792: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
9793:
9794: if ($errtext) { $fatal=2; }
9795: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
9796: }
9797:
9798: return (1,$outcome);
9799: }
9800:
9801: ############################################################
9802: ############################################################
9803:
9804: sub course_type {
9805: my ($cid) = @_;
9806: if (!defined($cid)) {
9807: $cid = $env{'request.course.id'};
9808: }
9809: if (defined($env{'course.'.$cid.'.type'})) {
9810: return $env{'course.'.$cid.'.type'};
9811: } else {
9812: return 'Course';
9813: }
9814: }
9815:
9816: sub group_term {
9817: my $crstype = &course_type();
9818: my %names = (
9819: 'Course' => 'group',
9820: 'Community' => 'group',
9821: );
9822: return $names{$crstype};
9823: }
9824:
9825: sub course_types {
9826: my @types = ('official','unofficial','community');
9827: my %typename = (
9828: official => 'Official course',
9829: unofficial => 'Unofficial course',
9830: community => 'Community',
9831: );
9832: return (\@types,\%typename);
9833: }
9834:
9835: sub icon {
9836: my ($file)=@_;
9837: my $curfext = lc((split(/\./,$file))[-1]);
9838: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
9839: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
9840: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
9841: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
9842: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9843: $curfext.".gif") {
9844: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
9845: $curfext.".gif";
9846: }
9847: }
9848: return &lonhttpdurl($iconname);
9849: }
9850:
9851: sub lonhttpdurl {
9852: #
9853: # Had been used for "small fry" static images on separate port 8080.
9854: # Modify here if lightweight http functionality desired again.
9855: # Currently eliminated due to increasing firewall issues.
9856: #
9857: my ($url)=@_;
9858: return $url;
9859: }
9860:
9861: sub connection_aborted {
9862: my ($r)=@_;
9863: $r->print(" ");$r->rflush();
9864: my $c = $r->connection;
9865: return $c->aborted();
9866: }
9867:
9868: # Escapes strings that may have embedded 's that will be put into
9869: # strings as 'strings'.
9870: sub escape_single {
9871: my ($input) = @_;
9872: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
9873: $input =~ s/\'/\\\'/g; # Esacpe the 's....
9874: return $input;
9875: }
9876:
9877: # Same as escape_single, but escape's "'s This
9878: # can be used for "strings"
9879: sub escape_double {
9880: my ($input) = @_;
9881: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
9882: $input =~ s/\"/\\\"/g; # Esacpe the "s....
9883: return $input;
9884: }
9885:
9886: # Escapes the last element of a full URL.
9887: sub escape_url {
9888: my ($url) = @_;
9889: my @urlslices = split(/\//, $url,-1);
9890: my $lastitem = &escape(pop(@urlslices));
9891: return join('/',@urlslices).'/'.$lastitem;
9892: }
9893:
9894: sub compare_arrays {
9895: my ($arrayref1,$arrayref2) = @_;
9896: my (@difference,%count);
9897: @difference = ();
9898: %count = ();
9899: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
9900: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
9901: foreach my $element (keys(%count)) {
9902: if ($count{$element} == 1) {
9903: push(@difference,$element);
9904: }
9905: }
9906: }
9907: return @difference;
9908: }
9909:
9910: # -------------------------------------------------------- Initliaze user login
9911: sub init_user_environment {
9912: my ($r, $username, $domain, $authhost, $form, $args) = @_;
9913: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
9914:
9915: my $public=($username eq 'public' && $domain eq 'public');
9916:
9917: # See if old ID present, if so, remove
9918:
9919: my ($filename,$cookie,$userroles);
9920: my $now=time;
9921:
9922: if ($public) {
9923: my $max_public=100;
9924: my $oldest;
9925: my $oldest_time=0;
9926: for(my $next=1;$next<=$max_public;$next++) {
9927: if (-e $lonids."/publicuser_$next.id") {
9928: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
9929: if ($mtime<$oldest_time || !$oldest_time) {
9930: $oldest_time=$mtime;
9931: $oldest=$next;
9932: }
9933: } else {
9934: $cookie="publicuser_$next";
9935: last;
9936: }
9937: }
9938: if (!$cookie) { $cookie="publicuser_$oldest"; }
9939: } else {
9940: # if this isn't a robot, kill any existing non-robot sessions
9941: if (!$args->{'robot'}) {
9942: opendir(DIR,$lonids);
9943: while ($filename=readdir(DIR)) {
9944: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
9945: unlink($lonids.'/'.$filename);
9946: }
9947: }
9948: closedir(DIR);
9949: }
9950: # Give them a new cookie
9951: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
9952: : $now.$$.int(rand(10000)));
9953: $cookie="$username\_$id\_$domain\_$authhost";
9954:
9955: # Initialize roles
9956:
9957: $userroles=&Apache::lonnet::rolesinit($domain,$username,$authhost);
9958: }
9959: # ------------------------------------ Check browser type and MathML capability
9960:
9961: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
9962: $clientunicode,$clientos) = &decode_user_agent($r);
9963:
9964: # -------------------------------------- Any accessibility options to remember?
9965: if (($form->{'interface'}) && ($form->{'remember'} eq 'true')) {
9966: foreach my $option ('imagesuppress','appletsuppress',
9967: 'embedsuppress','fontenhance','blackwhite') {
9968: if ($form->{$option} eq 'true') {
9969: &Apache::lonnet::put('environment',{$option => 'on'},
9970: $domain,$username);
9971: } else {
9972: &Apache::lonnet::del('environment',[$option],
9973: $domain,$username);
9974: }
9975: }
9976: }
9977: # ------------------------------------------------------------- Get environment
9978:
9979: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
9980: my ($tmp) = keys(%userenv);
9981: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9982: # default remote control to off
9983: if ($userenv{'remote'} ne 'on') { $userenv{'remote'} = 'off'; }
9984: } else {
9985: undef(%userenv);
9986: }
9987: if (($userenv{'interface'}) && (!$form->{'interface'})) {
9988: $form->{'interface'}=$userenv{'interface'};
9989: }
9990: $env{'environment.remote'}=$userenv{'remote'};
9991: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
9992:
9993: # --------------- Do not trust query string to be put directly into environment
9994: foreach my $option ('imagesuppress','appletsuppress',
9995: 'embedsuppress','fontenhance','blackwhite',
9996: 'interface','localpath','localres') {
9997: $form->{$option}=~s/[\n\r\=]//gs;
9998: }
9999: # --------------------------------------------------------- Write first profile
10000:
10001: {
10002: my %initial_env =
10003: ("user.name" => $username,
10004: "user.domain" => $domain,
10005: "user.home" => $authhost,
10006: "browser.type" => $clientbrowser,
10007: "browser.version" => $clientversion,
10008: "browser.mathml" => $clientmathml,
10009: "browser.unicode" => $clientunicode,
10010: "browser.os" => $clientos,
10011: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
10012: "request.course.fn" => '',
10013: "request.course.uri" => '',
10014: "request.course.sec" => '',
10015: "request.role" => 'cm',
10016: "request.role.adv" => $env{'user.adv'},
10017: "request.host" => $ENV{'REMOTE_ADDR'},);
10018:
10019: if ($form->{'localpath'}) {
10020: $initial_env{"browser.localpath"} = $form->{'localpath'};
10021: $initial_env{"browser.localres"} = $form->{'localres'};
10022: }
10023:
10024: if ($public) {
10025: $initial_env{"environment.remote"} = "off";
10026: }
10027: if ($form->{'interface'}) {
10028: $form->{'interface'}=~s/\W//gs;
10029: $initial_env{"browser.interface"} = $form->{'interface'};
10030: $env{'browser.interface'}=$form->{'interface'};
10031: foreach my $option ('imagesuppress','appletsuppress',
10032: 'embedsuppress','fontenhance','blackwhite') {
10033: if (($form->{$option} eq 'true') ||
10034: ($userenv{$option} eq 'on')) {
10035: $initial_env{"browser.$option"} = "on";
10036: }
10037: }
10038: }
10039:
10040: foreach my $tool ('aboutme','blog','portfolio') {
10041: $userenv{'availabletools.'.$tool} =
10042: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload');
10043: }
10044:
10045: foreach my $crstype ('official','unofficial','community') {
10046: $userenv{'canrequest.'.$crstype} =
10047: &Apache::lonnet::usertools_access($username,$domain,$crstype,
10048: 'reload','requestcourses');
10049: }
10050:
10051: $env{'user.environment'} = "$lonids/$cookie.id";
10052:
10053: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
10054: &GDBM_WRCREAT(),0640)) {
10055: &_add_to_env(\%disk_env,\%initial_env);
10056: &_add_to_env(\%disk_env,\%userenv,'environment.');
10057: &_add_to_env(\%disk_env,$userroles);
10058: if (ref($args->{'extra_env'})) {
10059: &_add_to_env(\%disk_env,$args->{'extra_env'});
10060: }
10061: untie(%disk_env);
10062: } else {
10063: &Apache::lonnet::logthis("<font color=\"blue\">WARNING: ".
10064: 'Could not create environment storage in lonauth: '.$!.'</font>');
10065: return 'error: '.$!;
10066: }
10067: }
10068: $env{'request.role'}='cm';
10069: $env{'request.role.adv'}=$env{'user.adv'};
10070: $env{'browser.type'}=$clientbrowser;
10071:
10072: return $cookie;
10073:
10074: }
10075:
10076: sub _add_to_env {
10077: my ($idf,$env_data,$prefix) = @_;
10078: if (ref($env_data) eq 'HASH') {
10079: while (my ($key,$value) = each(%$env_data)) {
10080: $idf->{$prefix.$key} = $value;
10081: $env{$prefix.$key} = $value;
10082: }
10083: }
10084: }
10085:
10086: # --- Get the symbolic name of a problem and the url
10087: sub get_symb {
10088: my ($request,$silent) = @_;
10089: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10090: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
10091: if ($symb eq '') {
10092: if (!$silent) {
10093: $request->print("Unable to handle ambiguous references:$url:.");
10094: return ();
10095: }
10096: }
10097: &Apache::lonenc::check_decrypt(\$symb);
10098: return ($symb);
10099: }
10100:
10101: # --------------------------------------------------------------Get annotation
10102:
10103: sub get_annotation {
10104: my ($symb,$enc) = @_;
10105:
10106: my $key = $symb;
10107: if (!$enc) {
10108: $key =
10109: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
10110: }
10111: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
10112: return $annotation{$key};
10113: }
10114:
10115: sub clean_symb {
10116: my ($symb,$delete_enc) = @_;
10117:
10118: &Apache::lonenc::check_decrypt(\$symb);
10119: my $enc = $env{'request.enc'};
10120: if ($delete_enc) {
10121: delete($env{'request.enc'});
10122: }
10123:
10124: return ($symb,$enc);
10125: }
10126:
10127: =pod
10128:
10129: =back
10130:
10131: =cut
10132:
10133: 1;
10134: __END__;
10135:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>